PSTH Widget Roadmap
PSTHWidget Development Roadmap
This document tracks remaining development tasks for the PSTH 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:
- Core rendering: OpenGL pipeline,
GatherResultintegration,HistogramMapper,SceneRenderer - Binning: Uniform time bins with configurable bin size
- Plot styles: Bar chart and step-function line rendering via shared
HistogramMapper - Interaction: Separated X/Y zoom, pan, double-click time navigation
- Axis system:
RelativeTimeAxisWidget(X) andVerticalAxisWidget(Y) with bidirectional sync - Properties panel: Alignment controls, event series management, style selection, per-event color picker
- State serialization: Full round-trip JSON via
rfl::json - Rate estimation integration:
PSTHStateDatanow storesEstimationParamsvariant directly.PSTHPropertiesWidgetuses the sharedEstimationMethodControlswidget fromRateEstimationControlslibrary for method selection and per-method parameter editing. Renderer extracts bin size fromestimationParams()viastd::get_if<BinningParams>. - Normalization/scaling :
PSTHStateDatastoresScalingModefrom the sharedRateEstimate.hpp.PSTHPropertiesWidgetuses the sharedScalingModeControlswidget.PSTHPlotOpenGLWidget::rebuildScene()applies scaling viaapplyScaling()fromRateNormalization.hpp, supporting all scaling modes (Raw Count, Firing Rate Hz, Z-Score, Normalized [0,1], Count/Trial).
Phase 3: Variability and Confidence Intervals
Status: Design phase. Depends on Phase 1 (normalization) and the Rate Estimation Redesign.
Goal: Display trial-to-trial variability in the PSTH, providing a visual measure of the reliability of the rate estimate.
This phase uses the shared uncertainty infrastructure from the redesign rather than defining bespoke per-trial histogram or confidence band types.
3.1 Per-Trial Data via estimateRateWithTrials()
The shared library provides estimateRateWithTrials(), which returns a RateEstimateWithTrials containing both the aggregate RateEstimate (mean across trials) and a PerTrialData matrix (each trial’s individual rate curve). This is the opt-in computation path — estimateRate() (the default) does not allocate per-trial storage.
3.3 Rendering Confidence Bands
Confidence bands should be rendered as a filled semi-transparent region behind the mean line/bars. The ConfidenceBand provides lower[i] and upper[i] at each time point, which maps directly to a filled polygon or rectangle batch.
The HistogramMapper could be extended with a toConfidenceBand() method that produces a filled polygon batch, or a new ConfidenceBandMapper could be introduced. The band should use the same fill color as the histogram but with reduced opacity (e.g., alpha = 0.2).
3.4 Properties Panel
Add controls to PSTHPropertiesWidget:
- Variability mode combo box (
None,SEM,CI95,Percentile,Bootstrap) - Confidence band color/opacity slider
- For Percentile mode: lower and upper percentile spinboxes
Phase 5: SVG Export
Status: Complete (Steps 5.1–5.7). End-to-end export from properties → PlottingSVG::SVGSceneRenderer is implemented and manually validated (bar and line modes). Shared patterns match EventPlotWidget and DataViewer_Widget.
Goal: Export the current PSTH plot to SVG for publication-quality figures.
Architecture Assessment
The PSTHWidget rendering pipeline is fully compatible with PlottingSVG:
HistogramMapper::buildScene()produces either aRenderableRectangleBatch(bar mode) or aRenderablePolyLineBatch(step-function line mode). Both batch types are already handled bySVGRectangleRendererandSVGPolyLineRendererrespectively.- The scene uses orthographic projection from
ViewStateData, matching theSVGSceneRenderercoordinate transform pipeline.
Key issues to address:
Scene not cachedDone (5.2): MemberCorePlotting::RenderableScene _sceneonPSTHPlotOpenGLWidget;uploadHistogramScene()(invoked fromrebuildScene()) assigns_scene = HistogramMapper::buildScene(...)then_scene_renderer.uploadScene(_scene); empty histogram resets_scenebeforeclearScene().Background color hardcodedDone (5.1):PSTHStateData::background_color(default"#1A1A1A"),getBackgroundColor()/setBackgroundColor()/backgroundColorChanged()onPSTHState, andPSTHPlotOpenGLWidget::updateBackgroundColor()(from state viaCoreUtilities/color.hpp::hexToRGB) called frominitializeGL(),paintGL(), and onbackgroundColorChangedinsetState().
Step 5.1: Add background_color to PSTHStateData — Done
Add a background color field so the SVG exporter can read it, matching the EventPlotStateData / HeatmapStateData pattern.
Files modified: - src/WhiskerToolbox/Plots/PSTHWidget/Core/PSTHState.hpp — std::string background_color = "#1A1A1A"; on PSTHStateData; accessors and backgroundColorChanged signal on PSTHState - src/WhiskerToolbox/Plots/PSTHWidget/Core/PSTHState.cpp — getBackgroundColor() / setBackgroundColor() - src/WhiskerToolbox/Plots/PSTHWidget/Rendering/PSTHPlotOpenGLWidget.hpp / .cpp — updateBackgroundColor(); initializeGL() and paintGL() use it; setState() connects backgroundColorChanged
Verify: Build compiles. Background color is driven by state.
Step 5.2: Cache RenderableScene in PSTHPlotOpenGLWidget — Done
Add a RenderableScene member so the scene persists for SVG export.
Files modified: - src/WhiskerToolbox/Plots/PSTHWidget/Rendering/PSTHPlotOpenGLWidget.hpp — member CorePlotting::RenderableScene _scene - src/WhiskerToolbox/Plots/PSTHWidget/Rendering/PSTHPlotOpenGLWidget.cpp — in uploadHistogramScene() (called at the end of rebuildScene()): assign _scene from HistogramMapper::buildScene(_histogram_data, mode, _histogram_style) then _scene_renderer.uploadScene(_scene); if counts are empty, _scene = RenderableScene{} then clearScene()
Verify: Build compiles. Existing OpenGL rendering unchanged.
Step 5.3: Add exportToSVG() to PSTHPlotOpenGLWidget — Done
Follows the EventPlotOpenGLWidget pattern: empty early-out when both rectangle_batches and poly_line_batches are empty; copies _view_matrix / _projection_matrix onto _scene; PlottingSVG::SVGSceneRenderer with widget canvas size and _state->getBackgroundColor() when state is set.
Files modified: - src/WhiskerToolbox/Plots/PSTHWidget/Rendering/PSTHPlotOpenGLWidget.hpp — exportToSVG() declaration (and #include <QString>) - src/WhiskerToolbox/Plots/PSTHWidget/Rendering/PSTHPlotOpenGLWidget.cpp — implementation; #include "PlottingSVG/SVGSceneRenderer.hpp" - src/WhiskerToolbox/Plots/PSTHWidget/CMakeLists.txt — PlottingSVG in target_link_libraries (PRIVATE)
Verify: Build compiles.
Step 5.4: Add exportSVGRequested signal to PSTHPropertiesWidget — Done
Add an “Export SVG” button to the properties panel.
Files modified: - src/WhiskerToolbox/Plots/PSTHWidget/UI/PSTHPropertiesWidget.hpp — signals: void exportSVGRequested(); with Doxygen; private Section * _export_section - src/WhiskerToolbox/Plots/PSTHWidget/UI/PSTHPropertiesWidget.cpp — collapsible Section titled “Export” with QPushButton “Export SVG…” (Expanding horizontal size policy), inserted before vertical_spacer; clicked → exportSVGRequested()
Verify: Build compiles. Button appears.
Step 5.5: Add handleExportSVG() to PSTHWidget — Done
Same flow as EventPlotWidget::handleExportSVG(): AppFileDialog (export_psth_svg), _opengl_widget->exportToSVG(), empty/write failure message boxes, QTextStream write, success message.
Files modified: - src/WhiskerToolbox/Plots/PSTHWidget/UI/PSTHWidget.hpp — public slots: void handleExportSVG(); - src/WhiskerToolbox/Plots/PSTHWidget/UI/PSTHWidget.cpp — implementation; includes for AppFileDialog, QFile, QMessageBox, QTextStream - src/WhiskerToolbox/Plots/PSTHWidget/CMakeLists.txt — WhiskerToolbox::StateManagement (PRIVATE) for AppFileDialog
Verify: Build compiles.
Step 5.6: Wire signals in PSTHWidgetRegistration — Done
In create_editor_custom, after props->setPlotWidget(view):
QObject::connect(props, &PSTHPropertiesWidget::exportSVGRequested, view, &PSTHWidget::handleExportSVG);
Files modified: - src/WhiskerToolbox/Plots/PSTHWidget/PSTHWidgetRegistration.cpp
Verify: Clicking “Export SVG” opens the save dialog and writes SVG (when a scene exists).
Step 5.7: Manual validation — Done
- Load a dataset with
DigitalEventSeriesdata - Open a PSTHWidget, configure alignment and event series
- Test both bar mode and line mode display styles
- Click “Export SVG” in the properties panel
- Open the resulting SVG in a web browser and/or Inkscape
- Verify:
- Bar mode: rectangles match on-screen bars (positions, heights, colors)
- Line mode: step-function polyline matches on-screen line
- Background color is correct
- Zoom/pan state is reflected
Outcome: Manual checks passed (export workflow, bar/line modes, background, view matrices in SVG).
Design Notes
- No PlottingSVG extensions needed: Both
RenderableRectangleBatch(bars) andRenderablePolyLineBatch(step-function line) are already supported by PlottingSVG. - Multiple event series: Currently all events are binned into a single histogram. When Phase 7 implements per-series histograms, each series will produce its own batch in the
RenderableScene, and SVG export will automatically render them with distinct colors. - Confidence bands: When Phase 3 adds confidence bands, their rendering as filled semi-transparent polygons will require a new batch type (filled polygon / triangle strip) in
CorePlottingand a correspondingSVGFilledPolygonRendererinPlottingSVG. This is a future extension.
Phase 6: Embeddable PSTH for Tooltips
Status: Design exploration. Depends on histogram infrastructure being factored for lightweight use.
Goal: Provide a lightweight, embeddable PSTH rendering that can appear in tooltips — for example, when hovering over a row of the HeatmapWidget.
6.1 Concept
When a user hovers over a unit row in the HeatmapWidget, a tooltip could display:
- A miniature PSTH for that unit
- Optionally, a combined raster + PSTH view
This requires decoupling the PSTH computation and rendering from the full widget machinery.
6.2 Lightweight Histogram Renderer
Use the shared estimateRate() from the EventRateEstimation library to compute the histogram data. The RateEstimate output (paired times[] + values[]) can be rendered directly by a lightweight QPainter-based renderer without needing the full OpenGL widget machinery.
For tooltip rendering, there are two approaches:
- QPixmap approach: Render the histogram to a
QPixmapvia a headless OpenGL context or a software rasterizer, then display inQToolTip - QPainter approach: Implement a simple
QPainter-based histogram renderer that doesn’t require OpenGL. This is simpler and avoids GL context issues in tooltips.
6.3 QPainter-based Mini Renderer
namespace CorePlotting::PSTH {
QPixmap renderMiniPSTH(
HistogramData const & data,
HistogramStyle const & style,
QSize size = {200, 80});
}This would use QPainter to draw bars/lines onto a QPixmap, suitable for embedding in tooltips, table cells, or any widget that can display a pixmap.
6.4 Combined Raster + PSTH Tooltip
For the HeatmapWidget tooltip showing both raster and PSTH:
┌─────────────────────┐
│ ▎ ▎ ▎▎ ▎ ▎ │ ← raster (mini)
│ ▎▎ ▎ ▎ ▎ ▎▎ │
│ ▎ ▎▎ ▎ ▎ ▎ │
├─────────────────────┤
│ ▓▓▓▓████▓▓▓▓▓▓▓▓▓ │ ← PSTH (mini)
└─────────────────────┘
Unit: spikes_unit_42
This requires factoring out the EventPlot’s raster rendering in a similar lightweight fashion.
6.5 Reuse with ACFWidget
The same QPainter-based mini histogram renderer could serve ACFWidget for ISI distribution tooltips or summary displays in other contexts where a full OpenGL widget is overkill.
Phase 7: Per-Series Histograms and Multi-Color Overlay
Status: Partially implemented. Multiple event series can be added but currently all events are binned into a single histogram.
Goal: When multiple DigitalEventSeries are overlaid, render separate histograms per series with distinct colors, with optional stacking or transparency.
7.1 Per-Series Binning
Modify rebuildScene() to produce separate HistogramData per event series rather than accumulating all events into a single histogram.
7.2 Overlay Modes
enum class PSTHOverlayMode {
Stacked, ///< Bars stacked vertically (colors distinguish series)
Overlaid, ///< Semi-transparent bars overlaid at same baseline
SideBySide ///< Bars placed side-by-side within each bin
};7.3 Color Application
The existing per-event hex_color in PSTHEventOptions should be applied to the HistogramStyle::fill_color when building each series’ scene. Currently, all series share a single default color.
Implementation Priority
Next Up
- Phase 2 (remaining): Migrate
PSTHPlotOpenGLWidget::rebuildScene()to useEventRateEstimationlibrary’sestimateRate(); then add Gaussian kernel and other smoothing methods - Phase 5: SVG export (PlottingSVG infrastructure proven; concrete step-by-step plan ready)
Following
- Phase 7: Per-series histograms and multi-color overlay
- Phase 3: Variability / confidence intervals
Later
- Phase 6: Embeddable PSTH for tooltips
Open Questions
SVG export scope: Should SVG export be a per-widget feature (button in each widget), or a centralized “Export All Visible Plots” action? The DataViewerWidget already has its own bespoke SVG exporter — should that be migrated to the shared infrastructure?
Tooltip rendering: Should tooltip histograms use
QPainter(simpler, no GL context needed) or render toQPixmapvia GL (consistent with main rendering)?QPainteris strongly preferred for reliability.Multiple event series: When overlaying multiple event series, should the default be stacked or overlaid? Neuroscience convention varies — PSTH typically shows one unit at a time, but comparing two conditions on the same unit is common.
See Also
- PSTHWidget Documentation — Full architecture and feature documentation
- Plot Widget Guide — Shared architecture, axis types, DataManager integration
- EventPlotWidget — Raster plot (natural companion)
- EventPlot Roadmap — Cross-widget linking design (Phase 6), SVG export plans
- HeatmapWidget — Shares alignment, GatherResult, and planned linking
- ACFWidget — Shares HistogramMapper, bar chart rendering; ISI histograms