-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathivplot_gallery.py
More file actions
489 lines (431 loc) · 13.6 KB
/
ivplot_gallery.py
File metadata and controls
489 lines (431 loc) · 13.6 KB
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
from pathlib import Path
import html
try:
# Package import
from .ivplot import ivplot
except ImportError:
# Fallback: standalone script
from ivplot import ivplot
# For optional thumbnails (static image export via Plotly + Kaleido)
try:
import plotly.graph_objects as go
_HAS_PLOTLY = True
except Exception:
_HAS_PLOTLY = False
def ivplot_gallery(
transistors,
output_dir,
auto_open=True,
use_thumbnails=True,
**ivplot_kwargs,
):
"""
For each transistor, call ivplot() to generate an individual HTML file,
then build a gallery HTML combining all plots into one scrollable page.
Any extra kwargs passed to ivplot_gallery(...) are forwarded to ivplot(),
except for the ones that must be overridden:
- html_path: per-transistor HTML filename
- name: transistor name
- auto_open: always False (only the gallery is auto-opened)
Parameters
----------
transistors : dict
Mapping transistor_name -> dict with at least key 'sweeps'.
Any other keys are treated as metadata and shown in the gallery.
output_dir : str or Path
Directory where individual plot HTML and the gallery index.html are saved.
auto_open : bool
If True, open the gallery HTML in the default browser.
use_thumbnails : bool
If True (default) generate and show 3D-log thumbnails.
If False, skip thumbnail generation and omit the thumbnail section.
**ivplot_kwargs :
Additional keyword arguments forwarded to ivplot().
"""
output_dir = Path(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
html_files = {}
meta_by_name = {}
thumb_files = {}
# ----------------------------------------------------------------------
# 1. Generate individual IV plot HTML files (and thumbnails if enabled)
# ----------------------------------------------------------------------
for name, transistor in transistors.items():
out_file = output_dir / f"{name}.html"
# Merge user kwargs with forced overrides
kwargs = dict(ivplot_kwargs)
kwargs.update({
"html_path": str(out_file),
"name": name,
"auto_open": False,
})
print(f"Generating IV plot for {name}")
fig = ivplot(transistor["sweeps"], **kwargs)
html_files[name] = out_file.name # relative filename
# Collect metadata (anything except 'sweeps')
meta_items = {k: v for k, v in transistor.items() if k != "sweeps"}
meta_by_name[name] = meta_items
# Optional thumbnail: only if user wants it, Plotly is available and we got a fig
if use_thumbnails and _HAS_PLOTLY and fig is not None:
try:
# ivplot may return fig or (fig, something)
fig_obj = fig[0] if isinstance(fig, tuple) else fig
# Select scatter3d traces in the LOG 3D scene.
# By convention, the log 3D panel is "scene", and the lin one is "scene2".
log3d_traces = [
tr for tr in getattr(fig_obj, "data", [])
if getattr(tr, "type", "").startswith("scatter3d")
and getattr(tr, "scene", "scene") == "scene"
]
if not log3d_traces:
# Nothing suitable; skip thumbnail for this transistor
continue
# Build a minimal single-scene figure just for the thumbnail
thumb_fig = go.Figure(data=log3d_traces)
# Try to reuse the camera from the original log 3D scene
camera = None
if hasattr(fig_obj.layout, "scene") and hasattr(fig_obj.layout.scene, "camera"):
camera = fig_obj.layout.scene.camera
thumb_layout_kwargs = dict(
showlegend=False,
margin=dict(l=0, r=0, t=0, b=0),
width=400,
height=300,
scene=dict(
xaxis_title="Vgs (V)",
yaxis_title="Vds (V)",
zaxis_title="Ids (A, log10)",
bgcolor="rgba(0,0,0,0)",
),
)
if camera is not None:
thumb_layout_kwargs["scene_camera"] = camera
thumb_fig.update_layout(**thumb_layout_kwargs)
# Export as PNG using Kaleido
thumb_path = output_dir / f"{name}_thumb.png"
thumb_fig.write_image(str(thumb_path))
thumb_files[name] = thumb_path.name
except Exception as e:
# Fail soft; gallery still works without thumbnail
print(f"Thumbnail generation failed for {name}: {e}")
# ----------------------------------------------------------------------
# 2. Build gallery HTML with lazy-loading iframes, optional thumbnails
# ----------------------------------------------------------------------
gallery_file = output_dir / "index.html"
lines = []
lines.append("<!DOCTYPE html>")
lines.append("<html>")
lines.append("<head>")
lines.append("<meta charset='UTF-8'>")
lines.append("<meta name='viewport' content='width=device-width, initial-scale=1.0'>")
lines.append("<title>Transistor IV Plot Gallery</title>")
lines.append(r"""
<style>
:root {
color-scheme: light dark;
}
body {
font-family: Arial, sans-serif;
margin: 20px;
background: #ffffff;
color: #111111;
}
body.dark {
background: #111111;
color: #eeeeee;
}
h1 {
text-align: center;
}
a {
color: #1a5fb4;
}
body.dark a {
color: #82aaff;
}
.plot-container {
margin-top: 60px;
border-top: 2px solid #aaa;
padding-top: 20px;
}
.back-to-top {
margin-top: 10px;
}
/* iframe (main plots) */
iframe.ivframe {
width: 100%;
height: 900px;
border: none;
}
/* nav list */
.nav-list {
line-height: 1.7;
}
/* status text */
.status {
font-size: 0.9em;
color: #555;
margin-bottom: 8px;
}
body.dark .status {
color: #ccc;
}
.status.loading::before {
content: "⏳ ";
}
.status.loaded {
color: #2b7a0b;
}
.status.loaded::before {
content: "✔ ";
}
.status.error {
color: #b00020;
}
.status.error::before {
content: "⚠ ";
}
/* metadata list */
.meta {
font-size: 0.9em;
margin-bottom: 8px;
}
.meta dt {
font-weight: bold;
}
.meta dd {
margin: 0 0 4px 0;
}
/* thumbnail grid */
.thumb-grid {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin: 10px 0 20px 0;
}
.thumb-item {
width: 220px;
text-align: center;
font-size: 0.85em;
}
.thumb-item img {
width: 100%;
height: auto;
border-radius: 4px;
border: 1px solid #aaa;
display: block;
}
body.dark .thumb-item img {
border-color: #555;
}
/* fullscreen mode */
.plot-container.fullscreen {
position: fixed;
inset: 0;
z-index: 9999;
background: #000000;
margin: 0;
padding: 10px;
border: none;
overflow: auto;
}
.plot-container.fullscreen h2,
.plot-container.fullscreen .meta,
.plot-container.fullscreen .back-to-top,
.plot-container.fullscreen .status {
color: #ffffff;
}
.plot-container.fullscreen iframe.ivframe {
height: calc(100vh - 80px);
}
/* buttons + toolbar */
.toolbar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
flex-wrap: wrap;
gap: 8px;
}
button {
cursor: pointer;
padding: 4px 10px;
font-size: 0.9em;
border-radius: 4px;
border: 1px solid #666;
background: #f0f0f0;
color: #111;
}
body.dark button {
background: #333;
color: #eee;
border-color: #888;
}
.fs-btn {
margin-bottom: 8px;
}
</style>
<script>
// Theme toggle + persist in localStorage
document.addEventListener('DOMContentLoaded', function() {
const body = document.body;
const storedTheme = localStorage.getItem('ivplot_theme');
if (storedTheme === 'dark') {
body.classList.add('dark');
}
const themeBtn = document.getElementById('themeToggle');
if (themeBtn) {
themeBtn.addEventListener('click', function() {
body.classList.toggle('dark');
localStorage.setItem(
'ivplot_theme',
body.classList.contains('dark') ? 'dark' : 'light'
);
});
}
});
// Fullscreen toggle
function toggleFullscreen(btn) {
const container = btn.closest('.plot-container');
if (!container) return;
if (!document.fullscreenElement) {
if (container.requestFullscreen) {
container.requestFullscreen();
}
container.classList.add('fullscreen');
btn.textContent = 'Exit fullscreen';
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
container.classList.remove('fullscreen');
btn.textContent = 'Fullscreen';
}
}
// Lazy-load and status handling for iframes
document.addEventListener('DOMContentLoaded', function() {
const frames = Array.from(document.querySelectorAll('iframe.ivframe'));
if (!('IntersectionObserver' in window)) {
frames.forEach(f => startLoad(f));
return;
}
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const iframe = entry.target;
if (!iframe.dataset.loaded) {
startLoad(iframe);
}
}
});
}, {
root: null,
rootMargin: '200px 0px',
threshold: 0.1
});
frames.forEach(f => observer.observe(f));
function startLoad(iframe) {
const src = iframe.dataset.src;
if (!src) return;
if (iframe.dataset.loading === '1') return;
iframe.dataset.loading = '1';
const status = iframe.parentElement.querySelector('.status');
if (status) {
status.textContent = 'Loading...';
status.className = 'status loading';
}
iframe.onerror = function() {
handleError(iframe);
};
iframe.onload = function() {
iframe.dataset.loaded = '1';
iframe.dataset.loading = '0';
const st = iframe.parentElement.querySelector('.status');
if (st) {
st.textContent = 'Loaded';
st.className = 'status loaded';
}
};
iframe.src = src;
}
function handleError(iframe) {
const tries = parseInt(iframe.dataset.tries || '0', 10);
const status = iframe.parentElement.querySelector('.status');
if (tries < 2) {
iframe.dataset.tries = String(tries + 1);
if (status) {
status.textContent = 'Error loading plot, retrying...';
status.className = 'status error';
}
setTimeout(() => {
iframe.removeAttribute('src');
iframe.dataset.loading = '0';
startLoad(iframe);
}, 1000);
} else {
if (status) {
status.textContent = 'Error loading plot (gave up).';
status.className = 'status error';
}
}
}
});
</script>
""")
lines.append("</head>")
lines.append("<body>")
# Toolbar: theme toggle
lines.append("<div class='toolbar'>")
lines.append("<h1>Transistor IV Plot Gallery</h1>")
lines.append("<button id='themeToggle'>Toggle dark / light theme</button>")
lines.append("</div>")
# Navigation + (optional) thumbnails
lines.append("<h2>Jump to transistor:</h2>")
lines.append("<ul class='nav-list'>")
for name in html_files:
safe = html.escape(name)
lines.append(f"<li><a href='#{safe}'>{safe}</a></li>")
lines.append("</ul>")
if use_thumbnails and thumb_files:
lines.append("<h3>Thumbnails (3D log view)</h3>")
lines.append("<div class='thumb-grid'>")
for name, thumb in thumb_files.items():
safe = html.escape(name)
thumb_esc = html.escape(thumb)
lines.append("<div class='thumb-item'>")
lines.append(
f"<a href='#{safe}'><img src='{thumb_esc}' alt='Thumbnail: {safe}'></a>"
)
lines.append(f"<div>{safe}</div>")
lines.append("</div>")
lines.append("</div>")
lines.append("<hr>")
# Embedded plots
for name, file in html_files.items():
safe = html.escape(name)
file_esc = html.escape(file)
meta = meta_by_name.get(name, {})
lines.append(f"<div class='plot-container' id='{safe}'>")
lines.append(f"<h2>{safe}</h2>")
# Metadata
if meta:
lines.append("<dl class='meta'>")
for k, v in meta.items():
key = html.escape(str(k))
val = html.escape(str(v))
lines.append(f"<dt>{key}</dt><dd>{val}</dd>")
lines.append("</dl>")
lines.append("<button class='fs-btn' onclick='toggleFullscreen(this)'>Fullscreen</button>")
lines.append("<div class='status loading'>Waiting to load…</div>")
lines.append(
f"<iframe class='ivframe' data-src='{file_esc}' loading='lazy'></iframe>"
)
lines.append("<div class='back-to-top'><a href='#'>Back to top</a></div>")
lines.append("</div>")
lines.append("</body></html>")
gallery_file.write_text("\n".join(lines), encoding="utf-8")
print(f"Gallery created: {gallery_file}")
if auto_open:
import webbrowser, os
webbrowser.open("file://" + os.path.abspath(gallery_file))
return gallery_file