Skip to content

Workspace: Spectra

The Spectra workspace is the core analytical environment for individual spectrum management. It handles loading, preprocessing, peak modeling, fitting, and exporting spectral data. It also serves as the base class that the Maps workspace extends via inheritance.

[!NOTE] This page covers the Spectra-specific View and ViewModel layers. For the shared data model (SpectraStore, MapData, MapInfo, proxies), see the dedicated Data Architecture: SpectraStore page.


Architecture Overview

The workspace follows a strict MVVM (Model-View-ViewModel) separation. No layer may cross its boundary in the wrong direction.

graph LR
    subgraph View ["View Layer (v_*)"]
        VWS["VWorkspaceSpectra<br/>(QWidget)"]
        SV["VSpectraViewer<br/>(Matplotlib canvas)"]
        SLE["SpectraLegendEditorDialog<br/>(batch legend editor)"]
        FMB["VFitModelBuilder<br/>(controls panel)"]
        PT["VPeakTable<br/>(parameter table)"]
        SL["VSpectraList<br/>(QListView)"]
        FR["VFitResults<br/>(results table)"]
        MVA["VMVA<br/>(PCA/NMF panel)"]
    end

    subgraph VM ["ViewModel Layer (vm_*)"]
        VMWS["VMWorkspaceSpectra<br/>(QObject)"]
        VMFMB["VMFitModelBuilder"]
        VMMVA["VMMVA"]
    end

    subgraph Model ["Model Layer"]
        SS["SpectraStore"]
        IO["m_io<br/>(file loaders)"]
        VBF["VBFthread<br/>(fit engine)"]
        WIO["WorkspaceIO<br/>(serialization)"]
    end

    VWS --> SV & FMB & SL & FR & MVA
    SV --> SLE
    VWS -->|"method calls"| VMWS
    VMWS -->|"Qt signals"| VWS
    VMWS --> SS & IO & VBF & WIO
    VMWS --> VMFMB & VMMVA

Component Responsibilities

Layer Class Responsibility
View VWorkspaceSpectra Assembles UI widgets, connects signals/slots, delegates all logic to ViewModel
View VSpectraViewer Matplotlib canvas — renders 1D spectra, baselines, peaks, best-fit, residuals, 2D heatmaps, interactive 3D views, and range selectors
View VRangeSelectorPanel Vertical right-side panel with red, blue, and green toggle buttons for spectral intervals
View RangeSelectorManager Canvas overlay managing draggable bracket markers and shaded spans for active selectors
View VLiveMaps Live Maps tab hosting three synchronized 2D heatmap subpanels (Red, Blue, Green)
View SpectraLegendEditorDialog Transactional palette, legend-limit, label, and color editor for selected spectra
View VFitModelBuilder X-correction, range, baseline and fit controls panel
View VPeakTable Editable table of peak parameters with per-row model selectors
View VSpectraList Checkbox list with coloring rules, drag-to-reorder, multi-select
ViewModel VMWorkspaceSpectra Business logic: orchestrates loading, preprocessing, fitting, persistence
ViewModel VMLiveMaps Computes 2D spatial parameter arrays from MapData on selector interval/parameter updates
Model spectral_parameters Vectorized calculations for integrated/mean/max intensity, peak position, height, and area
Model SpectraStore Tensor-centric in-memory store — see spectra_store.md
Model VBFthread QThread that runs the vectorized batch fitting engine off the main thread

How Spectra Uses MapData

In the Spectra workspace, each loaded spectrum is stored as an independent MapData block with N=1 (one row). Each block has its own x-axis, allowing spectra with different wavenumber ranges to coexist. See Data Hierarchy for the full tensor layout.


Workspace Components

VWorkspaceSpectra — The View Coordinator

File: v_workspace_spectra.py

VWorkspaceSpectra is a pure UI assembly class. It:

  1. Instantiates all child widgets and the ViewModel in __init__.
  2. Wires every signal/slot connection in setup_connections().
  3. Delegates every user action to the ViewModel (never manipulates data directly).
  4. Updates UI in response to ViewModel signals.

The layout is a horizontal splitter: left (SpectraViewer on top, tabbed controls below) and right (spectra list sidebar).

Key pattern — Ctrl-modified actions:

def _apply_with_ctrl(self, fn):
    apply_all = bool(QApplication.keyboardModifiers() & Qt.ControlModifier)
    fn(apply_all)

# Usage:
self.btn_reinit.clicked.connect(lambda: self._apply_with_ctrl(vm.reinit_spectra))

All bulk actions (baseline subtract, peak paste, reinit, fit) follow this pattern. A normal click applies to selected spectra; Ctrl+click applies to all spectra in the store.

VSpectraViewer — 2D Heatmap Mode

Package: spectra_viewer/ (v_plot_heatmap.py)

VSpectraViewer is the core spectral canvas widget. In addition to multi-line 1D spectrum visualization, it provides a native 2D Heatmap Mode (btn_heatmap, located alongside btn_3d on the right side of the toolbar directly to the left of btn_options / btn_copy) for visualizing series data (e.g., temperature variations, kinetics, line scans):

  • Data Alignment & Ragged Matrix Interpolation: When selected spectra possess differing or ragged wavenumber grids, _plot_heatmap() aligns all rows onto a common spectral range via scipy.interpolate.interp1d.
  • Y-Axis Token Extraction: Automatically parses numeric parameters embedded in filenames (e.g. _100C_, _250K_) using regex tokenization, or defaults to index-based ordering (0..N-1).
  • Smooth Vertical Interpolation: Supports 1D cubic/linear interpolation along the vertical axis when spin_heatmap_interp > 0 (default 300 points).
  • Dynamic Toolbar Adaptation: Activating heatmap mode toggles toolbar state: standard 1D tools (btn_peak, btn_baseline, btn_eraser, btn_norm, btn_bestfit, and shift_panel) are hidden via setVisible(False), while heatmap-specific controls (cbb_heatmap_yaxis, le_heatmap_ylabel, spin_heatmap_interp) become visible. Unchecking the mode restores the 1D tools immediately.

VSpectraViewer — Interactive 3D View Mode

VSpectraViewer provides an interactive 3D View (btn_3d, _3d_mode) built directly on Matplotlib's mpl_toolkits.mplot3d.Axes3D (_plot_3d()), keeping zero external dependencies and sharing PLOT_POLICY_LIGHT/PLOT_POLICY_DARK styling, clipboard figure export, and workspace option synchronization (view_3d in get_options_state()/set_options_state()):

  • Projection Switching & Callback Cleanup (_ensure_axes_projection): Switches self.ax between 2D rectilinear axes and Axes3D only when changing into or out of 3D mode, disconnecting Axes3D canvas callbacks and disabling 3D mouse bindings before figure.delaxes() to prevent callback accumulation across mode switches.
  • Vectorized 3D Rendering (FastLine3DCollection): Subclasses Line3DCollection to project all 3D points across uniform (N, M, 3) tensors or ragged tensor_list selections in a single vectorized proj3d._proj_trans_points() pass and updates Path._vertices in place during interactive camera rotation, supporting "line" and "dot" plot styles, normalization, raw overlays, best-fit curves, Z-log scaling, and legend/colorbar modes.
  • Mouse Rotation & Mode Exclusivity (_sync_mode_toolbar_state): btn_3d and btn_heatmap are mutually exclusive. Activating 3D mode automatically turns off NoDoubleClickZoomToolbar 2D zoom (_set_zoom_tool_active(False)), hides incompatible 1D tools (btn_zoom, btn_peak, btn_baseline, btn_eraser, shift_panel), and shares cbb_heatmap_yaxis / le_heatmap_ylabel for filename-token Y-axis positioning so left-drag rotates (elev, azim), middle-drag pans, right-drag or scroll scales Z, and Rescale (Ctrl+R) resets camera angles (25°, -60°) and data bounds.

Interactive Spectral Mapping & Live Maps

The interactive spectral mapping subsystem allows users to select up to three independent spectral ranges on the 1D spectrum viewer and see live-updating parameter visualizations in real time:

  • Spectra Workspace (mode="spectra"): Renders up to three color-coded (Red, Blue, Green) 1D trend curves (Spectrum # vs. parameter value) across the currently selected spectra in VSpectraList.
  • Maps Workspace (mode="map"): Automatically adapts to the dimensionality of the selected map: renders 2D spatial parameter heatmaps for 2D maps, or 1D line plots along the spatial coordinate (X (mm), Y (mm), or Distance (mm)) for 1D profile maps (line scans).
  • Red/Blue Ratio (R/B ratio): Available in the Green channel subpanel across both workspaces; computes the element-wise integrated intensity ratio \(I_{\mathrm{Red}} / I_{\mathrm{Blue}}\) with NaN masking for zero/near-zero Blue intensities and updates automatically when Red or Blue brackets move. While R/B ratio is selected, the Green bracket is hidden on VSpectraViewer so only the Red and Blue brackets driving the ratio remain visible.
graph TD
    subgraph Spectra Viewer
        RP["VRangeSelectorPanel<br/>(Red, Blue, Green toggle buttons)"]
        RSM["RangeSelectorManager<br/>(Interactive brackets & shaded spans)"]
    end

    subgraph ViewModel
        VMLM["VMLiveMaps<br/>(60 ms debounce timer, mode='spectra' | 'map')"]
    end

    subgraph Model
        SP["spectral_parameters.py<br/>(Vectorized numpy parameter calculation)"]
    end

    subgraph Live Maps Tab
        VLM["VLiveMaps<br/>(Tab placed immediately before More)"]
        Sub["LiveMapSubpanel x 3<br/>(1D Series Curve in Spectra / 2D Heatmap in Maps)"]
    end

    RP -->|"range_toggled(key, active)"| RSM & VMLM
    RSM -->|"range_changed(key, xmin, xmax)"| VMLM
    VMLM -->|"compute_spectral_parameter() /<br/>compute_series_spectral_parameter()"| SP
    VMLM -->|"series_data_ready / map_data_ready"| VLM
    VLM --> Sub
  • VRangeSelectorPanel & SpectraRangeBracketMixin (rgb_live_maps/v_range_selector.py, v_range_bracket_mixin.py): VRangeSelectorPanel is positioned as a dedicated vertical panel on the right side of VSpectraViewer with Red (#e74c3c), Blue (#3498db), and Green (#2ecc71) toggle buttons. SpectraRangeBracketMixin wires the panel, range initialization/clamping, hover cursor feedback, and Agg background blitting directly into VSpectraViewer.
  • RangeSelectorManager: Manages interactive vertical boundary lines, inward bracket annotations, and transparent spans for each selector, reusing existing artists in-place across drags and supporting set_animated(True) / active_artists(). Tracks per-channel parameter selection via set_parameter() / is_bracket_visible(), hiding and disabling hit-testing for the Green bracket whenever its Live Maps panel displays R/B ratio (restoring it immediately when another spectral parameter is selected). Dragging either line or the center span translates or resizes the interval via Agg background blitting (temporary layout_engine suspension, hover-peak bypass while dragging, and X-clamping outside vertical axes bounds), while emitting range_drag_finished on mouse release. Hit testing uses pixel tolerance with coordinate translation from Matplotlib transforms.
  • VMLiveMaps: Owns selector intervals, parameter selections, colormap choices, and mode ("spectra" or "map"). Uses an adaptive debounce timer (baseline 60 ms, scaling up to 250 ms on very large maps) during continuous dragging, flushes queued ranges immediately on release via flush_pending(), and automatically offloads map batches with >= 25,000 spectra (ASYNC_SPECTRUM_THRESHOLD) to a QThreadPool QRunnable (_LiveMapWorker) guarded by monotonic _generation_id stale cancellation and clean shutdown(). In "spectra" mode, set_series_data(mds) preserves user-adjusted bracket positions across spectrum selection changes when within axis bounds, emits spatial_sites_changed(None), and emits series_data_ready. In "map" mode, set_map_datas(mds, primary_name) enforces signature deduplication and MapData.data_version LRU result caching, excludes inactive (~is_active) spectra, caches regular/Delaunay MapGridder geometry, emits spatial_sites_changed with ordered active coordinates/profile positions for interactive selection, and emits map_data_ready, profile_data_ready, multi_profile_data_ready, map_2d_candidates_changed, or live_maps_cleared. Both workspaces skip Live Maps computation while the Live Maps tab is hidden (_live_maps_dirty), flushing once when the user opens the tab.
  • spectral_parameters.py: Model-level vectorized evaluation over slice-before-cast MapData.y_matrix[:, mask] views via compute_spectral_parameter() (with optional active_mask), across discrete selected spectra (list[MapData]) via compute_series_spectral_parameter(), map dimensionality detection via analyze_map_geometry(), reusable regular/Delaunay barycentric gridding via build_map_gridder() + compute_map_grid(), and safe element-wise ratio computation with relative epsilon NaN masking via compute_intensity_ratio(). Calculates:
  • Direct: Integrated intensity, Mean intensity, Maximum intensity, Peak position, Peak height (baseline-subtracted).
  • Derived (Green channel): R/B ratio (\(I_{\mathrm{Red}} / I_{\mathrm{Blue}}\)).
  • Fitted: Peak position (fit), Peak height (fit), Peak area (fit) using fitted peak parameters when available.
  • VLiveMaps & LiveMapSubpanel (rgb_live_maps/): QWidget tab installed in bottom_tabs (between Fit Results and MVA, with More placed at the end of the tabs). Hosts a top toolbar row combining a contextual left strip ([◀ | ComboBox | ▶] 2D map switcher and diagnostic notices — hidden when unused) with persistent right-aligned Show Legend and compact 2-column More view options controls (btn_legend, btn_options, (2, 2, 2, 2) row margins matching VSpectraViewer), plus 3 independent subpanels (LiveMapSubpanel in v_live_map_subpanel.py, 96 DPI baseline) featuring per-panel Rescale, Pan, and Zoom buttons synced to NoDoubleClickZoomToolbar (preserving legend double-click editing), size-invariant figure clipboard copy (Copied figure size default 5.5 × 4.0 in & Copied figure theme), and Ctrl + Click TSV data copy via copy_data_requested(color_id) / copy_df_to_clb() (copying spectrum index/labels + parameter values in "spectra" mode, 1D/multi-profile tables, or 2D (X, Y, Value) site data via VMLiveMaps.get_2d_copy_points()). In mode="map", LiveMapSubpanel reuses shared map_selection.py helpers (MapCanvasSelector, resolve_xy_selection(), resolve_1d_profile_selection()) to provide click, Ctrl+Click, and marquee-drag spectrum selection across R/B/G plots when Pan/Zoom and legend hits are inactive, emitting VLiveMaps.spectra_selected back to VWorkspaceMaps while keeping interactive XY selection disabled in mode="spectra". View options default to plot_theme="Light Mode" (independent of Qt UI theme via apply_global_theme()), plot_style="line", line_width=1.5, dot_size=1.5, show_figure_label=False, and show_grid=False, persist across restarts in MSettings (live_maps_view_options/*, cross-synced across Spectra & Maps workspaces), and use apply_view_options_fast(), @lru_cache mplstyle dicts (_get_cached_style_dict), settled-layout freezing (_on_canvas_draw), and parented 35 ms redraw timers for stall-free X/Y/Z scale, style, text size (6–24 pt), figure title label, gridline, shared-Y, heatmap smoothing, colorbar, and legend-editor updates backed by v_live_maps_legend_editor.py.
  • Zoom & Range Coordination: When a range selector is activated, btn_zoom is automatically deactivated so bracket adjustment can occur without triggering simultaneous zoom rectangles, and VWorkspaceSpectra._on_range_selector_toggled() automatically switches bottom_tabs to self.v_live_maps (flushing any deferred _live_maps_dirty selection before calculating the activated channel; deactivating a selector leaves the active tab unchanged). The Zoom button can also be toggled off by clicking it, and while Zoom is active, clicking inside the range span performs a zoom rather than moving the range body.

VMWorkspaceSpectra — The ViewModel

File: vm_workspace_spectra.py (composed with vm_spectra_preprocessing.py, vm_spectra_fitting.py, vm_spectra_results.py, and vm_spectra_persistence.py)

This is the largest and most critical class in the application. It owns the SpectraStore and orchestrates every operation.

Signals (ViewModel → View)

spectra_list_changed    = Signal(list)          # list[dict] — refresh the spectra list
spectra_selection_changed = Signal(object)      # dict payload for VSpectraViewer
count_changed           = Signal(int)           # total spectrum count label
show_xcorrection_value  = Signal(float)         # sync X-correction spinbox
spectral_range_changed  = Signal(float, float)  # sync range controls
fit_in_progress         = Signal(bool)          # enable/disable fit buttons
fit_progress_updated    = Signal(int, int, int, float, int)  # progress bar
fit_results_updated     = Signal(object)        # pd.DataFrame → results table
notify                  = Signal(str)           # floating notification message
send_df_to_graphs       = Signal(str, object)   # forward DataFrame to Graphs

Method Reference

Category Methods
Loading load_files(paths)
Selection set_selected_fnames(), set_selected_indices(), _get_selected_spectra(), _get_active_spectra()
Preprocessing apply_spectral_range(), apply_x_correction(), undo_x_correction(), apply_y_normalization()
Baseline set_baseline_settings(), preview_baseline(), add_baseline_point(), remove_baseline_point(), subtract_baseline(), delete_baseline(), copy_baseline(), paste_baseline()
Peaks add_peak_at(), remove_peak_at(), update_peak_label(), update_peak_model(), update_peak_param(), delete_peak(), copy_peaks(), paste_peaks(), delete_peaks()
Fitting fit(), stop_fit(), _run_fit_thread(), _on_fit_finished()
Results collect_fit_results(), save_fit_results(), split_filename(), add_column_from_filename(), compute_column_from_expression()
Fit model copy_fit_model(), paste_fit_model(), save_fit_model(), apply_fit_model()
Workspace reinit_spectra(), remove_selected_spectra(), reorder_spectra(), clear_workspace()
Persistence save_work(), load_work(), _load_legacy_spectra()
Display save_spectra_data(), copy_spectrum_data_to_clipboard()

Template Method Hooks

The ViewModel uses the Template Method pattern to allow the Maps subclass to customize bulk operations without duplicating the operation logic:

def _get_target_mds(self, apply_all: bool) -> list[MapData]:
    """Which MapData blocks to operate on."""
    # Spectra workspace: selected spectra → their MapData objects
    # Maps workspace (override): the current map, or all maps

def _on_map_data_changed(self, md: MapData, action: str):
    """Hook after each individual MapData is modified."""
    # Spectra workspace: no-op
    # Maps workspace (override): clears heatmap cache, re-runs batch_preprocess

def _post_bulk_action(self, apply_all: bool, action: str):
    """Hook after all target MapData objects have been processed."""
    # Spectra workspace: re-emits list and selection
    # Maps workspace (override): also refreshes fit results and map view

VSpectraViewer — The Plot Canvas

Package: spectra_viewer/ (v_spectra_viewer.py, v_spectra_options.py, v_plot_1d.py, v_plot_heatmap.py, v_plot_3d.py, v_interactions.py, v_spectra_legend_editor.py, common.py)

VSpectraViewer composes dedicated mixins over QWidget (SpectraOptionsMenuMixin, SpectraPlot1DMixin, SpectraHeatmapMixin, SpectraPlot3DMixin, SpectraLegendMixin, SpectraInteractionMixin, and SpectraRangeBracketMixin), separating the 2-column options menu and state sync, 1D/heatmap/3D rendering, mouse/peak/eraser interactions, and legend/colorbar management while keeping shared helpers in common.py.

The Matplotlib canvas renders everything visible in the spectrum plot. It receives a data dictionary from VMWorkspaceSpectra.spectra_selection_changed and redraws accordingly.

Rendered elements:

Element Source data key
Spectrum lines data["y"] (processed)
Raw overlay (optional) data["y0"] (raw)
Baseline curve data["y_baseline"]
Baseline anchor points data["baseline_config"]["points"]
Individual peak curves data["y_peaks"] (list of arrays)
Best-fit envelope data["y_bestfit"]
Residuals data["y"] - data["y_bestfit"]
R² annotation data["fit_r2"][0]

Interaction modes (radio button exclusive):

Mode Left click Right click
Zoom Standard Matplotlib zoom/pan —
Baseline Add anchor point at x Remove nearest anchor
Peak Add peak at x Remove nearest peak

Peaks can also be dragged. The viewer emits peak_dragged(x, y) during drag and peak_drag_finished() on release, which the ViewModel translates into update_dragged_peak() + finalize_peak_drag() calls.

Batch Legend Editing

VSpectraViewer caches the complete legend bounding box after rendering. A double-click anywhere within that box opens SpectraLegendEditorDialog from spectra_viewer/v_spectra_legend_editor.py; individual legend handles and text objects no longer launch separate editors.

The dialog is transactional: its palette selector, legend-limit spinbox, label fields, and color comboboxes hold temporary values until the user accepts it. Cancel therefore causes no mutation. On OK, VSpectraViewer._apply_legend_editor_values():

  1. Updates the shared color_palette and max_legend_items view options.
  2. Writes changed labels and explicit colors to the current tensor payload.
  3. Writes the same values through each SpectrumProxy, updating the source MapData.labels and MapData.colors arrays.
  4. Emits spectrumCustomized, causing the ViewModel to rebuild the selection payload and refresh the spectra list.

A color value of None represents Automatic and is resolved from the active palette during rendering. Explicit per-spectrum colors continue to take precedence when the palette changes. Continuous palettes are sampled across the complete selection; the editor offers a bounded selection of representative swatches.

Both workspaces enforce LEGEND_EDITOR_MAX_ROWS = 100. Only those editor rows are instantiated, preventing large map or spectrum selections from creating thousands of Qt widgets. The dialog receives the full selection count so automatic gradient previews still match their plotted spectrum positions. Values outside the current batch remain untouched.

View Options Synchronization & Persistence

The View Option menu and bottom toolbar provide user-configurable display settings arranged in a compact 2-column QWidgetAction panel (synchronized across workspaces and persisted across sessions):

  • Plot Theme (cbb_theme): Configures the Matplotlib canvas theme ("Dark Mode" or "Light Mode"), synchronized across the Spectra workspace, Maps workspace, and secondary 2D map viewer dialogs. By default, the plot theme is always set to "Light Mode" unless the user explicitly switches it to "Dark Mode". It is completely independent of the global application UI theme, and the user's explicit choice is persisted across sessions in view_options/theme.
  • Legend Placement & Outside Option (act_legend_outside): When checked, VSpectraViewer positions the legend outside the primary axes via loc="center left" and bbox_to_anchor=(1.02, 0.5). The figure's compressed layout dynamically adjusts plot margins so the legend fits cleanly without overlapping spectral traces. This setting is synchronized between Spectra and Maps workspaces and persisted across sessions in view_options/legend_outside. Legend double-click bounds detection dynamically refreshes window extents from the underlying legend artist to guarantee accurate hit-testing regardless of layout compression.
  • Colorbar Legend Mode (act_legend_colorbar, cbb_colorbar_param, le_colorbar_label): When checked (and btn_legend is enabled), VSpectraViewer replaces the discrete per-spectrum legend box with a right-side Matplotlib colorbar driven by the shared filename numeric token extractor (_extract_filename_tokens() / _extract_series_parameter_values(), shared with 2D Heatmap mode) or spectrum Index. The row_colorbar_param and row_colorbar_label rows in the 2-column options menu are shown only when act_legend_colorbar / chk_legend_colorbar is checked (_update_colorbar_options_visibility()). Parameter selections are tracked across the session by underscore token slot and normalized unit pattern (_refresh_token_combobox()), preserving the chosen parameter even when selecting different spectrum subsets whose first filename carries a different numeric value. For gradient palettes, each spectrum's automatic color is mapped directly from its extracted parameter value via _resolve_colorbar_cmap_and_norm() (custom per-spectrum color overrides continue to take priority). Persisted across sessions under view_options/legend_colorbar, view_options/colorbar_param, and view_options/colorbar_label, and synchronized between Spectra and Maps workspaces.

Heatmap & Signal Processing Optimizations

  • Vectorized Heatmap Matrix Interpolation: When 2D heatmap mode is active, cubic/linear Y-axis interpolation processes the entire intensity matrix simultaneously (scipy.interpolate.interp1d(..., axis=0)) rather than looping per spectral column, slashing heatmap render times by over 4× on large batches.
  • Fast Cosmic Ray / Eraser Noise Estimation: Replaced iterative sliding-window polynomial fitting with first-difference Median Absolute Deviation (\(MAD / (0.6745 \sqrt{2})\)), providing robust baseline noise estimation in \(O(N)\) vectorized NumPy time.
  • Hover Hit-Testing Pre-filter: _on_hover uses an x-range bounding pre-filter to skip expensive contains(event) line computations on irrelevant peak markers.

VFitModelBuilder — The Controls Panel

File: v_fit_model_builder.py

A splitter panel containing the full preprocessing and fitting control surface:

  • Left pane: X-correction, spectral range, baseline mode selector, baseline action buttons.
  • Right pane: VPeakTable (editable parameter rows) + fit action buttons (Fit, Copy model, Paste model, Save model, Apply model).
  • Drag-and-Drop Model Loading: Accepts dropped .json fit model files directly onto the panel or via the parent workspace. When dropped, fit_model_dropped(path) triggers load_fit_model_file(), delegating to VMFitModelBuilder.load_model_file(). This loads the external model into memory, updates the model dropdown, selects it, activates the Fit Model Builder tab, and displays a floating notification. Both Spectra and Maps workspaces inherit and support this functionality.

VPeakTable — The Parameter Table

File: v_peak_table.py

An interactive table where each row represents one peak. Columns show label, model shape, center (x₀), FWHM, amplitude, and bound toggles. Editing any cell emits a signal to VMWorkspaceSpectra, which updates md.fit_model and immediately reconstructs the Y_peaks preview.


Data Flow

Loading Spectra

  1. User Action: The user drag-and-drops files into the VWorkspaceSpectra UI.
  2. View → ViewModel: The View calls vm.load_files(paths).
  3. File Parsing: For each file, the ViewModel delegates to the m_io module (load_spectrum_file, load_wdf_spectrum, etc.). The IO module returns a dictionary containing raw arrays (x0, y0) and metadata.
  4. Data Storage: The ViewModel registers the data in the SpectraStore by calling add_map(name, x0, Y0, coords, fnames). A new MapData block is created with x and Y set to None (raw data only).
  5. UI Update: The ViewModel emits the spectra_list_changed signal. The View catches this and updates the VSpectraList sidebar.

The m_io module auto-detects format from file extension. Every loader returns a uniform dict:

{
    "type": "spectra",
    "items": [
        {"name": str, "x0": ndarray, "y0": ndarray, "metadata": dict},
        ...
    ]
}

WDF files may return multiple items (temporal series). All items are registered as separate MapData blocks.

Selecting Spectra

  1. User Action: The user clicks a spectrum in VSpectraList.
  2. View → ViewModel: The list widget emits a selection signal which calls vm.set_selected_indices().
  3. State Update: The ViewModel resolves indices to unique fnames and stores the active selection.
  4. Payload Construction: The ViewModel calls _emit_selected_spectra(), which queries SpectraStore to build a "type": "tensor_list" payload containing the arrays for all selected spectra.
  5. UI Update: The ViewModel emits spectra_selection_changed(data_dict). VSpectraViewer receives it, calls set_plot_data(), and redraws the Matplotlib canvas.

The selection payload (data_dict) contains pre-extracted arrays keyed by "type": "tensor_list" for the Spectra workspace (list of independent arrays, each potentially with a different x-axis). The Maps workspace overrides this to emit "type": "tensor" (shared x-axis matrix).

Fitting Workflow

  1. User Action: The user clicks "Fit" in VFitModelBuilder.
  2. Task Construction: The ViewModel builds a list of tasks (one per map/spectrum) containing indices and the fit_model dictionary.
  3. Thread Launch: The ViewModel instantiates VBFthread(store, tasks) and starts it. The UI buttons are disabled via the fit_in_progress(True) signal.
  4. Engine Execution (Background): For each task, the thread calls the VBFengine.fit_spectra(x, Y_sub, fit_model, weights).
  5. Result Storage (Background): As fits complete, the thread directly writes results to the SpectraStore via set_fit_results() and updates the Y_bestfit and Y_peaks arrays on the MapData object.
  6. Progress Updates: The thread emits progress signals which the ViewModel relays to the View's progress bar.
  7. Completion: The thread emits finished(). The ViewModel catches this, calls _on_fit_finished(), re-enables the UI, and triggers a canvas redraw.

[!NOTE] VBFthread calls store.set_fit_results() directly from the worker thread. This is safe because PySide6 allows writes to pure Python/NumPy objects from non-GUI threads, as long as no Qt widget operations occur. The finished() signal then triggers UI updates on the main thread.

Baseline Workflow

  1. User sets mode in VFitModelBuilder → set_baseline_settings() stores config in md.baseline_config.
  2. User clicks on spectrum → add_baseline_point(x) adds anchor to md.baseline_config["points"].
  3. preview_baseline() evaluates and stores md.Y_baseline for rendering (does not subtract).
  4. subtract_baseline() runs batch_preprocess() on the map — subtracts Y_baseline from Y, sets md.is_baseline_subtracted = True.
  5. delete_baseline() restores Y by running batch_preprocess() with an empty baseline config (crop only), resets is_baseline_subtracted.

Peak Editing Workflow

  1. User Ctrl+clicks peak mode on viewer → VSpectraViewer.peak_add_requested(x) → add_peak_at(x).
  2. ViewModel reads y-value at x from md.Y[spec_idx, idx], initializes peak_model dict with auto-estimated x0, ampli, fwhm, bounds.
  3. Peak dict is appended to md.fit_model["peak_models"] under the next integer key.
  4. eval_peak_initial() evaluates the model curve and appends it to md.Y_peaks.
  5. _emit_selected_spectra() triggers viewer redraw, showing the new peak curve instantly.

Fit Results Collection

# VMWorkspaceSpectra.collect_fit_results()
#   → SpectraStore.build_fit_results_df()
#   → returns pd.DataFrame with columns:
#      Filename, [x0_Peak1, fwhm_Peak1, ampli_Peak1, area_Peak1, ...], R2

build_fit_results_df() is fully vectorized — it reads md.peak_params directly (no Python loop over spectra), applies user peak labels, computes area columns, appends the per-spectrum R2 column (coefficient of determination, read straight from md.fit_r2 — the same value the SpectraViewer shows for the selected spectrum), and returns a pd.DataFrame. R2 is a single scalar per spectrum (not per-peak), so collect_fit_results()'s column sort leaves it at the end of the frame. In the Spectra workspace, X and Y columns are dropped before emitting to the results table.

Decimal precision is set by build_fit_results_df(..., decimals=…), which rounds every numeric fit column (parameters, areas, R²) while leaving the X/Y coordinates at full precision — it's the single rounding authority, so collect_fit_results() no longer rounds afterwards. VMWorkspaceSpectra.results_decimals (default 3) supplies the value; the Fit Results tab's "Fit results decimals" spinbox (above the Collect button) sets it through set_results_decimals() (applied on the next Collect). compute_column_from_expression() rounds its computed column to the same results_decimals. The public API's build_fit_results_df keeps its own default of 4.


Persistence

Modern Format (v2+, ZIP-backed)

Workspace files (.spectra) use the ZIP-backed format described in SpectraStore: Persistence. The metadata.json stores per-spectrum configuration and the arrays.npz stores the heavy numerical arrays.

Legacy Loader

_load_legacy_spectra() handles .spectra files from older SPECTROview versions (raw JSON with base64+zlib-compressed arrays). It:

  1. Decodes and decompresses x0/y0 arrays.
  2. Reconstructs baseline_config, evaluates md.Y_baseline.
  3. Re-evaluates peak curves to populate md.Y_peaks and md.Y_bestfit.

No migration is required — the legacy format is loaded transparently at runtime.


Extension Guide

Adding a New Preprocessing Tool

  1. ViewModel: Add a method (e.g., apply_smoothing(window, apply_all)) that calls _get_target_mds(apply_all), modifies md.Y, then calls _post_bulk_action().
  2. Model (if needed): Add a function to fit_engine/baseline.py or a new file for the algorithm.
  3. View: Add a button/control to VFitModelBuilder. Emit a new signal and connect it in VWorkspaceSpectra.setup_connections().
  4. Persistence: If the tool produces state that must survive save/load, add it to SpectraStore.to_metadata_dict() and restore it in load_map_from_npz().

Adding a New Peak Model

See the dedicated VBF Engine guide. In short:

  1. Add the model function and analytical Jacobian to fit_engine/models.py.
  2. Register the model name in spectroview/__init__.py → PEAK_MODELS.
  3. Add initialization logic to VMWorkspaceSpectra._initialize_peak_params().
  4. The VPeakTable and VFitModelBuilder will auto-populate the new model in their dropdowns.

Adding a New Viewer Rendering Feature

  1. Add the render logic to VSpectraViewer.set_plot_data() or a dedicated private method.
  2. Add the required data to the payload dict emitted by VMWorkspaceSpectra._emit_selected_spectra().
  3. If the feature requires a UI toggle, add a QCheckBox or menu action in VSpectraViewer and connect it to a redraw call.

Troubleshooting

Spectrum doesn't appear after loading

  • Check md.is_active[0] — loading sets this to True by default, but a failed load may leave the entry in an inconsistent state.
  • Verify that _emit_list_update() is called after store.add_map().

Peak table is empty after fit

  • _emit_selected_spectra() must be called after _on_fit_finished(). Check that store.set_fit_results() populated md.param_names.

R² shows 0.0 despite successful fit

  • The fit engine sets rsquared = 0 if fit_success is False. Check md.fit_success[idx] for the spectrum in question.

_emit_selected_spectra() causes a Qt signal loop

  • Never call _emit_selected_spectra() from within a slot that is connected to spectra_selection_changed. Use a QTimer.singleShot(0, ...) to defer if necessary.

For data-model troubleshooting (preprocessing not applied, memory issues), see SpectraStore: Troubleshooting.