Skip to main content

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, GatherResult integration, 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) and VerticalAxisWidget (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: PSTHStateData now stores EstimationParams variant directly. PSTHPropertiesWidget uses the shared EstimationMethodControls widget from RateEstimationControls library for method selection and per-method parameter editing. Renderer extracts bin size from estimationParams() via std::get_if<BinningParams>.
  • Normalization/scaling : PSTHStateData stores ScalingMode from the shared RateEstimate.hpp. PSTHPropertiesWidget uses the shared ScalingModeControls widget. PSTHPlotOpenGLWidget::rebuildScene() applies scaling via applyScaling() from RateNormalization.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.

See Rate Estimation Redesign — Per-Trial Data.

3.2 Confidence Bands via Shared API

The shared ConfidenceBand struct and computation functions handle all variability modes:

struct ConfidenceBand {
    std::vector<double> lower;    ///< Lower bound at each time point
    std::vector<double> upper;    ///< Upper bound at each time point
};

auto ci = computeSEM(data, 1.96);               // SEM × 1.96 for 95% CI
auto ci = computePercentileCI(data, 2.5, 97.5); // Percentile-based 95% CI
auto ci = bootstrapCI(data, 1000, 0.95);        // Bootstrap CI

For the normalization + uncertainty pipeline, use the applyScaling(RateEstimateWithTrials &) overload to ensure aggregate and per-trial data are normalized consistently before computing CI:

auto data = estimateRateWithTrials(gathered, tf, window_size, params);
applyScaling(data, ScalingMode::ZScore, 1000.0);  // normalizes aggregate + all trials
auto ci = computeSEM(data);  // CI is in z-score space — consistent

See Rate Estimation Redesign — Uncertainty.

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 a RenderableRectangleBatch (bar mode) or a RenderablePolyLineBatch (step-function line mode). Both batch types are already handled by SVGRectangleRenderer and SVGPolyLineRenderer respectively.
  • The scene uses orthographic projection from ViewStateData, matching the SVGSceneRenderer coordinate transform pipeline.

Key issues to address:

  1. Scene not cached Done (5.2): Member CorePlotting::RenderableScene _scene on PSTHPlotOpenGLWidget; uploadHistogramScene() (invoked from rebuildScene()) assigns _scene = HistogramMapper::buildScene(...) then _scene_renderer.uploadScene(_scene); empty histogram resets _scene before clearScene().
  2. Background color hardcoded Done (5.1): PSTHStateData::background_color (default "#1A1A1A"), getBackgroundColor() / setBackgroundColor() / backgroundColorChanged() on PSTHState, and PSTHPlotOpenGLWidget::updateBackgroundColor() (from state via CoreUtilities/color.hpp::hexToRGB) called from initializeGL(), paintGL(), and on backgroundColorChanged in setState().

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

  1. Load a dataset with DigitalEventSeries data
  2. Open a PSTHWidget, configure alignment and event series
  3. Test both bar mode and line mode display styles
  4. Click “Export SVG” in the properties panel
  5. Open the resulting SVG in a web browser and/or Inkscape
  6. 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) and RenderablePolyLineBatch (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 CorePlotting and a corresponding SVGFilledPolygonRenderer in PlottingSVG. 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:

  1. QPixmap approach: Render the histogram to a QPixmap via a headless OpenGL context or a software rasterizer, then display in QToolTip
  2. 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

  1. Phase 2 (remaining): Migrate PSTHPlotOpenGLWidget::rebuildScene() to use EventRateEstimation library’s estimateRate(); then add Gaussian kernel and other smoothing methods
  2. Phase 5: SVG export (PlottingSVG infrastructure proven; concrete step-by-step plan ready)

Following

  1. Phase 7: Per-series histograms and multi-color overlay
  2. Phase 3: Variability / confidence intervals

Later

  1. Phase 6: Embeddable PSTH for tooltips

Open Questions

  1. 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?

  2. Tooltip rendering: Should tooltip histograms use QPainter (simpler, no GL context needed) or render to QPixmap via GL (consistent with main rendering)? QPainter is strongly preferred for reliability.

  3. 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