File size: 6,371 Bytes
cc3506e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Matplotlib helpers shared across the dashboard pages.

Field plots use the SAME color scheme as the training code
(`training_code/*/train.py` plot_test_results): "seismic" for phase fields
(vmin=0, vmax=1) and "Oranges" for error maps, on white figure backgrounds —
so in-app results look exactly like the manuscript/training figures.

The navy palette is used only for the website chrome (.streamlit/config.toml)
and small accents here (GRF profile line), not for the result fields.
"""
from __future__ import annotations

import matplotlib.pyplot as plt
import numpy as np

NAVY = ["#0D1F45", "#1A3A66", "#245E94", "#7295AD", "#BCCBDC"]
BG, BG2, ACCENT, MUTED, LIGHT = NAVY

# white -> purple field colormap (matches the purple/green geometry panel):
# intact material white, fully cracked deep purple.
from matplotlib.colors import LinearSegmentedColormap

PHASE_CMAP = LinearSegmentedColormap.from_list(
    "purple_field",
    ["#FFFFFF", "#E2D7EE", "#B597CD", "#8255A8", "#4B2273"])
PHASE_CMAP.set_bad(color="#DCDCDC")          # masked pixels (hole) light gray
ERROR_CMAP = "Oranges"                       # training-code error colormap


def plot_field(field: np.ndarray, title: str = "", vmax: float = 1.0,
               cmap=PHASE_CMAP, mask: np.ndarray | None = None):
    fig, ax = plt.subplots(figsize=(4, 4 * field.shape[0] / field.shape[1]))
    shown = field.copy()
    if mask is not None:
        shown = np.ma.masked_where(mask, shown)
    im = ax.imshow(shown, cmap=cmap, vmin=0, vmax=vmax, origin="lower")
    ax.set_title(title, fontsize=10)
    ax.set_xticks([]); ax.set_yticks([])
    fig.colorbar(im, ax=ax, fraction=0.046)
    fig.tight_layout()
    return fig


def plot_comparison_row(fields: dict[str, np.ndarray], vmax: float | None = 1.0,
                        mask: np.ndarray | None = None,
                        suptitle: str = "",
                        cmap=None,
                        figsize: tuple | None = None,
                        n_slots: int | None = None,
                        cbar_label: str | None = None):
    """One row of panels with a CONSTANT per-panel size.

    The row is laid out into ``n_slots`` equal columns (default = number of
    fields).  Pass a fixed ``n_slots`` (e.g. max models + ground truth) so each
    panel keeps the same size no matter how many models are selected — empty
    slots are left blank (white space).  Pass cmap='Oranges' for error maps.
    Pass ``cbar_label`` to add a colour scale shared by all panels of the row.
    """
    if cmap is None:
        cmap = PHASE_CMAP
    n = len(fields)
    slots = max(n, n_slots or n)
    first = next(iter(fields.values()))
    h, w = first.shape[:2]
    if figsize is None:
        panel_w = 9.5 / slots                  # per-panel width (constant slots)
        fig_h = panel_w * (h / w) + 0.6        # + room for the label/caption
        figsize = (9.5, fig_h)
    fig, axes = plt.subplots(1, slots, figsize=figsize)
    if slots == 1:
        axes = [axes]
    items = list(fields.items())
    im, peak = None, 0.0
    for j, ax in enumerate(axes):
        if j < n:
            name, field = items[j]
            shown = field
            if mask is not None:
                shown = np.ma.masked_where(mask, field)
            im = ax.imshow(shown, cmap=cmap, vmin=0, vmax=vmax, origin="lower")
            peak = max(peak, float(np.ma.max(shown)))
            ax.set_xlabel(name, fontsize=9, labelpad=3)  # model label below panel
            ax.set_xticks([]); ax.set_yticks([])
        else:
            ax.axis("off")                                # blank slot -> white space
    if suptitle:
        fig.supxlabel(suptitle, fontsize=10)             # caption at the bottom
    with_cbar = cbar_label is not None and im is not None
    # a full row has no blank slot for the colour scale: reserve a right margin
    right = 0.92 if with_cbar and n == slots else 1
    fig.tight_layout(rect=[0, 0.06, right, 1], w_pad=4.5)  # gap between panels
    if with_cbar:
        fig.canvas.draw()                                # settle equal-aspect panel boxes
        panel = axes[n - 1].get_position()
        x0 = axes[n].get_position().x0 if n < slots else panel.x1 + 0.012
        cax = fig.add_axes([x0, panel.y0, 0.012, panel.height])
        clipped = vmax is not None and peak > vmax       # values above vmax saturate
        cb = fig.colorbar(im, cax=cax, extend="max" if clipped else "neither")
        cb.set_label(cbar_label, fontsize=9)
        cb.ax.tick_params(labelsize=8)
        cb.formatter.set_powerlimits((-3, 3))
        cb.update_ticks()
    return fig


# Dataset-2 configuration panel: light-gray plate, light green = hard
# inclusion (10 Em), dark green = soft (0.1 Em), purple pre-crack (matches
# the purple prediction colormap).
PLATE_GRAY = "#DCDCDC"
HARD_GREEN = "#8CB87C"
SOFT_GREEN = "#2F6B3C"
CRACK_PURPLE = "#4B2273"


def plot_d2_config(d0: np.ndarray, upper_hard: bool, lower_hard: bool,
                   upper_mask: np.ndarray, lower_mask: np.ndarray,
                   title: str = "Input: d(x,0) + inclusions"):
    from matplotlib.colors import to_rgb
    import matplotlib.patches as mpatches

    H, W = d0.shape
    img = np.ones((H, W, 3)) * np.array(to_rgb(PLATE_GRAY))
    img[upper_mask] = to_rgb(HARD_GREEN if upper_hard else SOFT_GREEN)
    img[lower_mask] = to_rgb(HARD_GREEN if lower_hard else SOFT_GREEN)
    img[d0 > 0.3] = to_rgb(CRACK_PURPLE)

    fig, ax = plt.subplots(figsize=(3, 3 * H / W))
    ax.imshow(img, origin="lower")
    ax.set_title(title, fontsize=9)
    ax.set_xticks([]); ax.set_yticks([])
    handles = [mpatches.Patch(color=HARD_GREEN, label="stiffer (10 Eₘ)"),
               mpatches.Patch(color=SOFT_GREEN, label="softer (0.1 Eₘ)"),
               mpatches.Patch(color=CRACK_PURPLE, label="initial crack")]
    ax.legend(handles=handles, loc="upper center",
              bbox_to_anchor=(0.5, -0.02), ncol=1, fontsize=7,
              frameon=False)
    fig.tight_layout()
    return fig


def plot_grf_profile(f: np.ndarray):
    fig, ax = plt.subplots(figsize=(5, 1.8))
    s = np.linspace(-1, 1, len(f))
    ax.plot(s, f, lw=1.8, color=ACCENT)
    ax.fill_between(s, f, f.min(), color=ACCENT, alpha=0.25)
    ax.set_xlabel("boundary coordinate"); ax.set_ylabel("f(x)")
    ax.grid(alpha=0.3)
    fig.tight_layout()
    return fig