Show1D#

Interactive 1D traces for live reconstruction metrics, line profiles, and linked image snapshots. Use it for loss curves, Adam/optimizer diagnostics, joint-time ptychography comparisons, and image-derived profiles that need a visible 2D context.

For a runnable notebook walkthrough, see the Show1D tutorial.

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.

Loss Comparisons#

Use Show1D.from_loss_runs when a notebook needs to compare several optimizer or reconstruction histories without hand-flattening labels:

from quantem.widget import Show1D

widget = Show1D.from_loss_runs(
    {
        "lambda 1": {
            "data": lambda1_data_loss,
            "temporal": lambda1_temporal_loss,
        },
        "lambda 10": {
            "data": lambda10_data_loss,
            "temporal": lambda10_temporal_loss,
        },
    },
    x=iterations,
    losses=["data", "temporal"],
    label_template="{run} / {loss}",
    title="Joint iterative ptychography loss comparison",
    x_label="iteration",
    y_label="loss",
    log_scale=True,
)

Automatic Jump Detection#

Use detect_jumps to mark abrupt increases or decreases while preserving every original sample:

events = widget.detect_jumps(
    threshold=8.0,
    min_abs_change=10.0,
    min_separation=1,
)

The detector scores consecutive-point slopes with a robust median/MAD baseline. It analyzes each contiguous finite trace segment independently, accounts for uneven x spacing, and suppresses weaker adjacent candidates. It does not bin, smooth, or modify the plotted values. Detected increases and decreases become colored plot markers and are recorded under report_metadata["detected_jumps"]. Manual markers are preserved; call clear_detected_jumps() to remove only the automatically generated markers.

For joint-time ptychography, add snapshots at checkpoint iterations with multiple named images such as object_t0, object_t5, object_t11, and probe. The frontend treats each call to snapshot(...) as one grouped checkpoint for playback and thumbnail inspection.

For saved joint-time reports, Show1D.from_joint_time_report(..., frame_by_frame=True) builds a frame-indexed loss view and groups the matching reconstructions.npz images by frame:

widget = Show1D.from_joint_time_report(
    "summary.json",
    frame_by_frame=True,
    snapshot_downsample=4,
    snapshot_columns=3,
    trial_sort_key="final_loss",
)

The review state is synced and exportable. Use star_best_trial(), hide_worst_trials(), set_trial_note(...), tag_trial(...), and export_run_summary(...) to preserve the morning review of an overnight sweep.

To inspect the reconstruction images behind a selected loss point with the full 2D analysis toolkit, convert the current snapshot group to Show2D:

show1d = Show1D.from_joint_time_report("summary.json", frame_by_frame=True)
show1d.goto_snapshot(5)

show2d = show1d.to_show2d()
show2d

The widget UI exposes the same path through View -> View selected as 2D. The embedded Show2D appears below the loss viewer and preserves image labels, colormap, scale bar units, stars, hidden trials, and the active visible comparison set. This is useful for opening the best/lambda-filtered reconstructions directly into Show2D zoom, pan, histogram, FFT, profile, and export tools without rebuilding arrays by hand.

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. Use show_scale_bar=False for a clean export without scale or zoom overlays.

Built-In Ducky Example#

For tutorials and quick regression checks, use the real ducky joint-time ptychography sweep hosted in the public QuantEM data repository:

from quantem.widget import Show1D

widget = Show1D.from_example("ducky", size="small")
widget

This is equivalent to downloading the monitor run and opening it directly:

from quantem.widget import Show1D
from quantem.widget.datasets import show1d_ducky

run = show1d_ducky(size="small")
widget = Show1D.from_monitor_file(
    run / "show1d_monitor.jsonl",
    title="Real ducky joint iterative ptychography",
    x_label="frame",
    y_label="final loss",
    log_scale=False,
    snapshot_columns=4,
    show_snapshot_fft=True,
    snapshot_contrast_preset="1-99",
)
widget

The dataset files live under widget-tutorials/show1d/ducky/small/... in bobleesj/quantem-data, so tutorial payloads stay grouped by widget instead of spreading across the dataset root. See Tutorial Datasets for the shared small, medium, large, and full size convention.

Overnight Monitors#

For live notebook reconstruction, mutate one widget instead of recreating cells. Use append(...) for one scalar sample, extend(...) / append_many(...) 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)

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"],
    },
)

Reopen it later with:

widget = Show1D.watch_run("run/show1d_monitor.jsonl", refresh_s=5)

watch_run(...) tails the monitor file incrementally: each complete appended JSONL line is applied to the existing widget state, while a partially written trailing line is ignored until the writer finishes it. Use widget.refresh_monitor(incremental=False) only when the run directory was rewritten and a full reload is needed.

If the kernel disconnects overnight, Show1D.from_monitor_file(...) rebuilds the same losses, snapshots, warnings, stars, hidden trials, notes, and tags from disk.

For UI and workflow checks, the repository includes a deterministic ptychography-style monitor simulator:

PYTHONPATH=src python scripts/show1d_live_monitor_sim.py \
  --run-dir /tmp/quantem-show1d-live-monitor \
  --export-html /tmp/quantem-show1d-live-monitor/show1d_live_monitor.html \
  --export-summary /tmp/quantem-show1d-live-monitor/run_summary.json

The simulated monitor writes multi-lambda losses, object/probe snapshots, warnings, notes/tags, hidden trials, and a starred candidate so the overnight review UI can be tested without waiting for a real reconstruction.

HTML export#

Show1D follows the package export signature, with a deliberately narrower set of supported values:

path = widget.export_html(
    "defocus-review.html",
    mode="single",
    encoding="full",
    downsample=4,
)

mode="single" and encoding="full" are the only supported packaging and encoding choices. downsample 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.

Show1D does not yet provide mode="folder" or encoding="uint8". Those values raise NotImplementedError with guidance to use a full single export and an image downsample factor. A full export can be large when hundreds of full-resolution snapshots are linked, so choose downsample=2, 4, or 8 when one-file portability matters more than preserving every image pixel.

The generated file is kernel-free, but the current embed loads RequireJS, AnyWidget, and the Jupyter HTML manager from public CDNs. Treat it as a standalone review file with a network dependency, not as proof of network- offline operation.

Reference#

class quantem.widget.show1d.Show1D(*args: Any, **kwargs: Any)#

Bases: StaticFallbackMixin, AnyWidget

Interactive 1D viewer for traces, line profiles, and live reconstruction.

Parameters:
  • data (array_like, mapping, or None) – A 1D array, a 2D (n_traces, n_points) array, a list of 1D arrays, a mapping of label -> trace, or None for a live empty monitor.

  • x (array_like, optional) – Shared x positions. Defaults to point indices. Empty monitors start without x values and fill them as append is called.

  • labels (list of str, optional) – Per-trace labels.

  • colors (list of str, optional) – Per-trace CSS colors.

  • title (str, optional) – Plot metadata shown in the widget and exported figures.

  • x_label (str, optional) – Plot metadata shown in the widget and exported figures.

  • y_label (str, optional) – Plot metadata shown in the widget and exported figures.

  • x_unit (str, optional) – Plot metadata shown in the widget and exported figures.

  • y_unit (str, optional) – Plot metadata shown in the widget and exported figures.

  • log_scale (bool, default False) – Use 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_* keyword arguments override preset values.

  • show_title (bool) – Toggle compact plot UI elements.

  • show_stats (bool) – Toggle compact plot UI elements.

  • show_review (bool) – Toggle compact plot UI elements.

  • show_legend (bool) – Toggle compact plot UI elements.

  • show_grid (bool) – Toggle compact plot UI elements.

  • show_controls (bool) – Toggle compact plot UI elements.

  • controls_collapsed (bool, default False) – Start with controls hidden while keeping a recoverable Controls button in the frontend.

  • plot_height_px (int, optional) – Initial plot height and snapshot/stats side-panel width in pixels.

  • side_panel_width_px (int, optional) – Initial plot height and snapshot/stats side-panel width in pixels.

  • image_cmap (str, default "viridis") – Colormap used for profile and snapshot images.

  • review_mode ({"trace", "optimization"}, optional) – Scientific traces default to "trace", which preserves review annotations without treating the final numeric value as a loss score. Optimization factories select "optimization" so trial ranking and loss-specific alerts remain available for reconstruction sweeps.

  • snapshot_contrast_preset ({"full", "0.5-99.5", "1-99", "2-98", "5-95"}, default "full") – Percentile contrast preset used for snapshot images and plot thumbnails.

  • snapshot_contrast_range (sequence of 2 floats, optional) – Explicit snapshot display range. Empty uses snapshot_contrast_preset; a two-value (min, max) range enables the draggable histogram clip.

  • show_snapshot_profile (bool, default False) – Show an interactive line-profile overlay on snapshot reconstruction panels and a compact profile comparison below the snapshot grid.

  • show_trial_notes (bool, default False) – Show the per-trial note/tag editor in the review panel. Notes and tags are preserved regardless of whether the editor is currently visible.

  • snapshot_profile_line (sequence, optional) – Initial profile endpoints as ((row0, col0), (row1, col1)) in snapshot image coordinates.

  • snapshot_histogram_width (int, default 360, 52) – Display size, in CSS pixels, for the draggable snapshot contrast histogram. The histogram is independent of the reconstruction grid width so overnight dashboards can stay compact.

  • snapshot_histogram_height (int, default 360, 52) – Display size, in CSS pixels, for the draggable snapshot contrast histogram. The histogram is independent of the reconstruction grid width so overnight dashboards can stay compact.

  • snapshot_loop (bool, default True) – Continue playback after reaching a snapshot endpoint. When disabled, playback stops at the final endpoint.

  • snapshot_bounce (bool, default False) – Reverse direction at snapshot endpoints instead of wrapping from the final group back to the first.

  • bookmarked_snapshot_groups (sequence of int, optional) – Zero-based snapshot-group indices starred in the playback timeline. Use star_snapshot_group() and related methods to update them after construction.

  • snapshot_thumbnail_size (int, default 48) – Size of plot-embedded snapshot thumbnails in pixels.

  • snapshot_panel_width_px (int, default 0) – Initial snapshot reconstruction panel width in pixels. Use 0 for automatic fit-to-view sizing; dragging the snapshot grid corner updates this value in the live widget. Values are clamped to the available frontend width, up to 4096 pixels.

  • snapshot_columns (int, default 0) – Number of columns used for the side-panel snapshot image grid. Use 0 for automatic overview columns, or 1 through 8 for a fixed count.

  • snapshot_overlay_position ({"top-left", "top-right", "bottom-left",) – “bottom-right”}, default “top-right” Corner used for the snapshot FFT inset when snapshot_fft_layout="overlay".

  • snapshot_fft_layout ({"overlay", "below"}, default "overlay") – How to display snapshot FFTs. "overlay" follows the compact Show3D-style inset; "below" stacks the FFT under each snapshot.

  • snapshot_real_space_zoom (float, default 1.0) – Initial zoom for real-space snapshot image panels.

  • snapshot_real_space_center (sequence of 2 floats, optional) – Initial real-space snapshot center as (row, col) in image pixels.

  • snapshot_fft_zoom (float, default 1.0) – Initial zoom for snapshot FFT panels.

  • snapshot_fft_center (sequence of 2 floats, optional) – Initial FFT snapshot center as (row, col) in FFT pixel coordinates.

  • sampling (float or sequence of float, optional) – Snapshot/profile image sampling used for the scale bar. Scalar values apply to both image axes; sequences use the last value as the displayed column-axis pixel size, matching Show2D/Show3D.

  • units (str or sequence of str, optional) – Physical unit for sampling. Sequences use the last unit. When no sampling is provided the frontend falls back to a pixel scale bar.

  • show_scale_bar (bool, default True) – Draw the Show3D-style scale bar and zoom readout on snapshot panels.

  • scale_bar_visible (bool, default True) – Draw the Show3D-style scale bar and zoom readout on snapshot panels.

  • show_snapshot_histogram (bool, default True) – Show the selected snapshot histogram and prefer WebGPU for snapshot histogram/FFT computation when the browser supports it.

  • prefer_webgpu (bool, default True) – Show the selected snapshot histogram and prefer WebGPU for snapshot histogram/FFT computation when the browser supports it.

  • show_snapshot_fft (bool, default False) – Show log-magnitude FFTs for snapshot images. The default layout is a compact inset overlay; set snapshot_fft_layout="below" for stacked panels.

  • snapshot_fft_window (bool, default True) – Apply a Hann window before snapshot FFT computation.

  • snapshot_fft_cmap (str, default "magma") – Colormap used for snapshot FFT panels.

  • state (dict or path, optional) – Restore display state saved with save().

Notes

Live use is intentionally split between high-rate scalars and lower-rate images: call append() every iteration and snapshot() every N iterations so notebook comms stay responsive.

get_state(key=None, drop_defaults=False)#

Trait state for comm sync and notebook embedding.

ipywidgets calls this with key=None to snapshot the FULL state that gets written into the saved notebook’s metadata.widgets. When save_state is False we drop the heavy buffers from that snapshot so a plain Show1D does not bake a monitor run’s snapshot stack into the .ipynb. Targeted syncs (key is a name or set, used by hold_sync / send_state during live rendering) are untouched, so the frontend still receives every buffer normally. save_state=True embeds everything so a reopened notebook restores the interactive widget without a kernel.

classmethod live(traces: Sequence[str] | None = None, *, title: str = 'Live Reconstruction', x_label: str = 'iteration', y_label: str = '', log_scale: bool = True, **kwargs: Any) Self#

Create an empty monitor intended for repeated append() calls.

classmethod from_loss_runs(runs: Mapping[str, Any], *, x: Any = None, losses: Sequence[str] | None = None, label_template: str = '{run} · {loss}', title: str = 'Loss Comparison', x_label: str = 'iteration', y_label: str = 'loss', **kwargs: Any) Self#

Create a multi-trace viewer from run/loss mappings.

runs may be either run_label -> loss_values or run_label -> {loss_name: loss_values}. The nested form is useful for comparing Adam/data/regularizer histories across ptychography lambda sweeps while keeping stable trace labels.

classmethod from_image(image: Any, *, line: Sequence[Sequence[float]], profile_width: int = 1, sampling: float = 1.0, x_unit: str = 'pixels', title: str = 'Line Profile', y_label: str = 'value', **kwargs: Any) Self#

Build a line-profile viewer from a 2D image and a (row, col) line.

classmethod from_joint_time_report(summary_path: str | Path, *, arrays_path: str | Path | None = None, metric_keys: Sequence[str] | None = None, frame_by_frame: bool = False, loss_key: str = 'final_losses', include_reference: bool = True, snapshot_downsample: int = 1, max_snapshot_frames: int | None = None, title: str = 'Joint-Time Ptychography Metrics', **kwargs: Any) Self#

Create a metric/snapshot viewer from a ducky joint-time report.

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: Any) Self#

Create a viewer from a file-backed JSONL reconstruction monitor.

Each line should be a JSON object with an iteration number and any of losses, snapshots, metrics, warnings, starred, hidden, notes, or tags. Snapshot values are paths to .npy or .npz arrays, resolved relative to the monitor file.

classmethod from_example(name: str = 'ducky', *, size: str = 'small', cache_dir: str | Path | None = None, revision: str | None = None, force_download: bool = False, title: str | None = None, x_label: str | None = None, y_label: str | None = None, log_scale: bool | None = None, **kwargs: Any) Self#

Create a Show1D viewer from a packaged tutorial example.

Parameters:
  • name – Example name. "ducky" loads the real joint-time ptychography lambda sweep used in the Show1D tutorial.

  • size – Tutorial payload size: "small", "medium", "large", or "full".

  • cache_dir – Forwarded to the Hugging Face tutorial-data loader.

  • revision – Forwarded to the Hugging Face tutorial-data loader.

  • force_download – Forwarded to the Hugging Face tutorial-data loader.

  • title – Optional overrides for the default example presentation.

  • x_label – Optional overrides for the default example presentation.

  • y_label – Optional overrides for the default example presentation.

  • log_scale – Optional overrides for the default example presentation.

  • **kwargs – Additional Show1D constructor options, such as snapshot_columns, show_snapshot_fft, and snapshot_real_space_zoom.

classmethod watch_run(path: str | Path, *, refresh_s: float = 5.0, start: bool = True, **kwargs: Any) Self#

Load a monitor file and optionally poll it while the kernel is alive.

static append_monitor_event(path: str | Path, event: Mapping[str, Any]) Path#

Append one JSON event to a monitor JSONL file.

append(x: float | None = None, **values: Any) Self#

Append one live sample to named traces.

New trace names are added automatically and back-filled with NaN for earlier samples. Missing existing traces receive NaN at this x value.

append_scalar(iteration: float | None = None, **values: Any) Self#

Alias for append() with reconstruction-friendly naming.

extend(x: Sequence[float] | ndarray | None = None, **values: Any) Self#

Append a batch of live scalar samples in one widget update.

Parameters:
  • x (sequence of float, optional) – Iteration or frame coordinates for the appended samples. If omitted, coordinates continue from the current final x value.

  • **values (array_like) – Mapping of trace name to a 1D sequence of values. New trace names are added automatically and existing traces omitted from values are back-filled with NaN for the appended span.

Returns:

The mutated widget, ready for the frontend to redraw via trait sync.

Return type:

Show1D

append_many(x: Sequence[float] | ndarray | None = None, **values: Any) Self#

Append a batch of live scalar samples in one widget update.

Parameters:
  • x (sequence of float, optional) – Iteration or frame coordinates for the appended samples. If omitted, coordinates continue from the current final x value.

  • **values (array_like) – Mapping of trace name to a 1D sequence of values. New trace names are added automatically and existing traces omitted from values are back-filled with NaN for the appended span.

Returns:

The mutated widget, ready for the frontend to redraw via trait sync.

Return type:

Show1D

apply_monitor_events(events: Sequence[Mapping[str, Any]], *, base_path: str | Path | None = None) Self#

Apply monitor JSONL events to this live widget incrementally.

This is the programmatic counterpart to refresh_monitor(): callers can feed parsed events directly, while watch_run tails newly written JSONL lines and calls the same method. Existing traces, snapshots, review state, notes, and tags remain in place.

snapshot(iteration: float, image: Any | None = None, *, label: str | None = None, **images: Any) Self#

Attach one or more 2D image snapshots to an iteration/x value.

Multiple images passed in one call are one logical snapshot group. This lets live ptychography monitors show related panels such as object and probe at the same optimizer iteration.

set_profile_image(image: Any, *, line: Sequence[Sequence[float]] | None = None, profile_width: int | None = None) Self#

Attach a 2D image context and optionally resample the displayed trace.

set_data(data: Any, *, x: Any = None, labels: Sequence[str] | None = None) Self#

Replace the trace data while preserving display settings.

add_marker(x: float, *, label: str = '', kind: str = 'checkpoint') Self#

Add a vertical marker at x, useful for checkpoints or events.

clear_markers() Self#

Remove all event markers.

detect_jumps(*, threshold: float = 8.0, min_abs_change: float = 0.0, min_separation: int = 1, replace: bool = True) list[dict[str, Any]]#

Detect abrupt increases and decreases without smoothing the traces.

Consecutive finite points are converted to slopes using their actual x spacing. Each contiguous finite segment is scored independently with a robust median and median absolute deviation (MAD). Nearby candidates are reduced to the strongest event so a one-point spike is not reported as two separate jumps.

Parameters:
  • threshold (float, default 8.0) – Minimum absolute robust z-score for a reported jump.

  • min_abs_change (float, default 0.0) – Minimum absolute raw y change between consecutive points.

  • min_separation (int, default 1) – Suppress weaker candidates within this many point indices of a stronger event in the same trace.

  • replace (bool, default True) – Replace markers created by an earlier detect_jumps call while preserving manually added markers.

Returns:

Detected events in trace/point order. Each event contains its trace, point index, x/y values, raw delta, slope, robust score, and increase/decrease direction.

Return type:

list of dict

Notes

The detector uses every original point. It does not bin, smooth, or modify the displayed data. NaNs split traces into independent segments, so folder or acquisition boundaries do not create synthetic jumps.

clear_detected_jumps() Self#

Remove auto-detected jump markers while preserving manual markers.

play(*, loop: bool | None = None, bounce: bool | None = None) Self#

Start cycling through snapshot groups in the frontend.

pause() Self#

Pause snapshot group playback.

stop() Self#

Stop playback and return to the first snapshot group.

goto_snapshot(index: int) Self#

Select a snapshot group by index.

The name intentionally follows the old single-image snapshot API. When a group contains multiple images, the first image in that group becomes the primary selected image while the frontend shows all group members.

to_show2d(group: int | str | None = None, images: Sequence[int | str] | int | str | None = None, *, title: str | None = None, copy: bool = True, include_hidden: bool = False, respect_review_filters: bool = True)#

Create a Show2D gallery from a snapshot group.

The default converts the currently selected snapshot group and applies the same hidden/starred/top/filter review state used by the frontend. Pass images=... to choose group-local image indices or labels.

star_trial(label: str) Self#

Mark a reconstruction/snapshot label as a candidate to revisit.

unstar_trial(label: str) Self#

Remove a reconstruction/snapshot label from the candidate list.

clear_starred_trials() Self#

Remove all starred reconstruction candidates.

star_snapshot_group(group: int | str | None = None) Self#

Star a snapshot group/iteration in the playback timeline.

unstar_snapshot_group(group: int | str | None = None) Self#

Remove a snapshot group/iteration star from the playback timeline.

toggle_snapshot_group_star(group: int | str | None = None) Self#

Toggle the playback-timeline star for a snapshot group/iteration.

clear_snapshot_group_stars() Self#

Remove every snapshot-group star from the playback timeline.

hide_trial(label: str) Self#

Hide a reconstruction/snapshot label from plots, stats, and panels.

show_trial(label: str) Self#

Show a reconstruction/snapshot label that was previously hidden.

show_all_trials() Self#

Restore all hidden reconstruction/snapshot labels.

set_trial_note(label: str, note: str) Self#

Attach a short note to a reconstruction/snapshot label.

clear_trial_note(label: str) Self#

Remove a note from a reconstruction/snapshot label.

tag_trial(label: str, tag: str) Self#

Add a tag such as best lambda or probe drift to a trial.

untag_trial(label: str, tag: str) Self#

Remove a tag from a trial.

clear_trial_tags(label: str) Self#

Remove all tags from a trial.

set_starred_only(value: bool = True) Self#

Show only starred reconstruction candidates in the frontend.

set_trial_sort(key: str | None = None, *, descending: bool | None = None, top: int | None = None, filter_text: str | None = None) Self#

Set ranking/sorting controls used by the frontend review panel.

rank_trials(key: str | None = None) list[dict[str, Any]]#

Recompute and return reconstruction ranking rows.

star_best_trial() Self#

Star the current best ranked non-hidden trial.

hide_worst_trials(count: int = 1) Self#

Hide the worst ranked non-starred trials.

export_run_summary(path: str | Path) Path#

Write a JSON summary of ranking, stars, hidden trials, tags, and alerts.

refresh_monitor(*, incremental: bool = True) Self#

Refresh the current monitor file while preserving review choices.

By default only newly appended JSONL lines are read and applied. Pass incremental=False to rebuild from the full monitor file, which is useful after a run directory is replaced or edited by hand.

start_monitor() Self#

Start a lightweight polling thread for monitor_path.

stop_monitor() Self#

Stop the monitor polling thread if one is running.

export_csv(path: str | Path, *, visible_range_only: bool = False) Path#

Write trace values to CSV.

save_image(path: str | Path, *, format: str | None = None, dpi: int = 150) Path#

Save a publication-style PNG or PDF line figure via matplotlib.

collapse_controls() Self#

Collapse controls behind the frontend Controls button.

expand_controls() Self#

Expand frontend controls when show_controls is enabled.

toggle_controls() Self#

Toggle whether frontend controls start collapsed.

export_html(path: str | Path | None = None, *, title: str | None = None, mode: str = 'single', encoding: str = 'full', downsample: int | None = None, **_: Any) Path#

Write a kernel-free interactive HTML viewer.

mode="single" with encoding="full" preserves float32 values. downsample=2, 4, or 8 reduces only linked 2D profile and snapshot panels; scientific line coordinates and trace samples remain exact. Folder storage and uint8 encoding require a frontend data-loader contract and are rejected with corrective guidance.

quantem.widget.show1d.sample_line_profile(image: ndarray, line: Sequence[Sequence[float]], *, profile_width: int = 1) ndarray#

Return values sampled along line in (row, col) image coordinates.

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

focused_trace, selected_snapshot_group_idx

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

plot_height_px, side_panel_width_px

Bottom-right loss-plot handle resizes plot height and reallocates width between the loss plot and snapshot panel

Reset view

x_range, y_range, focused_trace

Plot returns to full data extent

Grid toggle

show_grid

Grid lines show/hide

Log toggle

log_scale

Positive y values render on a logarithmic axis

Stats toggle

show_stats

Optional stats side table shows/hides; hidden by default

Review toggle

show_review

Optional ranking, notes, tags, and alerts UI shows/hides; hidden by default

Legend toggle

show_legend

Trace legend shows/hides

Snapshot panel visibility API

show_snapshots

Reconstruction snapshot panel is shown by default; set this from Python for plot-only summaries

Plot thumbnail API

show_snapshot_thumbnails, snapshot_thumbnail_size

Plot thumbnails are shown by default; set size from Python when a notebook needs denser or larger checkpoint previews

Snapshot colormap menu

image_cmap

Profile/snapshot images use the selected scientific colormap

Snapshot contrast buttons

snapshot_contrast_preset, snapshot_contrast_range

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

snapshot_contrast_range

Drag either endpoint knot to adjust min/max; drag the middle span to move the contrast window

Snapshot histogram visibility API

show_snapshot_histogram

Shows or hides the compact selected-snapshot histogram; it is shown by default

Snapshot histogram size API

snapshot_histogram_width, snapshot_histogram_height

Keeps the compact contrast histogram independent of the reconstruction grid size

Snapshot profile toggle

show_snapshot_profile, snapshot_profile_line, snapshot_profile_height

Draws a shared (row, col) line profile on reconstruction panels and compares visible panel intensities below the image grid

Snapshot columns menu

snapshot_columns

Snapshot object/probe image grid uses automatic overview columns or a fixed 1-8 columns

Snapshot FFT overlay position

snapshot_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

snapshot_panel_width_px

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

bookmarked_snapshot_groups; star_snapshot_group(), unstar_snapshot_group(), toggle_snapshot_group_star(), clear_snapshot_group_stars()

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

starred_snapshot_image_labels

In Review mode, marks candidate reconstructions to revisit while sweeping lambda or denoising settings

Snapshot hide button

hidden_snapshot_image_labels

In Review mode, hides bad trials from the snapshot grid, loss plot, legend, and stats

Show all hidden trials

hidden_snapshot_image_labels

In Review mode, restores hidden reconstruction trials

Starred-only toggle

show_starred_only

In Review mode, shows only starred candidates, while keeping reference panels visible

Ranking objective menu

trial_sort_key

In Review mode, sorts review rows and snapshot panels by final loss, RMSE, flicker, lambda, object/probe quality, alerts, or label

Ranking order toggle

trial_sort_descending

In Review mode, reverses candidate ranking order

Top-K menu

top_trial_count

In Review mode, restricts visible trials to the top ranked candidates

Trial filter field

trial_filter_text

In Review mode, filters trials by label, note, or tag

Trial notes editor toggle

show_trial_notes

In Review mode, shows or hides the note/tag editor while preserving stored notes and tags

Star best button

starred_snapshot_image_labels, trial_rankings

In Review mode, stars the current best ranked visible trial

Hide worst button

hidden_snapshot_image_labels, trial_rankings

In Review mode, hides the current worst ranked non-starred trial

Trial note field

trial_notes

In Review mode, stores per-trial review notes

Trial tag buttons

trial_tags

In Review mode, stores quick tags such as best, bad start, probe drift, and object issue

Review table

trial_rankings, trial_alerts, best_trial_label, run_summary

In Review mode, shows candidate ranking, alerts, and best-trial summary

View -> View selected as 2D

handoff_request, prepared_view_widget, handoff_status

Builds an embedded Show2D gallery from the selected snapshot group for deeper image analysis

Snapshot scale bar API

pixel_size, pixel_unit, scale_bar_visible

Snapshot panels show a Show3D-style scale bar and zoom readout

Snapshot real-space view API

snapshot_real_space_zoom, snapshot_real_space_center

Starts or restores real-space snapshot panels at a given zoom and (row, col) center

Snapshot FFT view API

snapshot_fft_zoom, snapshot_fft_center

Starts or restores FFT panels at a given zoom and (row, col) FFT center

Snapshot histogram

computed automatically

Selected snapshot histogram stays visible with draggable contrast knots and a numeric range readout

WebGPU preference API

prefer_webgpu

Hidden UI preference; histogram and snapshot FFT use WebGPU when available, with CPU fallback

Snapshot FFT toggle

show_snapshot_fft, snapshot_fft_layout

Log-magnitude FFTs show as compact inset overlays by default; set snapshot_fft_layout="below" for stacked panels

Snapshot FFT window toggle

snapshot_fft_window

Applies a Hann window before snapshot FFT computation

Snapshot FFT colormap menu

snapshot_fft_cmap

FFT panels use the selected scientific colormap

Snapshot play/pause

snapshot_playing

Snapshot groups advance through reconstruction checkpoints

Snapshot stop

snapshot_playing, selected_snapshot_group_idx

Playback stops and returns to the first snapshot group

Snapshot playback endpoint mode

snapshot_loop, snapshot_bounce

Playback either wraps, stops, or reverses direction at the first and final snapshot groups

Snapshot group slider

selected_snapshot_group_idx, selected_snapshot_idx

Object/probe/multi-object image group changes; plot marker moves to that iteration

Snapshot FPS slider

snapshot_fps

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_range

X-axis zooms about the cursor

Shift + zoom wheel

y_range

Y-axis zooms about the cursor

Double-click plot

x_range, y_range, focused_trace

View resets

Export -> HTML

export_request, export_payload

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.