File size: 31,293 Bytes
18f93b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
"""Plotly figures in the format of the LithoBench-PDE `vis/` notebooks."""
import base64
import io

import numpy as np
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
import torch
from matplotlib import colormaps
from matplotlib.colors import hsv_to_rgb
from PIL import Image
from plotly.subplots import make_subplots
from skimage import measure

HUE = hsv_to_rgb(np.stack([np.linspace(0, 1, 256), np.ones(256), np.ones(256)], axis=-1))
GAMMA = 0.7


def to_numpy(x):
    return x.detach().cpu().numpy() if torch.is_tensor(x) else np.asarray(x)


def cm2px(cm, dpi):
    return int(cm / 2.54 * dpi)


def pt2px(pt, dpi):
    return int(pt / 72 * dpi)


def rgb_colorscale(cmap_name):
    cmap = colormaps[cmap_name]
    return [[i / 255, 'rgb({},{},{})'.format(*[int(c * 255) for c in cmap(i / 255)[:3]])] for i in range(256)]


def alpha_colorscale(cmap_name, a_min, a_max):
    cmap = colormaps[cmap_name]
    scale = []
    for i in range(256):
        t = i / 255
        r, g, b, _ = cmap(t)
        a = a_min + (a_max - a_min) * t ** 5
        scale.append([t, f'rgba({int(r * 255)},{int(g * 255)},{int(b * 255)},{a:.3f})'])
    return scale


def plot_2d(data, heatmap_width_cm=2., heatmap_height_cm=2., dpi=300, scale=1.0,
            use_colorbar=True, colorbar_thickness=24, text_font_size=7, ticklabel_font_size=5,
            show_x_ticks=True, show_x_ticklabels=True, show_y_ticks=True, show_y_ticklabels=True,
            x_unit=0.004, y_unit=0.004, x_ticks=(0, 250, 500), y_ticks=(0, 250, 500),
            boundary_linewidth=1, tick_width=1, x_label='x [μm]', y_label='y [μm]', cmap='Jet',
            ticklen=16, colorbar_min=None, colorbar_max=None, outer_margin_cm=0.2, colorbar_title=None):
    """One heatmap, or a 2 x 2 grid of heatmaps for data of shape (2, 2, H, W)."""
    data = to_numpy(data)
    is_grid = data.ndim == 4 and data.shape[:2] == (2, 2)
    panels = data if is_grid else data[np.newaxis, np.newaxis]
    rows, cols = (2, 2) if is_grid else (1, 1)

    N = panels[0, 0].shape[0]
    if N > 1000:
        x_ticks, y_ticks = (0, 500, 1000), (0, 500, 1000)
        heatmap_width_cm *= 2
        heatmap_height_cm *= 2
        colorbar_thickness *= 2

    data_w = heatmap_width_cm / 2.54 * dpi
    data_h = heatmap_height_cm / 2.54 * dpi
    text_px = int(text_font_size / 72 * dpi * scale)
    tick_px = int(ticklabel_font_size / 72 * dpi * scale)
    pad = int(5 * scale)
    gap = pad * 5
    outer = outer_margin_cm / 2.54 * dpi
    cb_gap = pad * 4
    cb_tick_w = tick_px * 8

    ml = outer + boundary_linewidth + show_y_ticks * ticklen + show_y_ticklabels * tick_px + (1 if y_label else 0) * text_px + pad
    mr = outer + boundary_linewidth + pad + use_colorbar * (cb_gap + colorbar_thickness + cb_tick_w)
    mb = outer + boundary_linewidth + show_x_ticks * ticklen + show_x_ticklabels * tick_px + (1 if x_label else 0) * text_px * 3 + pad
    mt = outer + boundary_linewidth + pad

    fig_w = ml + mr + cols * data_w + (cols - 1) * gap
    fig_h = mt + mb + rows * data_h + (rows - 1) * gap
    grid_y0 = mb / fig_h
    grid_y1 = (mb + rows * data_h + (rows - 1) * gap) / fig_h

    vmin = float(colorbar_min if colorbar_min is not None else panels.min())
    vmax = float(colorbar_max if colorbar_max is not None else panels.max())

    border = dict(showline=True, linecolor='lightgray', linewidth=boundary_linewidth, mirror=True, fixedrange=True)

    def xname(i):
        return 'x' if i == 0 else f'x{i + 1}'

    def yname(i):
        return 'y' if i == 0 else f'y{i + 1}'

    def make_xaxis(domain, anchor, is_bottom):
        ax = dict(domain=domain, anchor=anchor, **border)
        if is_bottom:
            ax.update(ticks='outside' if show_x_ticks else '', ticklen=ticklen, tickwidth=tick_width,
                      tickcolor='black', tickfont=dict(size=tick_px, color='black'),
                      showticklabels=show_x_ticklabels,
                      title=dict(text=x_label or '', font=dict(size=text_px, color='black'), standoff=tick_px + ticklen),
                      tickmode='array', tickvals=list(x_ticks), ticktext=[f'{v * x_unit:.1f}' for v in x_ticks])
        else:
            ax.update(ticks='', ticklen=0, showticklabels=False, title=dict(text=''), showgrid=False)
        return ax

    def make_yaxis(domain, anchor, is_left):
        ax = dict(domain=domain, anchor=anchor, **border)
        if is_left:
            ax.update(ticks='outside' if show_y_ticks else '', ticklen=ticklen, tickwidth=tick_width,
                      tickcolor='black', tickfont=dict(size=tick_px, color='black'),
                      showticklabels=show_y_ticklabels,
                      title=dict(text=y_label or '', font=dict(size=text_px, color='black'), standoff=tick_px + ticklen),
                      tickmode='array', tickvals=list(y_ticks), ticktext=[f'{v * y_unit:.1f}' for v in y_ticks])
        else:
            ax.update(ticks='', ticklen=0, showticklabels=False, title=dict(text=''), showgrid=False)
        return ax

    fig = go.Figure()
    for r in range(rows):
        for c in range(cols):
            idx = r * cols + c
            x0 = (ml + c * (data_w + gap)) / fig_w
            x1 = (ml + c * (data_w + gap) + data_w) / fig_w
            y0 = (mb + (rows - 1 - r) * (data_h + gap)) / fig_h
            y1 = (mb + (rows - 1 - r) * (data_h + gap) + data_h) / fig_h
            fig.add_trace(go.Heatmap(z=panels[r, c], colorscale=cmap, showscale=False, zmin=vmin, zmax=vmax,
                                     xaxis=xname(idx), yaxis=yname(idx)))
            fig.update_layout(**{
                f'xaxis{"" if idx == 0 else idx + 1}': make_xaxis([x0, x1], yname(idx), r == rows - 1),
                f'yaxis{"" if idx == 0 else idx + 1}': make_yaxis([y0, y1], xname(idx), c == 0)})

    if use_colorbar:
        n_cb = 256
        cb_idx = rows * cols
        cb_x0 = (ml + cols * data_w + (cols - 1) * gap + cb_gap) / fig_w
        cb_x1 = cb_x0 + colorbar_thickness / fig_w
        fig.add_trace(go.Heatmap(z=np.linspace(vmin, vmax, n_cb).reshape(n_cb, 1), colorscale=cmap, showscale=False,
                                 zmin=vmin, zmax=vmax, xaxis=xname(cb_idx), yaxis=yname(cb_idx)))
        fig.update_layout(**{
            f'xaxis{cb_idx + 1}': dict(domain=[cb_x0, cb_x1], anchor=yname(cb_idx), visible=False, fixedrange=True,
                                       showline=True, linecolor='black', linewidth=boundary_linewidth, mirror=True),
            f'yaxis{cb_idx + 1}': dict(domain=[grid_y0, grid_y1], anchor=xname(cb_idx), side='right', fixedrange=True,
                                       tickmode='array', tickvals=np.linspace(0, n_cb - 1, 5),
                                       ticktext=[f'{v:.2f}' for v in np.linspace(vmin, vmax, 5)],
                                       tickfont=dict(size=tick_px, color='black'), tickcolor='black',
                                       tickwidth=tick_width, ticklen=ticklen // 2,
                                       showline=True, linecolor='black', linewidth=boundary_linewidth,
                                       showgrid=False, mirror=False,
                                       title=dict(text=colorbar_title or '', font=dict(size=text_px, color='black'),
                                                  standoff=tick_px + ticklen // 2))})

    fig.update_layout(autosize=False, width=int(fig_w), height=int(fig_h), margin=dict(l=0, r=0, t=0, b=0),
                      paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
                      font=dict(family='Arial, sans-serif', size=text_px, color='black'))
    return fig


def vis_mask(data, cmap='gray', x_unit=0.016):
    """Photomask (H, W); the mask grid is 16 nm / px."""
    return plot_2d(np.flipud(to_numpy(data)), cmap=cmap, use_colorbar=False, x_unit=x_unit, y_unit=x_unit)


def median_phase(field):
    """Phase of (median Re, median Im): the phase origin of one near-field component."""
    field = torch.as_tensor(field)
    return torch.complex(field.real.median(), field.imag.median()).angle().item()


def phase_amplitude_rgb(field, ref_phase=0.0, amp_max=1.0):
    """Hue = phase relative to ref_phase (hsv wheel); white -> pure hue with (|field| / amp_max)^0.7."""
    field = to_numpy(field)
    t = (np.angle(field * np.exp(-1j * ref_phase)) + np.pi) / (2 * np.pi)
    hue = HUE[np.clip((t * 255).astype(int), 0, 255)]
    v = np.clip(np.abs(field) / max(amp_max, 1e-30), 0, 1)[..., None] ** GAMMA
    return np.clip(1 - v + hue * v, 0, 1)


def png_source(rgb):
    buffer = io.BytesIO()
    Image.fromarray((rgb * 255).astype(np.uint8)).save(buffer, format='PNG')
    return 'data:image/png;base64,' + base64.b64encode(buffer.getvalue()).decode()


def vis_sc(E, reference=None, x_unit=0.016, panel_cm=2.0, dpi=300):
    """Near field E (2, 2, H, W) as a 2 x 2 grid of phase and amplitude (E[i, j]: output i, incident polarization j).
    The phase origin of each component and the amplitude scale come from `reference` (default: E itself),
    so a prediction drawn with its reference shares the color code of the reference."""
    E = torch.as_tensor(E)
    reference = E if reference is None else torch.as_tensor(reference)
    amp_max = reference.abs().max().item()
    n = E.shape[-1]
    ticks = (0, 250, 500) if n <= 1000 else (0, 500, 1000)
    legend_w = 40 if n <= 1000 else 80
    if n > 1000:
        panel_cm *= 2

    data_w = panel_cm / 2.54 * dpi
    text_px, tick_px = int(7 / 72 * dpi), int(5 / 72 * dpi)
    ticklen, pad, gap, legend_gap = 16, 5, 45, 20
    outer = 0.2 / 2.54 * dpi
    ml = outer + ticklen + tick_px + text_px + pad
    mb = outer + ticklen + tick_px + 3 * text_px + pad
    mr = outer + legend_gap + legend_w + ticklen + 3 * tick_px + 2 * text_px + pad
    mt = outer + pad
    grid = 2 * data_w + gap
    fig_w, fig_h = ml + grid + mr, mb + grid + mt

    axis = dict(showline=True, linecolor='gray', linewidth=2, mirror=True, showgrid=False, zeroline=False,
                fixedrange=True, tickmode='array', tickcolor='gray', tickwidth=1, ticklen=ticklen,
                tickfont=dict(size=tick_px, color='black'))
    labels = [f'{v * x_unit:.1f}' for v in ticks]
    fig = go.Figure()
    for i in range(2):
        for j in range(2):
            k = '' if i == j == 0 else str(2 * i + j + 1)
            rgb = phase_amplitude_rgb(E[i, j], median_phase(reference[i, j]), amp_max)
            fig.add_trace(go.Image(source=png_source(rgb), xaxis='x' + k, yaxis='y' + k))
            x0, y0 = ml + j * (data_w + gap), mb + (1 - i) * (data_w + gap)
            bottom, left = i == 1, j == 0
            fig.update_layout(**{
                'xaxis' + k: dict(axis, domain=[x0 / fig_w, (x0 + data_w) / fig_w], anchor='y' + k, range=[-0.5, n - 0.5],
                                  ticks='outside' if bottom else '', showticklabels=bottom,
                                  tickvals=list(ticks), ticktext=labels,
                                  title=dict(text='x [μm]' if bottom else '', font=dict(size=text_px))),
                'yaxis' + k: dict(axis, domain=[y0 / fig_h, (y0 + data_w) / fig_h], anchor='x' + k, range=[n - 0.5, -0.5],
                                  ticks='outside' if left else '', showticklabels=left,
                                  tickvals=[n - 0.5 - v for v in ticks], ticktext=labels,
                                  title=dict(text='y [μm]' if left else '', font=dict(size=text_px)))})

    rows = int(round(grid))
    phase = np.linspace(np.pi, -np.pi, rows)
    amplitude = np.linspace(0, 1, legend_w)
    legend = phase_amplitude_rgb(amplitude[None, :] * np.exp(1j * phase[:, None]))
    lx0 = ml + grid + legend_gap
    fig.add_trace(go.Image(source=png_source(legend), xaxis='x5', yaxis='y5'))
    fig.update_layout(
        xaxis5=dict(axis, domain=[lx0 / fig_w, (lx0 + legend_w) / fig_w], anchor='y5', range=[-0.5, legend_w - 0.5],
                    linecolor='black', linewidth=1, tickcolor='black', ticks='outside', ticklen=ticklen // 2,
                    tickvals=[0, legend_w - 1], ticktext=['0', '1'],
                    title=dict(text='Amp. [-]', font=dict(size=text_px))),
        yaxis5=dict(axis, domain=[mb / fig_h, (mb + grid) / fig_h], anchor='x5', side='right', range=[rows - 0.5, -0.5],
                    linecolor='black', linewidth=1, tickcolor='black', ticks='outside', ticklen=ticklen // 2,
                    tickvals=[(rows - 1) * f for f in (0, 0.25, 0.5, 0.75, 1)],
                    ticktext=['π', 'π/2', '0', '-π/2', '-π'],
                    title=dict(text='Phase [rad]', font=dict(size=text_px))))
    fig.update_layout(autosize=False, width=int(fig_w), height=int(fig_h), margin=dict(l=0, r=0, t=0, b=0),
                      paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)',
                      font=dict(family='Arial, sans-serif', size=text_px, color='black'))
    return fig


def vis_pattern(T_pred, T_ref, level=60.0, x_unit=0.004):
    """Printed pattern at the substrate: reference (gray, blue contour) and prediction (red contour)."""
    ref = np.flipud(to_numpy(T_ref))
    pred = np.flipud(to_numpy(T_pred))
    fig = plot_2d((ref > level).astype(float), cmap=[[0, 'white'], [1, '#C8C8C8']], use_colorbar=False,
                  colorbar_min=0, colorbar_max=1, x_unit=x_unit, y_unit=x_unit)
    for field, color in [(ref, 'rgba(0,0,255,0.7)'), (pred, 'rgba(255,0,0,0.7)')]:
        for c in measure.find_contours(field, level):
            fig.add_trace(go.Scatter(x=c[:, 1], y=c[:, 0], mode='lines', line=dict(color=color, width=1.5),
                                     showlegend=False, hoverinfo='skip', xaxis='x', yaxis='y'))
    return fig


def plot_tensor_slices(data, colorscale='jet', vmin=None, vmax=None, alpha_at_cmin=0.1, alpha_at_cmax=1,
                       colorbar_thickness=20, colorbar_title=None, colorbar_length=0.6,
                       colorbar_fontsize=7, colorbar_tick_fontsize=5, camera_distance=1.5,
                       fig_width_cm=6.0, fig_height_cm=4.0, dpi=300):
    """Semi-transparent xy slices of a 3-D field (Nx, Ny, Nz) plus the two far side faces."""
    data = to_numpy(data)
    N = data.shape[0]
    sf = 2 if N >= 513 else 1
    s, e = N // 2 - 128 * sf, N // 2 + 128 * sf
    data = data[s:e, s:e, :]
    fig_width_cm *= sf
    fig_height_cm *= sf
    camera_distance /= sf
    colorbar_thickness = int(colorbar_thickness * sf)

    Nx, Ny, Nz = data.shape
    vmin = float(np.nanmin(data)) if vmin is None else float(vmin)
    vmax = float(np.nanmax(data)) if vmax is None else float(vmax)
    x, y, z = np.arange(Nx), np.arange(Ny), np.arange(Nz)
    surf_kw = dict(colorscale=alpha_colorscale(colorscale, alpha_at_cmin, alpha_at_cmax), cmin=vmin, cmax=vmax,
                   lighting=dict(ambient=1.0), opacity=1.0, showscale=False)

    surfaces = []
    for k in range(0, Nz, 4):
        surfaces.append(go.Surface(x=np.tile(x[:, None], (1, Ny)), y=np.tile(y[None, :], (Nx, 1)),
                                   z=np.full((Nx, Ny), k), surfacecolor=data[:, :, k], name=f'XY @ z={k}', **surf_kw))
    surfaces.append(go.Surface(x=np.full((Ny, Nz), Nx - 1), y=np.tile(y[:, None], (1, Nz)),
                               z=np.tile(z[None, :], (Ny, 1)), surfacecolor=data[Nx - 1, :, :], name='YZ', **surf_kw))
    surfaces.append(go.Surface(x=np.tile(x[:, None], (1, Nz)), y=np.full((Nx, Nz), Ny - 1),
                               z=np.tile(z[None, :], (Nx, 1)), surfacecolor=data[:, Ny - 1, :], name='XZ', **surf_kw))
    fig = go.Figure(data=surfaces)

    colorbar = dict(lenmode='fraction', len=colorbar_length, thickness=colorbar_thickness, x=0.85, y=0.45,
                    tickfont=dict(family='Arial, sans-serif', size=pt2px(colorbar_tick_fontsize, dpi), color='black'),
                    tickwidth=1, tickcolor='black', outlinewidth=1, outlinecolor='black', nticks=5)
    if colorbar_title is not None:
        colorbar['title'] = dict(text=colorbar_title, side='right',
                                 font=dict(family='Arial, sans-serif', size=pt2px(colorbar_fontsize, dpi), color='black'))
    fig.add_trace(go.Scatter3d(x=[0.0, 0.0], y=[0.0, 0.0], z=[0.0, 0.0], mode='markers', showlegend=False,
                               hoverinfo='skip',
                               marker=dict(size=0.001, opacity=0.0, color=[vmin, vmax], cmin=vmin, cmax=vmax,
                                           colorscale=rgb_colorscale(colorscale), showscale=True, colorbar=colorbar)))

    bx = [0, Nx - 1, Nx - 1, 0, 0, None, 0, Nx - 1, Nx - 1, 0, 0, None, 0, 0, None, Nx - 1, Nx - 1, None, Nx - 1, Nx - 1, None, 0, 0]
    by = [0, 0, Ny - 1, Ny - 1, 0, None, 0, 0, Ny - 1, Ny - 1, 0, None, 0, 0, None, 0, 0, None, Ny - 1, Ny - 1, None, Ny - 1, Ny - 1]
    bz = [0, 0, 0, 0, 0, None, Nz - 1, Nz - 1, Nz - 1, Nz - 1, Nz - 1, None, 0, Nz - 1, None, 0, Nz - 1, None, 0, Nz - 1, None, 0, Nz - 1]
    fig.add_trace(go.Scatter3d(x=bx, y=by, z=bz, mode='lines', line=dict(color='black', width=1.5), showlegend=False))

    tick_px = int(2.5 / 72 * dpi)
    unit = 0.004
    sz = 1 if Nx < 257 else 2
    axis_style = dict(showbackground=False, mirror=True, linecolor='black', linewidth=0, tickwidth=0, tickcolor='black')
    title_font = dict(family='Arial, sans-serif', size=tick_px * 1.5, color='black')
    tick_font = dict(family='Arial, sans-serif', size=tick_px, color='black')
    centre = np.array([Nx / 2, Ny / 2, Nz / 2])
    diag_len = np.linalg.norm([Nx, Ny, Nz]) / 2
    eye_dir = np.array([1.0, 1.0, 1.7 * (2.5 if sf == 2 else 1.0)])
    eye = centre + camera_distance * diag_len * eye_dir / np.linalg.norm(eye_dir) / 1.1

    fig.update_layout(
        scene=dict(
            xaxis=dict(**axis_style, title=dict(text='x', font=title_font), tickfont=tick_font, tickmode='array',
                       tickvals=[0, Nx // 2, Nx - 1], ticktext=[f'{abs(sz - v * unit):.1f}' for v in [0, Nx // 2, Nx - 1]]),
            yaxis=dict(**axis_style, title=dict(text='y', font=title_font), tickfont=tick_font, tickmode='array',
                       tickvals=[0, Ny // 2, Ny - 1], ticktext=[f'{abs(sz - v * unit):.1f}' for v in [0, Ny // 2, Ny - 1]]),
            zaxis=dict(**axis_style, title=dict(text='z', font=title_font), tickfont=tick_font, tickmode='array',
                       tickvals=[Nz - 1], ticktext=[f'{Nz * unit:.2f}']),
            aspectmode='data',
            camera=dict(eye=dict(x=float(eye[0] * 0.01), y=float(eye[1] * 0.01), z=float(eye[2] * 0.01)))),
        width=cm2px(fig_width_cm, dpi), height=cm2px(fig_height_cm, dpi), paper_bgcolor='rgba(0,0,0,0)')
    return fig


def vis_field(data, cmap='jet', colorbar_title=None):
    """3-D resist field (Z, H, W) on the wafer grid (4 nm / px)."""
    data = to_numpy(data).transpose(2, 1, 0)[::-1, :, ::-1]
    return plot_tensor_slices(data, colorscale=cmap, colorbar_title=colorbar_title)


def ground_plane(xmin, xmax, ymin, ymax, z0=0.0, color='rgba(200,200,255,1)', grid_size=10):
    return go.Surface(x=[[xmin, xmax]] * 2, y=[[ymin, ymin], [ymax, ymax]], z=[[z0, z0]] * 2,
                      showscale=False, colorscale=[[0, color], [1, color]],
                      contours=dict(x=dict(show=True, color='black', start=xmin, end=xmax, size=(xmax - xmin) / grid_size, width=16),
                                    y=dict(show=True, color='black', start=ymin, end=ymax, size=(ymax - ymin) / grid_size, width=16),
                                    z=dict(show=False)))


def plot_mesh(vertices, faces, camera_distance=0.9, above_color='#86CDFF', width=800, height=600):
    """Triangle mesh of the developed resist on a ground plane; the bottom cap (z < 0.5 px) is hidden."""
    z_centroids = vertices[faces].mean(axis=1)[:, 2]
    face_colors = np.where(z_centroids < 0.5, 'rgba(0,0,0,0)', above_color)
    vertices = vertices / np.linalg.norm(np.ptp(vertices, axis=0))
    vmin, vmax = vertices.min(0), vertices.max(0)
    center, diag_vec = (vmin + vmax) / 2, vmax - vmin
    light = center + 2 * diag_vec
    mesh = go.Mesh3d(x=vertices[:, 0], y=vertices[:, 1], z=vertices[:, 2],
                     i=faces[:, 0], j=faces[:, 1], k=faces[:, 2], facecolor=face_colors, flatshading=False,
                     lighting=dict(ambient=0.20, diffuse=0.70, specular=0.45, roughness=0.35, fresnel=0.06),
                     lightposition=dict(x=light[0], y=light[1], z=light[2]), showscale=False, name='')
    p = 0.05 * vmax[0]
    eye = center + camera_distance * np.linalg.norm(diag_vec) * np.array([1.5, -2, 1.7]) / 4 * 5
    fig = go.Figure([mesh, ground_plane(p, vmax[0] - p, p, vmax[1] - p, z0=0.003)])
    fig.update_layout(width=width, height=height, margin=dict(l=0, r=0, t=0, b=0), paper_bgcolor='rgba(0,0,0,0)',
                      scene=dict(aspectmode='data', camera=dict(eye=dict(x=eye[0], y=eye[1], z=eye[2])),
                                 xaxis=dict(visible=False), yaxis=dict(visible=False), zaxis=dict(visible=False)))
    return fig


def vis_resist(T, level=60.0):
    """Developed resist {T > level} of a development-time field (Z, H, W) as a 3-D surface."""
    vol = to_numpy(T).transpose(1, 2, 0)[:, :, ::-1].copy()
    vol[:, :, 0] = np.maximum(vol[:, :, 0], level + 0.1)
    vertices, faces, _, _ = measure.marching_cubes(vol, level=level)
    return plot_mesh(vertices, faces)


def export_scatter_plotly(coords, intensity, scatter_width_cm=2.0, scatter_height_cm=2.0, dpi=300, scale=1.0,
                          marker_size=4.0, background_color='rgba(249, 240, 255, 1.0)', text_font_size=7,
                          ticklabel_font_size=5, ticks=(-1, 0, 1), boundary_linewidth=1, tick_width=1,
                          x_label='sx', y_label='sy', ticklen=16, outer_margin_cm=0.2):
    coords, intensity = to_numpy(coords), to_numpy(intensity)
    data_w = scatter_width_cm / 2.54 * dpi
    data_h = scatter_height_cm / 2.54 * dpi
    text_px = int(text_font_size / 72 * dpi * scale)
    tick_px = int(ticklabel_font_size / 72 * dpi * scale)
    pad = int(5 * scale)
    outer = outer_margin_cm / 2.54 * dpi
    ml = outer + boundary_linewidth + ticklen + tick_px + text_px + pad
    mr = outer + boundary_linewidth + pad
    mb = outer + boundary_linewidth + ticklen + tick_px + text_px * 3 + pad
    mt = outer + boundary_linewidth + pad
    fig_w = ml + mr + data_w
    fig_h = mt + mb + data_h

    def make_axis(label, domain, anchor):
        return dict(domain=domain, anchor=anchor, showline=True, linecolor='lightgray', linewidth=boundary_linewidth,
                    mirror=True, fixedrange=True, tickcolor='black', tickfont=dict(size=tick_px, color='black'),
                    tickwidth=tick_width, ticklen=ticklen, ticks='outside', range=[-1.1, 1.1],
                    title=dict(text=label, font=dict(size=text_px, color='black'), standoff=tick_px + ticklen),
                    tickmode='array', tickvals=list(ticks), ticktext=[f'{v:.1f}' for v in ticks])

    fig = go.Figure(go.Scatter(x=coords[:, 0], y=coords[:, 1], mode='markers',
                               marker=dict(size=marker_size, color='rgba(128,0,128,1.0)', opacity=intensity, line=dict(width=0))))
    fig.update_layout(autosize=False, width=int(fig_w), height=int(fig_h), margin=dict(l=0, r=0, t=0, b=0),
                      paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor=background_color,
                      font=dict(family='Arial, sans-serif', size=text_px, color='black'),
                      xaxis=make_axis(x_label, [ml / fig_w, (ml + data_w) / fig_w], 'y'),
                      yaxis=make_axis(y_label, [mb / fig_h, (mb + data_h) / fig_h], 'x'))
    return fig


def vis_source(points, weights):
    """Source points in pupil coordinates (sigma_x, sigma_y; unit circle = numerical aperture) with weights in [0, 1]."""
    return export_scatter_plotly(points, weights)


def color_gradient(start_hex, end_hex, n):
    def rgb(h):
        return tuple(int(h[i:i + 2], 16) for i in (1, 3, 5))
    s, e = rgb(start_hex), rgb(end_hex)
    if n <= 1:
        return [f'rgb{e}']
    return [f'rgb({int(s[0] + (e[0] - s[0]) * i / (n - 1))}, {int(s[1] + (e[1] - s[1]) * i / (n - 1))}, '
            f'{int(s[2] + (e[2] - s[2]) * i / (n - 1))})' for i in range(n)]


def plot_focus_exposure(data_list, dose_ary, cmap_idx=0, fig_width_cm=5, fig_height_cm=1.5, dpi=600,
                        text_font_size=1.5, ticklabel_font_size=2, x_label='Focus [nm]', y_label='CD [nm]',
                        showlegend=False):
    """CD versus focus per dose. data_list = [({dose: (focus_list, cd_list)}, panel title), ...]."""
    fig_w = fig_width_cm / 2.54 * dpi
    fig_h = fig_height_cm / 2.54 * dpi
    text_px = int(text_font_size / 72 * dpi)
    tick_px = int(ticklabel_font_size / 72 * dpi)
    n = len(data_list)
    fig = make_subplots(rows=1, cols=n, subplot_titles=[title for _, title in data_list])

    sorted_doses = sorted(dose_ary)
    colors = color_gradient('#D0D0D0', px.colors.qualitative.Plotly[cmap_idx], len(sorted_doses))
    dose_color = {dose: colors[i] for i, dose in enumerate(sorted_doses)}
    for col, (data, _) in enumerate(data_list, start=1):
        for dose in dose_ary:
            if dose not in data:
                continue
            focus, cd = data[dose]
            fig.add_trace(go.Scatter(x=focus, y=cd, mode='lines', name=f'{dose:g} mJ/cm²',
                                     line=dict(color=dose_color[dose], width=4),
                                     legendgroup=f'{dose}', showlegend=col == 1), row=1, col=col)

    axis = dict(showline=True, linecolor='black', mirror=True, linewidth=1, tickfont=dict(size=tick_px, color='black'), ticks='inside')
    for col in range(1, n + 1):
        s = '' if col == 1 else str(col)
        fig.update_layout(**{f'xaxis{s}': dict(**axis, title=dict(text=x_label), range=[-160, 160], nticks=5),
                             f'yaxis{s}': dict(**axis, title=dict(text=y_label if col == 1 else '', standoff=text_px * 0.8),
                                               range=[0, 310], showticklabels=col == 1)})
    fig.update_layout(autosize=False, width=int(fig_w), height=int(fig_h), paper_bgcolor='white', plot_bgcolor='white',
                      font=dict(family='Arial, sans-serif', size=text_px, color='black'), showlegend=showlegend)
    fig.update_annotations(font=dict(family='Arial, sans-serif', size=text_px, color='black'))
    return fig


def plot_profiles(bot, top, sem=None, dose_ary=(51, 39, 27), focus_ary=tuple(-100 + 20 * i for i in range(11)),
                  ny=50, nx=35, dpi=600, text_font_size=1.5, scale=1.5):
    """Resist profiles around the center line: bottom (red) and top (blue) contours, SEM image behind if given.
    bot / top / sem = {dose: {focus: (H, W)}}."""
    text_px = int(text_font_size / 72 * dpi)
    n_rows, n_cols = len(dose_ary), len(focus_ary)
    cell_h, cell_w = 2 * ny + 1, 2 * nx + 1
    margin_l, margin_t = text_px * 10, text_px * 4
    fig = make_subplots(rows=n_rows, cols=n_cols, horizontal_spacing=0.01, vertical_spacing=0.01,
                        subplot_titles=[f'{focus:g} nm' if r == 0 else '' for r in range(n_rows) for focus in focus_ary])

    def crop(table, dose, focus):
        N = to_numpy(table[dose][focus]).shape[0]
        c = N // 2 - 1
        return to_numpy(table[dose][focus])[c - ny:c + ny + 1, c - nx:c + nx + 1].astype(float)

    for r, dose in enumerate(dose_ary, start=1):
        for c, focus in enumerate(focus_ary, start=1):
            if sem is not None:
                fig.add_trace(go.Heatmap(z=crop(sem, dose, focus), colorscale=[[0, 'black'], [1, 'white']],
                                         zmin=0, zmax=255, showscale=False), row=r, col=c)
            else:
                fig.add_trace(go.Heatmap(z=crop(bot, dose, focus), colorscale=[[0, 'white'], [1, '#DDDDDD']],
                                         zmin=0, zmax=1, showscale=False), row=r, col=c)
            for table, color in [(bot, 'rgba(255,0,0,0.5)'), (top, 'rgba(0,0,255,0.5)')]:
                for contour in measure.find_contours(crop(table, dose, focus), 0.5):
                    fig.add_trace(go.Scatter(x=contour[:, 1], y=contour[:, 0], mode='lines',
                                             line=dict(color=color, width=4), showlegend=False), row=r, col=c)

    for i in range(1, n_rows * n_cols + 1):
        s = '' if i == 1 else str(i)
        fig.update_layout(**{f'xaxis{s}': dict(showline=False, showticklabels=False, ticks='', showgrid=False, zeroline=False, range=[-0.5, cell_w - 0.5]),
                             f'yaxis{s}': dict(showline=False, showticklabels=False, ticks='', showgrid=False, zeroline=False, range=[cell_h - 0.5, -0.5])})
    for r, dose in enumerate(dose_ary):
        fig.add_annotation(x=0, y=1 - (r + 0.5) / n_rows, xref='paper', yref='paper', xanchor='right', yanchor='middle',
                           xshift=-4, text=f'{dose:g} mJ/cm²', showarrow=False)
    background = ', Background: SEM' if sem is not None else ''
    fig.update_layout(width=int(n_cols * cell_w * scale + margin_l), height=int(n_rows * cell_h * scale + margin_t),
                      autosize=False, paper_bgcolor='white', plot_bgcolor='white',
                      font=dict(family='Arial, sans-serif', size=text_px, color='black'),
                      title_text=f'Resist profiles [Red: Bottom, Blue: Top{background}]', title_x=0.5, showlegend=False,
                      margin=dict(l=margin_l, t=margin_t, r=10, b=10))
    fig.update_annotations(font=dict(family='Arial, sans-serif', size=text_px, color='black'))
    return fig


def save_html(figures, filepath, title='Dashboard', layout=(), cols=2, subtitle=''):
    """Grid of figures in one standalone HTML page. layout = [{'row', 'col', 'title', 'colspan'}, ...]."""
    parts = [pio.to_html(fig, full_html=False, include_plotlyjs=(i == 0)) for i, fig in enumerate(figures)]
    items = ''
    for i, part in enumerate(parts):
        L = layout[i] if i < len(layout) else {}
        style = (f'grid-row: {L.get("row", "auto")} / span {L.get("rowspan", 1)}; '
                 f'grid-column: {L.get("col", "auto")} / span {L.get("colspan", 1)};')
        heading = f'<div class="fig-title">{L["title"]}</div>' if L.get('title') else ''
        items += f'<div class="fig-item" style="{style}">{heading}<div class="fig-inner">{part}</div></div>\n'
    html = f"""<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>{title}</title>
  <style>
    body {{ font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }}
    h1 {{ margin-bottom: 8px; }}
    p.subtitle {{ margin: 0 0 20px 0; color: #444; }}
    .grid-container {{ display: grid; grid-template-columns: repeat({cols}, 1fr); gap: 16px; }}
    .fig-item {{ background: white; border-radius: 8px; padding: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }}
    .fig-title {{ font-size: 1em; font-weight: bold; color: #333; margin-bottom: 8px; padding-bottom: 6px; border-bottom: 2px solid #e0e0e0; }}
    .fig-inner {{ width: 100%; overflow-x: auto; }}
  </style>
</head>
<body>
  <h1>{title}</h1>
  <p class="subtitle">{subtitle}</p>
  <div class="grid-container">{items}</div>
</body>
</html>"""
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(html)
    print('saved', filepath)