Workspace: Maps¶
The Maps workspace handles hyperspectral map data — spatially resolved spectral datasets where each pixel corresponds to a full spectrum. It extends the Spectra workspace via inheritance, gaining all fitting, baseline, peak-editing, and persistence capabilities for free, and adds spatial awareness, heatmap visualization, and coordinate-based operations on top.
[!NOTE] Prerequisites — Before reading this guide, ensure you are familiar with:
- Data Architecture: SpectraStore — the shared
MapData/SpectraStoredata model.- Workspace: Spectra — the base ViewModel, View components, and data flow patterns.
This page covers only the Maps-specific extensions. Inherited behavior is not repeated here.
How Maps Differs from Spectra¶
The fundamental difference is the cardinality of MapData.N:
| Workspace | MapData.N |
Meaning |
|---|---|---|
| Spectra | 1 | One spectrum per MapData block |
| Maps | 2 – 100 000 | N spectra sharing a single wavenumber axis |
Because the underlying tensor model is identical, a single vectorized fit that works for 1 spectrum also works for 100 000, with no code change in the engine.
MapData in Maps Context¶
MapData ("wafer_300mm") — 50×50 wafer (2500 spectra, 1000 wavenumbers)
├── x0: float64[1000] 1 shared wavenumber axis
├── Y0: float32[2500, 1000] raw intensities — 10 MB
├── x: float64[800] after spectral crop
├── Y: float32[2500, 800] after crop + baseline sub — 8 MB
├── coords: float64[2500, 2] (X, Y) stage positions in µm
├── fnames: list[str] × 2500 "wafer_300mm_(x_pos, y_pos)"
├── is_active: bool[2500] checkbox state
├── peak_params: float64[2500, K] after VBF fit — all 2500 at once
├── fit_success: bool[2500]
├── fit_r2: float64[2500]
├── Y_bestfit: float32[2500, 800] 8 MB
└── Y_peaks: [float32[2500, 800], ...] 8 MB per peak
Architecture Overview¶
graph LR
subgraph View ["View Layer"]
VWM["VWorkspaceMaps<br/>(extends VWorkspaceSpectra)"]
ML["VMapsList<br/>(maps list + actions)"]
MV["VMapViewer<br/>(Matplotlib heatmap)"]
MVD["VMapViewerDialog<br/>(detachable viewer)"]
SV_inh["VSpectraViewer<br/>(inherited)"]
FMB_inh["VFitModelBuilder<br/>(inherited)"]
end
subgraph VM ["ViewModel Layer"]
VMWM["VMWorkspaceMaps<br/>(extends VMWorkspaceSpectra)"]
VMWS_inh["VMWorkspaceSpectra<br/>(base class)"]
end
subgraph Model ["Model Layer"]
SS["SpectraStore"]
IO["m_io<br/>(map file loaders)"]
VBF["VBFthread<br/>(mega-batch fit)"]
WIO["WorkspaceIO"]
end
VWM --> ML & MV & MVD
VWM --> SV_inh & FMB_inh
VWM -->|"method calls"| VMWM
VMWM -.->|"extends"| VMWS_inh
VMWM -->|"Qt signals"| VWM
VMWM --> SS & IO & VBF & WIO
Why Inheritance Instead of Composition?¶
VMWorkspaceMaps extends VMWorkspaceSpectra rather than wrapping it:
- Every fitting algorithm (baseline, peaks, VBF engine) works identically on both single spectra (N=1) and maps (N>1).
- Duplicating or delegating the fitting code would introduce maintenance fragility.
- Overriding via the Template Method pattern (three hook methods) is sufficient to customize bulk-operation targeting without forking any algorithm logic.
The same pattern applies at the View level: VWorkspaceMaps extends VWorkspaceSpectra, overrides setup_connections() to prevent double-wiring during __init__, then replaces the right sidebar widget with the map-specific VMapsList + VMapViewer panel.
Maps-Specific Components¶
VMWorkspaceMaps — The ViewModel¶
File: vm_workspace_maps.py (with fitting/persistence mixins in spectroview/viewmodel/maps/)
Additional state beyond the inherited VMWorkspaceSpectra:
| Attribute | Type | Purpose |
|---|---|---|
maps |
dict[str, pd.DataFrame] |
Raw map DataFrames indexed by name (legacy cache) |
current_map_name |
str \| None |
Active map selection |
maps_metadata |
dict[str, dict] |
Acquisition metadata per map (WDF, SPC, L6M, NGC) |
map_type |
str |
'2Dmap' or 'Wafer_300mm' / 'Wafer_200mm' / 'Wafer_100mm' |
graphs_workspace |
ref | Injected reference for profile extraction |
Additional Signals¶
maps_list_changed = Signal(list) # map name list updated → VMapsList
map_data_updated = Signal(object) # current map DF changed → trigger heatmap redraw
send_spectra_to_workspace = Signal(list) # deep copies → Spectra workspace
clear_map_cache_requested = Signal(str) # map name → VMapViewer cache invalidation
switch_to_graphs_tab = Signal() # request tab switch after profile extraction
Additional Method Reference¶
| Category | Methods |
|---|---|
| Map loading | load_map_files(paths) |
| Map selection & order | select_map(name), select_maps(names, primary), reorder_maps(new_order), _show_map_spectra(name) |
| Map deletion | delete_current_map(), remove_map(name) |
| Map data | get_current_map_dataframe(), get_fit_results_dataframe() |
| Export | save_current_map_to_csv(file_path) |
| Fit | fit(), _run_fit_thread(), collect_fit_results() — all override parent |
| Cross-workspace | send_selected_spectra_to_spectra_workspace(), extract_and_send_profile_to_graphs() |
| Persistence | save_work(), load_work(), _load_legacy_maps() |
VWorkspaceMaps — The View¶
File: v_workspace_maps.py
Overrides _add_maps_panel() to replace the inherited spectra sidebar with:
VMapViewer— the heatmap canvas with Z-parameter and X-range sliders.VMapsList— maps list panel with map management and spectra action buttons.
The left side (SpectraViewer + bottom tabs) is inherited from VWorkspaceSpectra. While VWorkspaceSpectra initializes VLiveMaps and VMLiveMaps in "spectra" mode (rendering 1D parameter variation graphs across the currently selected spectra), VWorkspaceMaps switches the inherited v_live_maps and vm_live_maps instances to "map" mode (set_mode("map")).
In the Maps workspace, when maps are loaded or selected, VWorkspaceMaps synchronizes a Two-Tier selection model:
- Primary Map (
VMWorkspaceMaps.current_map_name): Drives preprocessing, fitting,VMapViewer,VSpectraViewer, MVA, andMoremetadata identically to single-selection workflows. - Selected Map List (
VMWorkspaceMaps.selected_map_names): Populated viaVMapsList(QAbstractItemView.ExtendedSelection), enablingCtrl+Click/Shift+Clickcomparison without altering Primary operations or triggeringVMapViewerredraws when the Primary stays unchanged.
VWorkspaceMaps forwards [MapData, ...] plus primary_name to self.vm_live_maps.set_map_datas(...) only when the Live Maps tab is active (otherwise flagging _live_maps_dirty = True for a single lazy flush upon tab activation, while VMapViewer spatial point clicks are ignored). Activating an R/B/G bracket on VSpectraViewer automatically switches bottom_tabs to Live Maps in VWorkspaceSpectra._on_range_selector_toggled() and flushes any pending selection immediately. VMLiveMaps inspects md.coords via cached analyze_map_geometry() and build_map_gridder() (which caches regular grid indices or Delaunay barycentric vertex/weights until coords or is_active change), excludes unchecked spectra (~md.is_active), caches per-parameter slices across drags using (id(md), md.name, md.data_version, param, range), and applies Primary-Precedence dimensionality adaptation:
- Primary is 1D profile: Emits
multi_profile_data_ready(when \(\ge 2\) profiles) orprofile_data_ready(single profile), overlaying all selected 1D profiles in matched colors (DEFAULT_COLORS) with uniform line thickness and any excluded 2D maps noted in the context header. - Primary is 2D map: Populates
map_2d_candidates_changedfor the tab's[◀ | ComboBox | ▶]2D map switcher, excludes 1D profiles, and computes/renders only the single currently visible 2D heatmap viamap_data_ready. - Red/Blue Intensity Ratio (
R/B ratio): Computes \(I_{\mathrm{Red}} / I_{\mathrm{Blue}}\) dynamically across both single/multi-1D profiles and 2D heatmaps, masking zero/near-zero Blue intensities and unchecked spectra asNaN. WhileR/B ratiois selected in the Green channel,VWorkspaceSpectra._on_range_selector_parameter_changed()notifiesVSpectraViewer.set_range_selector_parameter()so the Green range bracket is hidden on the spectrum canvas (and restored as soon as another spectral parameter is selected).
For massive batches (>= 25,000 active spectra by default via ASYNC_SPECTRUM_THRESHOLD), VMLiveMaps offloads pure-NumPy evaluation and gridding to a single-worker QThreadPool (_LiveMapWorker) bridged via a parented QObject (_LiveMapWorkerBridge) with monotonic _generation_id cancellation and clean shutdown() teardown on exit. VMLiveMaps also emits spatial_sites_changed (carrying ordered active site coordinates, optional 1D profile positions, and target map name) so Live Maps panels stay aligned with the active dataset. On the UI side, the RGB bracketing and Live Maps widgets live together under spectroview/view/components/rgb_live_maps/ (v_live_maps.py, v_live_maps_options.py, v_live_map_subpanel.py, v_live_map_1d.py, v_live_map_2d.py, v_live_map_selection.py, v_live_maps_legend_editor.py, v_range_selector.py, v_range_bracket_mixin.py, common.py). VLiveMaps provides persistent Show Legend and a compact 2-column More view options (btn_legend / btn_options) menu matching VSpectraViewer row spacing ((2, 2, 2, 2) margins) for instant client-side restyling at a crisp 96 DPI baseline: independent Plot theme ("Light Mode" default vs "Dark Mode", decoupled from global Qt UI icons via apply_global_theme()), Linear/Log X, Y, and Z color scaling with non-positive domain guards, line/dot/line+dots plot styles (default "line"), line width (1.5), dot size (1.5), graph text size (6–24 pt), Copied figure size (copy_fig_width/copy_fig_height, default 5.5 × 4.0 in) & Copied figure theme (Light Mode/Dark Mode) so clipboard figures are rendered at fixed physical size/aspect independent of window resizing, legend placement/columns/font size, LiveMapsLegendEditorDialog for custom canvas legend labels & colors, shared 1D Y-axis synchronization (restoring per-panel bounds when toggled off), axes figure label toggle (show_figure_label, default Off), warning-free gridlines (default Off), heatmap smoothing, and colorbar visibility. View options persist across restarts in MSettings (live_maps_view_options/*, debounced 250 ms save and exit flush) and cross-sync between Spectra and Maps workspaces. Each LiveMapSubpanel also embeds per-panel Rescale, Pan, and Zoom buttons synchronized bidirectionally with NoDoubleClickZoomToolbar (preserving legend double-click editing), supports dual-mode Copy (btn_copy: plain click copies the figure canvas at fixed copy_fig_width × copy_fig_height and copy_fig_theme; Ctrl + Click emits copy_data_requested(color_id) and copies the underlying tabular data as TSV via copy_df_to_clb() across 1D series, single/multi-1D profiles, and 2D (X, Y, Value) points backed by VMLiveMaps.get_2d_copy_points() with _grid/_extent fallback), swaps the 2D colormap picker on Row 2 for per-panel view-only 1D Normalization controls (btn_norm, norm_xmin, norm_xmax, backed by _normalize_1d_values() and normalized _get_primary_profile_values() / reset_view() + normalization_changed \(\rightarrow\) _sync_shared_y()) whenever 1D line plots are displayed, shares spatial geometry (compute_2d_spatial_geometry()), click/Ctrl+Click/marquee selection resolution (resolve_xy_selection() / resolve_1d_profile_selection()), and red selection overlays (MapCanvasSelector) with VMapViewer via map_selection.py whenever Pan/Zoom tools and legend boxes are inactive (routing VLiveMaps.spectra_selected through VWorkspaceMaps._on_live_maps_point_selection() to update VSpectraViewer, VMapViewer, dialog viewers, and all R/B/G panels without recalculating grids), while fast UI restyling (apply_view_options_fast()), @lru_cache mplstyle dicts (_get_cached_style_dict), settled-layout freezing (_on_canvas_draw / _request_relayout), and parented 35 ms coalesced redraw timers keep interactive option changes stall-free.
Range selector updates adaptively debounce (60–250 ms) during continuous motion and flush immediately on mouse release (VSpectraViewer.range_drag_finished \(\rightarrow\) VMLiveMaps.flush_pending()). During bracket dragging, RangeSelectorManager.render() updates existing Matplotlib artists in-place (set_animated(True) with Agg background blitting and temporary layout_engine suspension via SpectraRangeBracketMixin on VSpectraViewer plus horizontal clamping via transData.inverted()), while LiveMapSubpanel fast-path updates (update_series() / update_multi_profile()) cache theme/text-size/grid/X-domain signatures (_invalidate_style_caches()) and MapCanvasSelector.draw_1d_overlay() reuses existing 1D selection markers in-place to eliminate tick_params()/AutoLocator() redraw churn. Range selector artists use Matplotlib's ax.add_artist() so that ax.dataLim is never polluted, ensuring that the Rescale button (Ctrl+R) zooms exclusively to spectral data.
Centralized map type management: The selected_map_type attribute is the single source of truth for all viewers (main + dialogs). When the user changes the combobox in any viewer, _on_map_type_changed() updates all viewers synchronously, preventing drift.
VMapViewer — The Heatmap Canvas¶
Package: map_viewer/ (v_map_viewer.py, v_map_plot.py, v_map_data.py, v_map_interactions.py, map_selection.py)
The most complex View component (~1 300 lines). It renders both 2D rectangular maps and circular wafer maps. Features:
- Z-parameter combobox (Intensity / Area / any fit result column)
- X-range double slider (filters which wavenumbers contribute to Z)
- Outlier removal toggle
- Accurate Spatial Coordinate Placement: For regular Cartesian grids, renders via fast
imshowwith symmetric extent bounds. For irregular or scattered coordinates (such as wafer map files loaded in 2Dmap mode), automatically renders square pixel patches centered at each point's exact \((X, Y)\) coordinate viaPatchCollection, completely eliminating spatial drift between heatmap pixels and selection overlays. - Color-scale combobox (Linear / Log) in the options (
…) menu —_build_color_kwargs()returns amatplotlib.colors.LogNormfor "Log" (falling back to plain linearvmin/vmaxwhen the Z-range isn't strictly positive, since intensity/area are clipped>=0and fit parameters can be<=0); applies to both the 2Dmapimshowand the wafer griddataimshow - Interactive selection (click, rectangle drag, profile line)
- In-Place Artist Updates & Dataset Isolation: For parameter, X-range, or palette changes on the currently active map (
_last_rendered_map_name == map_df_name),_do_plot_heatmap_internal()fast-paths by updatingself.img(set_data/set_array,set_extent,set_clim) andself.cbar.update_normal(...)in-place, bypassing destructivefigure.clf(), subplot re-creation, and expensivetight_layout(). When switching between different map datasets or map types, a clean axes rebuild executes while reusing cached(heatmap_pivot, extent, vmin, vmax, grid_z, final_z_col, dx, dy)from_griddata_cache. - Fast Z-Range Slider Updates: Real-time slider drag events bypass cache key recomputations and map repaints, updating
set_clim()/set_norm()and colorbar directly in-place. - Vector Navigation Controls & Built-in Coordinates: Interactive navigation buttons (
btn_home/btn_rescale,btn_pan,btn_zoom) styled identically to SPECTROview toolbar controls (28x28,@surface_elevated, rounded corners) and vector SVG icons (Icons.rescale(),Icons.pan(),Icons.zoom()), replacing default matplotlib icons while maintaining bidirectional mode synchronization withNavigationToolbar2QT. The native matplotlib toolbar is completely hidden in the background, and live coordinates are rendered cleanly using a dedicated nativelbl_coordinateslabel (min-width: 180px,@text_secondary, right-aligned) without clipping or layout shifting. - Multi-viewer dialog spawning
VMapsList — The Maps List & Actions Panel¶
File: v_map_list.py
Displays loaded map names in an internal _ReorderableMapsList(QListWidget) (ExtendedSelection for Shift+Click / Ctrl+Click multi-selection with Primary focus tracking via maps_selection_changed(selected_names, primary_name), plus InternalMove drag-and-drop reordering emitting maps_order_changed(new_order) while ignoring external URL MIME drops so file drops propagate to parent windows). On internal drop, selection and Primary focus are preserved without transient selection churn and forwarded to VMWorkspaceMaps.reorder_maps(), which reorders self.maps, SpectraStore.reorder_maps(), and selected_map_names and refreshes both VMapsList and Live Maps without resetting VMapViewer. Paired with quick management buttons (View, Delete — prompting confirmation when deleting multiple selected maps, Export CSV) and unified spectra action buttons (Select All, Reinitialize, Fitting Statistics, Send to Spectra Workspace) targeting the Primary map and its spatially selected spectra.
VMapViewerDialog — Detachable Window¶
File: v_map_viewer_dialog.py
A QDialog wrapper around a second VMapViewer instance. Uses Qt.WindowStaysOnTopHint so the user can select pixels in the floating window while the main window shows the spectrum. Multiple dialogs can be open simultaneously, each showing a different Z-parameter on the same spatial data. Data is shared by reference — no duplication.
The Dual-Storage Pattern¶
The Maps workspace maintains two stores for the same data:
self.maps[map_name]— apd.DataFramewith columnsX, Y, w1, w2, ...(one row per spectrum). This is the legacy store populated at load time from the file parser.self.store.get_map_data(map_name)— theMapDatatensor block with all processing state.
The DataFrame is used for heatmap input (pivot table → imshow) and CSV export. The tensor block is used for all analysis operations (baseline, fitting, results collection). When saving processed data to CSV, save_current_map_to_csv() reads from md.x / md.Y (processed) rather than the raw DataFrame.
[!IMPORTANT] When a new developer is confused about "where is the data?", the answer is: both places, for different purposes. The DataFrame is the entry point from the file loader and the input to the heatmap pipeline. The tensor block is the source of truth for all analysis. Modifications (baseline, crop) only affect the tensor block — they do not update the DataFrame.
Filename Convention¶
Each spectrum row in a MapData block gets a unique fname constructed from its coordinates:
This convention is used throughout the codebase to:
- Filter spectra belonging to a specific map:
fname.startswith(f"{map_name}_(") - Extract coordinates from fnames: parse between
(and). - Match
SpectraStoreentries back toDataFramerows for heatmap rendering.
Coordinate parsing is centralized in parse_coords_from_fname() (viewmodel/common/spectral_utils.py, re-exported in viewmodel/utils.py); VWorkspaceMaps._extract_coords_from_fname() and VMWorkspaceMaps._extract_coords_for_spectra() both delegate to it. If you change the fname convention, update that single helper (and keep the float() formatting identical on the write side in _extract_spectra_from_map()).
Data Flow¶
Loading a Hyperspectral Map¶
- User Action: The user initiates a load map action in
VWorkspaceMaps. - View → ViewModel: The View calls
vm.load_map_files(paths). - File Parsing: For each file, the ViewModel delegates to the
m_iomodule (load_wdf_map,load_spc_map,load_l6m_map,load_ngc_map, etc.). The IO module returns a DataFrame containingX,Y, and all wavenumber columns, plus metadata. - Data Storage (Legacy): The ViewModel caches the returned DataFrame in
self.maps[name]. - Data Extraction: The ViewModel calls
_extract_spectra_from_map(name, map_df), which delegates toextract_map_arrays(name, map_df)inm_io.pyto extract thex0,Y0, and spatialcoordsarrays from the DataFrame and build the pixelfnameslist. - Data Storage (Tensor): The ViewModel registers the data in the
SpectraStoreviaadd_map(name, x0, Y0, coords, fnames, is_active). - UI Update: Once all files are processed, the ViewModel emits the
maps_list_changedsignal with the list of loaded map names.
extract_map_arrays() filters out any trailing or non-numeric Unnamed: columns while preserving all valid numeric wavenumber channels, and automatically appends _{k} suffixes to fnames only when duplicate (X, Y) spatial coordinates occur (e.g., time-resolved multi-scan maps at fixed wafer sites).
Map Selection¶
When the user clicks a map name in VMapsList or opens a new map:
- User Action: The user opens a map file or clicks a map name in the
VMapsListUI widget. - View → ViewModel: The View captures this and calls
vm.select_map(map_name). - State Update & Auto-Selection: The ViewModel sets
current_map_name = map_name, populates_show_map_spectra(map_name), and automatically selects the first spectrumself.selected_fnames = [md.fnames[0]], emittingspectra_selection_changedto immediately plot the first spectrum inVSpectraViewer. - Map Viewer Refresh: The ViewModel emits
map_data_updated(current_map_df). - Canvas Redraw & Selection Overlay:
VWorkspaceMapsforwards the updated data toVMapViewer.set_map_data(), which automatically highlights the first coordinate(x_0, y_0)with the red selection overlay and callsplot_heatmap()to render the spatial data. Floating viewer dialogs are kept in sync.
Fitting Workflow (Maps Override)¶
The Maps workspace overrides fit() to construct multi-task batches that can span the entire map:
- User Action: The user clicks "Fit" (or Ctrl+Fit to apply to all maps).
- Task Construction:
- If
apply_all = True: The ViewModel groups maps by x-axis length and stacks them into mega-batchYmatrices. - If
apply_all = False: The ViewModel builds a task for just the current map and selected indices.
- If
- Thread Launch: The ViewModel starts a
VBFthreadwith the task list. - Engine Execution (Background): For each task, the thread calls
VBFengine.fit_spectra(). Stacked multi-map tasks are fit as a single vectorized operation. - Result Storage (Background): The thread scatters results back to their respective maps via
SpectraStore.set_fit_results(). - Completion: The thread emits
finished(), and the ViewModel calls_on_fit_finished(). - Result Collection:
collect_fit_results()aggregates the results into a single DataFrame. - UI Refresh: Signals are emitted to redraw both the heatmap (
map_data_updated) and the results table (fit_results_updated).
Mega-batch grouping is the key performance optimization. When apply_all=True, maps with the same x-axis length are stacked into a single Y matrix and fit in one vectorized call. A 10-map wafer measurement that individually takes 30 s each can complete in ~35 s total when batched.
After Fitting: Propagating Results¶
After _on_fit_finished():
collect_fit_results()is called → buildsself.df_fit_results(DataFrame withX, Ycolumns + all fit columns).fit_results_updatedemitted →VFitResultstable updates.map_data_updatedemitted →VMapViewerre-readsdf_fit_resultsand adds fit columns to its Z-parameter combobox.clear_map_cache_requestedemitted →VMapViewerinvalidates itsgriddatacache for the affected map name.
Map Visualization Pipeline¶
- Data Source: Depending on preprocessing state, the source is either the processed intensities (
md.Y) or raw intensities (md.Y0). - DataFrame Filtering:
get_current_map_dataframe()filters out inactive spectra. - Viewer Binding: The DataFrame is passed to
VMapViewer.set_map_data(). - Z-Value Computation:
_compute_z_values()calculates the target metric based on the combobox selection:- Intensity: sums over the selected X-range slider.
- Area: calculates a trapezoidal integral.
- Fit parameter: retrieves values directly from
df_fit_results.
- Outlier Removal: Z-values are clipped using percentiles if the user toggles the feature.
- Rendering Logic: Depending on
map_type:- 2D map: Fast path. A pivot table maps
(X, Y)toZon an exact grid, rendered via Matplotlibimshow(). - Wafer map: Slow path.
scipy.griddatainterpolates irregular circular sites onto an 80×80 grid before rendering viaimshow().
- 2D map: Fast path. A pivot table maps
Why two rendering paths?
A 2D rectangular map has data on a regular grid — a pivot table suffices and renders in milliseconds. A wafer measurement has sites distributed across a circular region (not a grid), so scipy.griddata must interpolate onto a regular grid before imshow can render it. This is the expensive step.
Heatmap Caching Strategy¶
scipy.griddata can take 100–500 ms for large maps. The viewer uses a multi-key cache to avoid recomputation:
cache_key = (
map_name, # which map
parameter, # which Z parameter
(xmin, xmax), # X-range filter
map_type, # 2Dmap vs Wafer variant
mask_config, # mask settings or None
remove_outliers # outlier removal flag
)
The cache stores (heatmap_pivot, extent, vmin, vmax, grid_z, final_z_col, dx, dy), retaining exact pixel spatial dimensions (dx, dy) across map type switches and file selections to prevent cross-dataset geometry drift.
The cache is:
- Preserved across map switches — switching back to a previously viewed map is instant, restoring its exact spatial dimensions and griddata.
- Invalidated by name after fitting completes, via the
clear_map_cache_requestedsignal. - Not persisted across application sessions — it lives only in
VMapViewer._griddata_cache. - Dataset-isolated:
can_fast_updaterequires_last_rendered_map_name == map_df_nameand checksPatchCollectionpatch count, ensuring in-place artist updates only execute on the active dataset while dataset switches always trigger a clean redraw.
Interactive Selection¶
The VMapViewer supports three selection modes:
| Mode | Trigger | Behavior |
|---|---|---|
| Single click | Left-click on map | Selects nearest site, highlights with red rectangle |
| Rectangle drag | Click-and-drag | Selects all sites within dragged rectangle |
| Profile | Exactly 2 selected sites, 2D mode | Enables "Extract profile" button |
Selection in VMapViewer emits spectra_selected(list[tuple]). VWorkspaceMaps._on_map_viewer_selection() maps the (x, y) coordinates back to fnames and calls vm.set_selected_fnames(), which triggers _emit_selected_spectra() → VSpectraViewer redraws the selected spectrum.
Selected points are rendered as PatchCollection (one draw call for all rectangles) rather than individual add_patch() calls, giving O(1) rendering time regardless of selection size.
Template Method Overrides¶
The Maps workspace customizes the inherited bulk-operation pipeline via three hook methods. Understanding these is essential when debugging or extending bulk operations.
_get_target_mds(apply_all)¶
Determines which MapData objects a bulk operation targets.
apply_all |
Spectra workspace | Maps workspace |
|---|---|---|
False |
MapData blocks of selected spectra |
Current map's MapData block only |
True |
All MapData blocks in store |
All maps' MapData blocks |
This is why Ctrl+Subtract-Baseline in the Maps workspace subtracts from all spectra in the current map (not just selected ones) — the Maps override returns the entire map's MapData.
_on_map_data_changed(md, action)¶
Called after each individual MapData is modified within a bulk loop.
# Maps workspace override:
def _on_map_data_changed(self, md, action: str):
if action == "reinit_spectra":
self.store.clear_preprocess(md.name)
elif action in ("delete_baseline", "subtract_baseline", "apply_spectral_range"):
self.store.batch_preprocess(md.name, md.baseline_config, md.range_min, md.range_max)
elif action == "paste_peaks":
self._reconstruct_y_peaks(md)
# Always invalidate heatmap cache
self.clear_map_cache_requested.emit(md.name)
_post_bulk_action(apply_all, action)¶
Called once after all MapData objects have been processed. The Maps override refreshes fit results and re-emits the map view.
_emit_selected_spectra() Override¶
The Maps override builds a "type": "tensor" payload (shared x-axis batch) instead of the Spectra workspace's "type": "tensor_list" (independent arrays per spectrum):
# Maps workspace:
batch_data = {
'type': 'tensor',
'x': x, # shared float64[M_proc]
'y': Y, # float32[n_selected, M_proc]
'indices': indices, # which rows within the map
...
}
This lets VSpectraViewer render multiple map spectra using matrix operations rather than a Python loop.
Cross-Workspace Communication¶
Maps → Spectra Workspace¶
# User selects spectra in Maps workspace and clicks "Send to Spectra"
vm.send_selected_spectra_to_spectra_workspace()
For each selected spectrum:
- Builds a deep-copied payload dict (raw
x0,Y0,baseline_config,fit_model,range_min/max,is_subtracted). - Emits
send_spectra_to_workspace(payloads). main.pyconnects that signal to the Spectra ViewModel'sreceive_spectra(), which registers each payload as a new N=1MapDatablock in the Spectra workspace'sSpectraStore.
Deep copying prevents cross-workspace state pollution — editing the spectrum in the Spectra tab does not affect the original map.
Maps → Graphs Workspace (Profile Extraction)¶
When the user selects exactly 2 points in 2D map mode and clicks "Extract profile":
- User Action: The user selects exactly 2 points on a 2D map and clicks "Extract profile".
- View → ViewModel:
VMapViewersignalsextract_profile_requested(profile_name). - Extraction Logic:
VWorkspaceMapsdelegates to_extract_profile(), which constructs aprofile_dfdataframe by interpolating points along the line segment. - Forwarding Payload: The View passes the payload to
VMWorkspaceMaps.extract_and_send_profile_to_graphs(). - Workspace Transfer: The ViewModel directly invokes
VMWorkspaceGraphs.add_dataframe(). - UI Update: A signal instructs the main window to switch focus to the Graphs tab.
The profile DataFrame has columns distance (µm) and values (Z intensity). The Graphs workspace auto-creates a line plot from it.
Fit Results with Spatial Columns¶
collect_fit_results() overrides the parent to add spatial and zone columns:
# After super().collect_fit_results():
# base DataFrame includes: Filename, X, Y, [Quadrant, Zone for wafers],
# sorted fit parameters (x0_Peak1, fwhm_Peak1, area_Peak1, ...), and trailing R2
# Maps workspace adds X, Y, and ensures Quadrant and Zone are present for wafer maps
# Final columns:
# Filename | X | Y | Quadrant | Zone | x0_Peak1 | fwhm_Peak1 | area_Peak1 | ... | R2
Zone classifies by radial distance:
| Zone | Distance |
|---|---|
| Center | ≤ 35 % of radius |
| Mid-Radius | 35 – 80 % |
| Edge | ≥ 80 % |
Quadrant classifies by sign of (X, Y): Q1 (−,−), Q2 (−,+), Q3 (+,+), Q4 (+,−).
Persistence¶
Modern Format (v2+, ZIP-backed)¶
Maps workspace files (.maps) use the same ZIP structure described in SpectraStore: Persistence, with heavier content due to larger tensors.
Map DataFrames are serialized with a custom binary format for speed:
# Fast serialization (vs to_csv which is 20-70× slower)
arr = map_df.to_numpy()
buf = io.BytesIO(); np.save(buf, arr)
gzip.compress(buf.getvalue(), compresslevel=1) # level=1: 70× faster, ~5% larger
Legacy Loader¶
_load_legacy_maps() handles old .maps JSON files where each map was stored as a gzip+hex CSV string:
- Parses the top-level
"maps"dict (map_name → hex_string). - Decompresses and reads each CSV into a DataFrame.
- Builds a coordinate lookup dict from the
"spectrums_data"entries (keyed by(map_name, x, y)). - Registers each map into
SpectraStoreviaadd_map(). - Vectorized-restores baselines, peak curves, and fit results.
Extension Guide¶
Adding a New Map File Format¶
- Create a loader function in
spectroview/model/io/m_io.py(e.g.,load_xyz_map(path) → pd.DataFrame). - In
VMWorkspaceMaps.load_map_files(), add anelif path.suffix.lower() == '.xyz':branch. - The returned DataFrame must have
XandYcolumns followed by numeric wavenumber columns. - If the format provides metadata, return a
(DataFrame, dict)tuple and store the dict inself.maps_metadata[map_name].
Adding a New Z-Parameter Type¶
New Z-parameter types are computed in VMapViewer._compute_z_values(). To add, e.g., a peak ratio:
- Add the parameter name to the
VMapViewercombobox population logic. - In
_compute_z_values(), add anelif parameter == "My Ratio":branch that reads fromdf_fit_results. - The cache key already includes
parameter, so caching works automatically.
Adding a New Map Type (beyond Wafer)¶
New spatial layouts require:
- Add the type string to the
cbb_map_typecombobox. - In
VMapViewer.plot_heatmap(), add a rendering branch (likelyscipy.griddatawith a custom mask). - In
VMWorkspaceMaps.collect_fit_results(), add a zone/quadrant classification branch for the new type.
Troubleshooting¶
Heatmap does not update after fitting
collect_fit_results()must be called after_on_fit_finished(). Check thatclear_map_cache_requestedis emitted for the map name, and that the cache key'sparametermatches what is currently selected in the combobox.
Selected pixel does not highlight the correct spectrum
- The mapping from
(x, y)coordinates to fnames relies on the format{map_name}_(x, y)matchingmd.fnames. Check thatfloat(x_pos)renders the same string in_extract_spectra_from_map()and in_on_map_viewer_selection().
Fitting a large map freezes the UI briefly at start
- Task construction (
_run_fit_thread()) happens on the main thread beforeVBFthread.start(). For very large maps, thenp.arange(md.n_spectra)index build is fast, but thevstackof Y matrices can be slow. Profile the_run_fit_thread()call withcProfileif this becomes a bottleneck.
Send to Spectra creates duplicate spectra
- The Spectra ViewModel's
receive_spectra()checksname in self.store.map_namesbefore adding. If duplicates appear, check that the fname format is consistent (watch for floating-point rounding in(x_pos, y_pos)string representations).
Wafer griddata is slow on every redraw
- Ensure
clear_map_cache_requestedis only emitted when necessary (after fitting, not on every selection change). Check that thecache_keytuple is hashable and stable — if any element changes inadvertently between renders, the cache will never hit.
Memory spike when loading many large maps
- For a 50×50 map (2,500 spectra) at 1,000 wavenumbers,
MapData.Y0(float32) is ~10 MB; for a 25,000-spectrum map at 1,000 wavenumbers,Y0is ~100 MB, and fitting allocates additional arrays (Y_bestfitand oneY_peaksentry per peak). Useremove_map()for maps no longer needed.
For data-model troubleshooting (preprocessing not applied, memory management), see SpectraStore: Troubleshooting.