Skip to main content

MLCore Widget

Qt widget for interactive supervised and unsupervised ML workflows

Overview

MLCore_Widget (src/WhiskerToolbox/MLCore_Widget/) is a Qt6 widget providing an interactive GUI for machine learning workflows. It exposes the MLCore library’s classification, clustering, and dimensionality reduction pipelines through a tab-based interface with panel-per-step layout.

Architecture

The widget follows the self-contained tool widget pattern:

  • Single widget (no view/properties split)
  • Zone::Right placement as a tabbed panel
  • EditorState-backed serializable configuration
  • Background pipeline execution via QThread
MLCore_Widget/
├── MLCoreWidget.hpp/.cpp                    # Top-level tab widget
├── MLCoreWidgetRegistration.hpp/.cpp        # EditorRegistry registration
├── Core/
│   ├── MLCoreWidgetState.hpp/.cpp           # EditorState subclass
│   └── MLCoreWidgetStateData.hpp            # reflect-cpp POD state
└── UI/
    ├── FeatureSelectionPanel/
    │   └── FeatureSelectionPanel.hpp/.cpp/.ui   # Feature tensor selection
    ├── RegionSelectionPanel/
    │   └── RegionSelectionPanel.hpp/.cpp/.ui    # Training/prediction region
    ├── LabelConfigPanel/
    │   └── LabelConfigPanel.hpp/.cpp/.ui        # Label source configuration
    ├── ModelConfigPanel/
    │   └── ModelConfigPanel.hpp/.cpp/.ui        # Algorithm & parameter selection
    ├── PredictionPanel/
    │   └── PredictionPanel.hpp/.cpp/.ui         # Prediction region & output config
    ├── ResultsPanel/
    │   └── ResultsPanel.hpp/.cpp/.ui            # Classification results display
    ├── ClusteringPanel/
    │   └── ClusteringPanel.hpp/.cpp/.ui         # Clustering data & algorithm config
    ├── ClusterOutputPanel/
    │   └── ClusterOutputPanel.hpp/.cpp/.ui      # Clustering results display
    └── DimReductionPanel/
        └── DimReductionPanel.hpp/.cpp/.ui       # Dim reduction config & results

Dependencies

MLCore_Widget
├── Qt6::Widgets, Qt6::Core, Qt6::Gui
├── EditorState (public)
├── MLCore (private)
├── DataManager (private)
├── GroupManagementWidget (private — for GroupManager color integration)
└── reflectcpp (state serialization)

Widget State

MLCoreWidgetStateData holds all persistent configuration as a reflect-cpp POD struct:

Classification State

Field Type Description
feature_tensor_key string DataManager key for TensorData features
training_region_key string DigitalIntervalSeries key for training region
prediction_region_key string DigitalIntervalSeries key for prediction region
label_source_type string "intervals", "groups", or "entity_groups"
label_interval_key string Interval series key (interval mode)
label_positive_class_name string Positive class name (interval mode)
label_negative_class_name string Negative class name (interval mode)
label_group_ids vector<uint64_t> Group IDs (group modes)
label_data_key string Data key (entity_groups mode)
selected_model_name string Registry model name
model_parameters_json string Serialized model parameters
balancing_enabled bool Class balancing toggle
balancing_strategy string "subsample" or "oversample"
balancing_max_ratio double Majority-to-minority ratio
output_prefix string Prefix for output data keys
probability_threshold double Binary classification threshold
output_probabilities bool Write probability AnalogTimeSeries
output_predictions bool Write prediction DigitalIntervalSeries

Clustering State

Field Type Description
clustering_tensor_key string TensorData key for clustering features
clustering_model_name string Clustering algorithm name
clustering_output_prefix string Output prefix (e.g., "Cluster:")
clustering_write_intervals bool Write cluster intervals
clustering_write_probabilities bool Write soft probabilities (GMM)
clustering_zscore_normalize bool Z-score normalize before clustering

Dim Reduction State

Field Type Description
dim_reduction_tensor_key string TensorData key for dim reduction
dim_reduction_model_name string Algorithm name (default: "PCA")
dim_reduction_output_key string Output TensorData key (default: "reduced")
dim_reduction_n_components int Number of output components (default: 2)
dim_reduction_zscore_normalize bool Z-score normalize before reduction (default: true)
dim_reduction_supervised bool Supervised mode toggle (default: false)
dim_reduction_label_source_type string "intervals", "groups", "entity_groups", or "events"
dim_reduction_label_interval_key string Interval series key (interval mode)
dim_reduction_label_positive_class string Positive class name (interval mode, default: "Inside")
dim_reduction_label_negative_class string Negative class name (interval mode, default: "Outside")
dim_reduction_label_event_key string Event series key (events mode)
dim_reduction_label_group_ids vector<uint64_t> Group IDs (group modes)
dim_reduction_label_data_key string Data key (entity_groups mode)
dim_reduction_training_region_key string DigitalIntervalSeries key for training region (supervised)

UI State

Field Type Description
active_tab int Active workflow tab (0=classification, 1=clustering, 2=dim reduction)

Classification Tab

Panel Layout

┌─── Features ──────────────────────────────────┐
│ Feature Tensor: [combo ▼]  shape, columns     │
└───────────────────────────────────────────────┘
┌─── Training Region ──────────────────────────┐
│ Interval Series: [combo ▼]  frame count       │
└───────────────────────────────────────────────┘
┌─── Labels ───────────────────────────────────┐
│ Source: ○ Intervals  ● Groups  ○ Entity Groups│
│ (dynamic form based on selection)             │
└───────────────────────────────────────────────┘
┌─── Model ────────────────────────────────────┐
│ Task: [combo ▼]  Algorithm: [combo ▼]         │
│ Parameters: (stacked per-model widgets)       │
│ Balancing: ☐ Enabled  Strategy  Ratio         │
│ [Train Model]                                 │
└───────────────────────────────────────────────┘
┌─── Prediction ───────────────────────────────┐
│ Region: [combo ▼]  ☐ All frames               │
│ Threshold: [slider/spinbox]                   │
│ ☐ Probabilities  ☐ Predictions                │
│ [Predict]                                     │
└───────────────────────────────────────────────┘
┌─── Results ──────────────────────────────────┐
│ Metrics display, confusion matrix,            │
│ clickable output data keys                    │
└───────────────────────────────────────────────┘

Sub-Panels

Panel Purpose
FeatureSelectionPanel Combo box listing TensorData keys. Shows column names, row count, row type, time frame info.
RegionSelectionPanel Combo box for DigitalIntervalSeries keys. Shows frame count. “All frames” checkbox.
LabelConfigPanel Radio buttons for label source. Dynamic stacked form per mode. Class name editing.
ModelConfigPanel Task type → model filter. Stacked parameter widgets per model. HMM page includes diagonal covariance checkbox. Class balancing config. Train button.
PredictionPanel Prediction region selection. Threshold slider + spinbox. Output type checkboxes. Constrained decoding checkbox (visible only for sequence models). Predict button.
ResultsPanel Displays ClassificationPipelineResult. Metrics, confusion matrix, clickable output keys.

Clustering Tab

Panel Layout

┌─── Data Source ──────────────────────────────┐
│ TensorData: [combo ▼]  shape, columns, type   │
│ ☐ Z-score normalize                          │
└───────────────────────────────────────────────┘
┌─── Algorithm ────────────────────────────────┐
│ [combo ▼]  (per-algorithm parameters)         │
│ Output prefix: [text]                         │
│ ☐ Write intervals  ☐ Write probabilities      │
│ [Fit & Assign]                                │
└───────────────────────────────────────────────┘
┌─── Output ───────────────────────────────────┐
│ Cluster table, noise info, created keys       │
│ Color swatches from GroupManager              │
└───────────────────────────────────────────────┘

Sub-Panels

Panel Purpose
ClusteringPanel TensorData selection, algorithm combo filtered to MLTaskType::Clustering, per-algorithm parameter stack, normalization option, output config.
ClusterOutputPanel Algorithm summary, cluster assignment table with counts and fractions, noise point info, clickable output keys with color swatches.

Dim Reduction Tab

Panel Layout

The Dim Reduction tab supports both unsupervised (PCA, t-SNE, Robust PCA) and supervised (Logit Projection) modes, controlled by radio buttons at the top.

Unsupervised Mode (default)

┌─── Mode ─────────────────────────────────────┐
│ ● Unsupervised  ○ Supervised                  │
└───────────────────────────────────────────────┘
┌─── Data Source ──────────────────────────────┐
│ TensorData: [combo ▼]  shape info label       │
│ ☐ Z-score normalize                          │
└───────────────────────────────────────────────┘
┌─── Algorithm ────────────────────────────────┐
│ Algorithm: [combo ▼]  Components: [spinbox]   │
└───────────────────────────────────────────────┘
┌─── Output ───────────────────────────────────┐
│ Output key: [text]                            │
│ [Run Reduction]                               │
└───────────────────────────────────────────────┘
┌─── Results ──────────────────────────────────┐
│ Observations, features, dropped rows          │
│ Explained variance per component              │
└───────────────────────────────────────────────┘

Supervised Mode

When “Supervised” is selected, the algorithm list switches to MLTaskType::SupervisedDimensionalityReduction (Logit Projection) and a Labels section appears for configuring label assembly.

┌─── Mode ─────────────────────────────────────┐
│ ○ Unsupervised  ● Supervised                  │
└───────────────────────────────────────────────┘
┌─── Data Source ──────────────────────────────┐
│ TensorData: [combo ▼]  shape info label       │
│ ☐ Z-score normalize                          │
└───────────────────────────────────────────────┘
┌─── Algorithm ────────────────────────────────┐
│ Algorithm: [combo ▼]  Components: [spinbox]   │
└───────────────────────────────────────────────┘
┌─── Labels ───────────────────────────────────┐
│ Source: [combo ▼ Interval Series]             │
│   Interval Key: [combo ▼]                     │
│   Positive class: [text]  Negative: [text]    │
│  ── OR ──                                     │
│ Source: [combo ▼ Entity Groups]               │
│   Group: [combo ▼] [+] [-]                    │
│   Class 0: "Contact" (50 entities)            │
│   Class 1: "No Contact" (50 entities)         │
│  ── OR ──                                     │
│ Source: [combo ▼ Event Series]                │
│   Event Key: [combo ▼]                        │
└───────────────────────────────────────────────┘
┌─── Training Region ─────────────────────────┐
│ ☐ Use all frames                              │
│ Interval: [combo ▼]                           │
└───────────────────────────────────────────────┘
┌─── Output ───────────────────────────────────┐
│ Output key: [text]                            │
│ [Run Reduction]                               │
└───────────────────────────────────────────────┘
┌─── Results ──────────────────────────────────┐
│ Total observations, training observations,    │
│ features, output dims, dropped rows,          │
│ unlabeled count, classes, class names          │
└───────────────────────────────────────────────┘

The Training Region group is only visible in supervised mode. When “Use all frames” is checked, training_interval_key is left empty and all labeled rows are used for fitting. When unchecked, the combo populates with DigitalIntervalSeries keys from DataManager, and only labeled rows whose TimeFrameIndex falls within the selected interval are used for fitting. Transform is still applied to all valid rows.

Sub-Panel

Panel Purpose
DimReductionPanel TensorData selection, mode toggle (unsupervised/supervised), algorithm combo filtered by task type, n_components spinbox, z-score checkbox, label source configuration (supervised mode), output key, run button. Shows explained variance ratio per component (unsupervised) or class-specific training stats (supervised) after completion.

Label Source Configuration (Supervised Mode)

The supervised label configuration reuses the same 4 label assembly modes as the Classification tab’s LabelConfigPanel, presented through a QStackedWidget controlled by the label source combo box:

Mode Config Widgets
Interval Series Interval key combo, positive/negative class name text fields
Entity Groups Group selection combo + Add/Remove buttons, class assignment list
Data Entity Groups Data key combo, group selection combo + Add/Remove buttons
Event Series Event key combo

Auto-Focus

After a successful dim reduction, the output TensorData key is broadcast via SelectionContext::setDataFocus(). This causes DataFocusAware widgets (ScatterPlotWidget, DataInspector, etc.) to update automatically.

Pipeline Execution

All three pipelines (four including supervised dim reduction) run asynchronously in a QThread background worker:

  1. UI panels are disabled during execution
  2. Progress callback updates a status label and indeterminate progress bar
  3. On completion, results are displayed in the output panel
  4. On failure, an error message is shown
  5. Deferred writes are committed on the main thread for thread safety

The _runPipelineAsync() / _runClusteringPipelineAsync() / _runDimReductionPipelineAsync() / _runSupervisedDimReductionPipelineAsync() methods assemble the config from panel state, spawn a worker thread, and connect completion signals.

SelectionContext Integration

MLCoreWidget inherits the DataFocusAware mixin for bidirectional awareness:

Incoming

When another widget focuses a TensorData key via SelectionContext, the FeatureSelectionPanel auto-selects it. This lets users click a tensor in DataInspector and have it appear in ML Workflow.

Outgoing

  • Clicking an output data key in ResultsPanel or ClusterOutputPanel calls SelectionContext::setDataFocus so other widgets (DataViewer, DataInspector) navigate to that output.
  • Clicking a putative group entry calls SelectionContext::setSelectedEntities() to highlight the group’s entities across all widgets.

GroupManager Integration

GroupManager* is passed from MainWindow through registration:

  • Auto-assigned colors: GroupManager’s observer callback detects groups created by PredictionWriter and assigns palette colors. GroupManagementWidget automatically adds rows.
  • Color swatches: ClusterOutputPanel and ResultsPanel display group color icons via QPixmap swatches from GroupManager.
  • Entity selection: Clicking a putative group entry retrieves its entities and broadcasts selection.

Registration

Registered via MLCoreWidgetRegistration with:

  • Type ID: "MLCoreWidget"
  • Menu path: View/Analysis
  • Zone: Right
  • Single instance: allow_multiple = false
  • Receives GroupManager* from MainWindow

ContextAction: mlcore.cluster_tensor

MLCoreWidgetRegistration registers a ContextAction with action_id = "mlcore.cluster_tensor":

  • Applicability: The currently focused data key (via SelectionContext::currentDataKey()) must exist as a TensorData key in DataManager
  • Execute: Sets the clustering tensor key to the focused data key, switches the active tab to the Clustering tab (setActiveTab(1)), and opens the ML Workflow widget

This action is consumed by ScatterPlotWidget’s context menu — when a user right-clicks on a scatter plot backed by TensorData, the “Cluster with ML Workflow” option appears. The “Cluster Selection…” action in ScatterPlotOpenGLWidget also programmatically triggers this action after creating a filtered subset of selected points. See the ScatterPlotWidget documentation for the full workflow.