Heatmap Widget Roadmap
HeatmapWidget Development Roadmap
This document tracks remaining development tasks for the Heatmap Widget. For documentation of completed features and current architecture, see the main developer documentation.
Completed Work Summary
The following features are complete and documented in index.qmd:
- Widget skeleton: EditorState pattern, registration, state/view/properties factories
- State management:
HeatmapStatewithPlotAlignmentState,RelativeTimeAxisState,VerticalAxisStatecomposition - Axis system:
RelativeTimeAxisWidget(X) andVerticalAxisWidget(Y) with bidirectional sync - Interaction: Separated X/Y zoom, pan, double-click time navigation via shared
PlotInteractionHelpers - Properties panel: Alignment controls (
PlotAlignmentWidget), axis range controls in collapsible sections - OpenGL lifecycle:
SceneRendererinitialization, background color, projection/view matrix management - State serialization: Full round-trip JSON via
rfl::json - Unit selection state:
HeatmapStateData::unit_keyswith full add/remove/batch API andunitsChanged()signal - Unit selection UI:
Feature_Tree_Widgetembedded in properties panel, filtered toDigitalEventSeries, with prefix-based group toggling - Rate estimation infrastructure:
EventRateEstimationlibrary inPlots/Common/EventRateEstimation/providingcreateUnitGatherContext()/createUnitGatherContexts()for batched aligned gathering andestimateRate()/estimateRates()returningRateEstimate(pairedtimes[]+values[]) with astd::variant<BinningParams, GaussianKernelParams, CausalExponentialParams>-based variation point. See Rate Estimation Redesign for the full API design. - Colormap infrastructure:
CorePlotting::Colormapslibrary inCorePlotting/Colormaps/providingColormapFunction,ColormapPreset(Inferno, Viridis, Magma, Plasma, Coolwarm, Grayscale, Hot), LUT-based O(1) evaluation with linear interpolation,mapValue()/mapValues()/mapMatrix()utilities. Shared with SpectrogramWidget and any future external-feature coloring use cases. - Heatmap scene building:
HeatmapMapperinCorePlotting/Mappers/convertingHeatmapRowDatarows toRenderableRectangleBatchwith Auto / Manual / Symmetric color range modes.HeatmapOpenGLWidget::rebuildScene()now gathers units viacreateUnitGatherContexts(), estimates rates viaestimateRates(), applies scaling viaapplyScaling(), convertsRateEstimateobjects toHeatmapRowData, and uploads the scene. - Y-axis auto-fit:
HeatmapWidgetauto-fits the vertical axis when the unit count changes. Y bounds are set to[0, num_units], Y zoom is reset to 1.0, and Y pan is reset to 0.0 so all units are visible. TheVerticalAxisWidgetusesidentityAxis("Unit", 0)for integer unit-index labels. Signal renamed fromtrialCountChangedtounitCountChangedfor semantic clarity. - Scaling and normalization: Five scaling modes (Firing Rate Hz, Z-Score, Normalized [0,1], Raw Count, Count/Trial). Uses shared
ScalingMode/applyScaling()fromRateEstimate.hpp.HeatmapStateDataextended withscalingandcolor_range(Auto/Manual/Symmetric). Auto-switches to Coolwarm colormap for z-score and Symmetric color range. Properties panel has “Scaling & Color Range” collapsible section withScalingModeControlswidget and manual vmin/vmax spinboxes. - Rate estimation options :
EstimationParamsvariant (std::variant<BinningParams, GaussianKernelParams, CausalExponentialParams>) stored directly inHeatmapStateData::estimation_params. LightweightEstimationParams.hppheader (no heavy transitive deps) safe to include from state headers.RateEstimationControlslibrary provides composable Qt widgets:EstimationMethodControls(method combo + stacked per-method parameter pages) andScalingModeControls(scaling mode combo).HeatmapPropertiesWidgetuses both widgets. Renderer passesestimationParams()directly toestimateRates()— no intermediate conversion. - Row sorting: Five sorting modes (Manual, TimeToPeak, PeakRate, MeanRate, Alphabetical) with ascending/descending toggle.
HeatmapSortModeenum andsortModeLabel()/allSortModes()utilities defined inHeatmapState.hpp.HeatmapStateDataextended withsort_modeandsort_ascending. Sorting logic inHeatmapDataPipeline.hpp/cppviacomputeSortOrder()(returns index permutation) andapplySortOrder()(reorders rows, rate estimates, and unit keys in-place). Applied afterrunHeatmapPipeline()in renderer before colormap mapping. Properties panel has “Sorting” collapsible section with sort mode combo and ascending checkbox. Full serialization round-trip. - Colormap selection UI:
ColormapControlscomposable widget inPlots/Common/ColormapControls/with colormap preset combo (gradient icon previews from LUT), color range mode combo (Auto/Manual/Symmetric), and vmin/vmax spinboxes.HeatmapStateData::colormapfield withcolormapChanged()signal. Auto-switches to Coolwarm for z-score scaling. Renderer reads colormap from state.
Not yet implemented: colorbar display (Phase 4) and all cross-widget linking described below.
Phase 4: Colorbar Display
Status: Not started. Phases 2 and 3 are complete; this phase can proceed.
Goal: Render a color legend alongside the heatmap showing the value-to-color mapping.
4.1 ColorbarWidget
Create a lightweight QWidget that renders a vertical color gradient with tick labels:
CorePlotting/Widgets/
├── ColorbarWidget.hpp
└── ColorbarWidget.cpp
The ColorbarWidget needs:
- A
ColormapFunctionto render the gradient - A value range (
vmin,vmax) for tick label computation - An axis label (e.g., “Firing Rate (Hz)”, “Z-Score”)
- Optional tick formatting (integer, decimal, scientific notation)
4.2 Integration with HeatmapWidget
Place the colorbar to the right of the OpenGL canvas in the HeatmapWidget layout:
┌──────────────────────────────────┬────┐
│ │ │
│ HeatmapOpenGLWidget │ CB │
│ │ │
├──────────────────────────────────┴────┤
│ RelativeTimeAxisWidget │
└───────────────────────────────────────┘
The colorbar updates when the colormap, scaling mode, or value range changes.
Phase 8: Tooltip with Stacked PSTH + Raster
Status: In progress. Basic tooltip wiring is complete — hovering over a heatmap row shows the unit key name via PlotTooltipManager. The tooltip correctly reflects the current sort order. PSTH and raster glyph rendering in the tooltip is not yet implemented. Depends on Phase 1 and Phase 7.
Goal: When hovering over a heatmap row, display a tooltip containing a miniature stacked PSTH histogram and raster plot for that unit.
8.1 Concept
┌─────────────────────────────────────────────────────┐
│ Heatmap │
│ unit_A ██████████████████████████████████████████ │
│ unit_B ██████████████████████████████████████████ │
│ unit_C ████████▓▓▓▓████████████████████████████ ← hover
│ unit_D ██████████████████████████████████████████ │
│ │
│ ┌─────────────────────┐ │
│ │ unit_C PSTH │ │
│ │ ▄▄ ██ ▄▄ .. │ │
│ │─────────────────────│ │
│ │ unit_C Raster │ │
│ │ | || | || | │ │
│ │ || | | | || │ │
│ └─────────────────────┘ │
└─────────────────────────────────────────────────────┘
8.2 Lightweight Rendering
The tooltip must render quickly without creating full widget instances. Two approaches:
Option A: Pre-rendered QPixmap Cache
When the scene rebuilds, pre-render PSTH and raster thumbnails for each unit into QPixmap objects. The tooltip simply displays the cached pixmap. This has memory cost proportional to the number of units but provides instant tooltips.
Option B: On-Demand QPainter Rendering
When the hover event fires, compute the PSTH bins and raster tick positions for the hovered unit using the cached GatherResult data, and render directly with QPainter into a tooltip widget. This avoids the memory cost but requires fast rendering.
Recommendation: Option B with the cached GatherResult data from the scene rebuild. The rate computation uses the shared estimateRate() from the EventRateEstimation library (the same function used by the heatmap itself), and QPainter rendering of a simple histogram + tick marks is lightweight.
8.3 Tooltip Content
The tooltip should show:
- Header: Unit label / event key
- PSTH subplot: Bar or line histogram of the unit’s rate profile (same data as the heatmap row)
- Raster subplot: Tick marks for each trial’s events (using the unit’s
GatherResult) - Optional statistics: Peak rate, time to peak, mean rate
8.4 Implementation Approach
The tooltip lifecycle (dwell timer, suppression during pan/zoom, show/hide) is handled by the shared PlotTooltipManager (Plots/Common/TooltipManager/). The HeatmapWidget provides two callbacks:
- Hit test provider: Converts the screen position to a unit index (row lookup from Y coordinate). Returns a
PlotTooltipHitwith the unit index inuser_data. - Content provider: Receives the hit, renders the PSTH + raster thumbnail into a
QPixmapviaQPainter, and returns it asPlotTooltipContent. ThePlotTooltipManagerdisplays the pixmap in its built-inPixmapPopupwidget.
_tooltip_mgr = std::make_unique<PlotTooltipManager>(this);
_tooltip_mgr->setHitTestProvider([this](QPoint pos) -> std::optional<PlotTooltipHit> {
QPointF world = screenToWorld(pos);
int unit_index = worldToUnitIndex(world);
if (unit_index < 0) return std::nullopt;
PlotTooltipHit hit;
hit.world_x = static_cast<float>(world.x());
hit.world_y = static_cast<float>(world.y());
hit.user_data = unit_index;
return hit;
});
_tooltip_mgr->setContentProvider([this](PlotTooltipHit const & hit) -> PlotTooltipContent {
int unit_index = std::any_cast<int>(hit.user_data);
PlotTooltipContent content;
content.pixmap = renderUnitTooltip(unit_index); // QPainter PSTH + raster
return content;
});The renderUnitTooltip() method:
- Reuses the shared
estimateRate()from theEventRateEstimationlibrary for the PSTH portion - Reuses
RasterMapperlogic for the raster portion (a simplified version without full scene building) - Renders both subplots into a single
QPixmapviaQPainter
This is related to PSTH Roadmap Phase 6 (Embeddable PSTH for Tooltips), which proposes decoupling the PSTH computation and rendering from the full widget machinery.
Phase 9: Colormap Selection UI
Status: Complete. Implemented as a shared ColormapControls library in Plots/Common/ColormapControls/. See ColormapControls documentation.
Completed work:
ColormapControlswidget: Composable widget with colormap preset combo box (gradient icon previews rendered from LUT) and color range controls (Auto / Manual / Symmetric mode with vmin/vmax spinboxes). Embedded inHeatmapPropertiesWidgetwithin the “Rate Estimation & Scaling” collapsible section.- State extension:
HeatmapStateData::colormapfield (ColormapPreset, defaultInferno).HeatmapStateprovidescolormapPreset()/setColormapPreset()withcolormapChanged()signal. Full JSON serialization round-trip viarfl::json. - Auto-suggestion: When switching to z-score scaling, the colormap automatically changes to
Coolwarmand the color range switches toSymmetric. Reverting from z-score restoresInfernoandAuto. - Renderer integration:
HeatmapOpenGLWidget::rebuildScene()reads the colormap from_state->colormapPreset()instead of hard-coding based on scaling mode.
Phase 10: PNG Export
Status: Not started. Qt provides the underlying infrastructure via QOpenGLWidget::grabFramebuffer().
Goal: Export the current heatmap view as a publication-quality PNG image.
10.1 Basic Grab
The simplest approach uses Qt’s built-in framebuffer grab:
void HeatmapWidget::exportPNG(QString const & path) {
QImage image = _opengl_widget->grabFramebuffer();
image.save(path, "PNG");
}This captures exactly what is displayed, including the current zoom/pan state.
10.2 High-Resolution Export
For publication quality, render at a higher resolution than screen:
void HeatmapWidget::exportPNG(QString const & path, int scale_factor) {
// Resize OpenGL widget to scaled dimensions
// Render at high resolution
// Grab framebuffer
// Restore original size
}10.3 Composite Export with Axes and Colorbar
For a complete figure, composite the OpenGL framebuffer with axis labels and colorbar:
- Render the heatmap at target resolution
- Render axes using
QPainterat matching resolution - Render colorbar using
QPainter - Composite into a single
QImage - Save as PNG
10.4 UI Integration
Add an “Export PNG…” action to:
- The properties panel (button or menu)
- A right-click context menu on the plot
The dialog should offer:
- File path selection
- Resolution scale factor (1x, 2x, 4x)
- Include axes checkbox
- Include colorbar checkbox
10.5 SVG Export
SVG export for the HeatmapWidget is now covered by Phase 5: SVG Export using the PlottingSVG library infrastructure. See that phase for the step-by-step plan.
Phase 5: SVG Export
Status: Complete (steps 5.1–5.6). Heatmap SVG export uses PlottingSVG end-to-end; see also EventPlotWidget, ScatterPlotWidget, DataViewer_Widget, and the library-wide PlottingSVG library.
Goal: Export the current heatmap view to SVG for publication-quality figures.
Progress: Steps 5.1–5.6 done — cached scene, exportToSVG(), properties Export SVG…, handleExportSVG(), registration QObject::connect, and manual validation (browser/Inkscape vs on-screen heatmap).
Architecture Assessment
The HeatmapWidget rendering pipeline is fully compatible with PlottingSVG:
HeatmapMapper::buildScene()produces aRenderableRectangleBatch— one rectangle per heatmap cell, with pre-computed colormap colors.SVGRectangleRendereralready handles this batch type.- The scene uses orthographic projection from
ViewStateData, matching theSVGSceneRenderercoordinate transform pipeline. - Background color is stored in
HeatmapStateData::background_color(accessible viaHeatmapState::getBackgroundColor()). HeatmapOpenGLWidgetcaches the builtRenderableScenein_scene(kept in sync with the OpenGL upload inrebuildScene()).
Step 5.1: Cache RenderableScene in HeatmapOpenGLWidget — Done
Add a RenderableScene member to HeatmapOpenGLWidget so the scene is available for SVG export without rebuilding.
Files to modify: - src/WhiskerToolbox/Plots/HeatmapWidget/Rendering/HeatmapOpenGLWidget.hpp — add CorePlotting::RenderableScene _scene; member - src/WhiskerToolbox/Plots/HeatmapWidget/Rendering/HeatmapOpenGLWidget.cpp — in rebuildScene(), assign into _scene before uploadScene (and clear _scene on every clearScene() path via a small helper).
Verify: Build compiles. Existing OpenGL rendering is unchanged.
Verified: Yes — full build and Heatmap test suite pass.
Step 5.2: Add exportToSVG() to HeatmapOpenGLWidget — Done
Follow the EventPlotOpenGLWidget pattern:
[[nodiscard]] QString exportToSVG();Implementation:
QString HeatmapOpenGLWidget::exportToSVG() {
if (_scene.rectangle_batches.empty()) {
return {};
}
// Sync matrices from OpenGL state to scene
_scene.view_matrix = _view_matrix;
_scene.projection_matrix = _projection_matrix;
PlottingSVG::SVGSceneRenderer renderer;
renderer.setScene(_scene);
renderer.setCanvasSize(_widget_width, _widget_height);
if (_state) {
renderer.setBackgroundColor(_state->getBackgroundColor().toStdString());
}
return QString::fromStdString(renderer.render());
}Files to modify: - src/WhiskerToolbox/Plots/HeatmapWidget/Rendering/HeatmapOpenGLWidget.hpp — add declaration - src/WhiskerToolbox/Plots/HeatmapWidget/Rendering/HeatmapOpenGLWidget.cpp — implement - src/WhiskerToolbox/Plots/HeatmapWidget/CMakeLists.txt — add PlottingSVG to target_link_libraries (PRIVATE)
Verify: Build compiles.
Verified: Yes — full build and Heatmap test suite pass.
Step 5.3: Add exportSVGRequested signal to HeatmapPropertiesWidget — Done
Add an “Export SVG” button to the properties panel.
Files modified: - src/WhiskerToolbox/Plots/HeatmapWidget/UI/HeatmapPropertiesWidget.hpp — exportSVGRequested signal; Section * _export_section; _setupExportSection() - src/WhiskerToolbox/Plots/HeatmapWidget/UI/HeatmapPropertiesWidget.cpp — _setupExportSection() adds a collapsible Export Section with Export SVG… (QPushButton), inserted above the bottom spacer (same pattern as ScatterPlotPropertiesWidget). No .ui change.
Verify: Build compiles. Button appears in properties panel.
Verified: Yes — full build and Heatmap test suite pass.
Step 5.4: Add handleExportSVG() to HeatmapWidget — Done
Follow the EventPlotWidget::handleExportSVG() pattern:
void HeatmapWidget::handleExportSVG() {
QString const fileName = AppFileDialog::getSaveFileName(
this,
QStringLiteral("export_heatmap_svg"),
tr("Export Heatmap to SVG"),
tr("SVG Files (*.svg);;All Files (*)"));
if (fileName.isEmpty()) return;
QString const svg = _opengl_widget->exportToSVG();
if (svg.isEmpty()) {
QMessageBox::warning(this, tr("Export Failed"),
tr("No scene to export. Add units and configure alignment first."));
return;
}
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
QMessageBox::critical(this, tr("Export Failed"),
tr("Could not open file for writing:\n%1").arg(fileName));
return;
}
QTextStream out(&file);
out << svg;
file.close();
QMessageBox::information(this, tr("Export Successful"),
tr("Heatmap exported to:\n%1").arg(fileName));
}Files modified: - src/WhiskerToolbox/Plots/HeatmapWidget/UI/HeatmapWidget.hpp — public slots: handleExportSVG() - src/WhiskerToolbox/Plots/HeatmapWidget/UI/HeatmapWidget.cpp — implementation; includes StateManagement/AppFileDialog.hpp, QFile, QMessageBox, QTextStream - src/WhiskerToolbox/Plots/HeatmapWidget/CMakeLists.txt — PRIVATE WhiskerToolbox::StateManagement (for AppFileDialog)
Verify: Build compiles.
Verified: Yes — full project build and Heatmap test suite pass (including after linking WhiskerToolbox::StateManagement for AppFileDialog).
Step 5.5: Wire signals in HeatmapWidgetRegistration — Done
Connect the properties signal to the view slot in the create_editor_custom lambda (after props->setPlotWidget(view)), matching EventPlotWidgetRegistration:
QObject::connect(props, &HeatmapPropertiesWidget::exportSVGRequested,
view, &HeatmapWidget::handleExportSVG);Files modified: - src/WhiskerToolbox/Plots/HeatmapWidget/HeatmapWidgetRegistration.cpp
Verify: Full build succeeds. Clicking Export SVG… opens the save dialog and writes an SVG when the scene has data.
Verified: Yes — full build and tests; end-to-end export exercised (see 5.6).
Step 5.6: Manual validation — Done
- Load a dataset with
DigitalEventSeriesdata - Open a HeatmapWidget, add multiple units, configure alignment
- Click Export SVG… in the properties panel (Export section)
- Open the resulting SVG in a web browser and/or Inkscape
- Verify:
- Rectangle cells match the on-screen heatmap
- Colors correspond to the active colormap and scaling mode
- Row ordering matches the current sort mode
- Background color is correct
- Zoom/pan state is reflected (exported view matches what the user sees)
Verified: Yes — manual checks passed (SVG matches interactive view for cells, colormap, ordering, background, and camera).
Design Notes
- No PlottingSVG extensions needed: Heatmap cells render as
RenderableRectangleBatch, which is a batch type already fully supported bySVGRectangleRenderer. - Colorbar not included: The colorbar (Phase 4) is a separate Qt widget and is not part of the
RenderableScene. A futureSVGColorbarDecorationcould be added toPlottingSVG/Decorations/to render a colorbar legend in the SVG. - Axis annotation: Row unit labels and time axis labels are rendered by Qt axis widgets, not by the OpenGL pipeline. Future
SVGAxisRendererdecorations could add these. The existingPlottingSVG::SVGAxisRendererdecoration could be configured for the X axis; a new Y-axis label decoration (unit names) would require a new decoration class.
Phase 11: AnalogTimeSeries Heatmap Variant (Future)
Status: Early conceptual design. Separate from the DigitalEventSeries heatmap.
Goal: A sibling widget that creates heatmaps from AnalogTimeSeries data rather than discrete events. This enables visualization of continuous signals like ΔF/F calcium imaging traces across multiple cells, aligned to events.
11.1 Concept
Where the current HeatmapWidget computes rate from discrete events (analogous to stacking PSTHWidget rows), the AnalogTimeSeries variant would display raw continuous signals (analogous to stacking LinePlotWidget rows).
| Feature | Event Heatmap (current) | Analog Heatmap (future) |
|---|---|---|
| Data source | DigitalEventSeries |
AnalogTimeSeries |
| Per-unit computation | Binning + rate estimation | Direct value sampling / interpolation |
| Analogous single-unit view | PSTHWidget | LinePlotWidget |
| Typical use case | Population spike rate | ΔF/F, LFP, EMG across units |
| Normalization | Firing rate, z-score | Z-score, ΔF/F₀, % change |
11.3 Different Infrastructure
Key differences that may warrant a separate widget rather than a mode switch:
- Data gathering:
GatherResult<AnalogTimeSeries>instead ofGatherResult<DigitalEventSeries> - Value computation: Direct sampling/interpolation instead of binning + rate estimation
- Alignment: May align to
DigitalIntervalSeriesonly (baseline period for ΔF/F₀ normalization) - Time resolution: Native sampling rate rather than binned; may need downsampling for display
- Tooltip: Would show a line trace rather than a PSTH histogram
11.4 Recommendation
Implement as a separate widget (AnalogHeatmapWidget) that reuses the colormap, colorbar, sorting, linking, and export infrastructure. The rendering and data gathering paths are sufficiently different that forcing them into a single widget would add unwanted complexity. The two widgets can coexist in the Plot menu, clearly labeled:
- Plot → Heatmap Plot (Events) — current widget
- Plot → Heatmap Plot (Analog) — future widget
Open Questions
Row label rendering: Should unit labels be rendered as axis tick labels via
VerticalAxisWidget, or as a separate label column? The axis approach reuses existing infrastructure but may not handle long labels well.Performance at scale: What is the target unit count? 100 units × 200 bins = 20K rectangles is trivial for OpenGL. 1000 units × 1000 bins = 1M rectangles may need texture-based rendering instead of rectangle batches.
AnalogTimeSeries variant timing: Should the analog heatmap be a mode of this widget or a completely separate widget? The shared infrastructure is substantial, but the data pipelines are fundamentally different.
See Also
- HeatmapWidget Documentation — Full architecture and feature documentation
- Plot Widget Guide — Shared architecture, axis types, DataManager integration
- PSTHWidget — Single-unit PSTH; shares rate estimation pipeline
- PSTHWidget Roadmap — Rate estimation factoring, embeddable PSTH for tooltips
- EventPlotWidget — Trial-level raster plot; shares alignment and linking
- EventPlotWidget Roadmap — Cross-widget linking, external feature coloring
- SpectrogramWidget — Shares colormap infrastructure