Datasets:
File size: 18,646 Bytes
645beaf | 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 | import torch
import numpy as np
import plotly.graph_objects as go
from stl import mesh as stl_mesh
from matplotlib import cm
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 = cm.get_cmap(cmap_name) if isinstance(cmap_name, str) else 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 = cm.get_cmap(cmap_name) if isinstance(cmap_name, str) else 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,
):
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)
def cm2px(v): return v / 2.54 * dpi
N = panels[0, 0].shape[0]
if N > 1000:
x_ticks = [0, 500, 1000]; y_ticks = [0, 500, 1000]
heatmap_width_cm *= 2; heatmap_height_cm *= 2
colorbar_thickness *= 2
data_w = cm2px(heatmap_width_cm)
data_h = cm2px(heatmap_height_cm)
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 = cm2px(outer_margin_cm)
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 min(panels[r, c].min() for r in range(rows) for c in range(cols)))
vmax = float(colorbar_max if colorbar_max is not None else max(panels[r, c].max() for r in range(rows) for c in range(cols)))
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=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=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], anchor=yname(idx), is_bottom=(r == rows - 1)),
f'yaxis{"" if idx == 0 else idx+1}': make_yaxis([y0, y1], anchor=xname(idx), is_left=(c == 0)),
})
if use_colorbar:
n_cb = 256
cb_idx = rows * cols
cb_data = np.linspace(vmin, vmax, n_cb).reshape(n_cb, 1)
cb_x0 = (ml + cols * data_w + (cols - 1) * gap + cb_gap) / fig_w
cb_x1 = cb_x0 + colorbar_thickness / fig_w
cb_tickvals = np.linspace(0, n_cb - 1, 5)
cb_ticktext = [f"{v:.2f}" for v in np.linspace(vmin, vmax, 5)]
fig.add_trace(go.Heatmap(
z=cb_data, colorscale=cmap, showscale=False,
zmin=vmin, zmax=vmax, xaxis=xname(cb_idx), yaxis=yname(cb_idx),
))
fig.update_layout(**{
f'xaxis{"" if cb_idx == 0 else 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{"" if cb_idx == 0 else cb_idx+1}': dict(
domain=[grid_y0, grid_y1], anchor=xname(cb_idx), side='right', fixedrange=True,
tickmode='array', tickvals=cb_tickvals, ticktext=cb_ticktext,
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'):
return plot_2d(torch.flip(data, dims=(0,)), cmap=cmap, use_colorbar=False)
def vis_sc(data, cmap='jet'):
return plot_2d(torch.flip(data, dims=(2,)), cmap=cmap, use_colorbar=True, colorbar_title='Amplitude [-]')
def plot_tensor_slices(
data, slice_indices=None, opacity=None, colorscale="jet",
vmin=None, vmax=None, alpha_at_cmin=0.1, alpha_at_cmax=1,
use_colorbar=True, colorbar_thickness=20, colorbar_title=None,
colorbar_title_side="right", use_dummy_colorbar=True, colorbar_length=0.6,
colorbar_font="Arial, sans-serif", colorbar_fontsize=7, colorbar_tick_fontsize=5,
colorbar_nticks=None, show_axes=True, isotropic_view=True,
camera_distance=1.5, fig_width_cm=6.0, fig_height_cm=4.0, dpi=300, png_path=None,
):
if data.ndim != 3:
raise ValueError("`data` must be a 3-D array (Nx, Ny, Nz).")
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
ix, iy, iz = map(int, slice_indices) if slice_indices else (Nx // 2, Ny // 2, Nz // 2)
vmin = float(np.nanmin(data)) if vmin is None else float(vmin)
vmax = float(np.nanmax(data)) if vmax is None else float(vmax)
custom_scale = _alpha_colorscale(colorscale, alpha_at_cmin, alpha_at_cmax)
dummy_scale = _rgb_colorscale(colorscale)
x, y, z = np.arange(Nx), np.arange(Ny), np.arange(Nz)
def cb_cfg():
cb = dict(
lenmode="fraction", len=colorbar_length, thickness=colorbar_thickness,
x=0.85, y=0.45,
tickfont=dict(family=colorbar_font, size=_pt2px(colorbar_tick_fontsize, dpi), color="black"),
tickwidth=1, tickcolor="black", outlinewidth=1, outlinecolor="black",
nticks=colorbar_nticks or 5,
)
if colorbar_title is not None:
cb["title"] = dict(
text=colorbar_title, side=colorbar_title_side,
font=dict(family=colorbar_font, size=_pt2px(colorbar_fontsize, dpi), color="black"),
)
return cb
surf_kw = dict(
colorscale=custom_scale, cmin=vmin, cmax=vmax,
lighting=dict(ambient=1.0), opacity=1.0 if opacity is None else opacity,
)
surfaces = []
for k_z in range(0, Nz, 4):
show_scale = use_colorbar and not use_dummy_colorbar and len(surfaces) == 0
surfaces.append(go.Surface(
x=np.tile(x[:, None], (1, Ny)), y=np.tile(y[None, :], (Nx, 1)),
z=np.full((Nx, Ny), k_z), surfacecolor=data[:, :, k_z],
showscale=show_scale, colorbar=cb_cfg() if show_scale else None,
name=f"XY @ z={k_z}", **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, :, :],
showscale=False, name=f"YZ @ x={Nx-1}", **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, :],
showscale=False, name=f"XZ @ y={Ny-1}", **surf_kw,
))
fig = go.Figure(data=surfaces)
if use_colorbar and use_dummy_colorbar:
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=dummy_scale,
showscale=True, colorbar=cb_cfg(),
),
))
bbox_x = [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]
bbox_y = [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]
bbox_z = [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=bbox_x, y=bbox_y, z=bbox_z, 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(visible=show_axes, 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
if isotropic_view:
eye_dir = np.array([1.0, 1.0, 1.7 * (2.5 if sf == 2 else 1.0)])
eye_pos = centre + camera_distance * diag_len * eye_dir / np.linalg.norm(eye_dir) / 1.1
else:
eye_pos = centre + camera_distance * np.array([0.0, 0.0, diag_len])
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"{abs(Nz * unit):.2f}"]),
aspectmode="data",
camera=dict(eye=dict(x=float(eye_pos[0]*0.01), y=float(eye_pos[1]*0.01), z=float(eye_pos[2]*0.01))),
),
width=_cm2px(fig_width_cm, dpi), height=_cm2px(fig_height_cm, dpi),
paper_bgcolor="rgba(0,0,0,0)",
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
)
if png_path is not None:
fig.write_image(png_path, width=_cm2px(fig_width_cm, dpi), height=_cm2px(fig_height_cm, dpi), scale=1.0)
return fig
def vis_field(data, cmap="jet", colorbar_title=None):
data = data.permute(2, 1, 0).flip(dims=(0, 2))
return plot_tensor_slices(data, colorscale=cmap, colorbar_title=colorbar_title)
def _make_ground_plane(xmin, xmax, ymin, ymax, z0=0.0, color="#1653D0", grid_color="black", 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=grid_color, start=xmin, end=xmax, size=(xmax - xmin) / grid_size, width=16),
y=dict(show=True, color=grid_color, start=ymin, end=ymax, size=(ymax - ymin) / grid_size, width=16),
z=dict(show=False),
),
)
def plot_stl(
stl_path, z_th=0.5, scale_mode="auto", isotropic_view=True,
camera_distance=0.9, below_color="rgba(0,0,0,0)", above_color="#86CDFF",
flat_shading=False, ambient=0.20, diffuse=0.70, specular=0.45,
roughness=0.35, fresnel=0.06, light_xyz=None, width=800, height=600, margin=0,
):
tri = stl_mesh.Mesh.from_file(str(stl_path)).vectors
vertices, reindex = np.unique(tri.reshape(-1, 3), axis=0, return_inverse=True)
i, j, k = reindex.reshape(-1, 3).T
if scale_mode == "auto":
diag_len = np.linalg.norm(np.ptp(vertices, axis=0))
vertices = vertices / diag_len
elif isinstance(scale_mode, (int, float)):
vertices = vertices * float(scale_mode)
vmin, vmax = vertices.min(0), vertices.max(0)
center, diag_vec = (vmin + vmax) / 2, vmax - vmin
diag_len = np.linalg.norm(diag_vec)
z_centroids = tri.mean(axis=1)[:, 2]
if scale_mode == "auto":
z_centroids = z_centroids / diag_len
face_colors = np.where(z_centroids < z_th, below_color, above_color)
light_pos = light_xyz or (center + 2 * diag_vec)
mesh3d = go.Mesh3d(
x=vertices[:, 0], y=vertices[:, 1], z=vertices[:, 2],
i=i, j=j, k=k, facecolor=face_colors, flatshading=flat_shading,
lighting=dict(ambient=ambient, diffuse=diffuse, specular=specular, roughness=roughness, fresnel=fresnel),
lightposition=dict(x=light_pos[0], y=light_pos[1], z=light_pos[2]),
showscale=False, name="",
)
p = 0.05 * vmax[0]
ground = _make_ground_plane(p, vmax[0] - p, p, vmax[1] - p, z0=0.003, color="rgba(200,200,255,1)", grid_color="black")
eye_pos = center + camera_distance * diag_len * (
np.array([1.5, -2, 1.7]) / 4 * 5 if isotropic_view else np.array([0, 0, 1])
)
fig = go.Figure(mesh3d)
fig.add_trace(ground)
fig.update_layout(
width=width, height=height,
margin=dict(l=margin, r=margin, t=margin, b=margin),
paper_bgcolor="rgba(0,0,0,0)",
scene=dict(
aspectmode="data",
camera=dict(eye=dict(x=eye_pos[0], y=eye_pos[1], z=eye_pos[2])),
xaxis=dict(visible=False), yaxis=dict(visible=False), zaxis=dict(visible=False),
),
)
return fig
_default_layout = [
{'row': 1, 'col': 1, 'title': 'Photomask (M)'},
{'row': 1, 'col': 2, 'title': 'Diffracted near field (E)'},
{'row': 2, 'col': 1, 'title': 'Photoacid (h)'},
{'row': 2, 'col': 2, 'title': 'Deprotection image (m)'},
{'row': 3, 'col': 1, 'title': 'Development rate (R)'},
{'row': 3, 'col': 2, 'title': 'Development time (T)'},
]
def save_html(figures, filepath, title="Dashboard", layout=_default_layout, cols=2):
import plotly.io as pio
html_parts = [pio.to_html(fig, full_html=False, include_plotlyjs=(i == 0)) for i, fig in enumerate(figures)]
items_html = ""
for i, part in enumerate(html_parts):
L = layout[i] if layout and i < len(layout) else {}
row, col = L.get("row", "auto"), L.get("col", "auto")
rowspan, colspan = L.get("rowspan", 1), L.get("colspan", 1)
fig_title = L.get("title", "")
style = f"grid-row: {row} / span {rowspan}; grid-column: {col} / span {colspan};"
title_html = f'<div class="fig-title">{fig_title}</div>' if fig_title else ""
items_html += f'<div class="fig-item" style="{style}">{title_html}<div class="fig-inner">{part}</div></div>\n'
full_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: 20px; }}
.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%; }}
</style>
</head>
<body>
<h1>{title}</h1>
<div class="grid-container">{items_html}</div>
</body>
</html>"""
with open(filepath, "w", encoding="utf-8") as f:
f.write(full_html)
print(f"Saved → {filepath}") |