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:
- Instantiates all child widgets and the ViewModel in
__init__. - Wires every signal/slot connection in
setup_connections(). - Delegates every user action to the ViewModel (never manipulates data directly).
- 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 viascipy.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, andshift_panel) are hidden viasetVisible(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): Switchesself.axbetween 2D rectilinear axes andAxes3Donly when changing into or out of 3D mode, disconnectingAxes3Dcanvas callbacks and disabling 3D mouse bindings beforefigure.delaxes()to prevent callback accumulation across mode switches. - Vectorized 3D Rendering (
FastLine3DCollection): SubclassesLine3DCollectionto project all 3D points across uniform(N, M, 3)tensors or raggedtensor_listselections in a single vectorizedproj3d._proj_trans_points()pass and updatesPath._verticesin 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_3dandbtn_heatmapare mutually exclusive. Activating 3D mode automatically turns offNoDoubleClickZoomToolbar2D zoom (_set_zoom_tool_active(False)), hides incompatible 1D tools (btn_zoom,btn_peak,btn_baseline,btn_eraser,shift_panel), and sharescbb_heatmap_yaxis/le_heatmap_ylabelfor filename-token Y-axis positioning so left-drag rotates(elev, azim), middle-drag pans, right-drag or scroll scales Z, andRescale(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 inVSpectraList. - 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), orDistance (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}}\) withNaNmasking for zero/near-zero Blue intensities and updates automatically when Red or Blue brackets move. WhileR/B ratiois selected, the Green bracket is hidden onVSpectraViewerso 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):VRangeSelectorPanelis positioned as a dedicated vertical panel on the right side ofVSpectraViewerwith Red (#e74c3c), Blue (#3498db), and Green (#2ecc71) toggle buttons.SpectraRangeBracketMixinwires the panel, range initialization/clamping, hover cursor feedback, and Agg background blitting directly intoVSpectraViewer.RangeSelectorManager: Manages interactive vertical boundary lines, inward bracket annotations, and transparent spans for each selector, reusing existing artists in-place across drags and supportingset_animated(True)/active_artists(). Tracks per-channel parameter selection viaset_parameter()/is_bracket_visible(), hiding and disabling hit-testing for the Green bracket whenever its Live Maps panel displaysR/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 (temporarylayout_enginesuspension, hover-peak bypass while dragging, and X-clamping outside vertical axes bounds), while emittingrange_drag_finishedon mouse release. Hit testing uses pixel tolerance with coordinate translation from Matplotlib transforms.VMLiveMaps: Owns selector intervals, parameter selections, colormap choices, andmode("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 viaflush_pending(), and automatically offloads map batches with>= 25,000spectra (ASYNC_SPECTRUM_THRESHOLD) to aQThreadPoolQRunnable(_LiveMapWorker) guarded by monotonic_generation_idstale cancellation and cleanshutdown(). In"spectra"mode,set_series_data(mds)preserves user-adjusted bracket positions across spectrum selection changes when within axis bounds, emitsspatial_sites_changed(None), and emitsseries_data_ready. In"map"mode,set_map_datas(mds, primary_name)enforces signature deduplication andMapData.data_versionLRU result caching, excludes inactive (~is_active) spectra, caches regular/DelaunayMapGriddergeometry, emitsspatial_sites_changedwith ordered active coordinates/profile positions for interactive selection, and emitsmap_data_ready,profile_data_ready,multi_profile_data_ready,map_2d_candidates_changed, orlive_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-castMapData.y_matrix[:, mask]views viacompute_spectral_parameter()(with optionalactive_mask), across discrete selected spectra (list[MapData]) viacompute_series_spectral_parameter(), map dimensionality detection viaanalyze_map_geometry(), reusable regular/Delaunay barycentric gridding viabuild_map_gridder()+compute_map_grid(), and safe element-wise ratio computation with relative epsilonNaNmasking viacompute_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 inbottom_tabs(betweenFit ResultsandMVA, withMoreplaced 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 matchingVSpectraViewer), plus 3 independent subpanels (LiveMapSubpanelinv_live_map_subpanel.py, 96 DPI baseline) featuring per-panel Rescale, Pan, and Zoom buttons synced toNoDoubleClickZoomToolbar(preserving legend double-click editing), size-invariant figure clipboard copy (Copied figure sizedefault5.5 × 4.0in &Copied figure theme), andCtrl + ClickTSV data copy viacopy_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 viaVMLiveMaps.get_2d_copy_points()). Inmode="map",LiveMapSubpanelreuses sharedmap_selection.pyhelpers (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, emittingVLiveMaps.spectra_selectedback toVWorkspaceMapswhile keeping interactive XY selection disabled inmode="spectra". View options default toplot_theme="Light Mode"(independent of Qt UI theme viaapply_global_theme()),plot_style="line",line_width=1.5,dot_size=1.5,show_figure_label=False, andshow_grid=False, persist across restarts inMSettings(live_maps_view_options/*, cross-synced across Spectra & Maps workspaces), and useapply_view_options_fast(),@lru_cachemplstyledicts (_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 byv_live_maps_legend_editor.py.- Zoom & Range Coordination: When a range selector is activated,
btn_zoomis automatically deactivated so bracket adjustment can occur without triggering simultaneous zoom rectangles, andVWorkspaceSpectra._on_range_selector_toggled()automatically switchesbottom_tabstoself.v_live_maps(flushing any deferred_live_maps_dirtyselection 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():
- Updates the shared
color_paletteandmax_legend_itemsview options. - Writes changed labels and explicit colors to the current tensor payload.
- Writes the same values through each
SpectrumProxy, updating the sourceMapData.labelsandMapData.colorsarrays. - 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 inview_options/theme. - Legend Placement & Outside Option (
act_legend_outside): When checked,VSpectraViewerpositions the legend outside the primary axes vialoc="center left"andbbox_to_anchor=(1.02, 0.5). The figure'scompressedlayout 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 inview_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 (andbtn_legendis enabled),VSpectraViewerreplaces 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 spectrumIndex. Therow_colorbar_paramandrow_colorbar_labelrows in the 2-column options menu are shown only whenact_legend_colorbar/chk_legend_colorbaris 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 underview_options/legend_colorbar,view_options/colorbar_param, andview_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_hoveruses an x-range bounding pre-filter to skip expensivecontains(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
.jsonfit model files directly onto the panel or via the parent workspace. When dropped,fit_model_dropped(path)triggersload_fit_model_file(), delegating toVMFitModelBuilder.load_model_file(). This loads the external model into memory, updates the model dropdown, selects it, activates theFit Model Buildertab, 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¶
- User Action: The user drag-and-drops files into the
VWorkspaceSpectraUI. - View → ViewModel: The View calls
vm.load_files(paths). - File Parsing: For each file, the ViewModel delegates to the
m_iomodule (load_spectrum_file,load_wdf_spectrum, etc.). The IO module returns a dictionary containing raw arrays (x0,y0) and metadata. - Data Storage: The ViewModel registers the data in the
SpectraStoreby callingadd_map(name, x0, Y0, coords, fnames). A newMapDatablock is created withxandYset toNone(raw data only). - UI Update: The ViewModel emits the
spectra_list_changedsignal. The View catches this and updates theVSpectraListsidebar.
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¶
- User Action: The user clicks a spectrum in
VSpectraList. - View → ViewModel: The list widget emits a selection signal which calls
vm.set_selected_indices(). - State Update: The ViewModel resolves indices to unique
fnamesand stores the active selection. - Payload Construction: The ViewModel calls
_emit_selected_spectra(), which queriesSpectraStoreto build a"type": "tensor_list"payload containing the arrays for all selected spectra. - UI Update: The ViewModel emits
spectra_selection_changed(data_dict).VSpectraViewerreceives it, callsset_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¶
- User Action: The user clicks "Fit" in
VFitModelBuilder. - Task Construction: The ViewModel builds a list of tasks (one per map/spectrum) containing
indicesand thefit_modeldictionary. - Thread Launch: The ViewModel instantiates
VBFthread(store, tasks)and starts it. The UI buttons are disabled via thefit_in_progress(True)signal. - Engine Execution (Background): For each task, the thread calls the
VBFengine.fit_spectra(x, Y_sub, fit_model, weights). - Result Storage (Background): As fits complete, the thread directly writes results to the
SpectraStoreviaset_fit_results()and updates theY_bestfitandY_peaksarrays on theMapDataobject. - Progress Updates: The thread emits progress signals which the ViewModel relays to the View's progress bar.
- Completion: The thread emits
finished(). The ViewModel catches this, calls_on_fit_finished(), re-enables the UI, and triggers a canvas redraw.
[!NOTE]
VBFthreadcallsstore.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. Thefinished()signal then triggers UI updates on the main thread.
Baseline Workflow¶
- User sets mode in
VFitModelBuilder→set_baseline_settings()stores config inmd.baseline_config. - User clicks on spectrum →
add_baseline_point(x)adds anchor tomd.baseline_config["points"]. preview_baseline()evaluates and storesmd.Y_baselinefor rendering (does not subtract).subtract_baseline()runsbatch_preprocess()on the map — subtractsY_baselinefromY, setsmd.is_baseline_subtracted = True.delete_baseline()restoresYby runningbatch_preprocess()with an empty baseline config (crop only), resetsis_baseline_subtracted.
Peak Editing Workflow¶
- User Ctrl+clicks peak mode on viewer →
VSpectraViewer.peak_add_requested(x)→add_peak_at(x). - ViewModel reads y-value at x from
md.Y[spec_idx, idx], initializespeak_modeldict with auto-estimatedx0,ampli,fwhm,bounds. - Peak dict is appended to
md.fit_model["peak_models"]under the next integer key. eval_peak_initial()evaluates the model curve and appends it tomd.Y_peaks._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:
- Decodes and decompresses
x0/y0arrays. - Reconstructs
baseline_config, evaluatesmd.Y_baseline. - Re-evaluates peak curves to populate
md.Y_peaksandmd.Y_bestfit.
No migration is required — the legacy format is loaded transparently at runtime.
Extension Guide¶
Adding a New Preprocessing Tool¶
- ViewModel: Add a method (e.g.,
apply_smoothing(window, apply_all)) that calls_get_target_mds(apply_all), modifiesmd.Y, then calls_post_bulk_action(). - Model (if needed): Add a function to
fit_engine/baseline.pyor a new file for the algorithm. - View: Add a button/control to
VFitModelBuilder. Emit a new signal and connect it inVWorkspaceSpectra.setup_connections(). - Persistence: If the tool produces state that must survive save/load, add it to
SpectraStore.to_metadata_dict()and restore it inload_map_from_npz().
Adding a New Peak Model¶
See the dedicated VBF Engine guide. In short:
- Add the model function and analytical Jacobian to
fit_engine/models.py. - Register the model name in
spectroview/__init__.py→PEAK_MODELS. - Add initialization logic to
VMWorkspaceSpectra._initialize_peak_params(). - The
VPeakTableandVFitModelBuilderwill auto-populate the new model in their dropdowns.
Adding a New Viewer Rendering Feature¶
- Add the render logic to
VSpectraViewer.set_plot_data()or a dedicated private method. - Add the required data to the payload dict emitted by
VMWorkspaceSpectra._emit_selected_spectra(). - If the feature requires a UI toggle, add a
QCheckBoxor menu action inVSpectraViewerand connect it to a redraw call.
Troubleshooting¶
Spectrum doesn't appear after loading
- Check
md.is_active[0]— loading sets this toTrueby default, but a failed load may leave the entry in an inconsistent state. - Verify that
_emit_list_update()is called afterstore.add_map().
Peak table is empty after fit
_emit_selected_spectra()must be called after_on_fit_finished(). Check thatstore.set_fit_results()populatedmd.param_names.
R² shows 0.0 despite successful fit
- The fit engine sets
rsquared = 0iffit_successis False. Checkmd.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 tospectra_selection_changed. Use aQTimer.singleShot(0, ...)to defer if necessary.
For data-model troubleshooting (preprocessing not applied, memory issues), see SpectraStore: Troubleshooting.