Skip to content

Application Architecture

This guide covers the technical architecture, code organization, and development patterns of SPECTROview. It is intended for developers who want to understand, maintain, or extend the application.


MVVM Pattern

SPECTROview enforces a strict Model-View-ViewModel architecture. Every workspace follows the same three-layer separation of concerns:

  • Model — Pure data containers and domain logic. Models hold no references to Qt widgets and can be tested independently.
  • ViewModel — Business-logic orchestrator. The ViewModel reads and mutates Models, then notifies the View through Qt signals. It never imports or references View classes.
  • View — Qt widget layer. Views connect to ViewModel signals and call ViewModel methods in response to user actions.
graph LR
    A["User Action"] --> B["View (v_*)"]
    B -->|"method call"| C["ViewModel (vm_*)"]
    C -->|"method call"| D["Model (m_*)"]
    D -->|"return data"| C
    C -->|"emit Signal"| B
    B -->|"update UI"| A

File Naming Convention

Layer Prefix Example
View v_ workspaces/v_workspace_spectra.py
ViewModel vm_ spectra/vm_workspace_spectra.py
Model m_ spectra/spectra_store.py

Import Rules

Layer Can Import Cannot Import
View ViewModel, Components —
ViewModel Model, fit_engine View
Model Standard libs only View, ViewModel

Signal/Slot Communication

Views and ViewModels communicate exclusively via Qt signals and slots. A ViewModel must never call View methods directly, and a View must never modify Model state without going through its ViewModel.

# ── ViewModel defines signals ──
class VMWorkspaceSpectra(QObject):
    spectra_list_changed = Signal(list)       # ViewModel → View
    fit_progress_updated = Signal(int, int, int, float, int)

# ── View connects in __init__ ──
class VWorkspaceSpectra(QWidget):
    def __init__(self):
        self.vm.spectra_list_changed.connect(self._update_list)

Project Structure

spectroview/
├── __init__.py             # Constants, peak models, resource paths, VERSION, BUILD_NUMBER
├── _build_info.py          # Build metadata, populated with timestamp during wheel/sdist packaging
├── main.py                 # Entry point, QMainWindow, cross-workspace wiring
├── application/            # API facade for the currently running desktop state
│   ├── service.py          # Dataset/spectra/fit/graph/map domain operations
│   ├── dispatch.py         # Queued Qt main-thread execution boundary
│   └── errors.py           # Stable integration error codes
│
├── i18n/                   # Centralized multilingual localization & live Qt bindings
│   ├── __init__.py         # Public tr/tr_plural & declarative bind_* exports
│   ├── manager.py          # TranslationManager singleton, JSON catalog loader & QTranslator lifecycle
│   ├── bindings.py         # Weak-ref widget/tab/combo/header live retranslation bindings
│   └── validator.py        # AST key extractor, catalog validator & untranslated UI literal audit
│
├── settings/               # Unified settings architecture (Model, ViewModel, & 2-panel Settings UI)
│   ├── m_settings.py          # Persistent app settings & portable config.json
│   ├── vm_settings.py         # Settings ViewModel & background LLM connection tester
│   ├── secrets.py             # Cross-platform obfuscated QSettings secret store (_credentials/)
│   ├── build_info.py          # Dual-mode runtime dependency resolution & build snapshot capture
│   └── ui/                    # Two-panel settings dialog with sidebar & instant search
│       ├── settings_dialog.py # Host dialog with sidebar navigation & instant search
│       ├── tab_general.py     # General preferences & Working Folder
│       ├── tab_fit.py         # Fitting solver convergence & peak bounds
│       ├── tab_ai.py          # LLM credentials, connection tests, & local MCP
│       └── tab_about.py       # Application details, Python env, & runtime package dependencies
│
├── model/                  # Data models organized by domain (no Qt widgets)
│   ├── m_settings.py       # Persistent app settings compatibility facade (wraps spectroview.settings)
│   ├── io/                 # File loaders & workspace serialization
│   │   ├── m_io.py         # Universal file loader dispatch & text/CSV readers
│   │   ├── m_wdf.py        # Renishaw WiRE WDF binary reader
│   │   ├── m_spc.py        # Galactic SPC binary reader
│   │   ├── m_l6s.py        # HORIBA LabSpec 6 (.l6s / .l6m) binary reader
│   │   ├── m_ngs.py        # HORIBA LabSpec 5 (.ngs / .ngc) binary reader
│   │   └── workspace_io.py # Unified serialization for Workspaces
│   ├── spectra/            # Spectral tensor store, metrics, & fit model models
│   │   ├── spectra_store.py       # Tensor-centric SpectraStore & MapData structures
│   │   ├── spectral_parameters.py # Vectorized raw spectral metrics (Area, Max, Pos_Max, Barycenter, FWHM)
│   │   ├── heatmap.py             # Pure-NumPy 2D heatmap grid interpolation & triangulation
│   │   ├── peak_model.py          # Helper functions for peak parameters
│   │   └── m_fit_model_manager.py # Saved fit model file management
│   ├── graphs/             # Graph schemas, recipes, & style templates
│   │   ├── m_graph.py                 # Plot configuration model (MGraph dataclass)
│   │   ├── graph_control.py           # Graph control & validation contract
│   │   ├── graph_style.py             # Graph styling & restyle-without-replot predicate
│   │   ├── m_plot_recipe.py           # Plot recipe dataclass (+ m_plot_recipe_store.py)
│   │   └── m_style_template_store.py  # Graph style template persistence
│   ├── analysis/           # Numerical analysis & calculator engines
│   │   ├── m_mva.py               # PCA + NMF engine
│   │   └── m_quick_calculators.py # Pure math logic for scientific calculators
│   └── system/             # Runtime environment, TLS, & update services
│       ├── m_tls.py              # Hardened TLS trust-store & certifi/pip validation
│       ├── m_installation.py     # Centralized runtime install detection (InstallType & InstallationManager)
│       ├── m_update_manager.py   # Multi-platform UpdateManager facade, ETag cache, SHA256SUMS
│       ├── m_update_checker.py   # Legacy pip/wheel QThread workers & detached upgrade helper
│       └── m_macos_font_patch.py # macOS font rendering compatibility patch
│
├── viewmodel/              # Business logic and data orchestration (PEP 562 lazy facade)
│   ├── spectra/            # Spectra workspace ViewModel & mixins
│   │   ├── vm_workspace_spectra.py     # Core workspace state, selection & I/O coordination
│   │   ├── vm_spectra_preprocessing.py # X/Y corrections, ROI crop, baseline & cosmic-ray removal
│   │   ├── vm_spectra_fitting.py       # Peak editing, fit-model clipboard/JSON & VBFthread launch
│   │   ├── vm_spectra_results.py       # Fit results collection, computed columns & Excel/clipboard export
│   │   ├── vm_spectra_persistence.py   # ZIP/NPZ workspace save/load & legacy v1 .spectra loader
│   │   └── vm_fit_model_builder.py     # Fit model file management orchestration
│   ├── maps/               # Maps workspace & Live Maps ViewModels
│   │   ├── vm_workspace_maps.py        # Maps workspace (extends VMWorkspaceSpectra)
│   │   ├── vm_maps_fitting.py          # Batch map fitting & wafer Zone/Quadrant post-processing
│   │   ├── vm_maps_persistence.py      # Legacy v1 .maps JSON loader
│   │   ├── vm_live_maps.py             # Live Maps state, debounce & synchronous evaluation
│   │   └── live_maps_worker.py         # Asynchronous _LiveMapWorker (QRunnable) & snapshot offload
│   ├── graphs/             # Graphs workspace ViewModel
│   │   ├── vm_workspace_graphs.py      # DataFrames, filtering, graph CRUD & persistence
│   │   └── graph_undo.py               # Whole-workspace snapshot undo/redo & batching mixin
│   ├── analysis/           # Numerical analysis orchestration
│   │   └── vm_mva.py                   # Multivariate analysis (PCA/NMF) orchestration
│   ├── common/             # Shared ViewModel utilities
│   │   ├── spectral_utils.py           # closest_index, parse_coords_from_fname, Fano & metadata helpers
│   │   ├── export_utils.py             # Excel, clipboard & figure file export
│   │   └── ui_utils.py                 # Notification, alert, icon & status-color adapters
│   ├── vm_settings.py      # Compatibility facade -> spectroview.settings.vm_settings
│   └── utils.py            # Backward-compatible re-export facade -> viewmodel.common & v_metadata_tooltip
│
├── ai_agent/               # AI Data Chat module (multi-provider; runtime-optional)
│   ├── __init__.py              # Module docstring, keeps import guarded
│   ├── m_llm_client.py          # Multi-provider LLM clients (Ollama/OpenAI/Anthropic) + QThread workers
│   ├── m_conversation.py        # Conversation model (+ m_conversation_store.py: history)
│   ├── m_prompt_manager.py      # System-prompt / rules / knowledge assembly
│   ├── mcp/server.py            # Shared FastMCP chat + full desktop tool profiles
│   ├── mcp/runtime.py           # Opt-in loopback Streamable HTTP lifecycle
│   ├── config/, prompts/, rules/, knowledge/, examples/, utils/  # Prompt assets + helpers (see ai_agent.md)
│   ├── vm_chat.py               # Chat ViewModel (prompt-tier selection, agentic loop)
│   └── v_chat_panel.py          # Embedded chat panel (+ v_history_dialog.py)
│
├── view/                   # Qt widgets and UI layout (PEP 562 lazy facade)
│   ├── __init__.py               # Lazy exports for workspaces, components & theme
│   ├── workspaces/               # Top-level workspace View packages
│   │   ├── __init__.py                # Lazy workspace exports
│   │   ├── v_workspace_spectra.py     # Spectra workspace View
│   │   ├── v_workspace_maps.py        # Maps workspace View (extends Spectra)
│   │   └── graphs/                    # Graphs workspace View package
│   │       ├── __init__.py            # Package exports (VWorkspaceGraphs, MdiSubWindow)
│   │       ├── v_workspace_graphs.py  # VWorkspaceGraphs orchestrator
│   │       ├── v_mdi_subwindow.py     # MdiSubWindow (rubber-band resize/move)
│   │       ├── v_graphs_ui.py         # GraphsUIMixin (panels, toolbars, shortcuts)
│   │       ├── v_graphs_dataframes.py # GraphsDataFramesMixin (DF selection & sync)
│   │       ├── v_graphs_mdi.py        # GraphsMdiMixin (MDI creation & layout)
│   │       └── v_graphs_actions.py    # GraphsActionsMixin (plot create/update/export/undo)
│   ├── components/               # Shared / reusable widgets (PEP 562 lazy facade)
│   │   ├── __init__.py                # Lazy subpackage exports + settings alias
│   │   ├── v_settings.py              # Fit/view settings dialog (compat shim)
│   │   ├── common/                    # Shell, notifications, calculators & shared widgets
│   │   │   ├── __init__.py
│   │   │   ├── v_menubar.py           # Main menu bar
│   │   │   ├── v_about.py             # About dialog
│   │   │   ├── v_update_banner.py     # Update notification banner widget
│   │   │   ├── v_notification.py      # Native floating notification badges & manager
│   │   │   ├── v_quick_calculators.py # Scientific calculators GUI
│   │   │   ├── customized_widgets.py  # Palette combobox, custom toolbar
│   │   │   └── markdown_utils.py      # Markdown spacing normalizer for Python-Markdown
│   │   ├── lists/                     # Spectral/map list, DataFrame table & tooltips
│   │   │   ├── __init__.py
│   │   │   ├── v_spectra_list.py      # Spectrum list with checkboxes
│   │   │   ├── v_map_list.py          # Loaded maps list panel (Two-Tier Selection)
│   │   │   ├── v_dataframe_table.py   # Generic DataFrame viewer
│   │   │   └── v_metadata_tooltip.py  # Metadata tooltip popup builder
│   │   ├── spectra_viewer/            # Spectra viewer package (1D, Heatmap, 3D, interactions)
│   │   │   ├── __init__.py            # Package exports (VSpectraViewer, FastLine3DCollection, etc.)
│   │   │   ├── common.py              # Palettes, style cache, filename tokens & 1D normalization
│   │   │   ├── v_spectra_viewer.py    # VSpectraViewer main widget, toolbar & theme
│   │   │   ├── v_spectra_options.py   # SpectraOptionsMenuMixin (options menu, sync & plot style)
│   │   │   ├── v_plot_1d.py           # SpectraPlot1DMixin (1D segments, shifts, fit overlays)
│   │   │   ├── v_plot_heatmap.py      # SpectraHeatmapMixin (2D series heatmap & Y-axis tokens)
│   │   │   ├── v_plot_3d.py           # FastLine3DCollection & SpectraPlot3DMixin
│   │   │   ├── v_interactions.py      # SpectraInteractionMixin (zoom, hover, peak drag, eraser)
│   │   │   └── v_spectra_legend_editor.py  # Batch legend editor dialog, color combo & mixin
│   │   ├── lower_tabs/                # Lower workspace tab panels package
│   │   │   ├── __init__.py            # Package exports (VFitModelBuilder, VPeakTable, VFitResults, VMVA, VMoreTab)
│   │   │   ├── v_fit_model_builder.py # Baseline + Peak + Fit controls
│   │   │   ├── v_peak_table.py        # Interactive peak parameter table
│   │   │   ├── v_fit_results.py       # Fit results DataFrame table
│   │   │   ├── v_mva.py               # PCA/NMF controls and tab coordinator
│   │   │   ├── v_mva_plots.py         # MVA _PlotTab widget & Matplotlib plotting mixin
│   │   │   └── v_moretab.py           # Metadata & normalization tab panel
│   │   ├── map_viewer/                # Map viewer package (2D/wafer heatmap, interactions, dialog)
│   │   │   ├── __init__.py            # Package exports (VMapViewer, VMapViewerDialog, selection helpers)
│   │   │   ├── map_selection.py       # Shared spatial geometry, selection resolution & overlay helper
│   │   │   ├── v_map_data.py          # MapDataProcessingMixin (griddata cache, mask, outlier, profile)
│   │   │   ├── v_map_plot.py          # MapPlotMixin (2D/wafer heatmap rendering, stats, profile overlay)
│   │   │   ├── v_map_interactions.py  # MapInteractionMixin (mouse selection, coordinates, copy)
│   │   │   ├── v_map_viewer.py        # VMapViewer main widget, toolbar, sliders & options menu
│   │   │   └── v_map_viewer_dialog.py # VMapViewerDialog detachable map viewer window
│   │   ├── rgb_live_maps/             # RGB range bracketing & Live Maps package
│   │   │   ├── __init__.py            # Package exports for RGB range selectors & Live Maps
│   │   │   ├── common.py              # Shared palettes, themes, view options & 1D norm helpers
│   │   │   ├── v_live_maps.py         # VLiveMaps multi-panel tab view & options menu
│   │   │   ├── v_live_maps_options.py # LiveMapsOptionsMenuMixin (legend & view options menu)
│   │   │   ├── v_live_map_subpanel.py # LiveMapSubpanel container widget
│   │   │   ├── v_live_map_1d.py       # LiveMap1DMixin (1D series & profile rendering)
│   │   │   ├── v_live_map_2d.py       # LiveMap2DMixin (2D heatmap rendering)
│   │   │   ├── v_live_map_selection.py # LiveMapSelectionMixin (point/marquee/legend selection)
│   │   │   ├── v_live_maps_legend_editor.py # LiveMapsLegendEditorDialog labels & colors editor
│   │   │   ├── v_range_selector.py    # VRangeSelectorPanel & RangeSelectorManager
│   │   │   └── v_range_bracket_mixin.py # SpectraRangeBracketMixin for VSpectraViewer
│   │   ├── graphs/                    # Graphs plotting, rendering, filtering & export package
│   │   │   ├── __init__.py
│   │   │   ├── v_graph.py             # VGraph widget orchestrator (restyle/replot/actions)
│   │   │   ├── v_graph_canvas.py      # _DebouncedFigureCanvas & _FastNavigationToolbar
│   │   │   ├── v_graph_breaks.py      # GraphBreakInsetMixin (broken & inset axes)
│   │   │   ├── v_graph_axes.py        # GraphAxesStyleMixin (limits, scales, ticks, theme)
│   │   │   ├── v_graph_annotations.py # GraphAnnotationMixin (8 annotation types & canvas drag)
│   │   │   ├── v_plot_renderer.py     # Stateless Matplotlib plot rendering engine (PlotRenderer)
│   │   │   ├── v_plot_spatial.py      # SpatialPlotMixin & WaferPlot (2Dmap / wafer rendering)
│   │   │   ├── graph_commit.py        # Graph state snapshot & undo/redo diff engine
│   │   │   ├── v_export_dialog.py     # Single- & batch-graph figure export dialogs
│   │   │   ├── v_multipanel_dialog.py # Multi-panel publication figure composer
│   │   │   ├── v_plot_recipe_dialog.py    # Plot Recipe manager dialog
│   │   │   ├── v_style_template_dialog.py # Graph Style Template manager dialog
│   │   │   └── v_data_filter.py       # Dynamic query filter panel
│   │   └── customize_graph/           # Graph customization dialog (two-panel Settings-like package)
│           ├── customize_graph_dialog.py     # CustomizeGraphDialog (two-panel host with search & live preview)
│           ├── common.py                     # NavItemDelegate and highlight styling helpers
│           ├── tab_general.py                # General & Typography tab (theme, grid, rotation, fonts, sorting)
│           ├── tab_axes_limits.py            # Axes & Limits tab (scales, limits, sliders, breaks)
│           ├── tab_ticks_spines.py           # Ticks & Spines tab (direction, format, minor ticks, borders)
│           ├── tab_secondary_inset.py        # Secondary & Inset tab (Y2/Y3/X2 twin axes, zoom insets)
│           ├── tab_legend_series.py          # Legend & Series tab (legend box, unify markers, series table)
│           ├── tab_plot_styles.py            # Plot Style & Fitting tab (style options, unified error bars, trendlines, histograms)
│           ├── tab_annotations.py            # Annotations tab (add, edit, list, canvas drag sync)
│           └── customize_annotation_dialogs.py  # EditLineDialog/EditTextDialog/ColorDelegate
│       └── theme/                     # Theme & font architecture (ThemeManager, tokens, palettes, fonts)
│           ├── manager.py             # Single owner of application-wide theme state
│           ├── fonts.py               # Cross-platform application font configuration (macOS/Windows/Linux)
│           ├── palettes.py            # QPalette builders for 5 canonical themes
│           ├── qss_template.py        # Parameterized QSS template
│           └── tokens.py              # ThemeTokens dataclass and presets
│
├── fit_engine/             # High-performance batch fitting
│   ├── vbf_engine.py            # Orchestrator (VBFengine)
│   ├── evaluator.py             # Parameter mapping (VBFevaluator)
│   ├── optimizer.py             # Batched Levenberg-Marquardt
│   ├── models.py                # Batched peak functions + Jacobians
│   ├── scalar_models.py         # Fallback scalar functions + PEAK_MODEL_REGISTRY
│   ├── vbf_thread.py            # QThread wrapper
│   ├── baseline.py              # Baseline algorithms (arPLS, airPLS, etc)
│   ├── noise.py                 # Noise estimation functions
│   └── weights.py               # Region-weighted fitting mask & weight computation
│
├── resources/              # Icons, fonts, localization catalogs, Matplotlib stylesheets
│   ├── icons/
│   ├── i18n/{fr,zh,de,ru}.json  # Translation catalogs (`strings`, `plurals`, `contexts`)
│   └── *.mplstyle
│
packaging/                  # Standalone platform build pipelines (reusing root main.spec)
├── windows/build_windows.py      # PyInstaller --onedir + Portable ZIP + Velopack vpk pack
├── macos/{build_dmg.py,build_dmg.sh,entitlements.plist}
└── linux/{build_linux.py,build_appimage.sh,build_deb.sh,spectroview.desktop}

Application Entry Point

spectroview/main.py creates the QMainWindow and instantiates all workspaces as tabs in a QTabWidget:

graph LR
    Main["main.py"] --> Tabs["QTabWidget"]
    Tabs --> S["Spectra"]
    Tabs --> M["Maps"]
    Tabs --> G["Graphs"]
    Main --> W["setup_connections()"]
    W -->|"inject ref"| M
    W -->|"signal"| S
    W -->|"signal"| Tabs

The setup_connections() method in main.py wires cross-workspace dependencies:

  • Maps → Graphs: VMWorkspaceMaps.set_graphs_workspace(v_graphs) injects a reference so Maps can send profiles and DataFrames directly to the Graphs workspace.
  • Maps → Spectra: main.py connects send_spectra_to_workspace to the Spectra ViewModel's receive_spectra(), which ingests deep copies of the selected map spectra into the Spectra tab's SpectraStore.
  • Fit Results → Graphs: Both Spectra and Maps emit fit_results_updated with a pd.DataFrame that can be forwarded to the Graphs workspace for statistical plotting.

Keeping the startup path lean

Importing main.py transitively imports every module reachable from it, and that import graph dominates startup time. Two families of packages are deliberately kept off that graph and imported at their point of use instead:

Package Import cost Where it is now imported
anthropic, openai, ollama, mcp ~4.5 s combined Main.open_ai_chat(), _load_*() in ai_agent/m_llm_client.py, MCPHub._open_session()
scipy.stats, scipy.interpolate, scipy.linalg ~1.3 s combined PlotRenderer._plot_histogram() / WaferPlot.plot(), SpectraStore.batch_preprocess(), VMMVA._build_from_all_maps(), build_heatmap_grid(), optimizer._batched_solve()

scipy carries an extra constraint: a purely lazy import just moves the stall to the first histogram or wafer render, which made opening a saved .graphs workspace visibly slower. Main.showEvent() therefore starts a daemon thread (_prewarm_heavy_imports) that imports the three scipy submodules right after the first paint — the window is up at ~2 s and scipy is warm ~1 s later, so every function-local import scipy... is a sys.modules hit by the time a user can trigger one. The LLM SDKs are deliberately not prewarmed: most sessions never open the chat, and the panel already shows a loading state.

Verify with python -X importtime -c "import spectroview.main" before adding a new module-level import of a heavy third-party package — if it isn't needed to paint the first window, defer it. tests/performance/test_startup_imports.py fails if one of these reappears on the startup path.


Data Lifecycle

Spectra: Loading → Processing → Fitting → Results

sequenceDiagram
    participant View
    participant VM as ViewModel
    participant Engine as FitEngine

    View->>VM: load_spectra(paths)
    VM-->>View: spectra_list_changed

    View->>VM: subtract_baseline(), add_peak()

    View->>VM: fit(apply_all)
    VM->>Engine: fit_spectra()
    Engine-->>VM: results
    VM-->>View: fit_results_updated

Maps: Loading → Extraction → Heatmap → Profile

sequenceDiagram
    participant View
    participant VM as ViewModel
    participant Viewer as MapViewer

    View->>VM: load_map_files(paths)
    VM-->>View: maps_list_changed

    View->>VM: select_map(name)
    VM-->>View: map_data_updated
    View->>Viewer: plot_heatmap()

    View->>VM: extract_profile()
    VM-->>View: switch_to_graphs_tab

Workspace Inheritance

VMWorkspaceMaps extends VMWorkspaceSpectra. This means every fitting, baseline, peak, and serialization feature available in the Spectra workspace is automatically available in the Maps workspace, with additional map-specific overrides:

classDiagram
    class VMWorkspaceSpectra {
        +store
        +fit()
        +save_work()
    }

    class VMWorkspaceMaps {
        +maps
        +load_map_files()
        +select_map()
    }

    class VMWorkspaceGraphs {
        +dataframes
        +graphs
        +create_graph()
    }

    VMWorkspaceSpectra <|-- VMWorkspaceMaps

Reusable Component System

Workspaces are composed from shared components that follow the same signal-based pattern:

Component File Purpose
VSpectraViewer spectra_viewer/v_spectra_viewer.py Matplotlib canvas package for 1D/Heatmap/3D spectrum display, zoom/pan, peak/baseline/eraser interaction
SpectraLegendEditorDialog spectra_viewer/v_spectra_legend_editor.py Transactional palette, legend-limit, label, and color editor (100-row batches)
VFitModelBuilder lower_tabs/v_fit_model_builder.py X-correction, spectral range, baseline, peaks, fit controls
VPeakTable lower_tabs/v_peak_table.py Editable table of peak parameters (center, FWHM, amplitude, bounds)
VMapViewer map_viewer/v_map_viewer.py Heatmap/wafer canvas with Z/X range sliders, mask, profile extraction
VMapViewerDialog map_viewer/v_map_viewer_dialog.py Detachable always-on-top window wrapping VMapViewer
VGraph graphs/v_graph.py Matplotlib graph widget supporting 10+ plot styles
VDataFilter graphs/v_data_filter.py Dynamic pandas .query() filter builder
VFitResults lower_tabs/v_fit_results.py Color-coded fit results table
VMVA lower_tabs/v_mva.py PCA/NMF controls and embedded plotting
VMoreTab lower_tabs/v_moretab.py Spectrum metadata display and Y-normalization controls
CustomizeGraphDialog customize_graph/customize_graph_dialog.py Singleton dialog for graph annotation, legends, and axis customization

Theme & Typography System

SPECTROview uses a centralised theme and typography architecture (spectroview/view/theme/):

  • ThemeManager (manager.py): Owns the canonical active theme state (dark, gray, light, classic_dark, classic_light), applies QPalette and parameterized stylesheets (qss_template.py), and manages runtime switching.
  • Vector SVG Icon Architecture (icons_svg.py & icons.py): Real-time vector rendering engine (_SvgIconEngine(QIconEngine)) replacing pre-rasterized PNGs with crisp vector rendering at 1:1 physical device pixels, dynamic paint-time color tinting to theme tokens, and a unified Icons facade.
  • Cross-Platform Fonts (fonts.py): setup_application_font(app) applies the platform-appropriate default font to QApplication:
  • Windows: Segoe UI at 10pt (standard 96-DPI Windows desktop font, ~13.3px).
  • macOS: .AppleSystemUIFont (San Francisco) at 13pt (standard 72-DPI Apple HIG font, 13px).
  • Linux / Other: Desktop environment sans-serif font at >= 10pt.
  • DPI & Sizing Invariant: By avoiding universal QWidget { font-size: ... } in stylesheets, theme switches avoid expensive font-cache invalidation bottlenecks. Controls inherit their size from the application font, preserving native readability, standard menu metrics, and seamless multi-monitor DPI scaling across platforms.

Persistence & Serialization

SPECTROview delegates all loading and saving operations to the unified WorkspaceIO class (model/io/workspace_io.py), which isolates IO logic from the ViewModels. Each workspace uses its own save/load format via WorkspaceIO:

Workspace File Extension Key Strategy
Spectra .spectra ZIP archive (format_version: 2): metadata.json (store_meta per map) + per-map NPZ arrays. Written by the unified WorkspaceIO.save_workspace().
Maps .maps Same unified ZIP format as .spectra (WorkspaceIO.save_workspace()), whose metadata additionally carries maps_metadata, map_type, and the fit-results DataFrame.
Graphs .graphs ZIP archive (format_version: 4) via WorkspaceIO.save_workspace(): metadata.json (plots + DataFrame sources) + compressed DataFrames.

Spectrum Serialization Flow

# Save (format_version 2): SpectraStore → ZIP archive (metadata.json + NPZ arrays)
metadata = {
    "format_version": 2,
    "store_meta": {                 # keyed by map name (== fname for single spectra)
        "sample_001": {
            "fnames": ["sample_001"],
            "is_active": [True],
            "baseline_config": {...},
            "peak_params": [...],
            "range_min": None, "range_max": None,
            # ...
        }
    }
}
# arrays: per-map NPZ blocks produced by SpectraStore.to_npz_dict(map_name)
# (raw x0 float64 axis + Y0 float32 intensities, plus any processed/fit arrays)

Threading Model

Long-running operations run on QThread subclasses to prevent UI freezing. All threads emit progress signals that the ViewModel relays to the View's progress bar:

Thread Class Location Purpose
VBFthread fit_engine/vbf_thread.py Batched fitting (primary engine)
_LiveMapWorker viewmodel/maps/live_maps_worker.py Asynchronous QRunnable (QThreadPool) for Live Maps computation on large datasets (\(\ge 25,000\) spectra)
UnifiedUpdateCheckWorker / UnifiedUpdateDownloadWorker model/system/m_update_manager.py Multi-platform release checks (ETag cached) and SHA-256 verified downloads
UpdateCheckerWorker model/system/m_update_checker.py Legacy pip/wheel background checker & updater (backward compatibility)
LLMWorker / APIWorker / AnthropicWorker ai_agent/m_llm_client.py Streaming chat requests for AI Data Chat — one worker per backend (Ollama / OpenAI-compatible / Anthropic)
_ConnectionTestWorker settings/vm_settings.py Non-blocking background LLM provider connection verification

Thread lifecycle:

  1. ViewModel instantiates the thread and connects finished / progress signals.
  2. Thread .start() — runs run() on a separate OS thread.
  3. On completion, the finished signal triggers _on_fit_finished() in the ViewModel.
  4. ViewModel emits result signals → View updates UI.

Cross-Workspace Communication

SPECTROview avoids a global event bus. Instead, main.py uses dependency injection and direct signal connections:

# main.py → setup_connections()
# 1. Inject reference: Maps VM can call Graphs workspace methods
self.v_maps_workspace.vm.set_graphs_workspace(self.v_graphs_workspace)

# 2. Maps → Spectra: ingest spectra sent from the Maps workspace
self.v_maps_workspace.vm.send_spectra_to_workspace.connect(
    self.v_spectra_workspace.vm.receive_spectra
)

# 3. Signal: Maps requests tab switch after sending profile
self.v_maps_workspace.vm.switch_to_graphs_tab.connect(
    lambda: self.tabWidget.setCurrentWidget(self.v_graphs_workspace)
)

Global Constants (__init__.py)

spectroview/__init__.py defines application-wide constants:

Constant Purpose
VERSION, BUILD_NUMBER Application semantic version and immutable build timestamp
PEAK_MODELS Registered peak shapes (Lorentzian, Gaussian, PseudoVoigt, GaussianAsym, LorentzianAsym, Fano, DecaySingleExp, DecayBiExp)
PLOT_STYLES Available graph types (point, scatter, box, bar, line, trendline, histogram, wafer, 2Dmap)
PALETTE, DEFAULT_COLORS, MARKERS Colormaps, 20-color publication-safe default cycle, and Matplotlib marker styles
X_AXIS_UNIT, Y_AXIS_UNIT Axis label registries
AXIS_LABELS Autocomplete suggestions for graph labels
ICON_DIR Resolved path to resources/icons/
PLOT_POLICY_LIGHT, PLOT_POLICY_DARK Matplotlib stylesheet paths

Multi-Platform Update & Packaging Architecture

Overview

SPECTROview exposes a unified installation-detection and update facade (UpdateManager in model/system/m_update_manager.py) backed by InstallationManager (model/system/m_installation.py) and centralized TLS hardening (model/system/m_tls.py). Users receive the same banner, ETag-cached release check, pre-release toggle, and SHA256SUMS.txt integrity verification workflow across every distribution target without needing to understand how SPECTROview was installed.

Key Files

File Role
model/system/m_tls.py Pure-model CA trust enforcement (GHSA-6q48-6c7w-9gw2): SSL_CERT_FILE/REQUESTS_CA_BUNDLE → OS truststore → validated certifi >= 2026.10.23 (pip >= 26.2.2 build gate)
model/system/m_installation.py Pure-model InstallType classifier (DEV_SOURCE, PIP_WHEEL, WINDOWS_VELOPACK, WINDOWS_PORTABLE, MACOS_BUNDLE, LINUX_APPIMAGE, LINUX_DEB, STANDALONE_UNKNOWN)
model/system/m_macos_font_patch.py macOS font cache discovery patch intercepting system_profiler SPFontsDataType to prevent upstream matplotlib KeyError: '_items' crash and 10s freeze
model/system/m_update_manager.py GitHubReleaseClient (ETag + TTL cache), UpdateManager facade, UnifiedUpdateCheckWorker, UnifiedUpdateDownloadWorker, and platform updaters
model/system/m_update_checker.py Legacy pip/wheel workers preserved cleanly plus hardened pip upgrade runner (--use-feature=truststore / --cert)
view/components/common/v_update_banner.py Slim banner displaying version transition (current → latest) and dynamic platform action label
main.py Executes early _run_velopack_bootstrap() hook before QApplication only when Velopack is active; wires unified update banner & guided dialogs
main.spec & packaging/ Single-source PyInstaller config and platform builders for Windows (Setup.exe + Portable.zip), macOS (Apple Silicon arm64 .dmg), and Linux (.AppImage + .deb)

Platform Update Matrix & Design Rationale

InstallType Detection Basis Update Backend & Mechanism
DEV_SOURCE Unfrozen + .git / pyproject.toml / PEP 610 editable metadata UnsupportedUpdater: version notification only — never modifies dev checkouts
PIP_WHEEL Unfrozen site-packages install PythonUpdater: downloads SHA-256 verified .whl, launches detached hardened-TLS pip install --upgrade, restarts
WINDOWS_VELOPACK Frozen Windows inside current/ with Update.exe or sq.version WindowsVelopackUpdater: downloads releases.win.json & delta/full .nupkg in Python using hardened m_tls (bypassing Rust webpki-roots inside velopack 1.2.161), then passes local directory ONLY to velopack.UpdateManager
WINDOWS_PORTABLE Frozen Windows outside Velopack layout WindowsPortableUpdater: downloads & verifies Portable.zip, offers zip-slip-checked Extract to Folder...
MACOS_BUNDLE Frozen macOS inside *.app/Contents/MacOS MacOSUpdater: downloads verified arm64 .dmg (discontinued Intel x64 hosts do not download incompatible arm64 binaries) and presents Control-click Gatekeeper guidance (silent replacement deferred until Apple Developer ID signing/notarization is configured)
LINUX_APPIMAGE Frozen Linux with $APPIMAGE matching $APPDIR LinuxAppImageUpdater: checks ELF header & SHA-256; atomic mv swap + relaunch via shlex.quote script when $APPIMAGE is writable, guided download otherwise
LINUX_DEB Frozen Linux with /opt/spectroview/ or .spectroview-deb marker LinuxDebUpdater: verifies !<arch>\n + SHA-256 and provides one-click copyable sudo apt install command

Multi-Platform Release Automation (.github/workflows/release.yml)

Pushing a release tag (vMAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH-rc.N matching spectroview.VERSION) triggers a unified Python 3.14 workflow:

  1. verify: Validates tag/version parity, enforces pip>=26.2.2 and certifi>=2026.10.23, and runs the headless unit/startup-import suites.
  2. Parallel platform builders:
  3. build-python: .whl + .tar.gz, twine check, and clean venv wheel detection verification.
  4. build-windows: PyInstaller (--onedir) + offscreen smoke test + Portable.zip + Velopack vpk pack (Setup.exe, releases.win.json, *.nupkg, chaining delta history).
  5. build-macos (macos-15 arm64): Native Apple Silicon .app + .dmg build with PyInstaller runtime hook and offscreen --smoke-test verification (env-gated optional APPLE_SIGNING_IDENTITY / APPLE_CERTIFICATE_P12 / APPLE_ID notarization hooks ready when credentials are added).
  6. build-linux (ubuntu-22.04 glibc baseline): Builds .AppImage and .deb, validates .desktop, and runs live apt-get install, offscreen launch, AppImage launch, and config persistence (~/.config/CEA-Leti/) checks.
  7. release: Publishes unified GitHub Release with SHA256SUMS.txt (marking pre-releases automatically).
  8. publish-pypi: On stable releases, preserves the existing PyPI Trusted Publisher (pypi environment, id-token: write, pypa/gh-action-pypi-publish@release/v1).

Before the first PyPI release on a new fork/repository, register a Trusted Publisher for CEA-MetroCarac/SPECTROview in PyPI with workflow filename release.yml and environment pypi.


Internationalization (i18n)

SPECTROview provides live multilingual GUI localization across English ("en", default), French ("fr"), Simplified Chinese ("zh", zh_CN), German ("de", de_DE), and Russian ("ru", ru_RU) via spectroview/i18n/:

  • TranslationManager (manager.py): Singleton holding the active language (get_language() / set_language()), JSON catalogs (spectroview/resources/i18n/<lang>.json), locale-aware tr() / tr_plural() (including Chinese 1-form, French/German 2-form, and Russian 3-form Slavic pluralization), and Qt's QTranslator (qtbase_fr.qm, qtbase_zh_CN.qm, qtbase_de.qm, qtbase_ru.qm) without mutating QLocale (keeping dot . decimal parsing intact in scientific spinboxes).
  • Live Bindings (bindings.py): Weak-referenced declarative helpers (bind_text, bind_tooltip, bind_placeholder, bind_title, bind_window_title, bind_tab_text, bind_header_labels, bind_combo_items, on_language_changed) re-apply labels on set_language() while preserving canonical keys in Qt.UserRole (itemData) via combo_data_or_text() / set_combo_by_data_or_text().
  • Validation & Audit (validator.py): validate_catalog(...) verifies catalog completeness, per-language plural form counts (expected_plural_forms()), and placeholder parity across "fr", "zh", "de", and "ru", while audit_untranslated_ui_literals() scans active View/Settings/AI UI modules via AST (enforced in tests/unit/test_i18n.py).
  • Extending to a New Language: Register (code, native_name) in SUPPORTED_LANGUAGES, add spectroview/resources/i18n/<code>.json (plus optional qtbase_*.qm candidates), and update _plural_index() / expected_plural_forms() if plural rules differ.

Deep-Dive Documentation

Topic Page Summary
Data Architecture: SpectraStore spectra_store.md MapData, MapInfo, SpectrumProxy, data hierarchy, preprocessing pipeline, persistence
Spectra Workspace spectra.md VMWorkspaceSpectra, spectrum lifecycle, baseline/peak pipeline, fit model management
Maps Workspace maps.md VMWorkspaceMaps, hyperspectral data loading, heatmap rendering, coordinate handling
Graphs Workspace graphs.md VMWorkspaceGraphs, DataFrame management, plot creation, VGraph rendering
Vectorized Batch Fit Engine (VBF Engine) vbf_engine.md Batched LM optimizer, analytical Jacobians, adding new peak models
Multivariate Analysis mva.md PCA/NMF implementation, data pipeline, export to Graphs
AI Data Chat ai_agent.md Multi-provider LLM chat (Ollama/OpenAI/Anthropic/…), MCP tool calling, system prompt, Graphs workspace integration

Running & Testing

# Run from source
python -m spectroview.main

# Install in editable mode with dev dependencies
pip install -e ".[dev]"

# Run fast test suite (skips slow real-data benchmarks; headless offscreen auto-configured)
pytest tests/ -m "not slow" -q

# Run full test suite (including real benchmark datasets; ~7-8 min)
pytest tests/ -q

# Static syntax & import check on modified files
python -m pyflakes spectroview/<modified_file>.py

# Build and preview documentation
mkdocs serve

[!NOTE] For detailed developer and pair programming guidelines, refer to the AI Development Framework (AGENTS.md) and the test suite guide in tests/README.md.


Dependencies

Package Constraint Purpose
PySide6 — Qt 6 bindings (not PyQt)
matplotlib &ge; 3.8.0, < 3.10.9 Plotting backend for spectra and maps
numpy &ge; 2.0.2 Numerical array operations (NumPy 2.x)
scipy — Interpolation, KDTree, SVD
pandas — DataFrame management
superqt — Enhanced Qt widgets (range sliders)
ollama / openai / anthropic / mcp ollama ≥ 0.4, mcp ≥ 2.2 LLM backends + Model Context Protocol for AI Data Chat. Core dependencies (no [ai] extras group) — a plain pip install includes them; the feature is only optional to use at runtime.
truststore / certifi truststore ≥ 0.9.0, certifi ≥ 2026.10.23 Hardened TLS verification routing through the host OS trust store first and patched certifi fallback (GHSA-6q48-6c7w-9gw2); import is guarded
velopack / pyinstaller (optional [standalone]) velopack ≥ 1.2.161, pyinstaller ≥ 6.10.0 Standalone desktop bundling & Windows Velopack installer/updater runtime hooks