Show1D#
Interactive 1D traces for live reconstruction metrics, line profiles, and linked image snapshots. Use it for loss curves, optimizer diagnostics, joint-time ptychography comparisons, and image-derived profiles that need a visible 2D context.
Resizing a scientific curve#
Use plot_width_px=700, plot_height_px=300, and max_width=900 to set a
bounded initial size. Width values of zero keep the responsive layout. The
bottom-right corner handle resizes a standalone curve horizontally and
vertically. With a snapshot/stats side panel, horizontal dragging redistributes
the plot and side-panel space. Preview stays in the browser during dragging;
width and height are saved on release and retained in widget state and HTML
exports. The Reset toolbar action restores the initial plot dimensions.
Viewer UI#
Show1D supports the shared ui_mode, show_title, show_controls,
controls_collapsed, show_stats, show_review, show_legend, and
show_grid names. See Viewer UI controls. show_review is a
constructor parameter; the other toggles are synced traits and pass through
the constructor as keywords (Show1D(data, show_legend=False)).
Live monitors#
For a live notebook reconstruction, mutate one widget instead of recreating
cells. Use append(...) for one scalar sample per trace, extend(...) for a
block of samples, and snapshot(...) for grouped object/probe images:
widget = Show1D.live(["lambda 1", "lambda 10"], title="overnight loss")
widget.extend(
[0, 1, 2],
**{"lambda 1": [3.0, 2.0, 1.0], "lambda 10": [4.0, 3.0, 2.5]},
)
widget.snapshot(2, label="iter 2", object=obj, probe=probe)
Show1D.live ranks the traces as losses (review_mode="optimization"), so the
Review panel shows the best trial, loss alerts, and the ranking table. A plain
Show1D(data) keeps review_mode="trace" and only sorts trials by label.
For joint-time ptychography, add snapshots at checkpoint iterations with
multiple named images such as object_t0, object_t5, object_t11, and
probe. Each call to snapshot(...) is one grouped checkpoint for playback
and thumbnail inspection. goto_snapshot(index) selects a group from Python
and star_snapshot_group(...) marks it in the playback timeline.
File-backed monitors#
For long reconstructions that should survive notebook disconnects, write a JSONL monitor beside the run:
Show1D.append_monitor_event(
"run/show1d_monitor.jsonl",
{
"iteration": i,
"losses": {"lambda 1": loss1, "lambda 10": loss10},
"snapshots": {"lambda_1": "snapshots/lambda1_i040.npy"},
"warnings": ["loss spike on lambda 10"],
},
)
Each event may also carry metrics (per-trial values such as rmse or
flicker for the ranking table), starred, hidden, notes, and tags.
Reopen the file while the run is still writing:
widget = Show1D.watch_run("run/show1d_monitor.jsonl", refresh_s=5)
watch_run(...) tails the monitor file: each complete appended line is applied
to the existing widget state, while a partially written trailing line is
ignored until the writer finishes it. Call widget.stop_monitor() when the
notebook no longer needs to poll. After a disconnect,
Show1D.from_monitor_file(...) rebuilds the same losses, snapshots, warnings,
stars, hidden trials, notes, and tags from disk. A directory path resolves to
show1d_monitor.jsonl inside it.
Open the selected snapshot group in Show2D#
To inspect the images behind a selected loss point with the full 2D analysis
toolkit, convert a snapshot group to Show2D:
show1d.goto_snapshot(5)
show2d = show1d.to_show2d()
show2d
to_show2d(group=None, images=None, title=None) takes a group index or label
and group-local image indices or labels; hidden trials are left out by default.
The widget UI exposes the same path through View -> View selected as 2D,
which embeds the Show2D below the loss viewer. Image labels, colormap, scale
bar units, and stars carry over.
Snapshot panels use the same scale-bar convention as Show3D: pass
sampling=... and units=... for calibrated physical units, or omit them for
a pixel scale bar. Set show_scale_bar=False for a clean export.
Line profiles#
Show1D.from_image(image, line=((row0, col0), (row1, col1))) samples a profile
in (row, col) image coordinates and keeps the image beside the trace.
profile_width averages that many parallel lines; sampling and units
calibrate the distance axis. quantem.widget.show1d.sample_line_profile is the
sampling function on its own.
Built-in ducky example#
The Show1D tutorial reads reconstruction snapshots for the synthetic Ducky example from the public QuantEM data repository.
Ducky simulation tutorial: Georgios Varnavides, Trademark ducky dataset (October 23, 2025). The viewer files contain subsequent reconstruction results for the synthetic example.
from quantem.widget import Show1D
from quantem.widget.datasets import show1d_ducky
run = show1d_ducky()
widget = Show1D.from_monitor_file(
run / "show1d_monitor.jsonl",
title="Synthetic Ducky reconstructions (tutorial: Georgios Varnavides)",
x_label="frame",
y_label="final loss",
log_scale=False,
snapshot_columns=4,
show_snapshot_fft=True,
snapshot_contrast_preset="1-99",
)
widget
The default pins widget/ducky/ in bobleesj/quantem-data; all
monitor-relative snapshot paths stay intact. See Tutorial datasets
for the exact revision. This helper has one collection and no
size argument. Retain the visible source credit when exporting a notebook,
report or standalone widget. See Tutorial datasets for the
exact revisions and inputs.
HTML export#
Show1D writes one page with exact float32 traces; its only packing choice is the image image_bin:
path = widget.export_html("defocus-review.html", image_bin=4)
image_bin may be None, 1, 2, 4, or 8. It
preserves every 1D trace sample and x coordinate while applying a NaN-aware
area mean only to linked 2D snapshots and profile images. Calibrated pixel size,
snapshot view centers, and profile coordinates are rescaled with the image, so
the downsampled review remains physically calibrated.
A full export can be large when hundreds of full-resolution snapshots are
linked, so choose image_bin=2, 4, or 8 when one-file portability matters
more than preserving every image pixel.
The generated file is kernel-free and needs no network: RequireJS, AnyWidget and the Jupyter HTML manager travel inside the page (about 1.2 MB).
save_image("traces.png") writes a matplotlib figure of the traces (.pdf
also works); save("view.json") writes the display state that
Show1D(data, state="view.json") restores.
Reference#
- class quantem.widget.show1d.Show1D(*args: t.Any, **kwargs: t.Any)#
Bases:
Show1DState,Show1DExport,TrialReview,SavedStateMixin,HtmlExportMixin,StaticFallbackMixin,AnyWidgetInteractive 1D viewer for traces, line profiles, and live reconstruction.
- Parameters:
data (array_like, mapping, Dataset, or None) – A 1D array, a 2D
(n_traces, n_points)array, a list of 1D arrays, a mapping oflabel -> trace, orNonefor an empty live monitor.x (array_like, optional) – Shared x positions. Defaults to point indices; an empty monitor fills them as
append()is called.labels (list of str, optional) – Per-trace labels.
title (str, optional) – Plot text shown in the widget and exported figures.
x_label (str, optional) – Plot text shown in the widget and exported figures.
y_label (str, optional) – Plot text shown in the widget and exported figures.
x_integer (bool, default False) – Put x ticks on whole numbers only, for counted quantities such as epochs where a tick at 2.5 has no meaning.
log_scale (bool, default False) – Logarithmic y display; non-positive values are skipped in the plot.
ui_mode ({"interactive", "presentation", "report", "minimal"}, default "interactive") – Shared viewer UI preset. Explicit
show_*/controls_collapsedkeywords override the preset.show_review (bool, optional) – Start with the trial Review panel (ranking, alerts, notes, tags) open.
plot_height_px (int) – Initial plot height and snapshot side-panel width in pixels.
side_panel_width_px (int) – Initial plot height and snapshot side-panel width in pixels.
image_cmap (str, default "viridis") – Colormap for snapshot and profile images.
snapshot_columns (int, default 0) – Columns of the snapshot image grid; 0 picks an automatic overview.
snapshot_panel_width_px (int, default 0) – Snapshot tile width in pixels; 0 fits the available width.
snapshot_histogram_width (int, default 360, 52) – Size of the draggable snapshot contrast histogram in CSS pixels.
snapshot_histogram_height (int, default 360, 52) – Size of the draggable snapshot contrast histogram in CSS pixels.
profile_image – A 2D image shown beside the trace, with the
((row0, col0), (row1, col1))line that the trace was sampled along; seefrom_image().profile_line – A 2D image shown beside the trace, with the
((row0, col0), (row1, col1))line that the trace was sampled along; seefrom_image().profile_width – A 2D image shown beside the trace, with the
((row0, col0), (row1, col1))line that the trace was sampled along; seefrom_image().sampling – Pixel size and unit for the snapshot and profile scale bar. A sequence uses its last value, matching
Show2D/Show3D. Asamplinggiven withoutunitsis in angstrom.units – Pixel size and unit for the snapshot and profile scale bar. A sequence uses its last value, matching
Show2D/Show3D. Asamplinggiven withoutunitsis in angstrom.state (dict or path, optional) – Restore display state saved with
save().save_state (bool, default False) – Embed the snapshot and profile image buffers in the saved notebook.
**kwargs – Any synced trait, for example
show_snapshot_fft=Trueorsnapshot_contrast_preset="1-99".
Notes
Live use is split between high-rate scalars and lower-rate images: call
append()every iteration andsnapshot()everyNiterations so notebook comms stay responsive.- classmethod live(traces: Sequence[str] | None = None, *, title: str = 'Live Reconstruction', x_label: str = 'iteration', y_label: str = '', log_scale: bool = True, **kwargs) Self#
An empty loss-ranked monitor for repeated
append()calls.
- classmethod from_image(image, *, line: Sequence[Sequence[float]], profile_width: int = 1, sampling: float | None = None, units: str | None = None, **kwargs) Self#
A line-profile viewer: the trace sampled along
linewith the 2D image beside it.lineis((row0, col0), (row1, col1))in image pixels;samplingturns the pixel distance along the line intounits(angstrom whenunitsis omitted). Without asamplingthe distance is in pixels.
- classmethod from_monitor_file(path: str | Path, *, title: str = 'Overnight Reconstruction Monitor', x_label: str = 'iteration', y_label: str = 'loss', log_scale: bool = True, **kwargs) Self#
Rebuild a monitor from its JSONL file.
Each line is a JSON object with an
iterationnumber and any oflosses,snapshots,metrics,warnings,starred,hidden,notesortags. Snapshot values are paths to.npyor.npzarrays, resolved relative to the monitor file.
- classmethod watch_run(path: str | Path, *, refresh_s: float = 5.0, **kwargs) Self#
Open a monitor file and keep tailing it while the kernel is alive.
Every
refresh_sseconds the complete lines appended since the last read are applied; a half-written trailing line waits for the writer. Callstop_monitor()when the notebook no longer needs updates.
- static append_monitor_event(path: str | Path, event: Mapping) Path#
Append one JSON event line to a monitor file, creating the file on first use.
- append(x: float | None = None, **values) Self#
Append one sample to named traces; new names start a trace back-filled with NaN.
- extend(x: Sequence[float] | ndarray | None = None, **values) Self#
Append a block of samples to named traces in one widget update.
xdefaults to continuing from the last x value. New names start a trace back-filled with NaN; existing traces missing fromvaluesget NaN over the appended span.
- snapshot(iteration: float, *, label: str | None = None, **images) Self#
Attach named 2D images to an iteration as one snapshot group.
Images passed together (
object=..., probe=...) are one checkpoint: playback steps through groups and the plot marks the group’s x value.
- set_data(data, *, x=None, labels: Sequence[str] | None = None) Self#
Replace the traces while keeping every display setting.
- goto_snapshot(index: int) Self#
Select a snapshot group; its first image becomes the primary selected image.
- star_snapshot_group(group: int | str | None = None) Self#
Star a snapshot group (index, label, or the selected one) in the playback timeline.
- to_show2d(group: int | str | None = None, images: Sequence[int | str] | None = None, *, title: str | None = None)#
A
Show2Dgallery of one snapshot group for zoom, FFT, profile and export tools.groupis an index, a group label, orNonefor the selected group;imagespicks group-local indices or image labels, default every image that is not hidden. Colormap, scale bar and stars carry over.
- stop_monitor() Self#
Stop the
watch_run()polling thread.
- quantem.widget.show1d.sample_line_profile(image, line: Sequence[Sequence[float]], *, profile_width: int = 1) ndarray#
Values along
linein(row, col)image coordinates, one sample per pixel of length.profile_width> 1 averages that many parallel lines spaced one pixel apart across the line, which suppresses noise on a lattice fringe profile without smoothing along the profile direction.
Interactive controls#
Each control mutates the listed synced trait. A UI-test agent acts on the control, then asserts the trait changed and the canvas repainted (non-zero, no console error, no NaN frame).
Control |
Trait |
Expected effect |
|---|---|---|
Trace hover |
read-only canvas overlay, local snapshot preview |
Nearest trace point is highlighted and reported; when a snapshot group has the same x value, its images and group label preview in the side panel |
Trace or legend click |
|
A trace-point click pins its matching snapshot group and emphasizes the trace; a legend click only emphasizes the trace, and double-clicking the plot restores all traces |
Plot corner drag |
|
Bottom-right loss-plot handle resizes plot height and reallocates width between the loss plot and snapshot panel |
Reset view |
|
Plot returns to full data extent |
Grid toggle |
|
Grid lines show/hide |
Log toggle |
|
Positive y values render on a logarithmic axis |
Stats toggle |
|
Optional stats side table shows/hides; hidden by default |
Review toggle |
|
Optional ranking, notes, tags, and alerts UI shows/hides; hidden by default |
Legend toggle |
|
Trace legend shows/hides |
Snapshot panel visibility API |
|
Reconstruction snapshot panel is shown by default; set this from Python for plot-only summaries |
Plot thumbnail API |
|
Plot thumbnails are shown by default; set size from Python when a notebook needs denser or larger checkpoint previews |
Snapshot colormap menu |
|
Profile/snapshot images use the selected scientific colormap |
Snapshot contrast buttons |
|
Snapshot images use full, 0.5-99.5, 1-99, 2-98, or 5-95 percentile clipping; choosing a preset clears custom histogram clipping |
Snapshot histogram drag |
|
Drag either endpoint knot to adjust min/max; drag the middle span to move the contrast window |
Snapshot histogram visibility API |
|
Shows or hides the compact selected-snapshot histogram; it is shown by default |
Snapshot histogram size API |
|
Keeps the compact contrast histogram independent of the reconstruction grid size |
Snapshot profile toggle |
|
Draws a shared |
Snapshot columns menu |
|
Snapshot object/probe image grid uses automatic overview columns or a fixed 1-8 columns |
Snapshot FFT overlay position |
|
FFT inset overlays can sit in any corner; drag the inset to snap it to the nearest corner or set top-left, top-right, bottom-left, or bottom-right from Python |
Snapshot panel corner drag |
|
Every real snapshot tile has a Show2D-style corner grip; dragging any grip changes one shared tile size, keeps all panels equal, preserves the selected column count, and keeps controls aligned to the grid width |
Snapshot playback star |
|
Marks important reconstruction iterations in the playback timeline; starred positions render as gold timeline marks and persist in widget state/HTML export |
Snapshot star button |
|
In Review mode, marks candidate reconstructions to revisit while sweeping lambda or denoising settings |
Snapshot hide button |
|
In Review mode, hides bad trials from the snapshot grid, loss plot, legend, and stats |
Show all hidden trials |
|
In Review mode, restores hidden reconstruction trials |
Starred-only toggle |
|
In Review mode, shows only starred candidates, while keeping reference panels visible |
Ranking objective menu |
|
In Review mode, sorts review rows and snapshot panels by final loss, RMSE, flicker, lambda, object/probe quality, alerts, or label |
Ranking order toggle |
|
In Review mode, reverses candidate ranking order |
Top-K menu |
|
In Review mode, restricts visible trials to the top ranked candidates |
Trial filter field |
|
In Review mode, filters trials by label, note, or tag |
Trial notes editor toggle |
|
In Review mode, shows or hides the note/tag editor while preserving stored notes and tags |
Star best button |
|
In Review mode, stars the current best ranked visible trial |
Hide worst button |
|
In Review mode, hides the current worst ranked non-starred trial |
Trial note field |
|
In Review mode, stores per-trial review notes |
Trial tag buttons |
|
In Review mode, stores quick tags such as best, bad start, probe drift, and object issue |
Review table |
|
In Review mode, shows candidate ranking, alerts, and the best trial |
View -> View selected as 2D |
|
Builds an embedded Show2D gallery from the selected snapshot group for deeper image analysis |
Snapshot scale bar API |
|
Snapshot panels show a Show3D-style scale bar and zoom readout |
Snapshot real-space view API |
|
Starts or restores real-space snapshot panels at a given zoom and |
Snapshot FFT view API |
|
Starts or restores FFT panels at a given zoom and |
Snapshot histogram |
computed automatically |
Selected snapshot histogram stays visible with draggable contrast knots and a numeric range readout; histogram and snapshot FFT use WebGPU when the browser has it, with a CPU fallback |
Snapshot FFT toggle |
|
Log-magnitude FFTs show as compact inset overlays by default; set |
Snapshot FFT window toggle |
|
Applies a Hann window before snapshot FFT computation |
Snapshot FFT colormap menu |
|
FFT panels use the selected scientific colormap |
Snapshot play/pause |
|
Snapshot groups advance through reconstruction checkpoints |
Snapshot stop |
|
Playback stops and returns to the first snapshot group |
Snapshot playback endpoint mode |
|
Playback either wraps, stops, or reverses direction at the first and final snapshot groups |
Snapshot group slider |
|
Object/probe/multi-object image group changes; plot marker moves to that iteration |
Snapshot FPS slider |
|
Playback speed changes in whole frames per second |
Snapshot image wheel |
local image view |
Zooms snapshot/FFT panels under the cursor without scrolling the page |
Snapshot image drag |
local image view |
Pans the shared snapshot/FFT zoom view |
Zoom wheel |
|
X-axis zooms about the cursor |
Shift + zoom wheel |
|
Y-axis zooms about the cursor |
Double-click plot |
|
View resets |
Export -> HTML |
|
Writes a standalone interactive HTML viewer |
Export -> CSV |
browser download |
Downloads current trace arrays as CSV |
Export -> PNG |
browser download |
Downloads the current plot canvas |
plot_height_px and side_panel_width_px remain constructor/state parameters
for notebooks, reports, and saved views. They are intentionally not shown as
default toolbar sliders so overnight reconstruction review starts with fewer
visible controls.
See also
The shared HTML-export contract is documented in html-export.