Skip to content

Visualisation

btorch.visualisation

Visualization tools for neuromorphic data analysis.

This module provides plotting utilities for spike trains, network dynamics, connectome structure, and neuron state traces. The API is organized into five plotting families:

Aggregation plots (aggregation): - Grouped distributions: plot_group_distribution (kind="violin", "box" or "ecdf") - Neuropil timeseries: plot_neuropil_timeseries_overview, plot_neuropil_timeseries_panels

Dynamics plots (dynamics): - Multiscale analysis: plot_multiscale_fano, plot_dfa_analysis, plot_isi_cv - Criticality and attractors: plot_avalanche_analysis, plot_eigenvalue_spectrum, plot_lyapunov_spectrum - Micro-dynamics: plot_firing_rate_distribution, plot_micro_dynamics, plot_gain_stability

Timeseries plots (timeseries): - Spike visualization: plot_raster - Continuous traces: plot_traces, plot_neuron_traces - Spectral analysis: plot_spectrum, plot_log_hist

Network plots (network, hex.interactive): - Graph layout: plot_network - Hexagonal heatmaps: heatmap

Tuning plots (tuning): - Response curves: plot_fi_vi_curve

Attributes

__all__ = ['hex_heatmap', 'plot_network', 'plot_group_distribution', 'plot_neuropil_timeseries_overview', 'plot_neuropil_timeseries_panels', 'plot_log_hist', 'plot_raster', 'plot_spectrum', 'plot_traces', 'plot_neuron_traces', 'SimulationStates', 'TracePlotFormat', 'RasterStyle', 'RasterGrouping', 'GroupStripOptions', 'RatePanelOptions', 'RasterAnnotations', 'plot_multiscale_fano', 'plot_dfa_analysis', 'plot_isi_cv', 'DynamicsData', 'DFAConfig', 'DynamicsPlotFormat', 'FanoFactorConfig', 'plot_avalanche_analysis', 'plot_eigenvalue_spectrum', 'plot_firing_rate_distribution', 'plot_gain_stability', 'plot_lyapunov_spectrum', 'plot_micro_dynamics'] module-attribute

Classes

DFAConfig dataclass

Configuration for DFA (Detrended Fluctuation Analysis).

Attributes:

Name Type Description
min_window int

Minimum window size for DFA in timesteps.

max_window int | None

Maximum window size. If None, auto-calculated.

bin_size int

Bin size for spike binning in timesteps.

Source code in btorch/visualisation/dynamics.py
@dataclass
class DFAConfig:
    """Configuration for DFA (Detrended Fluctuation Analysis).

    Attributes:
        min_window: Minimum window size for DFA in timesteps.
        max_window: Maximum window size. If None, auto-calculated.
        bin_size: Bin size for spike binning in timesteps.
    """

    min_window: int = 4
    max_window: int | None = None
    bin_size: int = 1

DynamicsData dataclass

Container for dynamics analysis data and configs.

Attributes:

Name Type Description
spikes ndarray | Tensor

Spike trains with shape (time, neurons).

dt float

Simulation timestep in milliseconds.

neurons_df DataFrame | None

DataFrame with neuron metadata for grouping.

connections_df DataFrame | None

DataFrame with connection metadata for neuropil aggregation.

Source code in btorch/visualisation/dynamics.py
@dataclass
class DynamicsData:
    """Container for dynamics analysis data and configs.

    Attributes:
        spikes: Spike trains with shape (time, neurons).
        dt: Simulation timestep in milliseconds.
        neurons_df: DataFrame with neuron metadata for grouping.
        connections_df: DataFrame with connection metadata for neuropil
            aggregation.
    """

    spikes: np.ndarray | torch.Tensor
    dt: float = 1.0
    neurons_df: pd.DataFrame | None = None
    connections_df: pd.DataFrame | None = None

DynamicsPlotFormat dataclass

Figure formatting for dynamics plots.

Attributes:

Name Type Description
mode Literal['individual', 'grouped', 'distribution']

Visualization mode - "individual" for specific neurons, "grouped" for aggregated groups, "distribution" for summary stats.

group_by Literal['neuropil', 'neuron_type', None]

Grouping method for aggregation ("neuropil" or "neuron_type").

neuron_type_column str

Column name in neurons_df for neuron classification.

neuron_indices list[int] | None

Specific neuron indices for individual mode.

colors dict | None

Color mapping dictionary.

figsize tuple[float, float] | None

Figure size as (width, height) in inches.

Source code in btorch/visualisation/dynamics.py
@dataclass
class DynamicsPlotFormat:
    """Figure formatting for dynamics plots.

    Attributes:
        mode: Visualization mode - "individual" for specific neurons,
            "grouped" for aggregated groups, "distribution" for summary stats.
        group_by: Grouping method for aggregation ("neuropil" or "neuron_type").
        neuron_type_column: Column name in neurons_df for neuron classification.
        neuron_indices: Specific neuron indices for individual mode.
        colors: Color mapping dictionary.
        figsize: Figure size as (width, height) in inches.
    """

    mode: Literal["individual", "grouped", "distribution"] = "individual"
    group_by: Literal["neuropil", "neuron_type", None] = None
    neuron_type_column: str = "cell_type"
    neuron_indices: list[int] | None = None
    colors: dict | None = None
    figsize: tuple[float, float] | None = None

FanoFactorConfig dataclass

Configuration for Fano factor analysis.

Attributes:

Name Type Description
windows list[int] | None

Time windows in timesteps for multiscale analysis. If None, logarithmically spaced windows are auto-generated.

overlap int

Overlap between consecutive windows in timesteps.

Source code in btorch/visualisation/dynamics.py
@dataclass
class FanoFactorConfig:
    """Configuration for Fano factor analysis.

    Attributes:
        windows: Time windows in timesteps for multiscale analysis.
            If None, logarithmically spaced windows are auto-generated.
        overlap: Overlap between consecutive windows in timesteps.
    """

    windows: list[int] | None = None
    overlap: int = 0

GroupStripOptions dataclass

Colour strip beside the raster (also sets the group label side).

Attributes:

Name Type Description
show bool

Draw the strip. With show=False only color_key and side take effect (grouping colour column and label side).

color_key str | None

Column of neurons_df used for strip colours; defaults to RasterGrouping.group_key. A different column gives subgroups.

cmap str

Matplotlib colormap name for top-group and subgroup colours.

layout dict | None

Overrides for the strip geometry and label styling.

legend bool

Add a legend for the group colours.

label_mode Literal['top', 'sub', 'top_sub']

Which labels to print when subgroups are used.

side Literal['left', 'right']

Side of the raster on which strip and labels are drawn.

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class GroupStripOptions:
    """Colour strip beside the raster (also sets the group label side).

    Attributes:
        show: Draw the strip. With ``show=False`` only ``color_key`` and
            ``side`` take effect (grouping colour column and label side).
        color_key: Column of ``neurons_df`` used for strip colours; defaults to
            ``RasterGrouping.group_key``. A different column gives subgroups.
        cmap: Matplotlib colormap name for top-group and subgroup colours.
        layout: Overrides for the strip geometry and label styling.
        legend: Add a legend for the group colours.
        label_mode: Which labels to print when subgroups are used.
        side: Side of the raster on which strip and labels are drawn.
    """

    show: bool = True
    color_key: str | None = None
    cmap: str = "tab10"
    layout: dict | None = None
    legend: bool = True
    label_mode: Literal["top", "sub", "top_sub"] = "top_sub"
    side: Literal["left", "right"] = "right"

RasterAnnotations dataclass

Events, shaded regions and optional event tracks.

Attributes:

Name Type Description
events Sequence[float] | dict[str, Sequence[float]] | None

Event times, or a dict mapping names to event times.

regions Sequence[tuple[float, float]] | dict[str, Sequence[tuple[float, float]]] | None

(start, end) spans, or a dict mapping names to spans.

show_tracks bool

Draw events/regions as tracks below the raster.

event_kwargs dict | None

Extra keyword arguments for event lines.

region_kwargs dict | None

Extra keyword arguments for region patches.

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class RasterAnnotations:
    """Events, shaded regions and optional event tracks.

    Attributes:
        events: Event times, or a dict mapping names to event times.
        regions: ``(start, end)`` spans, or a dict mapping names to spans.
        show_tracks: Draw events/regions as tracks below the raster.
        event_kwargs: Extra keyword arguments for event lines.
        region_kwargs: Extra keyword arguments for region patches.
    """

    events: Sequence[float] | dict[str, Sequence[float]] | None = None
    regions: (
        Sequence[tuple[float, float]] | dict[str, Sequence[tuple[float, float]]] | None
    ) = None
    show_tracks: bool = False
    event_kwargs: dict | None = None
    region_kwargs: dict | None = None

RasterGrouping dataclass

Neuron grouping, ordering and group separators.

Attributes:

Name Type Description
neurons_df DataFrame | None

Neuron metadata, required for any grouping.

group_key str | None

Column of neurons_df to group neurons by.

group_sort list[str] | None

Explicit group order (unknown groups are ignored).

sort_neurons bool

Reorder neurons by group/subgroup so bands are contiguous; if False the original order is kept.

show_separators bool

Draw lines (and labels) between groups.

separator_style dict | None

Extra keyword arguments for the separator lines.

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class RasterGrouping:
    """Neuron grouping, ordering and group separators.

    Attributes:
        neurons_df: Neuron metadata, required for any grouping.
        group_key: Column of ``neurons_df`` to group neurons by.
        group_sort: Explicit group order (unknown groups are ignored).
        sort_neurons: Reorder neurons by group/subgroup so bands are
            contiguous; if False the original order is kept.
        show_separators: Draw lines (and labels) between groups.
        separator_style: Extra keyword arguments for the separator lines.
    """

    neurons_df: pd.DataFrame | None = None
    group_key: str | None = None
    group_sort: list[str] | None = None
    sort_neurons: bool = True
    show_separators: bool = True
    separator_style: dict | None = None

RasterStyle dataclass

Spike marker appearance.

Attributes:

Name Type Description
spike_color str | dict | Sequence[Any] | None

Default spike colour. A dict maps group names or neuron indices to colours; a sequence gives one colour per neuron.

marker str

Matplotlib marker for spikes.

marker_size float

Marker size in points squared.

neuron_specs dict | list | NeuronSpec | None

Per-neuron styling (dict keyed by neuron index, list, or a single :class:NeuronSpec).

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class RasterStyle:
    """Spike marker appearance.

    Attributes:
        spike_color: Default spike colour. A dict maps group names or neuron
            indices to colours; a sequence gives one colour per neuron.
        marker: Matplotlib marker for spikes.
        marker_size: Marker size in points squared.
        neuron_specs: Per-neuron styling (dict keyed by neuron index, list, or
            a single :class:`NeuronSpec`).
    """

    spike_color: str | dict | Sequence[Any] | None = "black"
    marker: str = "."
    marker_size: float = 5.0
    neuron_specs: dict | list | NeuronSpec | None = None

RatePanelOptions dataclass

Firing-rate panel below the raster.

Attributes:

Name Type Description
total bool | ndarray | Tensor | None

If True compute the population rate; an array of length T (or (T, 1)) is plotted as given.

per_group bool | dict[str, ndarray | Tensor] | ndarray | None

If True compute one rate per group (needs a group key); a dict maps group names to arrays, an array is (T, G) in the order of the resolved groups.

window_ms float

Smoothing window for computed rates, in ms.

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class RatePanelOptions:
    """Firing-rate panel below the raster.

    Attributes:
        total: If True compute the population rate; an array of length ``T``
            (or ``(T, 1)``) is plotted as given.
        per_group: If True compute one rate per group (needs a group key); a
            dict maps group names to arrays, an array is ``(T, G)`` in the
            order of the resolved groups.
        window_ms: Smoothing window for computed rates, in ms.
    """

    total: bool | np.ndarray | torch.Tensor | None = False
    per_group: bool | dict[str, np.ndarray | torch.Tensor] | np.ndarray | None = False
    window_ms: float = 10.0

SimulationStates dataclass

Container for simulation state data and configs.

Attributes:

Name Type Description
voltage ndarray | Tensor

Membrane voltage traces (time, neurons) or (time, batch, neurons) if batch dimension present

dt float

Simulation timestep in ms

asc ndarray | Tensor | None

Afterspike current traces (time, neurons), (time, batch, neurons), or (time, batch, neurons, n_asc) for multiple ASC components

psc ndarray | Tensor | None

Total postsynaptic current (time, neurons), (time, batch, neurons), or (time, batch, neurons, n_psc) for multiple PSC components

epsc ndarray | Tensor | None

Excitatory PSC (time, neurons) or (time, batch, neurons)

ipsc ndarray | Tensor | None

Inhibitory PSC (time, neurons) or (time, batch, neurons)

input ndarray | Tensor | None

Input current (time, neurons) or (time, batch, neurons)

spikes ndarray | Tensor | None

Spike trains (time, neurons) or (time, batch, neurons)

v_threshold float | Sequence[float] | ndarray | Tensor | None

Spike threshold voltage(s), scalar or per-neuron

v_reset float | Sequence[float] | ndarray | Tensor | None

Reset voltage(s), scalar or per-neuron

psc_labels Sequence[str] | None

Labels for multi-component PSC (defaults to PSC_<i>)

Source code in btorch/visualisation/timeseries/neuron_specs.py
@dataclass
class SimulationStates:
    """Container for simulation state data and configs.

    Attributes:
        voltage: Membrane voltage traces (time, neurons) or
            (time, batch, neurons) if batch dimension present
        dt: Simulation timestep in ms
        asc: Afterspike current traces (time, neurons), (time, batch, neurons),
            or (time, batch, neurons, n_asc) for multiple ASC components
        psc: Total postsynaptic current (time, neurons), (time, batch, neurons),
            or (time, batch, neurons, n_psc) for multiple PSC components
        epsc: Excitatory PSC (time, neurons) or (time, batch, neurons)
        ipsc: Inhibitory PSC (time, neurons) or (time, batch, neurons)
        input: Input current (time, neurons) or (time, batch, neurons)
        spikes: Spike trains (time, neurons) or (time, batch, neurons)
        v_threshold: Spike threshold voltage(s), scalar or per-neuron
        v_reset: Reset voltage(s), scalar or per-neuron
        psc_labels: Labels for multi-component PSC (defaults to ``PSC_<i>``)
    """

    voltage: np.ndarray | torch.Tensor
    dt: float = 1.0
    asc: np.ndarray | torch.Tensor | None = None
    psc: np.ndarray | torch.Tensor | None = None
    epsc: np.ndarray | torch.Tensor | None = None
    ipsc: np.ndarray | torch.Tensor | None = None
    input: np.ndarray | torch.Tensor | None = None
    spikes: np.ndarray | torch.Tensor | None = None
    v_threshold: float | Sequence[float] | np.ndarray | torch.Tensor | None = None
    v_reset: float | Sequence[float] | np.ndarray | torch.Tensor | None = None
    psc_labels: Sequence[str] | None = None

TracePlotFormat dataclass

Figure formatting configuration.

Attributes:

Name Type Description
neuron_indices list[int] | None

Specific neuron indices to plot

sample_size int | None

Number of neurons to randomly sample

seed int

Random seed for sampling

show_voltage bool

Whether to show voltage subplot

show_asc bool

Whether to show ASC subplot

show_psc bool

Whether to show PSC subplot

show_spikes_on_voltage bool

Mark spikes on voltage trace

separate_figures bool

Return dict of figures (one per trace type) if True

auto_width bool

Adjust figure width based on simulation duration

colors dict[str, str] | None

Color mapping for different traces

figsize_per_neuron tuple[float, float]

Figure size per neuron row (width, height)

neuron_labels Sequence[str] | Callable[[int], str] | None

Side labels as sequence or callable(neuron_idx) -> str. Default None disables side labels.

neuron_label_position Literal['side', 'top']

Position for neuron labels when enabled. "side" places labels at the right of each neuron slot; "top" places labels above each neuron slot.

neurons_per_row int | None

Number of neurons to place per row in combined mode

batch_idx int | None

Batch index to plot when data has shape (time, batch, neurons). If None and data is 3D, defaults to 0 (first batch sample).

Source code in btorch/visualisation/timeseries/neuron_specs.py
@dataclass
class TracePlotFormat:
    """Figure formatting configuration.

    Attributes:
        neuron_indices: Specific neuron indices to plot
        sample_size: Number of neurons to randomly sample
        seed: Random seed for sampling
        show_voltage: Whether to show voltage subplot
        show_asc: Whether to show ASC subplot
        show_psc: Whether to show PSC subplot
        show_spikes_on_voltage: Mark spikes on voltage trace
        separate_figures: Return dict of figures (one per trace type) if True
        auto_width: Adjust figure width based on simulation duration
        colors: Color mapping for different traces
        figsize_per_neuron: Figure size per neuron row (width, height)
        neuron_labels: Side labels as sequence or callable(neuron_idx) -> str.
            Default None disables side labels.
        neuron_label_position: Position for neuron labels when enabled.
            "side" places labels at the right of each neuron slot; "top"
            places labels above each neuron slot.
        neurons_per_row: Number of neurons to place per row in combined mode
        batch_idx: Batch index to plot when data has shape (time, batch, neurons).
            If None and data is 3D, defaults to 0 (first batch sample).
    """

    neuron_indices: list[int] | None = None
    sample_size: int | None = None
    seed: int = 42
    show_voltage: bool = True
    show_asc: bool = True
    show_psc: bool = True
    show_spikes_on_voltage: bool = True
    separate_figures: bool = False
    auto_width: bool = True
    colors: dict[str, str] | None = None
    figsize_per_neuron: tuple[float, float] = (12, 2.5)
    neuron_labels: Sequence[str] | Callable[[int], str] | None = None
    neuron_label_position: Literal["side", "top"] = "side"
    neuron_specs: list[NeuronSpec | dict] | NeuronSpec | dict | None = None
    neurons_per_row: int | None = None
    batch_idx: int | None = None

Functions:

hex_heatmap(df, dataset, style=None, sizing=None, dpi=72, custom_colorscale=None, title=None, colorbar=True, value_name='value', coord_format='axial', orientation='flat', layout=None, rotation_deg=0.0, include_flywire_hover=True)

Generate an interactive hexagonal heatmap.

Hex polygons are drawn as SVG path shapes in data coordinates — no pixel math, no marker-size estimation. A single invisible scatter trace at hex centres provides hover, colour bar, and optional text labels. Plotly handles all scaling (zoom, resize, export).

Parameters:

Name Type Description Default
df DataFrame

DataFrame with 'p' and 'q' columns plus one or more value columns. Single value column produces a static heatmap; multiple columns produce an animated heatmap with a slider.

required
dataset DataFrame

Reference hex grid ('p', 'q' columns). Background hexes are drawn white for spatial context.

required
style dict | None

Styling overrides — font_type, linecolor, papercolor.

None
sizing dict | None

Size overrides — fig_width, fig_height, hex_line_color, hex_line_width, cbar_thickness, cbar_len, etc.

None
dpi int

Dots per inch for pixel dimension calculations.

72
custom_colorscale list | None

Plotly colorscale (list of [pos, colour] pairs or a named string like "Viridis").

None
title str | None

Optional plot title.

None
colorbar bool

Whether to show colour bar (default True).

True
value_name str

Label for values in hover tooltip.

'value'
coord_format CoordFormat

How to interpret 'p'/'q' columns — any :data:~btorch.utils.hex.resolve.CoordFormat, e.g. "axial", "zigzag", "flywire", or "pixel".

'axial'
orientation Literal['pointy', 'flat']

"flat" or "pointy" hex orientation.

'flat'
layout str | None

Set to "flywire" to use the flywire pixel projection.

None
rotation_deg float

Rotation for flywire layout.

0.0
include_flywire_hover bool

Include axial and zigzag coordinates in hover tooltip (default True).

True

Returns:

Type Description
Figure

Plotly Figure with hexagonal heatmap.

Example

fig = heatmap(data_df, background_df) fig.show()

Source code in btorch/visualisation/hex/interactive.py
def heatmap(
    df: pd.DataFrame,
    dataset: pd.DataFrame,
    style: dict | None = None,
    sizing: dict | None = None,
    dpi: int = 72,
    custom_colorscale: list | None = None,
    title: str | None = None,
    colorbar: bool = True,
    value_name: str = "value",
    coord_format: CoordFormat = "axial",
    orientation: Literal["pointy", "flat"] = "flat",
    layout: str | None = None,
    rotation_deg: float = 0.0,
    include_flywire_hover: bool = True,
) -> go.Figure:
    """Generate an interactive hexagonal heatmap.

    Hex polygons are drawn as SVG path shapes in data coordinates — no
    pixel math, no marker-size estimation.  A single invisible scatter
    trace at hex centres provides hover, colour bar, and optional text
    labels.  Plotly handles all scaling (zoom, resize, export).

    Args:
        df: DataFrame with ``'p'`` and ``'q'`` columns plus one or more
            value columns.  Single value column produces a static heatmap;
            multiple columns produce an animated heatmap with a slider.
        dataset: Reference hex grid (``'p'``, ``'q'`` columns).  Background
            hexes are drawn white for spatial context.
        style: Styling overrides — ``font_type``, ``linecolor``,
            ``papercolor``.
        sizing: Size overrides — ``fig_width``, ``fig_height``,
            ``hex_line_color``, ``hex_line_width``, ``cbar_thickness``,
            ``cbar_len``, etc.
        dpi: Dots per inch for pixel dimension calculations.
        custom_colorscale: Plotly colorscale (list of [pos, colour] pairs
            or a named string like ``"Viridis"``).
        title: Optional plot title.
        colorbar: Whether to show colour bar (default ``True``).
        value_name: Label for values in hover tooltip.
        coord_format: How to interpret ``'p'``/``'q'`` columns —
            any :data:`~btorch.utils.hex.resolve.CoordFormat`, e.g.
            ``"axial"``, ``"zigzag"``, ``"flywire"``, or ``"pixel"``.
        orientation: ``"flat"`` or ``"pointy"`` hex orientation.
        layout: Set to ``"flywire"`` to use the flywire pixel projection.
        rotation_deg: Rotation for flywire layout.
        include_flywire_hover: Include axial and zigzag coordinates in
            hover tooltip (default ``True``).

    Returns:
        Plotly Figure with hexagonal heatmap.

    Example:
        >>> fig = heatmap(data_df, background_df)
        >>> fig.show()
    """
    go = _plotly_go()
    sty = _merge_style(style)
    sz = _merge_sizing(sizing)
    area_w, area_h, f_ticks, f_title = _compute_pixel_dims(sz, dpi)

    bg = dataset.drop_duplicates(subset=["p", "q"])[["p", "q"]].astype(float)
    _, _, _, _, bg_x, bg_y = _resolve_coords(
        bg.p.to_numpy(),
        bg.q.to_numpy(),
        coord_format,
        orientation,
        layout=layout,
        rotation_deg=rotation_deg,
    )
    dq, dr, dzx, dzy, dx, dy = _resolve_coords(
        df.p.to_numpy(),
        df.q.to_numpy(),
        coord_format,
        orientation,
        layout=layout,
        rotation_deg=rotation_deg,
    )
    ctx = _HeatmapContext(
        colorscale=custom_colorscale or _DEFAULT_COLORSCALE,
        vmin=min(0, float(df.values.min())),
        vmax=float(df.values.max()),
        orientation=orientation,
        sty=sty,
        sz=sz,
        f_ticks=f_ticks,
        f_title=f_title,
        value_name=value_name,
        include_flywire_hover=include_flywire_hover,
        bg_xy=(bg_x, bg_y),
        axial=(dq, dr),
        zigzag=(dzx, dzy),
        xy=(dx, dy),
    )

    hex_pad = 1.2  # hex circumradius (1.0) + margin
    x_range = (float(bg_x.min()) - hex_pad, float(bg_x.max()) + hex_pad)
    y_range = (float(bg_y.min()) - hex_pad, float(bg_y.max()) + hex_pad)

    value_cols = [c for c in df.columns if c not in ("p", "q")]
    if len(value_cols) <= 1:
        series = df[value_cols[0]] if value_cols else df.iloc[:, 0]
        fig = _static_heatmap(go, ctx, series, colorbar, area_w, area_h)
    else:
        fig = _animated_heatmap(go, ctx, df, value_cols, colorbar, area_w, area_h)
    _hide_axes(fig, x_range=x_range, y_range=y_range)

    if title:
        fig.update_layout(title=dict(text=title))

    return fig

plot_avalanche_analysis(spikes, bin_size=1, dt=1.0)

Plot avalanche size and duration distributions to analyze criticality.

Creates a 3-panel figure showing: 1. Avalanche size distribution P(S) with power-law fit 2. Avalanche duration distribution P(T) with power-law fit 3. Average size vs duration scaling relation <S>(T)

Criticality is indicated by power-law distributions and specific scaling exponents (tau, alpha, gamma).

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix with shape (time, neurons).

required
bin_size int

Bin size for avalanche detection in timesteps.

1
dt float

Timestep in ms (unused, kept for interface consistency).

1.0

Returns:

Type Description
Figure

Tuple of (figure, results) where results contains fitted exponents

dict

(tau, alpha, gamma), CCC (criticality consistency check), and

tuple[Figure, dict]

power-law fit objects.

Examples:

>>> fig, results = plot_avalanche_analysis(spikes, bin_size=5)
>>> print(f"Tau: {results['tau']:.2f}, CCC: {results['CCC']:.2f}")
Source code in btorch/visualisation/dynamics.py
def plot_avalanche_analysis(
    spikes: np.ndarray | torch.Tensor,
    bin_size: int = 1,
    dt: float = 1.0,  # Added for consistency
) -> tuple[Figure, dict]:
    """Plot avalanche size and duration distributions to analyze criticality.

    Creates a 3-panel figure showing:
    1. Avalanche size distribution P(S) with power-law fit
    2. Avalanche duration distribution P(T) with power-law fit
    3. Average size vs duration scaling relation `<S>(T)`

    Criticality is indicated by power-law distributions and specific
    scaling exponents (tau, alpha, gamma).

    Args:
        spikes: Spike matrix with shape (time, neurons).
        bin_size: Bin size for avalanche detection in timesteps.
        dt: Timestep in ms (unused, kept for interface consistency).

    Returns:
        Tuple of (figure, results) where results contains fitted exponents
        (tau, alpha, gamma), CCC (criticality consistency check), and
        power-law fit objects.

    Examples:
        >>> fig, results = plot_avalanche_analysis(spikes, bin_size=5)
        >>> print(f"Tau: {results['tau']:.2f}, CCC: {results['CCC']:.2f}")
    """
    from ..analysis.dynamic_tools.criticality import compute_avalanche_statistics

    spikes = to_numpy(spikes)
    results = compute_avalanche_statistics(spikes, bin_size=bin_size)

    fig = plt.figure(figsize=(15, 4))

    ax1 = fig.add_subplot(1, 3, 1)
    if results["fit_S"]:
        results["fit_S"].plot_pdf(color="b", linewidth=2, ax=ax1, label="Data")
        results["fit_S"].power_law.plot_pdf(
            color="b", linestyle="--", ax=ax1, label=f"Fit (tau={results['tau']:.2f})"
        )
    ax1.set_xlabel("Avalanche Size (S)")
    ax1.set_ylabel("P(S)")
    ax1.set_title("Size Distribution")
    if ax1.get_legend_handles_labels()[0]:
        ax1.legend()

    ax2 = fig.add_subplot(1, 3, 2)
    if results["fit_T"]:
        results["fit_T"].plot_pdf(color="r", linewidth=2, ax=ax2, label="Data")
        results["fit_T"].power_law.plot_pdf(
            color="r",
            linestyle="--",
            ax=ax2,
            label=f"Fit (alpha={results['alpha']:.2f})",
        )
    ax2.set_xlabel("Avalanche Duration (T)")
    ax2.set_ylabel("P(T)")
    ax2.set_title("Duration Distribution")
    if ax2.get_legend_handles_labels()[0]:
        ax2.legend()

    ax3 = fig.add_subplot(1, 3, 3)
    if (
        "avg_size_by_duration" in results
        and results["avg_size_by_duration"] is not None
    ):
        durations, mean_sizes = results["avg_size_by_duration"]
        ax3.loglog(durations, mean_sizes, "ko", markersize=4, label="Data")

        if not np.isnan(results["gamma"]):
            if results.get("gamma_stats") and "popt" in results["gamma_stats"]:
                popt = results["gamma_stats"]["popt"]
                a, gamma = popt
                x_fit = np.logspace(
                    np.log10(durations.min()), np.log10(durations.max()), 100
                )
                y_fit = a * np.power(x_fit, gamma)
                ax3.loglog(
                    x_fit,
                    y_fit,
                    "g--",
                    label=f"Fit (gamma={results['gamma']:.2f})",
                )

    if not np.isnan(results["CCC"]):
        txt = f"CCC = {results['CCC']:.2f}\nPred gamma = {results['gamma_pred']:.2f}"
        ax3.text(
            0.05,
            0.95,
            txt,
            transform=ax3.transAxes,
            verticalalignment="top",
            bbox=dict(boxstyle="round", facecolor="white", alpha=0.8),
        )

    ax3.set_xlabel("Duration (T)")
    ax3.set_ylabel("Average Size <S>")
    ax3.set_title("Scaling Relation")
    if ax3.get_legend_handles_labels()[0]:
        ax3.legend()

    plt.tight_layout()
    return fig, results

plot_dfa_analysis(data=None, config=None, format=None, spikes=None, dt=1.0, min_window=4, max_window=None, bin_size=1, mode='individual', neurons_df=None, **kwargs)

Plot DFA (Detrended Fluctuation Analysis) results.

DFA quantifies long-range temporal correlations in spike trains. The scaling exponent (alpha) indicates: - alpha ≈ 0.5: Uncorrelated (random) activity - alpha > 0.5: Long-range positive correlations - alpha < 0.5: Long-range anti-correlations

Supports both dataclass and plain argument interfaces.

Parameters:

Name Type Description Default
data DynamicsData | None

DynamicsData container with spikes.

None
config DFAConfig | None

DFAConfig with window and bin settings.

None
format DynamicsPlotFormat | None

DynamicsPlotFormat (mode affects plot style).

None
spikes ndarray | Tensor | None

Spike trains (time, neurons). Required if data not provided.

None
dt float

Timestep in milliseconds (for label consistency).

1.0
min_window int

Minimum window size for DFA in timesteps.

4
max_window int | None

Maximum window size. Auto-calculated if None.

None
bin_size int

Bin size for spike binning in timesteps.

1
mode Literal['individual', 'grouped', 'distribution']

Visualization mode (affects annotation style).

'individual'
neurons_df DataFrame | None

Neuron metadata for potential grouping.

None
**kwargs Any

Additional arguments.

{}

Returns:

Type Description
Figure

Figure with DFA summary and interpretation guide.

Raises:

Type Description
ValueError

If spikes are not provided.

Examples:

>>> fig = plot_dfa_analysis(spikes, bin_size=10)
Source code in btorch/visualisation/dynamics.py
def plot_dfa_analysis(
    # Dataclass interface
    data: DynamicsData | None = None,
    config: DFAConfig | None = None,
    format: DynamicsPlotFormat | None = None,
    # Plain args interface
    spikes: np.ndarray | torch.Tensor | None = None,
    dt: float = 1.0,
    min_window: int = 4,
    max_window: int | None = None,
    bin_size: int = 1,
    mode: Literal["individual", "grouped", "distribution"] = "individual",
    neurons_df: pd.DataFrame | None = None,
    **kwargs: Any,
) -> Figure:
    """Plot DFA (Detrended Fluctuation Analysis) results.

    DFA quantifies long-range temporal correlations in spike trains.
    The scaling exponent (alpha) indicates:
    - alpha ≈ 0.5: Uncorrelated (random) activity
    - alpha > 0.5: Long-range positive correlations
    - alpha < 0.5: Long-range anti-correlations

    Supports both dataclass and plain argument interfaces.

    Args:
        data: DynamicsData container with spikes.
        config: DFAConfig with window and bin settings.
        format: DynamicsPlotFormat (mode affects plot style).
        spikes: Spike trains (time, neurons). Required if `data` not provided.
        dt: Timestep in milliseconds (for label consistency).
        min_window: Minimum window size for DFA in timesteps.
        max_window: Maximum window size. Auto-calculated if None.
        bin_size: Bin size for spike binning in timesteps.
        mode: Visualization mode (affects annotation style).
        neurons_df: Neuron metadata for potential grouping.
        **kwargs: Additional arguments.

    Returns:
        Figure with DFA summary and interpretation guide.

    Raises:
        ValueError: If spikes are not provided.

    Examples:
        >>> fig = plot_dfa_analysis(spikes, bin_size=10)
    """
    if data is not None:
        spikes = data.spikes if spikes is None else spikes
        dt = data.dt if dt == 1.0 else dt
        neurons_df = data.neurons_df if neurons_df is None else neurons_df

    if config is not None:
        max_window = config.max_window if max_window is None else max_window
        bin_size = config.bin_size

    if spikes is None:
        raise ValueError("spikes is required")

    spikes = to_numpy(spikes)

    from ..analysis.dynamic_tools.criticality import compute_dfa

    alpha = compute_dfa(spikes, bin_size=bin_size)

    fig, ax = plt.subplots(1, 1, figsize=(8, 6))
    ax.text(
        0.5,
        0.5,
        f"DFA Exponent (α): {alpha:.3f}",
        ha="center",
        va="center",
        fontsize=16,
        transform=ax.transAxes,
    )
    ax.text(
        0.5,
        0.4,
        "α ≈ 0.5: uncorrelated\n"
        "α > 0.5: long-range correlations\n"
        "α < 0.5: anti-correlations",
        ha="center",
        va="center",
        fontsize=10,
        transform=ax.transAxes,
    )
    ax.set_title("Detrended Fluctuation Analysis")
    ax.axis("off")
    return fig

plot_eigenvalue_spectrum(weight_matrix, ax=None)

Plot the eigenvalue spectrum of a weight matrix.

Visualizes eigenvalues in the complex plane with the spectral radius indicated by a dashed circle. Outliers (eigenvalues outside the bulk) are highlighted in red.

Parameters:

Name Type Description Default
weight_matrix ndarray | Tensor

Square connectivity matrix (N, N).

required
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None

Returns:

Type Description
Figure

Tuple of (figure, axes, results) where results contains:

Axes
  • "eigenvalues": Complex array of all eigenvalues
dict
  • "spectral_radius": Radius of spectral bulk
tuple[Figure, Axes, dict]
  • "outliers": Array of outlier eigenvalues

Examples:

>>> fig, ax, results = plot_eigenvalue_spectrum(W)
>>> print(f"Spectral radius: {results['spectral_radius']:.2f}")
Source code in btorch/visualisation/dynamics.py
def plot_eigenvalue_spectrum(
    weight_matrix: np.ndarray | torch.Tensor, ax: Axes | None = None
) -> tuple[Figure, Axes, dict]:
    """Plot the eigenvalue spectrum of a weight matrix.

    Visualizes eigenvalues in the complex plane with the spectral radius
    indicated by a dashed circle. Outliers (eigenvalues outside the bulk)
    are highlighted in red.

    Args:
        weight_matrix: Square connectivity matrix (N, N).
        ax: Existing axes to plot on. Creates new figure if None.

    Returns:
        Tuple of (figure, axes, results) where results contains:
        - "eigenvalues": Complex array of all eigenvalues
        - "spectral_radius": Radius of spectral bulk
        - "outliers": Array of outlier eigenvalues

    Examples:
        >>> fig, ax, results = plot_eigenvalue_spectrum(W)
        >>> print(f"Spectral radius: {results['spectral_radius']:.2f}")
    """
    from ..analysis.dynamic_tools.attractor_dynamics import (
        compute_structural_eigenvalue_outliers,
    )

    W = to_numpy(weight_matrix)
    results = compute_structural_eigenvalue_outliers(W)

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 6))
    else:
        fig = ax.get_figure()

    evals = results["eigenvalues"]
    r_spec = results["spectral_radius"]

    circle = plt.Circle(
        (0, 0),
        r_spec,
        color="black",
        fill=False,
        linestyle="--",
        alpha=0.5,
        label=f"R={r_spec:.2f}",
    )
    ax.add_artist(circle)

    ax.scatter(evals.real, evals.imag, s=10, alpha=0.6, c="gray", edgecolors="none")

    outliers = results["outliers"]
    if len(outliers) > 0:
        ax.scatter(
            outliers.real,
            outliers.imag,
            s=30,
            c="red",
            label=f"Outliers ({len(outliers)})",
        )

    ax.set_aspect("equal")
    ax.set_xlabel(r"Re($\lambda$)")
    ax.set_ylabel(r"Im($\lambda$)")
    ax.set_title("Eigenvalue Spectrum")
    ax.grid(True, linestyle=":", alpha=0.3)
    ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
    plt.tight_layout()

    return fig, ax, results

plot_firing_rate_distribution(spikes, dt=1.0, ax=None)

Plot the distribution of firing rates across neurons.

Computes per-neuron firing rates and displays as a histogram with mean indicator.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix with shape (time, neurons).

required
dt float

Timestep in milliseconds for rate calculation.

1.0
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None

Returns:

Type Description
Figure

Tuple of (figure, stats) where stats contains:

dict
  • "rates": Array of firing rates per neuron (Hz)
tuple[Figure, dict]
  • "mean", "std", "median": Summary statistics

Examples:

>>> fig, stats = plot_firing_rate_distribution(spikes, dt=1.0)
>>> print(f"Mean rate: {stats['mean']:.1f} Hz")
Source code in btorch/visualisation/dynamics.py
def plot_firing_rate_distribution(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    ax: Axes | None = None,
) -> tuple[Figure, dict]:
    """Plot the distribution of firing rates across neurons.

    Computes per-neuron firing rates and displays as a histogram with
    mean indicator.

    Args:
        spikes: Spike matrix with shape (time, neurons).
        dt: Timestep in milliseconds for rate calculation.
        ax: Existing axes to plot on. Creates new figure if None.

    Returns:
        Tuple of (figure, stats) where stats contains:
        - "rates": Array of firing rates per neuron (Hz)
        - "mean", "std", "median": Summary statistics

    Examples:
        >>> fig, stats = plot_firing_rate_distribution(spikes, dt=1.0)
        >>> print(f"Mean rate: {stats['mean']:.1f} Hz")
    """
    from ..analysis.dynamic_tools.micro_scale import compute_fr_distribution

    spikes = to_numpy(spikes)
    stats = compute_fr_distribution(spikes, dt=dt)

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 4))
    else:
        fig = ax.get_figure()

    rates = stats["rates"]
    ax.hist(rates, bins=30, color="skyblue", edgecolor="black", alpha=0.7)
    ax.axvline(
        stats["mean"],
        color="red",
        linestyle="--",
        label=f"Mean={stats['mean']:.1f} Hz",
    )
    ax.set_xlabel("Firing Rate (Hz)")
    ax.set_ylabel("Count")
    ax.set_title("Rate Distribution")
    ax.legend()
    ax.grid(alpha=0.3)

    if ax is None:
        plt.tight_layout()

    return fig, stats

plot_gain_stability(data)

Plot gain stability analysis results.

Visualizes the relationship between network gain (g) and stability metrics (e.g., maximum Lyapunov exponent or spectral abscissa). A linear fit indicates consistent scaling behavior.

Parameters:

Name Type Description Default
data tuple

Tuple of (slope, intercept, g_values, lambda_values) where: - slope, intercept: Linear fit parameters - g_values: Array of gain values tested - lambda_values: Corresponding stability metrics

required

Returns:

Type Description
tuple[Figure, Axes]

Tuple of (figure, axes) with scatter plot and fit line.

Examples:

>>> data = (slope, intercept, g_vals, lyap_vals)
>>> fig, ax = plot_gain_stability(data)
Source code in btorch/visualisation/dynamics.py
def plot_gain_stability(data: tuple) -> tuple[Figure, Axes]:
    """Plot gain stability analysis results.

    Visualizes the relationship between network gain (g) and stability
    metrics (e.g., maximum Lyapunov exponent or spectral abscissa).
    A linear fit indicates consistent scaling behavior.

    Args:
        data: Tuple of (slope, intercept, g_values, lambda_values) where:
            - slope, intercept: Linear fit parameters
            - g_values: Array of gain values tested
            - lambda_values: Corresponding stability metrics

    Returns:
        Tuple of (figure, axes) with scatter plot and fit line.

    Examples:
        >>> data = (slope, intercept, g_vals, lyap_vals)
        >>> fig, ax = plot_gain_stability(data)
    """
    slope, intercept, g_values, lambda_values = data

    fig, ax = plt.subplots(figsize=(6, 4))

    ax.scatter(g_values, lambda_values, label="Data", color="blue", alpha=0.6)

    x_range = np.linspace(min(g_values), max(g_values), 100)
    y_fit = slope * x_range + intercept
    ax.plot(x_range, y_fit, "r--", label=f"Fit: y={slope:.2f}x+{intercept:.2f}")

    ax.set_xlabel("Gain (g)")
    ax.set_ylabel("Lyapunov / Eigenvalue metric")
    ax.set_title("Gain Stability Analysis")
    ax.legend()
    ax.grid(True, alpha=0.3)

    plt.tight_layout()
    return fig, ax

plot_group_distribution(values, neurons_df, group_by, *, kind='violin', simple_id_col='simple_id', value_name='value', group_order=None, dropna=True, ax=None, figsize=(9.0, 5.0), title=None, showfliers=False, linewidth=1.5, alpha=0.8)

Plot grouped value distributions as violin, box, or ECDF.

Groups per-neuron values by a categorical column in neurons_df and visualizes the distribution using the specified plot type.

Parameters:

Name Type Description Default
values TensorLike

Per-neuron values with shape (neurons,) or (time, neurons). If 2D, values are flattened across time for each neuron.

required
neurons_df DataFrame

DataFrame with neuron metadata. Must contain simple_id_col and group_by columns.

required
group_by str

Column name in neurons_df to group by (e.g., "cell_type").

required
kind GroupPlotKind

Plot type - "violin", "box", or "ecdf".

'violin'
simple_id_col str

Column name for neuron identifiers in neurons_df.

'simple_id'
value_name str

Label for the y-axis / value dimension.

'value'
group_order Sequence | None

Explicit order for groups. If None, uses natural sort.

None
dropna bool

Whether to drop NaN values before plotting.

True
ax Axes | None

Existing axes to plot on. If None, creates new figure.

None
figsize tuple[float, float]

Figure size (width, height) in inches.

(9.0, 5.0)
title str | None

Plot title. If None, auto-generated from kind and group_by.

None
showfliers bool

For box plots, whether to show outlier points.

False
linewidth float

Line width for ECDF curves.

1.5
alpha float

Opacity for violin/box fill.

0.8

Returns:

Type Description
tuple[Figure, Axes]

Tuple of (figure, axes) containing the plot.

Raises:

Type Description
ValueError

If kind is not one of "violin", "box", "ecdf".

Example

fig, ax = plot_group_distribution( ... firing_rates, neurons_df, group_by="cell_type", kind="violin" ... )

Source code in btorch/visualisation/aggregation.py
def plot_group_distribution(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    kind: GroupPlotKind = "violin",
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (9.0, 5.0),
    title: str | None = None,
    showfliers: bool = False,
    linewidth: float = 1.5,
    alpha: float = 0.8,
) -> tuple[Figure, Axes]:
    """Plot grouped value distributions as violin, box, or ECDF.

    Groups per-neuron values by a categorical column in `neurons_df` and
    visualizes the distribution using the specified plot type.

    Args:
        values: Per-neuron values with shape (neurons,) or (time, neurons).
            If 2D, values are flattened across time for each neuron.
        neurons_df: DataFrame with neuron metadata. Must contain `simple_id_col`
            and `group_by` columns.
        group_by: Column name in `neurons_df` to group by (e.g., "cell_type").
        kind: Plot type - "violin", "box", or "ecdf".
        simple_id_col: Column name for neuron identifiers in `neurons_df`.
        value_name: Label for the y-axis / value dimension.
        group_order: Explicit order for groups. If None, uses natural sort.
        dropna: Whether to drop NaN values before plotting.
        ax: Existing axes to plot on. If None, creates new figure.
        figsize: Figure size (width, height) in inches.
        title: Plot title. If None, auto-generated from `kind` and `group_by`.
        showfliers: For box plots, whether to show outlier points.
        linewidth: Line width for ECDF curves.
        alpha: Opacity for violin/box fill.

    Returns:
        Tuple of (figure, axes) containing the plot.

    Raises:
        ValueError: If `kind` is not one of "violin", "box", "ecdf".

    Example:
        >>> fig, ax = plot_group_distribution(
        ...     firing_rates, neurons_df, group_by="cell_type", kind="violin"
        ... )
    """
    fig, ax = _resolve_figure_ax(ax=ax, figsize=figsize)

    if kind in {"violin", "box"}:
        grouped = group_values(
            values,
            neurons_df,
            group_by,
            simple_id_col=simple_id_col,
            value_name=value_name,
            group_order=group_order,
            dropna=dropna,
        )
        order = list(grouped.keys())
        grouped_arrays = [grouped[group] for group in order]

        if kind == "violin":
            _plot_violin(ax, grouped_arrays, order, alpha=alpha)
        else:
            _plot_box(
                ax,
                grouped_arrays,
                order,
                showfliers=showfliers,
                alpha=alpha,
            )

        ax.set_xlabel(group_by)
        ax.set_ylabel(value_name)
    elif kind == "ecdf":
        ecdf_by_group = group_ecdf(
            values,
            neurons_df,
            group_by,
            simple_id_col=simple_id_col,
            value_name=value_name,
            group_order=group_order,
            dropna=dropna,
        )
        _plot_ecdf(
            ax,
            ecdf_by_group,
            group_by=group_by,
            value_name=value_name,
            linewidth=linewidth,
        )
    else:
        raise ValueError(f"Unsupported kind `{kind}`.")

    if title is None:
        title = f"{kind.upper()} grouped by {group_by}"
    ax.set_title(title)
    ax.grid(alpha=0.2)

    return fig, ax

plot_isi_cv(data=None, format=None, spikes=None, dt=1.0, mode='individual', neurons_df=None, group_by=None, neuron_type_column='cell_type', **kwargs)

Plot ISI CV (Coefficient of Variation) distribution.

ISI CV measures spike train irregularity: - CV = 1: Poisson-like (irregular) firing - CV < 1: Regular, periodic firing - CV > 1: Bursty, irregular firing

Supports histogram view for distributions and bar plots for grouped comparisons.

Parameters:

Name Type Description Default
data DynamicsData | None

DynamicsData container with spikes and metadata.

None
format DynamicsPlotFormat | None

DynamicsPlotFormat with visualization settings.

None
spikes ndarray | Tensor | None

Spike trains (time, neurons). Required if data not provided.

None
dt float

Timestep in milliseconds for ISI calculation.

1.0
mode Literal['individual', 'grouped', 'distribution']

Visualization mode - "distribution", "individual", or "grouped".

'individual'
neurons_df DataFrame | None

DataFrame with neuron metadata for grouping.

None
group_by Literal['neuropil', 'neuron_type', None]

Grouping method - "neuropil" or "neuron_type".

None
neuron_type_column str

Column name for neuron types in neurons_df.

'cell_type'
**kwargs Any

Additional arguments.

{}

Returns:

Type Description
Figure

Figure with ISI CV histogram or grouped bar plot.

Raises:

Type Description
ValueError

If spikes are not provided, or if grouped mode is requested without required metadata.

Examples:

>>> fig = plot_isi_cv(spikes, dt=1.0, mode="distribution")
>>>
>>> # Grouped by cell type
>>> fig = plot_isi_cv(spikes, neurons_df=df,
...                   mode="grouped", group_by="neuron_type")
Source code in btorch/visualisation/dynamics.py
def plot_isi_cv(
    # Dataclass interface
    data: DynamicsData | None = None,
    format: DynamicsPlotFormat | None = None,
    # Plain args interface
    spikes: np.ndarray | torch.Tensor | None = None,
    dt: float = 1.0,
    mode: Literal["individual", "grouped", "distribution"] = "individual",
    neurons_df: pd.DataFrame | None = None,
    group_by: Literal["neuropil", "neuron_type", None] = None,
    neuron_type_column: str = "cell_type",
    **kwargs: Any,
) -> Figure:
    """Plot ISI CV (Coefficient of Variation) distribution.

    ISI CV measures spike train irregularity:
    - CV = 1: Poisson-like (irregular) firing
    - CV < 1: Regular, periodic firing
    - CV > 1: Bursty, irregular firing

    Supports histogram view for distributions and bar plots for grouped
    comparisons.

    Args:
        data: DynamicsData container with spikes and metadata.
        format: DynamicsPlotFormat with visualization settings.
        spikes: Spike trains (time, neurons). Required if `data` not provided.
        dt: Timestep in milliseconds for ISI calculation.
        mode: Visualization mode - "distribution", "individual", or "grouped".
        neurons_df: DataFrame with neuron metadata for grouping.
        group_by: Grouping method - "neuropil" or "neuron_type".
        neuron_type_column: Column name for neuron types in neurons_df.
        **kwargs: Additional arguments.

    Returns:
        Figure with ISI CV histogram or grouped bar plot.

    Raises:
        ValueError: If spikes are not provided, or if grouped mode is
            requested without required metadata.

    Examples:
        >>> fig = plot_isi_cv(spikes, dt=1.0, mode="distribution")
        >>>
        >>> # Grouped by cell type
        >>> fig = plot_isi_cv(spikes, neurons_df=df,
        ...                   mode="grouped", group_by="neuron_type")
    """
    if data is not None:
        spikes = data.spikes if spikes is None else spikes
        dt = data.dt if dt == 1.0 else dt
        neurons_df = data.neurons_df if neurons_df is None else neurons_df

    if format is not None:
        mode = format.mode
        group_by = format.group_by if group_by is None else group_by
        neuron_type_column = format.neuron_type_column

    if spikes is None:
        raise ValueError("spikes is required")

    spikes = to_numpy(spikes)

    cv_results = _isi_cv_stats(spikes, dt)
    cv_values = cv_results["cv_isi"]

    fig, ax = plt.subplots(1, 1, figsize=(10, 6))

    if mode == "distribution" or mode == "individual":
        valid_cv = cv_values[~np.isnan(cv_values)]
        ax.hist(valid_cv, bins=30, color="skyblue", edgecolor="black", alpha=0.7)
        ax.axvline(
            cv_results["mean"],
            color="red",
            linestyle="--",
            label=f"Mean={cv_results['mean']:.2f}",
        )
        ax.set_xlabel("ISI CV")
        ax.set_ylabel("Count")
        ax.set_title("ISI Coefficient of Variation Distribution")
        ax.legend()
        ax.grid(alpha=0.3)

    elif mode == "grouped":
        if group_by is None or neurons_df is None:
            raise ValueError("group_by and neurons_df required for grouped mode")

        grouped = agg_by_neuron(
            cv_values, neurons_df, agg="mean", neuron_type_column=neuron_type_column
        )

        names = list(grouped.keys())
        values = list(grouped.values())
        ax.bar(names, values, color="teal", alpha=0.7, edgecolor="black")
        ax.set_xlabel("Neuron Type")
        ax.set_ylabel("Mean ISI CV")
        ax.set_title(f"ISI CV by {neuron_type_column}")
        ax.grid(axis="y", alpha=0.3)
        plt.xticks(rotation=45, ha="right")

    plt.tight_layout()
    return fig

plot_log_hist(values, ax=None, title='Distribution', xlabel='Value', **kwargs)

Plot log-log histogram with logarithmic binning.

Creates a scatter plot of histogram counts using logarithmically spaced bins. Useful for visualizing heavy-tailed distributions (e.g., power laws).

Parameters:

Name Type Description Default
values ndarray | Tensor

Input values to histogram. Flattened if multidimensional.

required
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None
title str

Plot title.

'Distribution'
xlabel str

X-axis label.

'Value'
**kwargs Any

Additional arguments passed to ax.scatter().

{}

Returns:

Type Description
Axes

Axes containing the log-log histogram.

Example

ax = plot_log_hist(synapse_weights, title="Weight Distribution")

Source code in btorch/visualisation/timeseries/histogram.py
def plot_log_hist(
    values: np.ndarray | torch.Tensor,
    ax: Axes | None = None,
    title: str = "Distribution",
    xlabel: str = "Value",
    **kwargs: Any,
) -> Axes:
    """Plot log-log histogram with logarithmic binning.

    Creates a scatter plot of histogram counts using logarithmically
    spaced bins. Useful for visualizing heavy-tailed distributions
    (e.g., power laws).

    Args:
        values: Input values to histogram. Flattened if multidimensional.
        ax: Existing axes to plot on. Creates new figure if None.
        title: Plot title.
        xlabel: X-axis label.
        **kwargs: Additional arguments passed to ax.scatter().

    Returns:
        Axes containing the log-log histogram.

    Example:
        >>> ax = plot_log_hist(synapse_weights, title="Weight Distribution")
    """
    vals = to_numpy(values)
    hist, bin_centers = compute_log_hist(vals)

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 4))

    ax.scatter(bin_centers, hist, **kwargs)
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set_xlabel(xlabel)
    ax.set_ylabel("Count")
    ax.set_title(title)

    return ax

plot_lyapunov_spectrum(spectrum, ax=None)

Plot the Lyapunov exponents spectrum.

Displays Lyapunov exponents sorted by magnitude. Positive exponents indicate chaos; the number of non-negative exponents relates to the Kaplan-Yorke dimension.

Parameters:

Name Type Description Default
spectrum list[float] | ndarray

List or array of Lyapunov exponents.

required
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple of (figure, axes) with the spectrum plot.

Examples:

>>> fig, ax = plot_lyapunov_spectrum(lyap_spectrum)
>>> # Positive exponents indicate chaotic dynamics
Source code in btorch/visualisation/dynamics.py
def plot_lyapunov_spectrum(
    spectrum: list[float] | np.ndarray, ax: Axes | None = None
) -> tuple[Figure, Axes]:
    """Plot the Lyapunov exponents spectrum.

    Displays Lyapunov exponents sorted by magnitude. Positive exponents
    indicate chaos; the number of non-negative exponents relates to the
    Kaplan-Yorke dimension.

    Args:
        spectrum: List or array of Lyapunov exponents.
        ax: Existing axes to plot on. Creates new figure if None.

    Returns:
        Tuple of (figure, axes) with the spectrum plot.

    Examples:
        >>> fig, ax = plot_lyapunov_spectrum(lyap_spectrum)
        >>> # Positive exponents indicate chaotic dynamics
    """
    from ..analysis.dynamic_tools.attractor_dynamics import (
        compute_kaplan_yorke_dimension,
    )

    spec = to_numpy(spectrum)
    spec = np.sort(spec)[::-1]

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 4))
    else:
        fig = ax.get_figure()

    x = np.arange(1, len(spec) + 1)
    ax.plot(x, spec, "o-", markersize=4, linewidth=1, color="black")
    ax.axhline(0, color="k", linestyle="--", linewidth=0.8)

    ky_dim = compute_kaplan_yorke_dimension(spec)

    title = f"Lyapunov Spectrum (D_KY = {ky_dim:.2f})"
    ax.set_title(title)
    ax.set_xlabel("Index")
    ax.set_ylabel("Lyapunov Exponent")
    ax.grid(True, alpha=0.3)
    plt.tight_layout()

    return fig, ax

plot_micro_dynamics(spikes, dt=1.0)

Plot firing rate and ISI CV distributions side-by-side.

Creates a 2-panel figure summarizing micro-scale dynamics: - Left: Firing rate distribution histogram - Right: ISI CV distribution histogram

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix with shape (time, neurons).

required
dt float

Timestep in milliseconds.

1.0

Returns:

Type Description
Figure

Tuple of (figure, stats) where stats is a dict with keys:

dict
  • "fr": Firing rate statistics
tuple[Figure, dict]
  • "cv": ISI CV statistics

Examples:

>>> fig, stats = plot_micro_dynamics(spikes, dt=1.0)
>>> print(f"Rate: {stats['fr']['mean']:.1f} Hz, CV: {stats['cv']['mean']:.2f}")
Source code in btorch/visualisation/dynamics.py
def plot_micro_dynamics(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
) -> tuple[Figure, dict]:
    """Plot firing rate and ISI CV distributions side-by-side.

    Creates a 2-panel figure summarizing micro-scale dynamics:
    - Left: Firing rate distribution histogram
    - Right: ISI CV distribution histogram

    Args:
        spikes: Spike matrix with shape (time, neurons).
        dt: Timestep in milliseconds.

    Returns:
        Tuple of (figure, stats) where stats is a dict with keys:
        - "fr": Firing rate statistics
        - "cv": ISI CV statistics

    Examples:
        >>> fig, stats = plot_micro_dynamics(spikes, dt=1.0)
        >>> print(f"Rate: {stats['fr']['mean']:.1f} Hz, CV: {stats['cv']['mean']:.2f}")
    """
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

    _, fr_stats = plot_firing_rate_distribution(spikes, dt=dt, ax=ax1)

    spikes_np = to_numpy(spikes)
    cv_results = _isi_cv_stats(spikes_np, dt)
    cv_values = cv_results["cv_isi"]
    valid_cv = cv_values[~np.isnan(cv_values)]

    if len(valid_cv) > 0:
        ax2.hist(valid_cv, bins=30, color="orange", edgecolor="black", alpha=0.7)
        ax2.axvline(
            cv_results["mean"],
            color="red",
            linestyle="--",
            label=f"Mean={cv_results['mean']:.2f}",
        )
        ax2.set_xlabel("CV (ISI)")
        ax2.set_ylabel("Count")
        ax2.set_title("CV Distribution")
        ax2.legend()
    else:
        ax2.text(0.5, 0.5, "No valid CVs", ha="center")
    ax2.grid(alpha=0.3)

    plt.tight_layout()
    return fig, {"fr": fr_stats, "cv": cv_results}

plot_multiscale_fano(data=None, config=None, format=None, spikes=None, dt=1.0, windows=None, overlap=0, mode='individual', neurons_df=None, connections_df=None, group_by=None, neuron_type_column='cell_type', neuron_indices=None, **kwargs)

Plot multiscale Fano factor analysis.

Computes and visualizes Fano factor (spike count variance/mean) across multiple time windows. Supports three visualization modes: - "individual": Line plots for selected neurons - "grouped": Aggregated by neuron type or neuropil - "distribution": Violin plots showing population distribution

Supports both dataclass and plain argument interfaces. Dataclass arguments take precedence when both are provided.

Parameters:

Name Type Description Default
data DynamicsData | None

DynamicsData container with spikes and metadata.

None
config FanoFactorConfig | None

FanoFactorConfig with window settings.

None
format DynamicsPlotFormat | None

DynamicsPlotFormat with visualization options.

None
spikes ndarray | Tensor | None

Spike trains with shape (time, neurons). Required if data is not provided.

None
dt float

Timestep in milliseconds. Default 1.0.

1.0
windows list[int] | None

List of window sizes in timesteps. Auto-generated if None.

None
overlap int

Window overlap in timesteps. Default 0.

0
mode Literal['individual', 'grouped', 'distribution']

Visualization mode - "individual", "grouped", "distribution".

'individual'
neurons_df DataFrame | None

DataFrame with neuron metadata for grouping.

None
connections_df DataFrame | None

DataFrame with connection metadata for neuropil grouping.

None
group_by Literal['neuropil', 'neuron_type', None]

Grouping method - "neuropil" or "neuron_type".

None
neuron_type_column str

Column name for neuron types in neurons_df.

'cell_type'
neuron_indices list[int] | None

Specific neuron indices for "individual" mode. If None, first 10 neurons are plotted.

None
**kwargs Any

Additional arguments passed to plotting functions.

{}

Returns:

Type Description
Figure

Figure with Fano factor plots.

Raises:

Type Description
ValueError

If spikes are not provided through either data or spikes argument.

Examples:

>>> # Plain args interface
>>> fig = plot_multiscale_fano(spikes, dt=1.0, mode="distribution")
>>>
>>> # Dataclass interface
>>> data = DynamicsData(spikes=spikes, dt=1.0, neurons_df=df)
>>> config = FanoFactorConfig(windows=[10, 50, 100])
>>> fig = plot_multiscale_fano(data=data, config=config)
Source code in btorch/visualisation/dynamics.py
def plot_multiscale_fano(
    # Dataclass interface
    data: DynamicsData | None = None,
    config: FanoFactorConfig | None = None,
    format: DynamicsPlotFormat | None = None,
    # Plain args interface
    spikes: np.ndarray | torch.Tensor | None = None,
    dt: float = 1.0,
    windows: list[int] | None = None,
    overlap: int = 0,
    mode: Literal["individual", "grouped", "distribution"] = "individual",
    neurons_df: pd.DataFrame | None = None,
    connections_df: pd.DataFrame | None = None,
    group_by: Literal["neuropil", "neuron_type", None] = None,
    neuron_type_column: str = "cell_type",
    neuron_indices: list[int] | None = None,
    **kwargs: Any,
) -> Figure:
    """Plot multiscale Fano factor analysis.

    Computes and visualizes Fano factor (spike count variance/mean) across
    multiple time windows. Supports three visualization modes:
    - "individual": Line plots for selected neurons
    - "grouped": Aggregated by neuron type or neuropil
    - "distribution": Violin plots showing population distribution

    Supports both dataclass and plain argument interfaces. Dataclass
    arguments take precedence when both are provided.

    Args:
        data: DynamicsData container with spikes and metadata.
        config: FanoFactorConfig with window settings.
        format: DynamicsPlotFormat with visualization options.
        spikes: Spike trains with shape (time, neurons). Required if
            `data` is not provided.
        dt: Timestep in milliseconds. Default 1.0.
        windows: List of window sizes in timesteps. Auto-generated if None.
        overlap: Window overlap in timesteps. Default 0.
        mode: Visualization mode - "individual", "grouped", "distribution".
        neurons_df: DataFrame with neuron metadata for grouping.
        connections_df: DataFrame with connection metadata for neuropil
            grouping.
        group_by: Grouping method - "neuropil" or "neuron_type".
        neuron_type_column: Column name for neuron types in neurons_df.
        neuron_indices: Specific neuron indices for "individual" mode.
            If None, first 10 neurons are plotted.
        **kwargs: Additional arguments passed to plotting functions.

    Returns:
        Figure with Fano factor plots.

    Raises:
        ValueError: If spikes are not provided through either `data` or
            `spikes` argument.

    Examples:
        >>> # Plain args interface
        >>> fig = plot_multiscale_fano(spikes, dt=1.0, mode="distribution")
        >>>
        >>> # Dataclass interface
        >>> data = DynamicsData(spikes=spikes, dt=1.0, neurons_df=df)
        >>> config = FanoFactorConfig(windows=[10, 50, 100])
        >>> fig = plot_multiscale_fano(data=data, config=config)
    """
    if data is not None:
        spikes = data.spikes if spikes is None else spikes
        dt = data.dt if dt == 1.0 else dt
        neurons_df = data.neurons_df if neurons_df is None else neurons_df
        connections_df = (
            data.connections_df if connections_df is None else connections_df
        )

    if config is not None:
        windows = config.windows if windows is None else windows
        overlap = config.overlap if overlap == 0 else overlap

    if format is not None:
        mode = format.mode
        group_by = format.group_by if group_by is None else group_by
        neuron_type_column = format.neuron_type_column
        neuron_indices = (
            format.neuron_indices if neuron_indices is None else neuron_indices
        )

    if spikes is None:
        raise ValueError("spikes is required")

    spikes = to_numpy(spikes)
    n_time, n_neurons = spikes.shape

    # Default windows: logarithmically spaced
    if windows is None:
        windows = [int(w) for w in np.logspace(1, np.log10(n_time // 4), 10)]

    fano_results = {}
    for w in windows:
        fano_values, info = fano(spikes, window=w, overlap=overlap)
        fano_results[w] = fano_values

    if mode == "individual":
        return _plot_fano_individual(
            fano_results, windows, dt, neuron_indices, n_neurons
        )
    elif mode == "grouped":
        if group_by is None:
            raise ValueError("group_by must be specified for grouped mode")
        return _plot_fano_grouped(
            fano_results,
            windows,
            dt,
            spikes,
            neurons_df,
            connections_df,
            group_by,
            neuron_type_column,
        )
    elif mode == "distribution":
        return _plot_fano_distribution(fano_results, windows, dt)
    else:
        raise ValueError(f"Unknown mode: {mode}")

plot_network(sparse_mat, ax=None)

Plot a network graph from a sparse connectivity matrix.

Uses NetworkX spring layout to visualize the graph structure. Nodes are colored skyblue, edges are gray.

Parameters:

Name Type Description Default
sparse_mat sparray

Sparse matrix (scipy.sparse) representing connections. Non-zero entries indicate edges.

required
ax Axes | None

Existing axes to plot on. If None, creates new figure.

None

Returns:

Type Description
Figure

Figure containing the network plot.

Raises:

Type Description
ImportError

If networkx is not installed.

Example

from scipy.sparse import random mat = random(50, 50, density=0.1, format="csr") fig = plot_network(mat)

Source code in btorch/visualisation/network.py
def plot_network(sparse_mat: scipy.sparse.sparray, ax: Axes | None = None) -> Figure:
    """Plot a network graph from a sparse connectivity matrix.

    Uses NetworkX spring layout to visualize the graph structure.
    Nodes are colored skyblue, edges are gray.

    Args:
        sparse_mat: Sparse matrix (scipy.sparse) representing connections.
            Non-zero entries indicate edges.
        ax: Existing axes to plot on. If None, creates new figure.

    Returns:
        Figure containing the network plot.

    Raises:
        ImportError: If networkx is not installed.

    Example:
        >>> from scipy.sparse import random
        >>> mat = random(50, 50, density=0.1, format="csr")
        >>> fig = plot_network(mat)
    """
    import matplotlib.pyplot as plt
    import networkx as nx

    G = nx.from_scipy_sparse_array(sparse_mat)
    pos = nx.spring_layout(G)

    if ax is None:
        fig, ax = plt.subplots(figsize=(8, 8))
    else:
        fig = ax.figure

    nx.draw(
        G,
        pos,
        with_labels=True,
        node_color="skyblue",
        edge_color="gray",
        ax=ax,
    )
    ax.set_title("Network Graph")
    return fig

plot_neuron_traces(states, format=None)

Plot neuron state traces.

Each selected neuron gets a row of subplots showing voltage, ASC and PSC traces. All data goes into states and all presentation options (neuron selection, panels, labels, layout) into format.

Parameters:

Name Type Description Default
states SimulationStates

Simulation state arrays, dt, thresholds and PSC labels (:class:SimulationStates). Arrays are (time, neurons) or (time, batch, neurons); ASC/PSC may add a trailing component axis. If psc has a component axis (n_psc > 1), epsc, ipsc and input must be None.

required
format TracePlotFormat | None

Neuron selection, panel visibility, labels, per-neuron styles and figure layout (:class:TracePlotFormat). Defaults to TracePlotFormat().

None

Returns:

Type Description
Figure | dict[str, Figure]

Figure with neuron trace subplots, or a dict of figures (one per trace

Figure | dict[str, Figure]

type) when format.separate_figures is True.

Raises:

Type Description
ValueError

On invalid shapes, neurons_per_row < 1, conflicting PSC layouts, or a bad batch_idx / threshold length.

Source code in btorch/visualisation/timeseries/neuron_traces.py
def plot_neuron_traces(
    states: SimulationStates,
    format: TracePlotFormat | None = None,
) -> Figure | dict[str, Figure]:
    """Plot neuron state traces.

    Each selected neuron gets a row of subplots showing voltage, ASC and PSC
    traces. All data goes into ``states`` and all presentation options
    (neuron selection, panels, labels, layout) into ``format``.

    Args:
        states: Simulation state arrays, ``dt``, thresholds and PSC labels
            (:class:`SimulationStates`). Arrays are (time, neurons) or
            (time, batch, neurons); ASC/PSC may add a trailing component
            axis. If ``psc`` has a component axis (n_psc > 1), ``epsc``,
            ``ipsc`` and ``input`` must be None.
        format: Neuron selection, panel visibility, labels, per-neuron styles
            and figure layout (:class:`TracePlotFormat`). Defaults to
            ``TracePlotFormat()``.

    Returns:
        Figure with neuron trace subplots, or a dict of figures (one per trace
        type) when ``format.separate_figures`` is True.

    Raises:
        ValueError: On invalid shapes, ``neurons_per_row < 1``, conflicting PSC
            layouts, or a bad ``batch_idx`` / threshold length.
    """
    fmt = format or TracePlotFormat()
    data = _prepare_trace_data(states, fmt.batch_idx)
    n_time, n_neurons = data.voltage.shape
    times = np.arange(n_time) * states.dt
    duration_ms = n_time * states.dt

    neuron_indices = _select_trace_neurons(
        n_neurons, fmt.neuron_indices, fmt.sample_size, fmt.seed
    )
    n_plot = len(neuron_indices)
    neurons_per_row = 1 if fmt.neurons_per_row is None else fmt.neurons_per_row
    if neurons_per_row < 1:
        raise ValueError("neurons_per_row must be >= 1")

    v_thresholds = _resolve_per_neuron_values(
        states.v_threshold, neuron_indices, n_neurons, "v_threshold"
    )
    v_resets = _resolve_per_neuron_values(
        states.v_reset, neuron_indices, n_neurons, "v_reset"
    )

    if fmt.auto_width:
        # ~1 inch per 40 ms, bounded to [10, 30]
        base_width = max(10.0, min(duration_ms * 0.025, 30.0))
    else:
        base_width = fmt.figsize_per_neuron[0]
    height_per_row = fmt.figsize_per_neuron[1]

    colors = fmt.colors or _DEFAULT_TRACE_COLORS
    resolve_label = _make_label_resolver(fmt.neuron_labels)
    kinds = _trace_panel_kinds(fmt, data)

    if fmt.separate_figures:
        return _plot_separate_trace_figures(
            kinds,
            data,
            neuron_indices,
            times,
            colors,
            fmt,
            v_thresholds,
            v_resets,
            resolve_label,
            fmt.neuron_label_position,
            (base_width, height_per_row * n_plot),
            fmt.neuron_specs,
        )

    if not kinds:
        # Nothing requested/available: fall back to the required voltage panel.
        kinds = ["voltage"]

    resolved_labels = [
        resolve_label(plot_idx, neuron_idx)
        for plot_idx, neuron_idx in enumerate(neuron_indices)
    ]
    max_label_len = max((len(label) for label in resolved_labels if label), default=0)
    top_labels = fmt.neuron_label_position == "top"

    grid = _create_trace_grid(
        n_plot,
        len(kinds),
        neurons_per_row,
        top_labels,
        max_label_len,
        base_width,
        height_per_row,
    )
    used_axes = _draw_combined_traces(
        grid,
        kinds,
        data,
        neuron_indices,
        times,
        colors,
        fmt,
        v_thresholds,
        v_resets,
        fmt.neuron_specs,
        resolved_labels,
    )
    _hide_unused_trace_axes(grid, used_axes, n_plot)
    if top_labels and grid.label_axes:
        _widen_for_top_labels(grid)

    right_margin = 0.96 if fmt.neuron_label_position == "side" else 1.0
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        grid.fig.tight_layout(rect=(0.0, 0.0, right_margin, 1.0), w_pad=0.8, h_pad=0.8)
    return grid.fig

plot_neuropil_timeseries_overview(data, *, dt, mode='all_innervated', agg='mean', connections=None, neurons=None, kind='wave', figsize=(12, 8), cmap='viridis', top_n=50, use_polars=False, show=False)

Plot aggregated neuropil traces as a single overview figure.

Visualizes neural activity aggregated by brain regions (neuropils). Can display as stacked waveforms or a heatmap.

Parameters:

Name Type Description Default
data TensorLike | Mapping[str, TensorLike]

Spike matrix (time, neurons) or pre-computed dict of {region_name: activity_array}.

required
dt float

Time step in seconds for x-axis scaling.

required
mode Literal['top_innervated', 'all_innervated']

Aggregation mode - "top_innervated" uses primary neuropil per neuron, "all_innervated" includes all neuropil connections.

'all_innervated'
agg AggName

Aggregation function applied per neuropil ("mean", "sum", "std").

'mean'
connections DataFrame | None

DataFrame with connection metadata (required if data is a matrix, not a dict).

None
neurons DataFrame | None

DataFrame with neuron metadata (required if data is a matrix, not a dict).

None
kind Literal['wave', 'heatmap']

Visualization style - "wave" for stacked traces, "heatmap" for 2D intensity map.

'wave'
figsize tuple[float, float]

Figure size (width, height) in inches.

(12, 8)
cmap str

Colormap for heatmap style.

'viridis'
top_n int

Number of top regions to show in wave style (ranked by maximum absolute activity).

50
use_polars bool

Whether to use Polars for aggregation (faster for large datasets).

False
show bool

Whether to call plt.show() before returning.

False

Returns:

Type Description
tuple[Figure, Axes]

Tuple of (figure, axes) containing the plot.

Raises:

Type Description
ValueError

If no neuropil traces can be computed from inputs.

Example

fig, ax = plot_neuropil_timeseries_overview( ... spikes, dt=0.001, connections=conn_df, neurons=neurons_df ... )

Source code in btorch/visualisation/aggregation.py
def plot_neuropil_timeseries_overview(
    data: TensorLike | Mapping[str, TensorLike],
    *,
    dt: float,
    mode: Literal["top_innervated", "all_innervated"] = "all_innervated",
    agg: AggName = "mean",
    connections: pd.DataFrame | None = None,
    neurons: pd.DataFrame | None = None,
    kind: Literal["wave", "heatmap"] = "wave",
    figsize: tuple[float, float] = (12, 8),
    cmap: str = "viridis",
    top_n: int = 50,
    use_polars: bool = False,
    show: bool = False,
) -> tuple[Figure, Axes]:
    """Plot aggregated neuropil traces as a single overview figure.

    Visualizes neural activity aggregated by brain regions (neuropils).
    Can display as stacked waveforms or a heatmap.

    Args:
        data: Spike matrix (time, neurons) or pre-computed dict of
            {region_name: activity_array}.
        dt: Time step in seconds for x-axis scaling.
        mode: Aggregation mode - "top_innervated" uses primary neuropil per
            neuron, "all_innervated" includes all neuropil connections.
        agg: Aggregation function applied per neuropil ("mean", "sum", "std").
        connections: DataFrame with connection metadata (required if `data`
            is a matrix, not a dict).
        neurons: DataFrame with neuron metadata (required if `data` is a
            matrix, not a dict).
        kind: Visualization style - "wave" for stacked traces, "heatmap"
            for 2D intensity map.
        figsize: Figure size (width, height) in inches.
        cmap: Colormap for heatmap style.
        top_n: Number of top regions to show in wave style (ranked by
            maximum absolute activity).
        use_polars: Whether to use Polars for aggregation (faster for large
            datasets).
        show: Whether to call `plt.show()` before returning.

    Returns:
        Tuple of (figure, axes) containing the plot.

    Raises:
        ValueError: If no neuropil traces can be computed from inputs.

    Example:
        >>> fig, ax = plot_neuropil_timeseries_overview(
        ...     spikes, dt=0.001, connections=conn_df, neurons=neurons_df
        ... )
    """
    traces = _resolve_neuropil_traces(
        data,
        mode=mode,
        agg=agg,
        connections=connections,
        neurons=neurons,
        use_polars=use_polars,
    )
    if not traces:
        raise ValueError("No neuropil traces available for plotting.")

    n_time = len(next(iter(traces.values())))
    time_points = np.arange(n_time, dtype=float) * dt

    fig, ax = plt.subplots(figsize=figsize)
    if kind == "wave":
        _plot_wave_style(ax, traces, time_points, top_n=top_n)
    else:
        _plot_heatmap_style(ax, traces, time_points, cmap=cmap)

    ax.set_ylabel("Neuropil Activity (z-scored)", fontsize=12)
    ax.set_title("Neuropil Activity Traces", fontsize=14)
    ax.set_xlabel("Time (s)", fontsize=12)

    fig.tight_layout()
    if show:
        plt.show()
    return fig, ax

plot_neuropil_timeseries_panels(data, *, dt, mode='all_innervated', agg='mean', connections=None, neurons=None, regions=None, figsize=(15, 10), cols=3, use_polars=False, show=False)

Plot selected neuropil traces as a subplot grid.

Creates a grid of subplots showing individual neuropil activity traces, with optional statistics annotations.

Parameters:

Name Type Description Default
data TensorLike | Mapping[str, TensorLike]

Spike matrix (time, neurons) or pre-computed dict of {region_name: activity_array}.

required
dt float

Time step in seconds for x-axis scaling.

required
mode Literal['top_innervated', 'all_innervated']

Aggregation mode - "top_innervated" or "all_innervated".

'all_innervated'
agg AggName

Aggregation function applied per neuropil ("mean", "sum", "std").

'mean'
connections DataFrame | None

DataFrame with connection metadata.

None
neurons DataFrame | None

DataFrame with neuron metadata.

None
regions Sequence[str] | None

List of region names to plot. If None, top 9 regions by maximum activity are selected automatically.

None
figsize tuple[float, float]

Figure size (width, height) in inches.

(15, 10)
cols int

Number of columns in the subplot grid.

3
use_polars bool

Whether to use Polars for aggregation.

False
show bool

Whether to call plt.show() before returning.

False

Returns:

Type Description
tuple[Figure, ndarray]

Tuple of (figure, axes_array) containing the subplot grid.

Raises:

Type Description
ValueError

If no neuropil traces available or regions is empty.

Source code in btorch/visualisation/aggregation.py
def plot_neuropil_timeseries_panels(
    data: TensorLike | Mapping[str, TensorLike],
    *,
    dt: float,
    mode: Literal["top_innervated", "all_innervated"] = "all_innervated",
    agg: AggName = "mean",
    connections: pd.DataFrame | None = None,
    neurons: pd.DataFrame | None = None,
    regions: Sequence[str] | None = None,
    figsize: tuple[float, float] = (15, 10),
    cols: int = 3,
    use_polars: bool = False,
    show: bool = False,
) -> tuple[Figure, np.ndarray]:
    """Plot selected neuropil traces as a subplot grid.

    Creates a grid of subplots showing individual neuropil activity traces,
    with optional statistics annotations.

    Args:
        data: Spike matrix (time, neurons) or pre-computed dict of
            {region_name: activity_array}.
        dt: Time step in seconds for x-axis scaling.
        mode: Aggregation mode - "top_innervated" or "all_innervated".
        agg: Aggregation function applied per neuropil ("mean", "sum", "std").
        connections: DataFrame with connection metadata.
        neurons: DataFrame with neuron metadata.
        regions: List of region names to plot. If None, top 9 regions by
            maximum activity are selected automatically.
        figsize: Figure size (width, height) in inches.
        cols: Number of columns in the subplot grid.
        use_polars: Whether to use Polars for aggregation.
        show: Whether to call `plt.show()` before returning.

    Returns:
        Tuple of (figure, axes_array) containing the subplot grid.

    Raises:
        ValueError: If no neuropil traces available or regions is empty.
    """
    traces = _resolve_neuropil_traces(
        data,
        mode=mode,
        agg=agg,
        connections=connections,
        neurons=neurons,
        use_polars=use_polars,
    )
    if not traces:
        raise ValueError("No neuropil traces available for plotting.")

    if regions is None:
        ranked = sorted(
            traces.items(),
            key=lambda x: float(np.max(np.abs(np.asarray(x[1])))),
            reverse=True,
        )[:9]
        regions = [region for region, _ in ranked]

    n_regions = len(regions)
    if n_regions == 0:
        raise ValueError("`regions` must contain at least one region.")

    rows = int(np.ceil(n_regions / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize)
    if rows == 1:
        axes = np.asarray(axes).reshape(1, -1)
    if cols == 1:
        axes = np.asarray(axes).reshape(-1, 1)

    n_time = len(next(iter(traces.values())))
    time_points = np.arange(n_time, dtype=float) * dt

    for i, region in enumerate(regions):
        row = i // cols
        col = i % cols
        ax = axes[row, col]

        if region in traces:
            activity = np.asarray(traces[region])
            ax.plot(time_points, activity, linewidth=1.5, color="darkblue")
            ax.set_title(str(region), fontsize=10)
            ax.set_xlabel("Time (s)", fontsize=8)
            ax.set_ylabel("Activity", fontsize=8)
            ax.grid(True, alpha=0.3)

            mean_act = float(np.mean(activity))
            std_act = float(np.std(activity))
            ax.text(
                0.02,
                0.98,
                f"μ={mean_act:.2f}\nσ={std_act:.2f}",
                transform=ax.transAxes,
                verticalalignment="top",
                bbox=dict(boxstyle="round", facecolor="white", alpha=0.8),
                fontsize=8,
            )

    for i in range(n_regions, rows * cols):
        row = i // cols
        col = i % cols
        fig.delaxes(axes[row, col])

    fig.suptitle("Neuropil Activity Comparison", fontsize=16)
    fig.tight_layout()
    if show:
        plt.show()
    return fig, axes

plot_raster(spikes, *, dt=None, times=None, ax=None, title=None, xlabel='Time (ms)', ylabel='Neuron Index', style=None, grouping=None, strip=None, rate=None, annotations=None)

Plot spike raster with optional grouping and styling.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix of shape (time, neurons).

required
dt float | None

Time step in ms. Default is 1.0 if times is not provided.

None
times Sequence[float] | None

Explicit time array.

None
ax Axes | None

Axis to plot on. If None, a new figure is created. Ignored (with a warning) when a rate panel is requested.

None
title str | None

Plot title; defaults to a "Fired/Spikes" summary.

None
xlabel str

Label for the x-axis (moved to the rate panel if present).

'Time (ms)'
ylabel str

Label for the y-axis.

'Neuron Index'
style RasterStyle | None

Marker, colour and per-neuron styling (:class:RasterStyle).

None
grouping RasterGrouping | None

Neuron grouping and separators (:class:RasterGrouping).

None
strip GroupStripOptions | None

Group colour strip (:class:GroupStripOptions); None draws no strip.

None
rate RatePanelOptions | None

Firing-rate panel (:class:RatePanelOptions); None draws no panel.

None
annotations RasterAnnotations | None

Events, regions and tracks (:class:RasterAnnotations).

None

Returns:

Type Description
Axes | tuple[Axes, Axes]

ax_raster, or (ax_raster, ax_rate) when a rate panel is drawn.

Raises:

Type Description
ValueError

If spikes is not 2D, or per-group rates are requested without grouping.group_key.

Source code in btorch/visualisation/timeseries/raster.py
def plot_raster(
    spikes: np.ndarray | torch.Tensor,
    *,
    dt: float | None = None,
    times: Sequence[float] | None = None,
    ax: Axes | None = None,
    title: str | None = None,
    xlabel: str = "Time (ms)",
    ylabel: str = "Neuron Index",
    style: RasterStyle | None = None,
    grouping: RasterGrouping | None = None,
    strip: GroupStripOptions | None = None,
    rate: RatePanelOptions | None = None,
    annotations: RasterAnnotations | None = None,
) -> Axes | tuple[Axes, Axes]:
    """Plot spike raster with optional grouping and styling.

    Args:
        spikes: Spike matrix of shape (time, neurons).
        dt: Time step in ms. Default is 1.0 if ``times`` is not provided.
        times: Explicit time array.
        ax: Axis to plot on. If None, a new figure is created. Ignored (with a
            warning) when a rate panel is requested.
        title: Plot title; defaults to a "Fired/Spikes" summary.
        xlabel: Label for the x-axis (moved to the rate panel if present).
        ylabel: Label for the y-axis.
        style: Marker, colour and per-neuron styling (:class:`RasterStyle`).
        grouping: Neuron grouping and separators (:class:`RasterGrouping`).
        strip: Group colour strip (:class:`GroupStripOptions`); None draws no
            strip.
        rate: Firing-rate panel (:class:`RatePanelOptions`); None draws no
            panel.
        annotations: Events, regions and tracks (:class:`RasterAnnotations`).

    Returns:
        ``ax_raster``, or ``(ax_raster, ax_rate)`` when a rate panel is drawn.

    Raises:
        ValueError: If ``spikes`` is not 2D, or per-group rates are requested
            without ``grouping.group_key``.
    """
    style_opts = style or RasterStyle()
    grouping = grouping or RasterGrouping()
    strip = strip or GroupStripOptions(show=False)
    rate = rate or RatePanelOptions()
    annotations = annotations or RasterAnnotations()
    group_key = grouping.group_key
    neurons_df = grouping.neurons_df

    spikes_np = to_numpy(spikes)
    if spikes_np.ndim != 2:
        raise ValueError("spikes must be 2D (time, neurons)")

    n_time, n_neurons = spikes_np.shape
    t = _get_time_axis(n_time, dt, times)

    show_group_rate = _wants_group_rate(rate)
    with_rate_panel = _wants_total_rate(rate) or show_group_rate
    if show_group_rate and group_key is None:
        raise ValueError(
            "RatePanelOptions.per_group requires grouping.group_key (and "
            "neurons_df) so per-group rates can be computed."
        )

    ax_raster, ax_rate = _create_raster_axes(ax, n_neurons, with_rate_panel)
    groups = _resolve_raster_groups(n_neurons, grouping, strip)

    # sorted_indices[0] is plotted at y=0 (bottom).
    idx_map = np.empty(n_neurons)
    idx_map[groups.sorted_indices] = np.arange(len(groups.sorted_indices))

    orig_neuron_indices, spike_times = compute_raster(spikes_np, t)
    plot_neuron_indices = idx_map[orig_neuron_indices]

    spike_style = _resolve_spike_style(
        style_opts, grouping, groups, orig_neuron_indices, n_neurons
    )
    # With a group strip, spikes are drawn later using the strip colours.
    if not strip.show:
        _draw_spikes(ax_raster, spike_times, plot_neuron_indices, spike_style)

    ax_raster.set_xlim(t[0], t[-1])
    ax_raster.set_ylim(-0.5, n_neurons - 0.5)
    ax_raster.set_ylabel(ylabel)
    ax_raster.yaxis.set_major_locator(MaxNLocator(integer=True))

    _draw_raster_annotations(ax_raster, t, n_neurons, annotations)

    spike_count = len(spike_times)
    fired_neurons = len(np.unique(orig_neuron_indices)) if spike_count > 0 else 0
    stats_title = f"Fired {fired_neurons}/{n_neurons}, Spikes {spike_count}"
    ax_raster.set_title(title if title else f"Spike raster {stats_title}")

    if group_key and grouping.show_separators:
        _draw_group_separators(
            ax_raster,
            groups.boundaries,
            n_neurons,
            grouping.separator_style,
            label_groups=not strip.show,
            group_strip_side=strip.side,
        )

    if strip.show:
        strip_colors = _draw_group_strip(
            ax_raster, groups, neurons_df, group_key, strip, n_neurons
        )
        _draw_strip_spikes(
            ax_raster,
            spike_times,
            plot_neuron_indices,
            orig_neuron_indices,
            groups,
            strip_colors,
            spike_style,
            style_opts.marker_size,
        )

    ax_raster.text(
        0.01,
        0.99,
        f"N={spike_count}",
        transform=ax_raster.transAxes,
        ha="left",
        va="top",
        bbox=dict(facecolor="white", alpha=0.7, edgecolor="none"),
        fontsize=8,
    )

    if ax_rate is None:
        ax_raster.set_xlabel(xlabel)
        return ax_raster

    _draw_rate_panel(
        ax_raster,
        ax_rate,
        t,
        spikes_np,
        dt,
        xlabel,
        rate,
        groups,
        style_opts,
        strip,
    )
    return ax_raster, ax_rate

plot_spectrum(data, dt=None, nperseg=None, ax=None, mode='loglog', show_mean=True, title='Frequency Spectrum', color=None, label='Mean', alpha=0.2, mean_linewidth=1.5)

Plot frequency spectrum of timeseries data.

Computes power spectral density using Welch's method and visualizes the frequency content. For 2D input (time, neurons), plots individual traces with optional mean overlay.

Parameters:

Name Type Description Default
data ndarray | Tensor

Input timeseries with shape (time,) or (time, neurons).

required
dt float | None

Sampling interval in ms. Default 1.0.

None
nperseg int | None

Length of FFT segments. Default is min(256, time//4).

None
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None
mode str

Plot scale - "loglog" (default) or "semilogx".

'loglog'
show_mean bool

Whether to overlay the mean spectrum (for 2D data).

True
title str

Plot title.

'Frequency Spectrum'
color str | None

Color for traces. Uses default if None.

None
label str | None

Legend label for mean trace.

'Mean'
alpha float

Opacity for individual traces.

0.2
mean_linewidth float

Line width for mean trace.

1.5

Returns:

Type Description
tuple[ndarray, ndarray, Axes]

Tuple of (frequencies, power_spectrum, axes).

Example

freqs, power, ax = plot_spectrum(spikes, dt=1.0, mode="loglog")

Source code in btorch/visualisation/timeseries/spectrum.py
def plot_spectrum(
    data: np.ndarray | torch.Tensor,
    dt: float | None = None,
    nperseg: int | None = None,
    ax: Axes | None = None,
    mode: str = "loglog",
    show_mean: bool = True,
    title: str = "Frequency Spectrum",
    color: str | None = None,
    label: str | None = "Mean",
    alpha: float = 0.2,
    mean_linewidth: float = 1.5,
) -> tuple[np.ndarray, np.ndarray, Axes]:
    """Plot frequency spectrum of timeseries data.

    Computes power spectral density using Welch's method and visualizes
    the frequency content. For 2D input (time, neurons), plots individual
    traces with optional mean overlay.

    Args:
        data: Input timeseries with shape (time,) or (time, neurons).
        dt: Sampling interval in ms. Default 1.0.
        nperseg: Length of FFT segments. Default is min(256, time//4).
        ax: Existing axes to plot on. Creates new figure if None.
        mode: Plot scale - "loglog" (default) or "semilogx".
        show_mean: Whether to overlay the mean spectrum (for 2D data).
        title: Plot title.
        color: Color for traces. Uses default if None.
        label: Legend label for mean trace.
        alpha: Opacity for individual traces.
        mean_linewidth: Line width for mean trace.

    Returns:
        Tuple of (frequencies, power_spectrum, axes).

    Example:
        >>> freqs, power, ax = plot_spectrum(spikes, dt=1.0, mode="loglog")
    """
    data_np = to_numpy(data)
    if dt is None:
        dt = 1.0

    freqs, power = compute_spectrum(data_np, dt=dt, nperseg=nperseg)

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 4))

    power_db = 10 * np.log10(power)

    y_data = power if "log" in mode else power_db

    trace_color = color if color else "blue"
    mean_color = color if color else "black"

    if show_mean and data_np.ndim > 1:
        if alpha > 0:
            ax.plot(freqs, y_data, color=trace_color, alpha=alpha, lw=0.5)
        mean_power = y_data.mean(axis=1) if y_data.ndim > 1 else y_data
        ax.plot(freqs, mean_power, color=mean_color, lw=mean_linewidth, label=label)
    else:
        ax.plot(freqs, y_data, color=mean_color, label=label)

    if mode == "loglog":
        ax.set_xscale("log")
        ax.set_yscale("log")
        ax.set_ylabel("Power")
    elif mode == "semilogx":
        ax.set_xscale("log")
        ax.set_ylabel("Power (dB)")

    ax.set_xlabel("Frequency (Hz)")
    ax.set_title(title)

    return freqs, power, ax

plot_traces(data, dt=None, times=None, ax=None, neurons=None, labels=None, colors=None, title=None, xlabel='Time (ms)', ylabel=None, legend=True, alpha=0.8)

Plot continuous timeseries traces.

Parameters

data : array-like Shape (Time, Neurons) or (Time, Neurons, Features). dt : float, optional Time step. times : array-like, optional Explicit time array. ax : Axes, optional Axis to plot on. neurons : list of int or int, optional Indices of neurons to plot. If None, plots all (careful with large N). If int, samples that many neurons randomly. labels : list of str, optional Labels for the legend. colors : list of colors, optional Colors for traces. title : str, optional Plot title.

Returns

Axes

Source code in btorch/visualisation/timeseries/traces.py
def plot_traces(
    data: np.ndarray | torch.Tensor,
    dt: float | None = None,
    times: Sequence[float] | None = None,
    ax: Axes | None = None,
    neurons: Sequence[int] | int | None = None,
    labels: Sequence[str] | str | None = None,
    colors: Sequence[Any] | None = None,
    title: str | None = None,
    xlabel: str = "Time (ms)",
    ylabel: str | None = None,
    legend: bool = True,
    alpha: float = 0.8,
) -> Axes:
    """Plot continuous timeseries traces.

    Parameters
    ----------
    data : array-like
        Shape (Time, Neurons) or (Time, Neurons, Features).
    dt : float, optional
        Time step.
    times : array-like, optional
        Explicit time array.
    ax : Axes, optional
        Axis to plot on.
    neurons : list of int or int, optional
        Indices of neurons to plot. If None, plots all (careful with large N).
        If int, samples that many neurons randomly.
    labels : list of str, optional
        Labels for the legend.
    colors : list of colors, optional
        Colors for traces.
    title : str, optional
        Plot title.

    Returns
    -------
    Axes
    """
    data_np = to_numpy(data)
    t = _get_time_axis(data_np.shape[0], dt, times)

    if data_np.ndim == 2:
        data_np = data_np[:, :, np.newaxis]
    elif data_np.ndim != 3:
        raise ValueError("Data must be 2D (T, N) or 3D (T, N, F)")

    n_neurons = data_np.shape[1]
    if neurons is None:
        neuron_indices = np.arange(n_neurons)
    elif isinstance(neurons, int):
        if neurons >= n_neurons:
            neuron_indices = np.arange(n_neurons)
        else:
            neuron_indices = np.sort(
                np.random.choice(n_neurons, neurons, replace=False)
            )
    else:
        neuron_indices = np.array(neurons)

    n_features = data_np.shape[2]

    if ax is None:
        fig, ax = plt.subplots(figsize=(8, 4))

    if colors is None:
        cmap = plt.get_cmap("turbo", len(neuron_indices))
        colors = [cmap(i) for i in range(len(neuron_indices))]

    for i, idx in enumerate(neuron_indices):
        c = (
            colors[i]
            if isinstance(colors, (list, np.ndarray))
            and len(colors) == len(neuron_indices)
            else None
        )

        for feat in range(n_features):
            trace = data_np[:, idx, feat]

            lbl = None
            if labels is not None:
                if isinstance(labels, str):
                    lbl = f"{labels} {idx}"
                elif len(labels) == len(neuron_indices):
                    lbl = labels[i]
                else:
                    lbl = f"Neuron {idx}"
            else:
                lbl = f"Neuron {idx}"

            if n_features > 1:
                lbl += f" (f{feat})"

            ax.plot(t, trace, label=lbl, color=c, alpha=alpha)

    ax.set_xlabel(xlabel)
    if ylabel:
        ax.set_ylabel(ylabel)
    ax.set_xlim(t[0], t[-1])

    if title:
        ax.set_title(title)

    if legend and len(neuron_indices) <= 20:  # Limit legend clutter
        ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left")

    return ax

btorch.visualisation.aggregation

Attributes

AggName = Literal['mean', 'sum', 'std'] module-attribute

Reduction names resolved on numpy / torch by the agg_* helpers.

GroupPlotKind = Literal['violin', 'box', 'ecdf'] module-attribute

TensorLike = np.ndarray | torch.Tensor module-attribute

__all__ = ['GroupPlotKind', 'plot_group_distribution', 'plot_neuropil_timeseries_overview', 'plot_neuropil_timeseries_panels'] module-attribute

Functions:

_plot_box(ax, grouped_values, order, *, showfliers, alpha)

Source code in btorch/visualisation/aggregation.py
def _plot_box(
    ax: Axes,
    grouped_values: list[np.ndarray],
    order: list[object],
    *,
    showfliers: bool,
    alpha: float,
) -> None:
    box = ax.boxplot(
        grouped_values,
        tick_labels=[str(group) for group in order],
        patch_artist=True,
        showfliers=showfliers,
    )
    for patch in box["boxes"]:
        patch.set_alpha(alpha)

    for label in ax.get_xticklabels():
        label.set_rotation(45)
        label.set_ha("right")

_plot_ecdf(ax, ecdf_by_group, *, group_by, value_name, linewidth)

Source code in btorch/visualisation/aggregation.py
def _plot_ecdf(
    ax: Axes,
    ecdf_by_group: dict[object, pd.DataFrame],
    *,
    group_by: str,
    value_name: str,
    linewidth: float,
) -> None:
    for group, ecdf in ecdf_by_group.items():
        ax.step(
            ecdf[value_name].to_numpy(),
            ecdf["ecdf"].to_numpy(),
            where="post",
            label=str(group),
            linewidth=linewidth,
        )

    ax.set_xlabel(value_name)
    ax.set_ylabel("ECDF")
    ax.set_ylim(0.0, 1.0)
    ax.legend(title=group_by)

_plot_heatmap_style(ax, traces, time_points, *, cmap)

Source code in btorch/visualisation/aggregation.py
def _plot_heatmap_style(
    ax: Axes,
    traces: Mapping[str, np.ndarray],
    time_points: np.ndarray,
    *,
    cmap: str,
) -> None:
    regions = list(traces.keys())
    if not regions:
        raise ValueError("No regions available for heatmap plot.")

    activity_matrix = np.array([traces[region] for region in regions])
    im = ax.imshow(
        activity_matrix,
        aspect="auto",
        cmap=cmap,
        interpolation="nearest",
        extent=[time_points[0], time_points[-1], 0, len(regions)],
    )

    cbar = plt.colorbar(im, ax=ax)
    cbar.set_label("Activity Magnitude", fontsize=10)

    n_time_ticks = min(10, len(time_points))
    time_ticks = np.linspace(time_points[0], time_points[-1], n_time_ticks)
    ax.set_xticks(time_ticks)
    ax.set_xticklabels([f"{t:.1f}" for t in time_ticks])
    ax.set_yticks(np.arange(len(regions)) + 0.5)
    ax.set_yticklabels(regions, fontsize=8)

_plot_violin(ax, grouped_values, order, *, alpha)

Source code in btorch/visualisation/aggregation.py
def _plot_violin(
    ax: Axes,
    grouped_values: list[np.ndarray],
    order: list[object],
    *,
    alpha: float,
) -> None:
    parts = ax.violinplot(grouped_values, showmeans=False, showmedians=True)
    for body in parts["bodies"]:
        body.set_alpha(alpha)

    positions = np.arange(1, len(order) + 1)
    ax.set_xticks(positions)
    ax.set_xticklabels([str(group) for group in order], rotation=45, ha="right")

_plot_wave_style(ax, traces, time_points, *, top_n)

Source code in btorch/visualisation/aggregation.py
def _plot_wave_style(
    ax: Axes,
    traces: Mapping[str, np.ndarray],
    time_points: np.ndarray,
    *,
    top_n: int,
) -> None:
    ranked = sorted(
        traces.items(),
        key=lambda x: float(np.max(np.abs(x[1]))),
        reverse=True,
    )[:top_n]
    if not ranked:
        raise ValueError("No regions available for wave plot.")

    offset_step = 3.0
    stacked = np.concatenate([trace for _, trace in ranked])
    mean = float(stacked.mean())
    std = float(stacked.std())

    for i, (region, trace) in enumerate(ranked):
        offset = i * offset_step
        normalized = (trace - mean) / (std + 1e-8)
        ax.plot(
            time_points,
            normalized + offset,
            linewidth=0.8,
            alpha=0.7,
            label=str(region),
        )

    yticks = np.arange(len(ranked), dtype=float) * offset_step
    ax.set_yticks(yticks)
    ax.set_yticklabels([str(region) for region, _ in ranked], fontsize=8)
    ax.grid(True, alpha=0.3)

_resolve_figure_ax(*, ax, figsize)

Source code in btorch/visualisation/aggregation.py
def _resolve_figure_ax(
    *,
    ax: Axes | None,
    figsize: tuple[float, float],
) -> tuple[Figure, Axes]:
    if ax is not None:
        return ax.figure, ax

    fig, created_ax = plt.subplots(figsize=figsize)
    return fig, created_ax

_resolve_neuropil_traces(data, *, mode, agg, connections, neurons, use_polars)

Source code in btorch/visualisation/aggregation.py
def _resolve_neuropil_traces(
    data: TensorLike | Mapping[str, TensorLike],
    *,
    mode: Literal["top_innervated", "all_innervated"],
    agg: AggName,
    connections: pd.DataFrame | None,
    neurons: pd.DataFrame | None,
    use_polars: bool,
) -> dict[str, np.ndarray]:
    if isinstance(data, Mapping):
        traces = {key: np.asarray(value) for key, value in data.items()}
    else:
        pre_traces, _ = agg_by_neuropil(
            data,
            mode=mode,
            connections=connections,
            neurons=neurons,
            agg=agg,
            use_polars=use_polars,
        )
        traces = {key: np.asarray(value) for key, value in pre_traces.items()}

    if not traces:
        return {}

    lengths = {trace.shape[0] for trace in traces.values()}
    if len(lengths) != 1:
        raise ValueError("All neuropil traces must have the same time length.")

    return traces

agg_by_neuropil(y, neurons=None, connections=None, mode='all_innervated', agg='mean', use_polars=False)

Aggregate activations by neuropil under a validated aggregation mode.

Raises:

Type Description
ValueError

If mode="top_innervated" and neurons is None, if mode="all_innervated" and connections is None, or if mode is not one of the two supported values.

Source code in btorch/analysis/aggregation.py
def agg_by_neuropil(
    y,
    neurons: pd.DataFrame | None = None,
    connections: pd.DataFrame | None = None,
    mode: Literal["top_innervated", "all_innervated"] = "all_innervated",
    agg: AggName = "mean",
    use_polars: bool = False,
) -> tuple[dict, dict]:
    """Aggregate activations by neuropil under a validated aggregation mode.

    Raises:
        ValueError: If ``mode="top_innervated"`` and ``neurons`` is None, if
            ``mode="all_innervated"`` and ``connections`` is None, or if
            ``mode`` is not one of the two supported values.
    """
    agg_func = getattr(np, agg) if isinstance(y, np.ndarray) else getattr(torch, agg)
    if use_polars:
        # polars is an accelerator (``pip install "btorch[fast]"``): without it
        # the numpy/torch path below gives identical results, only slower.
        try:
            import polars as pl
        except ImportError:
            use_polars = False

    if mode == "top_innervated":
        if neurons is None:
            raise ValueError("neurons must be provided for top_innervated mode")
        tmp = neurons[["group", "simple_id"]].copy()
        tmp = tmp[tmp["simple_id"] < y.shape[-1]]
        pre_ret: dict = {}
        post_ret: dict = {}

        if use_polars:
            tmp["pre"] = tmp["group"].str.split(".").str[0]
            tmp["post"] = tmp["group"].str.split(".").str[-1]
            ptbl = pl.from_pandas(tmp)

            pre_groups = ptbl.group_by("pre", maintain_order=True).agg(
                pl.col("simple_id")
            )
            for row in pre_groups.iter_rows(named=True):
                sid = np.asarray(row["simple_id"], dtype=int)
                pre_ret[row["pre"]] = agg_func(y[..., sid], -1)

            post_groups = ptbl.group_by("post", maintain_order=True).agg(
                pl.col("simple_id")
            )
            for row in post_groups.iter_rows(named=True):
                sid = np.asarray(row["simple_id"], dtype=int)
                post_ret[row["post"]] = agg_func(y[..., sid], -1)
        else:
            tmp["pre"] = tmp["group"].apply(lambda x: x.split(".")[0])
            tmp["post"] = tmp["group"].apply(lambda x: x.split(".")[-1])
            for pre, group in tmp.groupby("pre", dropna=True):
                pre_ret[pre] = agg_func(y[..., group.simple_id], -1)
            for post, group in tmp.groupby("post", dropna=True):
                post_ret[post] = agg_func(y[..., group.simple_id], -1)
        return pre_ret, post_ret
    if mode == "all_innervated":
        if connections is None:
            raise ValueError("connections must be provided for all_innervated mode")
        tmp = connections[["pre_simple_id", "post_simple_id", "neuropil"]]
        tmp = tmp[
            (tmp["pre_simple_id"] < y.shape[-1]) & (tmp["post_simple_id"] < y.shape[-1])
        ]
        pre_ret: dict = {}
        post_ret: dict = {}

        if use_polars:
            ptbl = pl.from_pandas(tmp)
            groups = ptbl.group_by("neuropil", maintain_order=True).agg(
                pl.col("pre_simple_id"), pl.col("post_simple_id")
            )
            for row in groups.iter_rows(named=True):
                neuropil = row["neuropil"]
                pre_ids = np.asarray(row["pre_simple_id"], dtype=int)
                post_ids = np.asarray(row["post_simple_id"], dtype=int)
                pre_ret[neuropil] = agg_func(y[..., pre_ids], -1)
                post_ret[neuropil] = agg_func(y[..., post_ids], -1)
        else:
            for neuropil, group in tmp.groupby("neuropil", dropna=True):
                pre_ret[neuropil] = agg_func(y[..., group.pre_simple_id.to_numpy()], -1)
                post_ret[neuropil] = agg_func(
                    y[..., group.post_simple_id.to_numpy()], -1
                )
        return pre_ret, post_ret

    raise ValueError(
        "Invalid `mode` for `agg_by_neuropil`. "
        "Expected one of: {'top_innervated', 'all_innervated'}."
    )

group_ecdf(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', group_order=None, dropna=True)

Compute grouped ECDF points ready for plotting or analysis.

Source code in btorch/analysis/aggregation.py
def group_ecdf(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
) -> dict[object, pd.DataFrame]:
    """Compute grouped ECDF points ready for plotting or analysis."""
    grouped = group_values(
        values,
        neurons_df,
        group_by,
        simple_id_col=simple_id_col,
        value_name=value_name,
        group_order=group_order,
        dropna=dropna,
    )

    ret: dict[object, pd.DataFrame] = {}
    for group, vals in grouped.items():
        x = np.sort(vals)
        y = np.arange(1, len(x) + 1, dtype=float) / len(x)
        ret[group] = pd.DataFrame({value_name: x, "ecdf": y})
    return ret

group_values(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', group_order=None, dropna=True)

Return grouped value arrays, keyed by group label in plotting order.

Source code in btorch/analysis/aggregation.py
def group_values(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
) -> dict[object, np.ndarray]:
    """Return grouped value arrays, keyed by group label in plotting order."""
    frame = build_group_frame(
        values,
        neurons_df,
        group_by,
        simple_id_col=simple_id_col,
        value_name=value_name,
        dropna=dropna,
    )
    order = _resolve_group_order(frame, group_by, group_order)
    return {
        group: frame.loc[frame[group_by] == group, value_name].to_numpy(dtype=float)
        for group in order
    }

plot_group_distribution(values, neurons_df, group_by, *, kind='violin', simple_id_col='simple_id', value_name='value', group_order=None, dropna=True, ax=None, figsize=(9.0, 5.0), title=None, showfliers=False, linewidth=1.5, alpha=0.8)

Plot grouped value distributions as violin, box, or ECDF.

Groups per-neuron values by a categorical column in neurons_df and visualizes the distribution using the specified plot type.

Parameters:

Name Type Description Default
values TensorLike

Per-neuron values with shape (neurons,) or (time, neurons). If 2D, values are flattened across time for each neuron.

required
neurons_df DataFrame

DataFrame with neuron metadata. Must contain simple_id_col and group_by columns.

required
group_by str

Column name in neurons_df to group by (e.g., "cell_type").

required
kind GroupPlotKind

Plot type - "violin", "box", or "ecdf".

'violin'
simple_id_col str

Column name for neuron identifiers in neurons_df.

'simple_id'
value_name str

Label for the y-axis / value dimension.

'value'
group_order Sequence | None

Explicit order for groups. If None, uses natural sort.

None
dropna bool

Whether to drop NaN values before plotting.

True
ax Axes | None

Existing axes to plot on. If None, creates new figure.

None
figsize tuple[float, float]

Figure size (width, height) in inches.

(9.0, 5.0)
title str | None

Plot title. If None, auto-generated from kind and group_by.

None
showfliers bool

For box plots, whether to show outlier points.

False
linewidth float

Line width for ECDF curves.

1.5
alpha float

Opacity for violin/box fill.

0.8

Returns:

Type Description
tuple[Figure, Axes]

Tuple of (figure, axes) containing the plot.

Raises:

Type Description
ValueError

If kind is not one of "violin", "box", "ecdf".

Example

fig, ax = plot_group_distribution( ... firing_rates, neurons_df, group_by="cell_type", kind="violin" ... )

Source code in btorch/visualisation/aggregation.py
def plot_group_distribution(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    kind: GroupPlotKind = "violin",
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
    ax: Axes | None = None,
    figsize: tuple[float, float] = (9.0, 5.0),
    title: str | None = None,
    showfliers: bool = False,
    linewidth: float = 1.5,
    alpha: float = 0.8,
) -> tuple[Figure, Axes]:
    """Plot grouped value distributions as violin, box, or ECDF.

    Groups per-neuron values by a categorical column in `neurons_df` and
    visualizes the distribution using the specified plot type.

    Args:
        values: Per-neuron values with shape (neurons,) or (time, neurons).
            If 2D, values are flattened across time for each neuron.
        neurons_df: DataFrame with neuron metadata. Must contain `simple_id_col`
            and `group_by` columns.
        group_by: Column name in `neurons_df` to group by (e.g., "cell_type").
        kind: Plot type - "violin", "box", or "ecdf".
        simple_id_col: Column name for neuron identifiers in `neurons_df`.
        value_name: Label for the y-axis / value dimension.
        group_order: Explicit order for groups. If None, uses natural sort.
        dropna: Whether to drop NaN values before plotting.
        ax: Existing axes to plot on. If None, creates new figure.
        figsize: Figure size (width, height) in inches.
        title: Plot title. If None, auto-generated from `kind` and `group_by`.
        showfliers: For box plots, whether to show outlier points.
        linewidth: Line width for ECDF curves.
        alpha: Opacity for violin/box fill.

    Returns:
        Tuple of (figure, axes) containing the plot.

    Raises:
        ValueError: If `kind` is not one of "violin", "box", "ecdf".

    Example:
        >>> fig, ax = plot_group_distribution(
        ...     firing_rates, neurons_df, group_by="cell_type", kind="violin"
        ... )
    """
    fig, ax = _resolve_figure_ax(ax=ax, figsize=figsize)

    if kind in {"violin", "box"}:
        grouped = group_values(
            values,
            neurons_df,
            group_by,
            simple_id_col=simple_id_col,
            value_name=value_name,
            group_order=group_order,
            dropna=dropna,
        )
        order = list(grouped.keys())
        grouped_arrays = [grouped[group] for group in order]

        if kind == "violin":
            _plot_violin(ax, grouped_arrays, order, alpha=alpha)
        else:
            _plot_box(
                ax,
                grouped_arrays,
                order,
                showfliers=showfliers,
                alpha=alpha,
            )

        ax.set_xlabel(group_by)
        ax.set_ylabel(value_name)
    elif kind == "ecdf":
        ecdf_by_group = group_ecdf(
            values,
            neurons_df,
            group_by,
            simple_id_col=simple_id_col,
            value_name=value_name,
            group_order=group_order,
            dropna=dropna,
        )
        _plot_ecdf(
            ax,
            ecdf_by_group,
            group_by=group_by,
            value_name=value_name,
            linewidth=linewidth,
        )
    else:
        raise ValueError(f"Unsupported kind `{kind}`.")

    if title is None:
        title = f"{kind.upper()} grouped by {group_by}"
    ax.set_title(title)
    ax.grid(alpha=0.2)

    return fig, ax

plot_neuropil_timeseries_overview(data, *, dt, mode='all_innervated', agg='mean', connections=None, neurons=None, kind='wave', figsize=(12, 8), cmap='viridis', top_n=50, use_polars=False, show=False)

Plot aggregated neuropil traces as a single overview figure.

Visualizes neural activity aggregated by brain regions (neuropils). Can display as stacked waveforms or a heatmap.

Parameters:

Name Type Description Default
data TensorLike | Mapping[str, TensorLike]

Spike matrix (time, neurons) or pre-computed dict of {region_name: activity_array}.

required
dt float

Time step in seconds for x-axis scaling.

required
mode Literal['top_innervated', 'all_innervated']

Aggregation mode - "top_innervated" uses primary neuropil per neuron, "all_innervated" includes all neuropil connections.

'all_innervated'
agg AggName

Aggregation function applied per neuropil ("mean", "sum", "std").

'mean'
connections DataFrame | None

DataFrame with connection metadata (required if data is a matrix, not a dict).

None
neurons DataFrame | None

DataFrame with neuron metadata (required if data is a matrix, not a dict).

None
kind Literal['wave', 'heatmap']

Visualization style - "wave" for stacked traces, "heatmap" for 2D intensity map.

'wave'
figsize tuple[float, float]

Figure size (width, height) in inches.

(12, 8)
cmap str

Colormap for heatmap style.

'viridis'
top_n int

Number of top regions to show in wave style (ranked by maximum absolute activity).

50
use_polars bool

Whether to use Polars for aggregation (faster for large datasets).

False
show bool

Whether to call plt.show() before returning.

False

Returns:

Type Description
tuple[Figure, Axes]

Tuple of (figure, axes) containing the plot.

Raises:

Type Description
ValueError

If no neuropil traces can be computed from inputs.

Example

fig, ax = plot_neuropil_timeseries_overview( ... spikes, dt=0.001, connections=conn_df, neurons=neurons_df ... )

Source code in btorch/visualisation/aggregation.py
def plot_neuropil_timeseries_overview(
    data: TensorLike | Mapping[str, TensorLike],
    *,
    dt: float,
    mode: Literal["top_innervated", "all_innervated"] = "all_innervated",
    agg: AggName = "mean",
    connections: pd.DataFrame | None = None,
    neurons: pd.DataFrame | None = None,
    kind: Literal["wave", "heatmap"] = "wave",
    figsize: tuple[float, float] = (12, 8),
    cmap: str = "viridis",
    top_n: int = 50,
    use_polars: bool = False,
    show: bool = False,
) -> tuple[Figure, Axes]:
    """Plot aggregated neuropil traces as a single overview figure.

    Visualizes neural activity aggregated by brain regions (neuropils).
    Can display as stacked waveforms or a heatmap.

    Args:
        data: Spike matrix (time, neurons) or pre-computed dict of
            {region_name: activity_array}.
        dt: Time step in seconds for x-axis scaling.
        mode: Aggregation mode - "top_innervated" uses primary neuropil per
            neuron, "all_innervated" includes all neuropil connections.
        agg: Aggregation function applied per neuropil ("mean", "sum", "std").
        connections: DataFrame with connection metadata (required if `data`
            is a matrix, not a dict).
        neurons: DataFrame with neuron metadata (required if `data` is a
            matrix, not a dict).
        kind: Visualization style - "wave" for stacked traces, "heatmap"
            for 2D intensity map.
        figsize: Figure size (width, height) in inches.
        cmap: Colormap for heatmap style.
        top_n: Number of top regions to show in wave style (ranked by
            maximum absolute activity).
        use_polars: Whether to use Polars for aggregation (faster for large
            datasets).
        show: Whether to call `plt.show()` before returning.

    Returns:
        Tuple of (figure, axes) containing the plot.

    Raises:
        ValueError: If no neuropil traces can be computed from inputs.

    Example:
        >>> fig, ax = plot_neuropil_timeseries_overview(
        ...     spikes, dt=0.001, connections=conn_df, neurons=neurons_df
        ... )
    """
    traces = _resolve_neuropil_traces(
        data,
        mode=mode,
        agg=agg,
        connections=connections,
        neurons=neurons,
        use_polars=use_polars,
    )
    if not traces:
        raise ValueError("No neuropil traces available for plotting.")

    n_time = len(next(iter(traces.values())))
    time_points = np.arange(n_time, dtype=float) * dt

    fig, ax = plt.subplots(figsize=figsize)
    if kind == "wave":
        _plot_wave_style(ax, traces, time_points, top_n=top_n)
    else:
        _plot_heatmap_style(ax, traces, time_points, cmap=cmap)

    ax.set_ylabel("Neuropil Activity (z-scored)", fontsize=12)
    ax.set_title("Neuropil Activity Traces", fontsize=14)
    ax.set_xlabel("Time (s)", fontsize=12)

    fig.tight_layout()
    if show:
        plt.show()
    return fig, ax

plot_neuropil_timeseries_panels(data, *, dt, mode='all_innervated', agg='mean', connections=None, neurons=None, regions=None, figsize=(15, 10), cols=3, use_polars=False, show=False)

Plot selected neuropil traces as a subplot grid.

Creates a grid of subplots showing individual neuropil activity traces, with optional statistics annotations.

Parameters:

Name Type Description Default
data TensorLike | Mapping[str, TensorLike]

Spike matrix (time, neurons) or pre-computed dict of {region_name: activity_array}.

required
dt float

Time step in seconds for x-axis scaling.

required
mode Literal['top_innervated', 'all_innervated']

Aggregation mode - "top_innervated" or "all_innervated".

'all_innervated'
agg AggName

Aggregation function applied per neuropil ("mean", "sum", "std").

'mean'
connections DataFrame | None

DataFrame with connection metadata.

None
neurons DataFrame | None

DataFrame with neuron metadata.

None
regions Sequence[str] | None

List of region names to plot. If None, top 9 regions by maximum activity are selected automatically.

None
figsize tuple[float, float]

Figure size (width, height) in inches.

(15, 10)
cols int

Number of columns in the subplot grid.

3
use_polars bool

Whether to use Polars for aggregation.

False
show bool

Whether to call plt.show() before returning.

False

Returns:

Type Description
tuple[Figure, ndarray]

Tuple of (figure, axes_array) containing the subplot grid.

Raises:

Type Description
ValueError

If no neuropil traces available or regions is empty.

Source code in btorch/visualisation/aggregation.py
def plot_neuropil_timeseries_panels(
    data: TensorLike | Mapping[str, TensorLike],
    *,
    dt: float,
    mode: Literal["top_innervated", "all_innervated"] = "all_innervated",
    agg: AggName = "mean",
    connections: pd.DataFrame | None = None,
    neurons: pd.DataFrame | None = None,
    regions: Sequence[str] | None = None,
    figsize: tuple[float, float] = (15, 10),
    cols: int = 3,
    use_polars: bool = False,
    show: bool = False,
) -> tuple[Figure, np.ndarray]:
    """Plot selected neuropil traces as a subplot grid.

    Creates a grid of subplots showing individual neuropil activity traces,
    with optional statistics annotations.

    Args:
        data: Spike matrix (time, neurons) or pre-computed dict of
            {region_name: activity_array}.
        dt: Time step in seconds for x-axis scaling.
        mode: Aggregation mode - "top_innervated" or "all_innervated".
        agg: Aggregation function applied per neuropil ("mean", "sum", "std").
        connections: DataFrame with connection metadata.
        neurons: DataFrame with neuron metadata.
        regions: List of region names to plot. If None, top 9 regions by
            maximum activity are selected automatically.
        figsize: Figure size (width, height) in inches.
        cols: Number of columns in the subplot grid.
        use_polars: Whether to use Polars for aggregation.
        show: Whether to call `plt.show()` before returning.

    Returns:
        Tuple of (figure, axes_array) containing the subplot grid.

    Raises:
        ValueError: If no neuropil traces available or regions is empty.
    """
    traces = _resolve_neuropil_traces(
        data,
        mode=mode,
        agg=agg,
        connections=connections,
        neurons=neurons,
        use_polars=use_polars,
    )
    if not traces:
        raise ValueError("No neuropil traces available for plotting.")

    if regions is None:
        ranked = sorted(
            traces.items(),
            key=lambda x: float(np.max(np.abs(np.asarray(x[1])))),
            reverse=True,
        )[:9]
        regions = [region for region, _ in ranked]

    n_regions = len(regions)
    if n_regions == 0:
        raise ValueError("`regions` must contain at least one region.")

    rows = int(np.ceil(n_regions / cols))
    fig, axes = plt.subplots(rows, cols, figsize=figsize)
    if rows == 1:
        axes = np.asarray(axes).reshape(1, -1)
    if cols == 1:
        axes = np.asarray(axes).reshape(-1, 1)

    n_time = len(next(iter(traces.values())))
    time_points = np.arange(n_time, dtype=float) * dt

    for i, region in enumerate(regions):
        row = i // cols
        col = i % cols
        ax = axes[row, col]

        if region in traces:
            activity = np.asarray(traces[region])
            ax.plot(time_points, activity, linewidth=1.5, color="darkblue")
            ax.set_title(str(region), fontsize=10)
            ax.set_xlabel("Time (s)", fontsize=8)
            ax.set_ylabel("Activity", fontsize=8)
            ax.grid(True, alpha=0.3)

            mean_act = float(np.mean(activity))
            std_act = float(np.std(activity))
            ax.text(
                0.02,
                0.98,
                f"μ={mean_act:.2f}\nσ={std_act:.2f}",
                transform=ax.transAxes,
                verticalalignment="top",
                bbox=dict(boxstyle="round", facecolor="white", alpha=0.8),
                fontsize=8,
            )

    for i in range(n_regions, rows * cols):
        row = i // cols
        col = i % cols
        fig.delaxes(axes[row, col])

    fig.suptitle("Neuropil Activity Comparison", fontsize=16)
    fig.tight_layout()
    if show:
        plt.show()
    return fig, axes

btorch.visualisation.dynamics

Multiscale dynamics visualization with unified dual interface.

This module provides plotting functions for multiscale dynamics analysis including Fano factor, DFA (Detrended Fluctuation Analysis), ISI CV (Coefficient of Variation), and criticality analysis. Supports both dataclass and plain argument interfaces for flexible usage.

The visualization modes include: - Individual neuron traces - Grouped aggregations (by neuron type or neuropil) - Distribution summaries (violin, histogram)

Classes

DFAConfig dataclass

Configuration for DFA (Detrended Fluctuation Analysis).

Attributes:

Name Type Description
min_window int

Minimum window size for DFA in timesteps.

max_window int | None

Maximum window size. If None, auto-calculated.

bin_size int

Bin size for spike binning in timesteps.

Source code in btorch/visualisation/dynamics.py
@dataclass
class DFAConfig:
    """Configuration for DFA (Detrended Fluctuation Analysis).

    Attributes:
        min_window: Minimum window size for DFA in timesteps.
        max_window: Maximum window size. If None, auto-calculated.
        bin_size: Bin size for spike binning in timesteps.
    """

    min_window: int = 4
    max_window: int | None = None
    bin_size: int = 1

DynamicsData dataclass

Container for dynamics analysis data and configs.

Attributes:

Name Type Description
spikes ndarray | Tensor

Spike trains with shape (time, neurons).

dt float

Simulation timestep in milliseconds.

neurons_df DataFrame | None

DataFrame with neuron metadata for grouping.

connections_df DataFrame | None

DataFrame with connection metadata for neuropil aggregation.

Source code in btorch/visualisation/dynamics.py
@dataclass
class DynamicsData:
    """Container for dynamics analysis data and configs.

    Attributes:
        spikes: Spike trains with shape (time, neurons).
        dt: Simulation timestep in milliseconds.
        neurons_df: DataFrame with neuron metadata for grouping.
        connections_df: DataFrame with connection metadata for neuropil
            aggregation.
    """

    spikes: np.ndarray | torch.Tensor
    dt: float = 1.0
    neurons_df: pd.DataFrame | None = None
    connections_df: pd.DataFrame | None = None

DynamicsPlotFormat dataclass

Figure formatting for dynamics plots.

Attributes:

Name Type Description
mode Literal['individual', 'grouped', 'distribution']

Visualization mode - "individual" for specific neurons, "grouped" for aggregated groups, "distribution" for summary stats.

group_by Literal['neuropil', 'neuron_type', None]

Grouping method for aggregation ("neuropil" or "neuron_type").

neuron_type_column str

Column name in neurons_df for neuron classification.

neuron_indices list[int] | None

Specific neuron indices for individual mode.

colors dict | None

Color mapping dictionary.

figsize tuple[float, float] | None

Figure size as (width, height) in inches.

Source code in btorch/visualisation/dynamics.py
@dataclass
class DynamicsPlotFormat:
    """Figure formatting for dynamics plots.

    Attributes:
        mode: Visualization mode - "individual" for specific neurons,
            "grouped" for aggregated groups, "distribution" for summary stats.
        group_by: Grouping method for aggregation ("neuropil" or "neuron_type").
        neuron_type_column: Column name in neurons_df for neuron classification.
        neuron_indices: Specific neuron indices for individual mode.
        colors: Color mapping dictionary.
        figsize: Figure size as (width, height) in inches.
    """

    mode: Literal["individual", "grouped", "distribution"] = "individual"
    group_by: Literal["neuropil", "neuron_type", None] = None
    neuron_type_column: str = "cell_type"
    neuron_indices: list[int] | None = None
    colors: dict | None = None
    figsize: tuple[float, float] | None = None

FanoFactorConfig dataclass

Configuration for Fano factor analysis.

Attributes:

Name Type Description
windows list[int] | None

Time windows in timesteps for multiscale analysis. If None, logarithmically spaced windows are auto-generated.

overlap int

Overlap between consecutive windows in timesteps.

Source code in btorch/visualisation/dynamics.py
@dataclass
class FanoFactorConfig:
    """Configuration for Fano factor analysis.

    Attributes:
        windows: Time windows in timesteps for multiscale analysis.
            If None, logarithmically spaced windows are auto-generated.
        overlap: Overlap between consecutive windows in timesteps.
    """

    windows: list[int] | None = None
    overlap: int = 0

Functions:

_isi_cv_stats(spikes, dt)

Per-neuron ISI CV (NaN below three spikes) and its NaN-aware mean.

Source code in btorch/visualisation/dynamics.py
def _isi_cv_stats(spikes: np.ndarray, dt: float) -> dict:
    """Per-neuron ISI CV (NaN below three spikes) and its NaN-aware mean."""
    cv_values, _ = isi_cv(spikes, dt=dt)
    return {"cv_isi": cv_values, "mean": np.nanmean(cv_values)}

_plot_fano_distribution(fano_results, windows, dt)

Plot Fano factor distribution across neurons.

Source code in btorch/visualisation/dynamics.py
def _plot_fano_distribution(fano_results, windows, dt):
    """Plot Fano factor distribution across neurons."""
    fig, ax = plt.subplots(1, 1, figsize=(12, 6))

    # Use ordinal positions for violins to avoid log-scale width artifacts
    positions = np.arange(len(windows))
    data_list = [fano_results[w] for w in windows]

    ax.violinplot(
        data_list,
        positions=positions,
        widths=0.7,
        showmeans=True,
        showmedians=True,
    )

    ax.set_xticks(positions)
    labels = [f"{w * dt:.1f}" if (w * dt) % 1 else f"{int(w * dt)}" for w in windows]
    ax.set_xticklabels(labels, rotation=45, ha="right")

    ax.set_xlabel("Time Window (ms)")
    ax.set_ylabel("Fano Factor")
    ax.set_title("Multiscale Fano Factor - Distribution")
    ax.grid(alpha=0.3, axis="y")
    plt.tight_layout()
    return fig

_plot_fano_grouped(fano_results, windows, dt, spikes, neurons_df, connections_df, group_by, neuron_type_column)

Plot Fano factor grouped by neuropil or neuron type.

Source code in btorch/visualisation/dynamics.py
def _plot_fano_grouped(
    fano_results,
    windows,
    dt,
    spikes,
    neurons_df,
    connections_df,
    group_by,
    neuron_type_column,
):
    """Plot Fano factor grouped by neuropil or neuron type."""
    if group_by not in ("neuron_type", "neuropil"):
        raise ValueError(
            f"group_by must be 'neuron_type' or 'neuropil', got {group_by!r}"
        )
    if neurons_df is None and group_by == "neuron_type":
        raise ValueError("neurons_df required for neuron_type grouping")
    if connections_df is None and group_by == "neuropil":
        raise ValueError("connections_df required for neuropil grouping")

    fig, ax = plt.subplots(1, 1, figsize=(10, 6))

    # Organize data by group first: {group_name: [val_w1, val_w2, ...]}
    group_data = {}

    first_window_data = fano_results[windows[0]]
    if group_by == "neuron_type":
        grouped_init = agg_by_neuron(
            first_window_data,
            neurons_df,
            agg="mean",
            neuron_type_column=neuron_type_column,
        )
    elif group_by == "neuropil":
        grouped_init, _ = agg_by_neuropil(
            first_window_data,
            neurons=neurons_df,
            connections=connections_df,
            mode="top_innervated",
            agg="mean",
        )
        grouped_init = grouped_init if grouped_init else {}

    if grouped_init:
        for group_name in grouped_init.keys():
            group_data[group_name] = []

        for w in windows:
            fano_arr = fano_results[w]

            if group_by == "neuron_type":
                grouped = agg_by_neuron(
                    fano_arr,
                    neurons_df,
                    agg="mean",
                    neuron_type_column=neuron_type_column,
                )
            elif group_by == "neuropil":
                pre_grouped, _ = agg_by_neuropil(
                    fano_arr,
                    neurons=neurons_df,
                    connections=connections_df,
                    mode="top_innervated",
                    agg="mean",
                )
                grouped = pre_grouped

            for group_name in group_data:
                if group_name in grouped:
                    group_data[group_name].append(grouped[group_name])
                else:
                    group_data[group_name].append(np.nan)

        times = np.array(windows) * dt
        for group_name, values in group_data.items():
            ax.plot(times, values, marker="o", label=group_name)

    ax.set_xlabel("Time Window (ms)")
    ax.set_ylabel("Fano Factor (mean)")
    ax.set_title(f"Multiscale Fano Factor - Grouped by {group_by}")
    ax.set_xscale("log")
    ax.grid(alpha=0.3, which="both")
    ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left", fontsize=8)
    plt.tight_layout()
    return fig

_plot_fano_individual(fano_results, windows, dt, neuron_indices, n_neurons)

Plot Fano factor for individual neurons.

Source code in btorch/visualisation/dynamics.py
def _plot_fano_individual(fano_results, windows, dt, neuron_indices, n_neurons):
    """Plot Fano factor for individual neurons."""
    if neuron_indices is None:
        neuron_indices = list(range(min(10, n_neurons)))

    fig, ax = plt.subplots(1, 1, figsize=(10, 6))

    for neuron_idx in neuron_indices:
        fano_values = [fano_results[w][neuron_idx] for w in windows]
        ax.plot(
            np.array(windows) * dt,
            fano_values,
            marker="o",
            label=f"N{neuron_idx}",
            alpha=0.7,
        )

    ax.set_xlabel("Time Window (ms)")
    ax.set_ylabel("Fano Factor")
    ax.set_title("Multiscale Fano Factor - Individual Neurons")
    ax.set_xscale("log")
    ax.grid(alpha=0.3)
    ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left", fontsize=8)
    plt.tight_layout()
    return fig

agg_by_neuron(y, neurons, agg='mean', neuron_type_column='cell_type', **kwargs)

Aggregate data by neuron type.

Source code in btorch/analysis/aggregation.py
def agg_by_neuron(
    y,
    neurons: pd.DataFrame,
    agg: AggName = "mean",
    neuron_type_column: str = "cell_type",
    **kwargs,
) -> dict:
    """Aggregate data by neuron type."""
    agg_func = getattr(np, agg) if isinstance(y, np.ndarray) else getattr(torch, agg)
    ret = {}
    for neuron_type, group in neurons.groupby(
        neuron_type_column, dropna=True, **kwargs
    ):
        ret[neuron_type] = agg_func(y[..., group.simple_id.to_numpy()], -1)
    return ret

agg_by_neuropil(y, neurons=None, connections=None, mode='all_innervated', agg='mean', use_polars=False)

Aggregate activations by neuropil under a validated aggregation mode.

Raises:

Type Description
ValueError

If mode="top_innervated" and neurons is None, if mode="all_innervated" and connections is None, or if mode is not one of the two supported values.

Source code in btorch/analysis/aggregation.py
def agg_by_neuropil(
    y,
    neurons: pd.DataFrame | None = None,
    connections: pd.DataFrame | None = None,
    mode: Literal["top_innervated", "all_innervated"] = "all_innervated",
    agg: AggName = "mean",
    use_polars: bool = False,
) -> tuple[dict, dict]:
    """Aggregate activations by neuropil under a validated aggregation mode.

    Raises:
        ValueError: If ``mode="top_innervated"`` and ``neurons`` is None, if
            ``mode="all_innervated"`` and ``connections`` is None, or if
            ``mode`` is not one of the two supported values.
    """
    agg_func = getattr(np, agg) if isinstance(y, np.ndarray) else getattr(torch, agg)
    if use_polars:
        # polars is an accelerator (``pip install "btorch[fast]"``): without it
        # the numpy/torch path below gives identical results, only slower.
        try:
            import polars as pl
        except ImportError:
            use_polars = False

    if mode == "top_innervated":
        if neurons is None:
            raise ValueError("neurons must be provided for top_innervated mode")
        tmp = neurons[["group", "simple_id"]].copy()
        tmp = tmp[tmp["simple_id"] < y.shape[-1]]
        pre_ret: dict = {}
        post_ret: dict = {}

        if use_polars:
            tmp["pre"] = tmp["group"].str.split(".").str[0]
            tmp["post"] = tmp["group"].str.split(".").str[-1]
            ptbl = pl.from_pandas(tmp)

            pre_groups = ptbl.group_by("pre", maintain_order=True).agg(
                pl.col("simple_id")
            )
            for row in pre_groups.iter_rows(named=True):
                sid = np.asarray(row["simple_id"], dtype=int)
                pre_ret[row["pre"]] = agg_func(y[..., sid], -1)

            post_groups = ptbl.group_by("post", maintain_order=True).agg(
                pl.col("simple_id")
            )
            for row in post_groups.iter_rows(named=True):
                sid = np.asarray(row["simple_id"], dtype=int)
                post_ret[row["post"]] = agg_func(y[..., sid], -1)
        else:
            tmp["pre"] = tmp["group"].apply(lambda x: x.split(".")[0])
            tmp["post"] = tmp["group"].apply(lambda x: x.split(".")[-1])
            for pre, group in tmp.groupby("pre", dropna=True):
                pre_ret[pre] = agg_func(y[..., group.simple_id], -1)
            for post, group in tmp.groupby("post", dropna=True):
                post_ret[post] = agg_func(y[..., group.simple_id], -1)
        return pre_ret, post_ret
    if mode == "all_innervated":
        if connections is None:
            raise ValueError("connections must be provided for all_innervated mode")
        tmp = connections[["pre_simple_id", "post_simple_id", "neuropil"]]
        tmp = tmp[
            (tmp["pre_simple_id"] < y.shape[-1]) & (tmp["post_simple_id"] < y.shape[-1])
        ]
        pre_ret: dict = {}
        post_ret: dict = {}

        if use_polars:
            ptbl = pl.from_pandas(tmp)
            groups = ptbl.group_by("neuropil", maintain_order=True).agg(
                pl.col("pre_simple_id"), pl.col("post_simple_id")
            )
            for row in groups.iter_rows(named=True):
                neuropil = row["neuropil"]
                pre_ids = np.asarray(row["pre_simple_id"], dtype=int)
                post_ids = np.asarray(row["post_simple_id"], dtype=int)
                pre_ret[neuropil] = agg_func(y[..., pre_ids], -1)
                post_ret[neuropil] = agg_func(y[..., post_ids], -1)
        else:
            for neuropil, group in tmp.groupby("neuropil", dropna=True):
                pre_ret[neuropil] = agg_func(y[..., group.pre_simple_id.to_numpy()], -1)
                post_ret[neuropil] = agg_func(
                    y[..., group.post_simple_id.to_numpy()], -1
                )
        return pre_ret, post_ret

    raise ValueError(
        "Invalid `mode` for `agg_by_neuropil`. "
        "Expected one of: {'top_innervated', 'all_innervated'}."
    )

fano(spikes, window=None, overlap=0, batch_axis=None, dtype=None)

Compute Fano factor for spike trains using optimized cumulative sums.

Supports both NumPy and PyTorch inputs. GPU-friendly operation.

This function is decorated with @use_stats and @use_percentiles. See :func:~btorch.analysis.statistics.use_stats and :func:~btorch.analysis.statistics.use_percentiles for detailed usage.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike train of shape [T, ...]. First dimension is time.

required
window int | None

Window size in time bins (not ms) for spike counting. If None, uses full duration T.

None
overlap int

Overlap between consecutive windows.

0
batch_axis BatchAxis

Axes to average across for FF computation (e.g., trials).

None
dtype dtype | dtype | None

Data type for accumulation. If None, uses float64 for NumPy and input dtype (or float32 for float16/bfloat16) for Torch.

None

Other Parameters:

Name Type Description
stat str | None

Aggregation statistic to return instead of per-neuron values. Options: "mean", "median", "max", "min", "std", "var", "argmax", "argmin", "cv". See :func:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

Returns:

Name Type Description
fano StatsResult

Fano factor values with shape [...] (input shape without time dimension). If stat is provided, returns the aggregated statistic instead.

info StatsResult

Dictionary with optional computed statistics and percentile data.

Source code in btorch/analysis/spiking.py
@use_percentiles(value_key="fano")
@use_stats(value_key="fano")
def fano(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> StatsResult:
    """Compute Fano factor for spike trains using optimized cumulative sums.

    Supports both NumPy and PyTorch inputs. GPU-friendly operation.

    This function is decorated with `@use_stats` and `@use_percentiles`.
    See :func:`~btorch.analysis.statistics.use_stats` and
    :func:`~btorch.analysis.statistics.use_percentiles` for detailed usage.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses full duration T.
        overlap: Overlap between consecutive windows.
        batch_axis: Axes to average across for FF computation (e.g., trials).
        dtype: Data type for accumulation. If None, uses float64 for NumPy
            and input dtype (or float32 for float16/bfloat16) for Torch.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        fano: Fano factor values with shape [...]
            (input shape without time dimension).
            If `stat` is provided, returns the aggregated statistic instead.
        info: Dictionary with optional computed statistics and percentile data.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    if window is None:
        # Default window size to get ~10 bins for variance computation
        # Need at least 2 bins for valid variance with unbiased=True
        window = max(1, spikes.shape[0] // 10)
    if isinstance(spikes, torch.Tensor):
        return _fano_torch(spikes, window, overlap, batch_axis, dtype)
    else:
        return _fano_numpy(spikes, window, overlap, batch_axis, dtype)

isi_cv(spikes, dt=1.0, batch_axis=None, dtype=None)

Calculate coefficient of variation of ISIs per neuron.

Supports both NumPy and PyTorch inputs. For GPU tensors, uses a hybrid approach: aggregates on GPU, transfers to CPU for ISI extraction, then returns to GPU.

This function is decorated with @use_stats and @use_percentiles. See :func:~btorch.analysis.statistics.use_stats and :func:~btorch.analysis.statistics.use_percentiles for detailed usage.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike train array of shape [T, ...]. First dimension is time. Values are binary (0/1) or spike counts.

required
dt float

Time step in milliseconds for converting ISI to ms.

1.0
batch_axis BatchAxis

Axes to aggregate ISIs across (e.g., (1, 2) for trials). If None, computes CV per element in the non-time dimensions.

None
dtype dtype | dtype | None

Data type for accumulation.

None

Other Parameters:

Name Type Description
stat str | None

Aggregation statistic to return instead of per-neuron values. Options: "mean", "median", "max", "min", "std", "var", "argmax", "argmin", "cv". See :func:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

Returns:

Name Type Description
cv_values StatsResult

CV values reshaped to match input without time dimension. Shape: [...] (original shape without T, aggregated over batch_axis). If stat is provided, returns the aggregated statistic instead.

info StatsResult

Dictionary with 'isi_total' (aggregate ISI statistics), 'isi_stats' (per-neuron statistics), and optional percentile data.

Source code in btorch/analysis/spiking.py
@use_percentiles(value_key="cv")
@use_stats(value_key="cv")
def isi_cv(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> StatsResult:
    """Calculate coefficient of variation of ISIs per neuron.

    Supports both NumPy and PyTorch inputs. For GPU tensors, uses a hybrid
    approach: aggregates on GPU, transfers to CPU for ISI extraction, then
    returns to GPU.

    This function is decorated with `@use_stats` and `@use_percentiles`.
    See :func:`~btorch.analysis.statistics.use_stats` and
    :func:`~btorch.analysis.statistics.use_percentiles` for detailed usage.

    Args:
        spikes: Spike train array of shape [T, ...]. First dimension is time.
            Values are binary (0/1) or spike counts.
        dt: Time step in milliseconds for converting ISI to ms.
        batch_axis: Axes to aggregate ISIs across (e.g., (1, 2) for trials).
            If None, computes CV per element in the non-time dimensions.
        dtype: Data type for accumulation.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        cv_values: CV values reshaped to match input without time dimension.
            Shape: [...] (original shape without T, aggregated over batch_axis).
            If `stat` is provided, returns the aggregated statistic instead.
        info: Dictionary with 'isi_total' (aggregate ISI statistics),
            'isi_stats' (per-neuron statistics), and optional percentile data.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    return _cv(spikes, dt, batch_axis, dtype)

plot_avalanche_analysis(spikes, bin_size=1, dt=1.0)

Plot avalanche size and duration distributions to analyze criticality.

Creates a 3-panel figure showing: 1. Avalanche size distribution P(S) with power-law fit 2. Avalanche duration distribution P(T) with power-law fit 3. Average size vs duration scaling relation <S>(T)

Criticality is indicated by power-law distributions and specific scaling exponents (tau, alpha, gamma).

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix with shape (time, neurons).

required
bin_size int

Bin size for avalanche detection in timesteps.

1
dt float

Timestep in ms (unused, kept for interface consistency).

1.0

Returns:

Type Description
Figure

Tuple of (figure, results) where results contains fitted exponents

dict

(tau, alpha, gamma), CCC (criticality consistency check), and

tuple[Figure, dict]

power-law fit objects.

Examples:

>>> fig, results = plot_avalanche_analysis(spikes, bin_size=5)
>>> print(f"Tau: {results['tau']:.2f}, CCC: {results['CCC']:.2f}")
Source code in btorch/visualisation/dynamics.py
def plot_avalanche_analysis(
    spikes: np.ndarray | torch.Tensor,
    bin_size: int = 1,
    dt: float = 1.0,  # Added for consistency
) -> tuple[Figure, dict]:
    """Plot avalanche size and duration distributions to analyze criticality.

    Creates a 3-panel figure showing:
    1. Avalanche size distribution P(S) with power-law fit
    2. Avalanche duration distribution P(T) with power-law fit
    3. Average size vs duration scaling relation `<S>(T)`

    Criticality is indicated by power-law distributions and specific
    scaling exponents (tau, alpha, gamma).

    Args:
        spikes: Spike matrix with shape (time, neurons).
        bin_size: Bin size for avalanche detection in timesteps.
        dt: Timestep in ms (unused, kept for interface consistency).

    Returns:
        Tuple of (figure, results) where results contains fitted exponents
        (tau, alpha, gamma), CCC (criticality consistency check), and
        power-law fit objects.

    Examples:
        >>> fig, results = plot_avalanche_analysis(spikes, bin_size=5)
        >>> print(f"Tau: {results['tau']:.2f}, CCC: {results['CCC']:.2f}")
    """
    from ..analysis.dynamic_tools.criticality import compute_avalanche_statistics

    spikes = to_numpy(spikes)
    results = compute_avalanche_statistics(spikes, bin_size=bin_size)

    fig = plt.figure(figsize=(15, 4))

    ax1 = fig.add_subplot(1, 3, 1)
    if results["fit_S"]:
        results["fit_S"].plot_pdf(color="b", linewidth=2, ax=ax1, label="Data")
        results["fit_S"].power_law.plot_pdf(
            color="b", linestyle="--", ax=ax1, label=f"Fit (tau={results['tau']:.2f})"
        )
    ax1.set_xlabel("Avalanche Size (S)")
    ax1.set_ylabel("P(S)")
    ax1.set_title("Size Distribution")
    if ax1.get_legend_handles_labels()[0]:
        ax1.legend()

    ax2 = fig.add_subplot(1, 3, 2)
    if results["fit_T"]:
        results["fit_T"].plot_pdf(color="r", linewidth=2, ax=ax2, label="Data")
        results["fit_T"].power_law.plot_pdf(
            color="r",
            linestyle="--",
            ax=ax2,
            label=f"Fit (alpha={results['alpha']:.2f})",
        )
    ax2.set_xlabel("Avalanche Duration (T)")
    ax2.set_ylabel("P(T)")
    ax2.set_title("Duration Distribution")
    if ax2.get_legend_handles_labels()[0]:
        ax2.legend()

    ax3 = fig.add_subplot(1, 3, 3)
    if (
        "avg_size_by_duration" in results
        and results["avg_size_by_duration"] is not None
    ):
        durations, mean_sizes = results["avg_size_by_duration"]
        ax3.loglog(durations, mean_sizes, "ko", markersize=4, label="Data")

        if not np.isnan(results["gamma"]):
            if results.get("gamma_stats") and "popt" in results["gamma_stats"]:
                popt = results["gamma_stats"]["popt"]
                a, gamma = popt
                x_fit = np.logspace(
                    np.log10(durations.min()), np.log10(durations.max()), 100
                )
                y_fit = a * np.power(x_fit, gamma)
                ax3.loglog(
                    x_fit,
                    y_fit,
                    "g--",
                    label=f"Fit (gamma={results['gamma']:.2f})",
                )

    if not np.isnan(results["CCC"]):
        txt = f"CCC = {results['CCC']:.2f}\nPred gamma = {results['gamma_pred']:.2f}"
        ax3.text(
            0.05,
            0.95,
            txt,
            transform=ax3.transAxes,
            verticalalignment="top",
            bbox=dict(boxstyle="round", facecolor="white", alpha=0.8),
        )

    ax3.set_xlabel("Duration (T)")
    ax3.set_ylabel("Average Size <S>")
    ax3.set_title("Scaling Relation")
    if ax3.get_legend_handles_labels()[0]:
        ax3.legend()

    plt.tight_layout()
    return fig, results

plot_dfa_analysis(data=None, config=None, format=None, spikes=None, dt=1.0, min_window=4, max_window=None, bin_size=1, mode='individual', neurons_df=None, **kwargs)

Plot DFA (Detrended Fluctuation Analysis) results.

DFA quantifies long-range temporal correlations in spike trains. The scaling exponent (alpha) indicates: - alpha ≈ 0.5: Uncorrelated (random) activity - alpha > 0.5: Long-range positive correlations - alpha < 0.5: Long-range anti-correlations

Supports both dataclass and plain argument interfaces.

Parameters:

Name Type Description Default
data DynamicsData | None

DynamicsData container with spikes.

None
config DFAConfig | None

DFAConfig with window and bin settings.

None
format DynamicsPlotFormat | None

DynamicsPlotFormat (mode affects plot style).

None
spikes ndarray | Tensor | None

Spike trains (time, neurons). Required if data not provided.

None
dt float

Timestep in milliseconds (for label consistency).

1.0
min_window int

Minimum window size for DFA in timesteps.

4
max_window int | None

Maximum window size. Auto-calculated if None.

None
bin_size int

Bin size for spike binning in timesteps.

1
mode Literal['individual', 'grouped', 'distribution']

Visualization mode (affects annotation style).

'individual'
neurons_df DataFrame | None

Neuron metadata for potential grouping.

None
**kwargs Any

Additional arguments.

{}

Returns:

Type Description
Figure

Figure with DFA summary and interpretation guide.

Raises:

Type Description
ValueError

If spikes are not provided.

Examples:

>>> fig = plot_dfa_analysis(spikes, bin_size=10)
Source code in btorch/visualisation/dynamics.py
def plot_dfa_analysis(
    # Dataclass interface
    data: DynamicsData | None = None,
    config: DFAConfig | None = None,
    format: DynamicsPlotFormat | None = None,
    # Plain args interface
    spikes: np.ndarray | torch.Tensor | None = None,
    dt: float = 1.0,
    min_window: int = 4,
    max_window: int | None = None,
    bin_size: int = 1,
    mode: Literal["individual", "grouped", "distribution"] = "individual",
    neurons_df: pd.DataFrame | None = None,
    **kwargs: Any,
) -> Figure:
    """Plot DFA (Detrended Fluctuation Analysis) results.

    DFA quantifies long-range temporal correlations in spike trains.
    The scaling exponent (alpha) indicates:
    - alpha ≈ 0.5: Uncorrelated (random) activity
    - alpha > 0.5: Long-range positive correlations
    - alpha < 0.5: Long-range anti-correlations

    Supports both dataclass and plain argument interfaces.

    Args:
        data: DynamicsData container with spikes.
        config: DFAConfig with window and bin settings.
        format: DynamicsPlotFormat (mode affects plot style).
        spikes: Spike trains (time, neurons). Required if `data` not provided.
        dt: Timestep in milliseconds (for label consistency).
        min_window: Minimum window size for DFA in timesteps.
        max_window: Maximum window size. Auto-calculated if None.
        bin_size: Bin size for spike binning in timesteps.
        mode: Visualization mode (affects annotation style).
        neurons_df: Neuron metadata for potential grouping.
        **kwargs: Additional arguments.

    Returns:
        Figure with DFA summary and interpretation guide.

    Raises:
        ValueError: If spikes are not provided.

    Examples:
        >>> fig = plot_dfa_analysis(spikes, bin_size=10)
    """
    if data is not None:
        spikes = data.spikes if spikes is None else spikes
        dt = data.dt if dt == 1.0 else dt
        neurons_df = data.neurons_df if neurons_df is None else neurons_df

    if config is not None:
        max_window = config.max_window if max_window is None else max_window
        bin_size = config.bin_size

    if spikes is None:
        raise ValueError("spikes is required")

    spikes = to_numpy(spikes)

    from ..analysis.dynamic_tools.criticality import compute_dfa

    alpha = compute_dfa(spikes, bin_size=bin_size)

    fig, ax = plt.subplots(1, 1, figsize=(8, 6))
    ax.text(
        0.5,
        0.5,
        f"DFA Exponent (α): {alpha:.3f}",
        ha="center",
        va="center",
        fontsize=16,
        transform=ax.transAxes,
    )
    ax.text(
        0.5,
        0.4,
        "α ≈ 0.5: uncorrelated\n"
        "α > 0.5: long-range correlations\n"
        "α < 0.5: anti-correlations",
        ha="center",
        va="center",
        fontsize=10,
        transform=ax.transAxes,
    )
    ax.set_title("Detrended Fluctuation Analysis")
    ax.axis("off")
    return fig

plot_eigenvalue_spectrum(weight_matrix, ax=None)

Plot the eigenvalue spectrum of a weight matrix.

Visualizes eigenvalues in the complex plane with the spectral radius indicated by a dashed circle. Outliers (eigenvalues outside the bulk) are highlighted in red.

Parameters:

Name Type Description Default
weight_matrix ndarray | Tensor

Square connectivity matrix (N, N).

required
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None

Returns:

Type Description
Figure

Tuple of (figure, axes, results) where results contains:

Axes
  • "eigenvalues": Complex array of all eigenvalues
dict
  • "spectral_radius": Radius of spectral bulk
tuple[Figure, Axes, dict]
  • "outliers": Array of outlier eigenvalues

Examples:

>>> fig, ax, results = plot_eigenvalue_spectrum(W)
>>> print(f"Spectral radius: {results['spectral_radius']:.2f}")
Source code in btorch/visualisation/dynamics.py
def plot_eigenvalue_spectrum(
    weight_matrix: np.ndarray | torch.Tensor, ax: Axes | None = None
) -> tuple[Figure, Axes, dict]:
    """Plot the eigenvalue spectrum of a weight matrix.

    Visualizes eigenvalues in the complex plane with the spectral radius
    indicated by a dashed circle. Outliers (eigenvalues outside the bulk)
    are highlighted in red.

    Args:
        weight_matrix: Square connectivity matrix (N, N).
        ax: Existing axes to plot on. Creates new figure if None.

    Returns:
        Tuple of (figure, axes, results) where results contains:
        - "eigenvalues": Complex array of all eigenvalues
        - "spectral_radius": Radius of spectral bulk
        - "outliers": Array of outlier eigenvalues

    Examples:
        >>> fig, ax, results = plot_eigenvalue_spectrum(W)
        >>> print(f"Spectral radius: {results['spectral_radius']:.2f}")
    """
    from ..analysis.dynamic_tools.attractor_dynamics import (
        compute_structural_eigenvalue_outliers,
    )

    W = to_numpy(weight_matrix)
    results = compute_structural_eigenvalue_outliers(W)

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 6))
    else:
        fig = ax.get_figure()

    evals = results["eigenvalues"]
    r_spec = results["spectral_radius"]

    circle = plt.Circle(
        (0, 0),
        r_spec,
        color="black",
        fill=False,
        linestyle="--",
        alpha=0.5,
        label=f"R={r_spec:.2f}",
    )
    ax.add_artist(circle)

    ax.scatter(evals.real, evals.imag, s=10, alpha=0.6, c="gray", edgecolors="none")

    outliers = results["outliers"]
    if len(outliers) > 0:
        ax.scatter(
            outliers.real,
            outliers.imag,
            s=30,
            c="red",
            label=f"Outliers ({len(outliers)})",
        )

    ax.set_aspect("equal")
    ax.set_xlabel(r"Re($\lambda$)")
    ax.set_ylabel(r"Im($\lambda$)")
    ax.set_title("Eigenvalue Spectrum")
    ax.grid(True, linestyle=":", alpha=0.3)
    ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left")
    plt.tight_layout()

    return fig, ax, results

plot_firing_rate_distribution(spikes, dt=1.0, ax=None)

Plot the distribution of firing rates across neurons.

Computes per-neuron firing rates and displays as a histogram with mean indicator.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix with shape (time, neurons).

required
dt float

Timestep in milliseconds for rate calculation.

1.0
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None

Returns:

Type Description
Figure

Tuple of (figure, stats) where stats contains:

dict
  • "rates": Array of firing rates per neuron (Hz)
tuple[Figure, dict]
  • "mean", "std", "median": Summary statistics

Examples:

>>> fig, stats = plot_firing_rate_distribution(spikes, dt=1.0)
>>> print(f"Mean rate: {stats['mean']:.1f} Hz")
Source code in btorch/visualisation/dynamics.py
def plot_firing_rate_distribution(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    ax: Axes | None = None,
) -> tuple[Figure, dict]:
    """Plot the distribution of firing rates across neurons.

    Computes per-neuron firing rates and displays as a histogram with
    mean indicator.

    Args:
        spikes: Spike matrix with shape (time, neurons).
        dt: Timestep in milliseconds for rate calculation.
        ax: Existing axes to plot on. Creates new figure if None.

    Returns:
        Tuple of (figure, stats) where stats contains:
        - "rates": Array of firing rates per neuron (Hz)
        - "mean", "std", "median": Summary statistics

    Examples:
        >>> fig, stats = plot_firing_rate_distribution(spikes, dt=1.0)
        >>> print(f"Mean rate: {stats['mean']:.1f} Hz")
    """
    from ..analysis.dynamic_tools.micro_scale import compute_fr_distribution

    spikes = to_numpy(spikes)
    stats = compute_fr_distribution(spikes, dt=dt)

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 4))
    else:
        fig = ax.get_figure()

    rates = stats["rates"]
    ax.hist(rates, bins=30, color="skyblue", edgecolor="black", alpha=0.7)
    ax.axvline(
        stats["mean"],
        color="red",
        linestyle="--",
        label=f"Mean={stats['mean']:.1f} Hz",
    )
    ax.set_xlabel("Firing Rate (Hz)")
    ax.set_ylabel("Count")
    ax.set_title("Rate Distribution")
    ax.legend()
    ax.grid(alpha=0.3)

    if ax is None:
        plt.tight_layout()

    return fig, stats

plot_gain_stability(data)

Plot gain stability analysis results.

Visualizes the relationship between network gain (g) and stability metrics (e.g., maximum Lyapunov exponent or spectral abscissa). A linear fit indicates consistent scaling behavior.

Parameters:

Name Type Description Default
data tuple

Tuple of (slope, intercept, g_values, lambda_values) where: - slope, intercept: Linear fit parameters - g_values: Array of gain values tested - lambda_values: Corresponding stability metrics

required

Returns:

Type Description
tuple[Figure, Axes]

Tuple of (figure, axes) with scatter plot and fit line.

Examples:

>>> data = (slope, intercept, g_vals, lyap_vals)
>>> fig, ax = plot_gain_stability(data)
Source code in btorch/visualisation/dynamics.py
def plot_gain_stability(data: tuple) -> tuple[Figure, Axes]:
    """Plot gain stability analysis results.

    Visualizes the relationship between network gain (g) and stability
    metrics (e.g., maximum Lyapunov exponent or spectral abscissa).
    A linear fit indicates consistent scaling behavior.

    Args:
        data: Tuple of (slope, intercept, g_values, lambda_values) where:
            - slope, intercept: Linear fit parameters
            - g_values: Array of gain values tested
            - lambda_values: Corresponding stability metrics

    Returns:
        Tuple of (figure, axes) with scatter plot and fit line.

    Examples:
        >>> data = (slope, intercept, g_vals, lyap_vals)
        >>> fig, ax = plot_gain_stability(data)
    """
    slope, intercept, g_values, lambda_values = data

    fig, ax = plt.subplots(figsize=(6, 4))

    ax.scatter(g_values, lambda_values, label="Data", color="blue", alpha=0.6)

    x_range = np.linspace(min(g_values), max(g_values), 100)
    y_fit = slope * x_range + intercept
    ax.plot(x_range, y_fit, "r--", label=f"Fit: y={slope:.2f}x+{intercept:.2f}")

    ax.set_xlabel("Gain (g)")
    ax.set_ylabel("Lyapunov / Eigenvalue metric")
    ax.set_title("Gain Stability Analysis")
    ax.legend()
    ax.grid(True, alpha=0.3)

    plt.tight_layout()
    return fig, ax

plot_isi_cv(data=None, format=None, spikes=None, dt=1.0, mode='individual', neurons_df=None, group_by=None, neuron_type_column='cell_type', **kwargs)

Plot ISI CV (Coefficient of Variation) distribution.

ISI CV measures spike train irregularity: - CV = 1: Poisson-like (irregular) firing - CV < 1: Regular, periodic firing - CV > 1: Bursty, irregular firing

Supports histogram view for distributions and bar plots for grouped comparisons.

Parameters:

Name Type Description Default
data DynamicsData | None

DynamicsData container with spikes and metadata.

None
format DynamicsPlotFormat | None

DynamicsPlotFormat with visualization settings.

None
spikes ndarray | Tensor | None

Spike trains (time, neurons). Required if data not provided.

None
dt float

Timestep in milliseconds for ISI calculation.

1.0
mode Literal['individual', 'grouped', 'distribution']

Visualization mode - "distribution", "individual", or "grouped".

'individual'
neurons_df DataFrame | None

DataFrame with neuron metadata for grouping.

None
group_by Literal['neuropil', 'neuron_type', None]

Grouping method - "neuropil" or "neuron_type".

None
neuron_type_column str

Column name for neuron types in neurons_df.

'cell_type'
**kwargs Any

Additional arguments.

{}

Returns:

Type Description
Figure

Figure with ISI CV histogram or grouped bar plot.

Raises:

Type Description
ValueError

If spikes are not provided, or if grouped mode is requested without required metadata.

Examples:

>>> fig = plot_isi_cv(spikes, dt=1.0, mode="distribution")
>>>
>>> # Grouped by cell type
>>> fig = plot_isi_cv(spikes, neurons_df=df,
...                   mode="grouped", group_by="neuron_type")
Source code in btorch/visualisation/dynamics.py
def plot_isi_cv(
    # Dataclass interface
    data: DynamicsData | None = None,
    format: DynamicsPlotFormat | None = None,
    # Plain args interface
    spikes: np.ndarray | torch.Tensor | None = None,
    dt: float = 1.0,
    mode: Literal["individual", "grouped", "distribution"] = "individual",
    neurons_df: pd.DataFrame | None = None,
    group_by: Literal["neuropil", "neuron_type", None] = None,
    neuron_type_column: str = "cell_type",
    **kwargs: Any,
) -> Figure:
    """Plot ISI CV (Coefficient of Variation) distribution.

    ISI CV measures spike train irregularity:
    - CV = 1: Poisson-like (irregular) firing
    - CV < 1: Regular, periodic firing
    - CV > 1: Bursty, irregular firing

    Supports histogram view for distributions and bar plots for grouped
    comparisons.

    Args:
        data: DynamicsData container with spikes and metadata.
        format: DynamicsPlotFormat with visualization settings.
        spikes: Spike trains (time, neurons). Required if `data` not provided.
        dt: Timestep in milliseconds for ISI calculation.
        mode: Visualization mode - "distribution", "individual", or "grouped".
        neurons_df: DataFrame with neuron metadata for grouping.
        group_by: Grouping method - "neuropil" or "neuron_type".
        neuron_type_column: Column name for neuron types in neurons_df.
        **kwargs: Additional arguments.

    Returns:
        Figure with ISI CV histogram or grouped bar plot.

    Raises:
        ValueError: If spikes are not provided, or if grouped mode is
            requested without required metadata.

    Examples:
        >>> fig = plot_isi_cv(spikes, dt=1.0, mode="distribution")
        >>>
        >>> # Grouped by cell type
        >>> fig = plot_isi_cv(spikes, neurons_df=df,
        ...                   mode="grouped", group_by="neuron_type")
    """
    if data is not None:
        spikes = data.spikes if spikes is None else spikes
        dt = data.dt if dt == 1.0 else dt
        neurons_df = data.neurons_df if neurons_df is None else neurons_df

    if format is not None:
        mode = format.mode
        group_by = format.group_by if group_by is None else group_by
        neuron_type_column = format.neuron_type_column

    if spikes is None:
        raise ValueError("spikes is required")

    spikes = to_numpy(spikes)

    cv_results = _isi_cv_stats(spikes, dt)
    cv_values = cv_results["cv_isi"]

    fig, ax = plt.subplots(1, 1, figsize=(10, 6))

    if mode == "distribution" or mode == "individual":
        valid_cv = cv_values[~np.isnan(cv_values)]
        ax.hist(valid_cv, bins=30, color="skyblue", edgecolor="black", alpha=0.7)
        ax.axvline(
            cv_results["mean"],
            color="red",
            linestyle="--",
            label=f"Mean={cv_results['mean']:.2f}",
        )
        ax.set_xlabel("ISI CV")
        ax.set_ylabel("Count")
        ax.set_title("ISI Coefficient of Variation Distribution")
        ax.legend()
        ax.grid(alpha=0.3)

    elif mode == "grouped":
        if group_by is None or neurons_df is None:
            raise ValueError("group_by and neurons_df required for grouped mode")

        grouped = agg_by_neuron(
            cv_values, neurons_df, agg="mean", neuron_type_column=neuron_type_column
        )

        names = list(grouped.keys())
        values = list(grouped.values())
        ax.bar(names, values, color="teal", alpha=0.7, edgecolor="black")
        ax.set_xlabel("Neuron Type")
        ax.set_ylabel("Mean ISI CV")
        ax.set_title(f"ISI CV by {neuron_type_column}")
        ax.grid(axis="y", alpha=0.3)
        plt.xticks(rotation=45, ha="right")

    plt.tight_layout()
    return fig

plot_lyapunov_spectrum(spectrum, ax=None)

Plot the Lyapunov exponents spectrum.

Displays Lyapunov exponents sorted by magnitude. Positive exponents indicate chaos; the number of non-negative exponents relates to the Kaplan-Yorke dimension.

Parameters:

Name Type Description Default
spectrum list[float] | ndarray

List or array of Lyapunov exponents.

required
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None

Returns:

Type Description
tuple[Figure, Axes]

Tuple of (figure, axes) with the spectrum plot.

Examples:

>>> fig, ax = plot_lyapunov_spectrum(lyap_spectrum)
>>> # Positive exponents indicate chaotic dynamics
Source code in btorch/visualisation/dynamics.py
def plot_lyapunov_spectrum(
    spectrum: list[float] | np.ndarray, ax: Axes | None = None
) -> tuple[Figure, Axes]:
    """Plot the Lyapunov exponents spectrum.

    Displays Lyapunov exponents sorted by magnitude. Positive exponents
    indicate chaos; the number of non-negative exponents relates to the
    Kaplan-Yorke dimension.

    Args:
        spectrum: List or array of Lyapunov exponents.
        ax: Existing axes to plot on. Creates new figure if None.

    Returns:
        Tuple of (figure, axes) with the spectrum plot.

    Examples:
        >>> fig, ax = plot_lyapunov_spectrum(lyap_spectrum)
        >>> # Positive exponents indicate chaotic dynamics
    """
    from ..analysis.dynamic_tools.attractor_dynamics import (
        compute_kaplan_yorke_dimension,
    )

    spec = to_numpy(spectrum)
    spec = np.sort(spec)[::-1]

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 4))
    else:
        fig = ax.get_figure()

    x = np.arange(1, len(spec) + 1)
    ax.plot(x, spec, "o-", markersize=4, linewidth=1, color="black")
    ax.axhline(0, color="k", linestyle="--", linewidth=0.8)

    ky_dim = compute_kaplan_yorke_dimension(spec)

    title = f"Lyapunov Spectrum (D_KY = {ky_dim:.2f})"
    ax.set_title(title)
    ax.set_xlabel("Index")
    ax.set_ylabel("Lyapunov Exponent")
    ax.grid(True, alpha=0.3)
    plt.tight_layout()

    return fig, ax

plot_micro_dynamics(spikes, dt=1.0)

Plot firing rate and ISI CV distributions side-by-side.

Creates a 2-panel figure summarizing micro-scale dynamics: - Left: Firing rate distribution histogram - Right: ISI CV distribution histogram

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix with shape (time, neurons).

required
dt float

Timestep in milliseconds.

1.0

Returns:

Type Description
Figure

Tuple of (figure, stats) where stats is a dict with keys:

dict
  • "fr": Firing rate statistics
tuple[Figure, dict]
  • "cv": ISI CV statistics

Examples:

>>> fig, stats = plot_micro_dynamics(spikes, dt=1.0)
>>> print(f"Rate: {stats['fr']['mean']:.1f} Hz, CV: {stats['cv']['mean']:.2f}")
Source code in btorch/visualisation/dynamics.py
def plot_micro_dynamics(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
) -> tuple[Figure, dict]:
    """Plot firing rate and ISI CV distributions side-by-side.

    Creates a 2-panel figure summarizing micro-scale dynamics:
    - Left: Firing rate distribution histogram
    - Right: ISI CV distribution histogram

    Args:
        spikes: Spike matrix with shape (time, neurons).
        dt: Timestep in milliseconds.

    Returns:
        Tuple of (figure, stats) where stats is a dict with keys:
        - "fr": Firing rate statistics
        - "cv": ISI CV statistics

    Examples:
        >>> fig, stats = plot_micro_dynamics(spikes, dt=1.0)
        >>> print(f"Rate: {stats['fr']['mean']:.1f} Hz, CV: {stats['cv']['mean']:.2f}")
    """
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

    _, fr_stats = plot_firing_rate_distribution(spikes, dt=dt, ax=ax1)

    spikes_np = to_numpy(spikes)
    cv_results = _isi_cv_stats(spikes_np, dt)
    cv_values = cv_results["cv_isi"]
    valid_cv = cv_values[~np.isnan(cv_values)]

    if len(valid_cv) > 0:
        ax2.hist(valid_cv, bins=30, color="orange", edgecolor="black", alpha=0.7)
        ax2.axvline(
            cv_results["mean"],
            color="red",
            linestyle="--",
            label=f"Mean={cv_results['mean']:.2f}",
        )
        ax2.set_xlabel("CV (ISI)")
        ax2.set_ylabel("Count")
        ax2.set_title("CV Distribution")
        ax2.legend()
    else:
        ax2.text(0.5, 0.5, "No valid CVs", ha="center")
    ax2.grid(alpha=0.3)

    plt.tight_layout()
    return fig, {"fr": fr_stats, "cv": cv_results}

plot_multiscale_fano(data=None, config=None, format=None, spikes=None, dt=1.0, windows=None, overlap=0, mode='individual', neurons_df=None, connections_df=None, group_by=None, neuron_type_column='cell_type', neuron_indices=None, **kwargs)

Plot multiscale Fano factor analysis.

Computes and visualizes Fano factor (spike count variance/mean) across multiple time windows. Supports three visualization modes: - "individual": Line plots for selected neurons - "grouped": Aggregated by neuron type or neuropil - "distribution": Violin plots showing population distribution

Supports both dataclass and plain argument interfaces. Dataclass arguments take precedence when both are provided.

Parameters:

Name Type Description Default
data DynamicsData | None

DynamicsData container with spikes and metadata.

None
config FanoFactorConfig | None

FanoFactorConfig with window settings.

None
format DynamicsPlotFormat | None

DynamicsPlotFormat with visualization options.

None
spikes ndarray | Tensor | None

Spike trains with shape (time, neurons). Required if data is not provided.

None
dt float

Timestep in milliseconds. Default 1.0.

1.0
windows list[int] | None

List of window sizes in timesteps. Auto-generated if None.

None
overlap int

Window overlap in timesteps. Default 0.

0
mode Literal['individual', 'grouped', 'distribution']

Visualization mode - "individual", "grouped", "distribution".

'individual'
neurons_df DataFrame | None

DataFrame with neuron metadata for grouping.

None
connections_df DataFrame | None

DataFrame with connection metadata for neuropil grouping.

None
group_by Literal['neuropil', 'neuron_type', None]

Grouping method - "neuropil" or "neuron_type".

None
neuron_type_column str

Column name for neuron types in neurons_df.

'cell_type'
neuron_indices list[int] | None

Specific neuron indices for "individual" mode. If None, first 10 neurons are plotted.

None
**kwargs Any

Additional arguments passed to plotting functions.

{}

Returns:

Type Description
Figure

Figure with Fano factor plots.

Raises:

Type Description
ValueError

If spikes are not provided through either data or spikes argument.

Examples:

>>> # Plain args interface
>>> fig = plot_multiscale_fano(spikes, dt=1.0, mode="distribution")
>>>
>>> # Dataclass interface
>>> data = DynamicsData(spikes=spikes, dt=1.0, neurons_df=df)
>>> config = FanoFactorConfig(windows=[10, 50, 100])
>>> fig = plot_multiscale_fano(data=data, config=config)
Source code in btorch/visualisation/dynamics.py
def plot_multiscale_fano(
    # Dataclass interface
    data: DynamicsData | None = None,
    config: FanoFactorConfig | None = None,
    format: DynamicsPlotFormat | None = None,
    # Plain args interface
    spikes: np.ndarray | torch.Tensor | None = None,
    dt: float = 1.0,
    windows: list[int] | None = None,
    overlap: int = 0,
    mode: Literal["individual", "grouped", "distribution"] = "individual",
    neurons_df: pd.DataFrame | None = None,
    connections_df: pd.DataFrame | None = None,
    group_by: Literal["neuropil", "neuron_type", None] = None,
    neuron_type_column: str = "cell_type",
    neuron_indices: list[int] | None = None,
    **kwargs: Any,
) -> Figure:
    """Plot multiscale Fano factor analysis.

    Computes and visualizes Fano factor (spike count variance/mean) across
    multiple time windows. Supports three visualization modes:
    - "individual": Line plots for selected neurons
    - "grouped": Aggregated by neuron type or neuropil
    - "distribution": Violin plots showing population distribution

    Supports both dataclass and plain argument interfaces. Dataclass
    arguments take precedence when both are provided.

    Args:
        data: DynamicsData container with spikes and metadata.
        config: FanoFactorConfig with window settings.
        format: DynamicsPlotFormat with visualization options.
        spikes: Spike trains with shape (time, neurons). Required if
            `data` is not provided.
        dt: Timestep in milliseconds. Default 1.0.
        windows: List of window sizes in timesteps. Auto-generated if None.
        overlap: Window overlap in timesteps. Default 0.
        mode: Visualization mode - "individual", "grouped", "distribution".
        neurons_df: DataFrame with neuron metadata for grouping.
        connections_df: DataFrame with connection metadata for neuropil
            grouping.
        group_by: Grouping method - "neuropil" or "neuron_type".
        neuron_type_column: Column name for neuron types in neurons_df.
        neuron_indices: Specific neuron indices for "individual" mode.
            If None, first 10 neurons are plotted.
        **kwargs: Additional arguments passed to plotting functions.

    Returns:
        Figure with Fano factor plots.

    Raises:
        ValueError: If spikes are not provided through either `data` or
            `spikes` argument.

    Examples:
        >>> # Plain args interface
        >>> fig = plot_multiscale_fano(spikes, dt=1.0, mode="distribution")
        >>>
        >>> # Dataclass interface
        >>> data = DynamicsData(spikes=spikes, dt=1.0, neurons_df=df)
        >>> config = FanoFactorConfig(windows=[10, 50, 100])
        >>> fig = plot_multiscale_fano(data=data, config=config)
    """
    if data is not None:
        spikes = data.spikes if spikes is None else spikes
        dt = data.dt if dt == 1.0 else dt
        neurons_df = data.neurons_df if neurons_df is None else neurons_df
        connections_df = (
            data.connections_df if connections_df is None else connections_df
        )

    if config is not None:
        windows = config.windows if windows is None else windows
        overlap = config.overlap if overlap == 0 else overlap

    if format is not None:
        mode = format.mode
        group_by = format.group_by if group_by is None else group_by
        neuron_type_column = format.neuron_type_column
        neuron_indices = (
            format.neuron_indices if neuron_indices is None else neuron_indices
        )

    if spikes is None:
        raise ValueError("spikes is required")

    spikes = to_numpy(spikes)
    n_time, n_neurons = spikes.shape

    # Default windows: logarithmically spaced
    if windows is None:
        windows = [int(w) for w in np.logspace(1, np.log10(n_time // 4), 10)]

    fano_results = {}
    for w in windows:
        fano_values, info = fano(spikes, window=w, overlap=overlap)
        fano_results[w] = fano_values

    if mode == "individual":
        return _plot_fano_individual(
            fano_results, windows, dt, neuron_indices, n_neurons
        )
    elif mode == "grouped":
        if group_by is None:
            raise ValueError("group_by must be specified for grouped mode")
        return _plot_fano_grouped(
            fano_results,
            windows,
            dt,
            spikes,
            neurons_df,
            connections_df,
            group_by,
            neuron_type_column,
        )
    elif mode == "distribution":
        return _plot_fano_distribution(fano_results, windows, dt)
    else:
        raise ValueError(f"Unknown mode: {mode}")

to_numpy(data, *, strict=False, name='data')

Convert a tensor or array-like to a dense NumPy array.

Torch tensors are detached and moved to CPU; anything else goes through :func:numpy.asarray.

Parameters:

Name Type Description Default
data Any

torch.Tensor, np.ndarray or array-like.

required
strict bool

Accept only torch.Tensor and np.ndarray and raise :class:TypeError for anything else (lists, scalars, ...).

False
name str

Argument name used in the strict error message.

'data'

Returns:

Type Description
ndarray

NumPy array (a view of the input when no conversion is needed).

Raises:

Type Description
TypeError

If strict and data is not a tensor or ndarray.

Source code in btorch/utils/array.py
def to_numpy(data: Any, *, strict: bool = False, name: str = "data") -> np.ndarray:
    """Convert a tensor or array-like to a dense NumPy array.

    Torch tensors are detached and moved to CPU; anything else goes through
    :func:`numpy.asarray`.

    Args:
        data: ``torch.Tensor``, ``np.ndarray`` or array-like.
        strict: Accept only ``torch.Tensor`` and ``np.ndarray`` and raise
            :class:`TypeError` for anything else (lists, scalars, ...).
        name: Argument name used in the ``strict`` error message.

    Returns:
        NumPy array (a view of the input when no conversion is needed).

    Raises:
        TypeError: If ``strict`` and ``data`` is not a tensor or ndarray.
    """
    if isinstance(data, torch.Tensor):
        return data.detach().cpu().numpy()
    if strict and not isinstance(data, np.ndarray):
        raise TypeError(f"`{name}` must be a numpy array or torch tensor.")
    return np.asarray(data)

btorch.visualisation.hex

Hexagonal visualization subpackage.

Supports multiple coordinate formats: axial (q,r), FlyWire (x,y).

Attributes

__all__ = ['HexColorMap', 'HexGeometry', 'HexPatchStyle', 'HexReference', 'heatmap', 'scatter', 'quiver', 'grid', 'looming_stimulus', 'draw_axes', 'compass', 'HexScatter', 'HexQuiver', 'kernel', 'strf', 'ReceptiveFieldViewer'] module-attribute

Classes

HexColorMap dataclass

Colour mapping of the plotted values (or vector magnitudes).

Attributes:

Name Type Description
cmap str

Matplotlib colormap name.

vmin float | None

Lower colour limit; defaults to the data minimum.

vmax float | None

Upper colour limit; defaults to the data maximum.

Source code in btorch/visualisation/hex/options.py
@dataclass(frozen=True, kw_only=True)
class HexColorMap:
    """Colour mapping of the plotted values (or vector magnitudes).

    Attributes:
        cmap: Matplotlib colormap name.
        vmin: Lower colour limit; defaults to the data minimum.
        vmax: Upper colour limit; defaults to the data maximum.
    """

    cmap: str = "viridis"
    vmin: float | None = None
    vmax: float | None = None

HexGeometry dataclass

How hex coordinates are laid out in pixel space.

Attributes:

Name Type Description
layout str | None

Explicit pixel layout (e.g. "flat"); defaults to "flat" for zigzag/flywire coordinates and to orientation otherwise.

size float

Hexagon size used to convert coordinates to pixels.

orientation Literal['pointy', 'flat']

"pointy" or "flat" top.

rotation_deg float

Global display rotation in degrees (only applied by the "flywire" layout).

Source code in btorch/visualisation/hex/options.py
@dataclass(frozen=True, kw_only=True)
class HexGeometry:
    """How hex coordinates are laid out in pixel space.

    Attributes:
        layout: Explicit pixel layout (e.g. ``"flat"``); defaults to ``"flat"`` for
            zigzag/flywire coordinates and to ``orientation`` otherwise.
        size: Hexagon size used to convert coordinates to pixels.
        orientation: ``"pointy"`` or ``"flat"`` top.
        rotation_deg: Global display rotation in degrees (only applied by
            the ``"flywire"`` layout).
    """

    layout: str | None = None
    size: float = 1.0
    orientation: Literal["pointy", "flat"] = "pointy"
    rotation_deg: float = 0.0

HexPatchStyle dataclass

Appearance of the hexagon patches.

Attributes:

Name Type Description
edgecolor str | None

Hexagon edge colour (None for matplotlib's default).

edgewidth float

Hexagon edge width.

alpha float

Transparency (0-1).

Source code in btorch/visualisation/hex/options.py
@dataclass(frozen=True, kw_only=True)
class HexPatchStyle:
    """Appearance of the hexagon patches.

    Attributes:
        edgecolor: Hexagon edge colour (``None`` for matplotlib's default).
        edgewidth: Hexagon edge width.
        alpha: Transparency (0-1).
    """

    edgecolor: str | None = None
    edgewidth: float = 0.5
    alpha: float = 1.0

HexQuiver

Animated vector field on hex grid.

Parameters:

Name Type Description Default
flow ndarray

Flow data, shape (n_frames, 2, n_hexes) where [:, 0, :] = dc1, [:, 1, :] = dc2

required
c1 ndarray

First coordinate (interpreted based on coord_format)

required
c2 ndarray

Second coordinate (interpreted based on coord_format)

required
coord_format CoordFormat

Any :data:~btorch.utils.hex.resolve.CoordFormat, e.g. "axial" (q,r), "zigzag" (x,y), or "pixel" (px,py)

'axial'
scale float

Vector scale factor

1.0
cwheel bool

Show colorwheel for direction encoding

True
Example

anim = HexQuiver(flow_data, q, r, coord_format="axial") anim.save("flow.mp4")

Source code in btorch/visualisation/hex/animate.py
class HexQuiver:
    """Animated vector field on hex grid.

    Args:
        flow: Flow data, shape (n_frames, 2, n_hexes) where
            [:, 0, :] = dc1, [:, 1, :] = dc2
        c1: First coordinate (interpreted based on coord_format)
        c2: Second coordinate (interpreted based on coord_format)
        coord_format: Any :data:`~btorch.utils.hex.resolve.CoordFormat`, e.g. "axial"
            (q,r), "zigzag" (x,y), or "pixel" (px,py)
        scale: Vector scale factor
        cwheel: Show colorwheel for direction encoding

    Example:
        >>> anim = HexQuiver(flow_data, q, r, coord_format="axial")
        >>> anim.save("flow.mp4")
    """

    def __init__(
        self,
        flow: np.ndarray,
        c1: np.ndarray,
        c2: np.ndarray,
        coord_format: CoordFormat = "axial",
        layout: str | None = None,
        figsize: tuple[float, float] = (6, 6),
        scale: float = 1.0,
        cmap: str = "hsv",
        cwheel: bool = True,
        interval: int = 200,
        ax: Axes | None = None,
    ):
        self.flow = flow
        self.c1 = c1
        self.c2 = c2
        self.coord_format = coord_format
        self.n_frames = flow.shape[0]
        self.scale = scale

        is_flat = coord_format in ("zigzag", "flywire")
        effective = layout or ("flat" if is_flat else "pointy")
        _, _, self.x, self.y = resolve_hex(
            c1,
            c2,
            coord_format=coord_format,
            layout=effective,
        )

        if ax is None:
            self.fig, self.ax = plt.subplots(figsize=figsize)
        else:
            self.ax = ax
            self.fig = ax.figure

        self.cmap = cmap
        self.cwheel = cwheel
        self.interval = interval

        self._init_plot()

    def _init_plot(self) -> None:
        """Initialize the plot."""
        u = self.flow[0, 0] * self.scale
        v = self.flow[0, 1] * self.scale

        angles = np.arctan2(v, u)

        self.quiver = self.ax.quiver(
            self.x,
            self.y,
            u,
            v,
            angles,
            cmap=self.cmap,
            scale_units="xy",
            angles="xy",
            scale=1,
        )
        self.ax.set_aspect("equal")
        self.ax.axis("off")

    def update(self, frame: int) -> None:
        """Update animation for given frame."""
        u = self.flow[frame, 0] * self.scale
        v = self.flow[frame, 1] * self.scale
        angles = np.arctan2(v, u)

        self.quiver.set_UVC(u, v, angles)

    def _create_animation(self) -> FuncAnimation:
        """Create the animation object."""
        return FuncAnimation(
            self.fig,
            self.update,
            frames=self.n_frames,
            interval=self.interval,
            blit=False,
        )

    def save(self, path: str, **kwargs: Any) -> None:
        """Save animation to file."""
        anim = self._create_animation()
        anim.save(path, **kwargs)
        plt.close(self.fig)

    def show(self) -> None:
        """Display animation."""
        self._create_animation()
        plt.show()
Methods:
save(path, **kwargs)

Save animation to file.

Source code in btorch/visualisation/hex/animate.py
def save(self, path: str, **kwargs: Any) -> None:
    """Save animation to file."""
    anim = self._create_animation()
    anim.save(path, **kwargs)
    plt.close(self.fig)
show()

Display animation.

Source code in btorch/visualisation/hex/animate.py
def show(self) -> None:
    """Display animation."""
    self._create_animation()
    plt.show()
update(frame)

Update animation for given frame.

Source code in btorch/visualisation/hex/animate.py
def update(self, frame: int) -> None:
    """Update animation for given frame."""
    u = self.flow[frame, 0] * self.scale
    v = self.flow[frame, 1] * self.scale
    angles = np.arctan2(v, u)

    self.quiver.set_UVC(u, v, angles)

HexReference dataclass

Orientation aids drawn on top of the plot.

Attributes:

Name Type Description
axes_alignment Literal['vertex', 'edge'] | None

If "vertex" or "edge", draw q/r/s reference axes.

show_compass Literal['vertex', 'edge'] | None

If "vertex" or "edge", draw a hex compass rose inset.

Source code in btorch/visualisation/hex/options.py
@dataclass(frozen=True, kw_only=True)
class HexReference:
    """Orientation aids drawn on top of the plot.

    Attributes:
        axes_alignment: If ``"vertex"`` or ``"edge"``, draw q/r/s reference axes.
        show_compass: If ``"vertex"`` or ``"edge"``, draw a hex compass rose inset.
    """

    axes_alignment: Literal["vertex", "edge"] | None = None
    show_compass: Literal["vertex", "edge"] | None = None

HexScatter

Animated hex scatter plot for time-series data.

Parameters:

Name Type Description Default
values ndarray

Time-series data, shape (n_frames, n_hexes)

required
c1 ndarray

First coordinate (interpreted based on coord_format)

required
c2 ndarray

Second coordinate (interpreted based on coord_format)

required
coord_format CoordFormat

Any :data:~btorch.utils.hex.resolve.CoordFormat, e.g. "axial" (q,r), "zigzag" (x,y), or "pixel" (px,py)

'axial'
figsize tuple[float, float]

Figure size

(6, 6)
cmap str

Colormap

'viridis'
vmin float | None

Lower color limit

None
vmax float | None

Upper color limit

None
interval int

Animation interval in milliseconds

200
Example

anim = HexScatter(data, q, r, coord_format="axial") anim.save("output.mp4")

Source code in btorch/visualisation/hex/animate.py
class HexScatter:
    """Animated hex scatter plot for time-series data.

    Args:
        values: Time-series data, shape (n_frames, n_hexes)
        c1: First coordinate (interpreted based on coord_format)
        c2: Second coordinate (interpreted based on coord_format)
        coord_format: Any :data:`~btorch.utils.hex.resolve.CoordFormat`, e.g. "axial"
            (q,r), "zigzag" (x,y), or "pixel" (px,py)
        figsize: Figure size
        cmap: Colormap
        vmin: Lower color limit
        vmax: Upper color limit
        interval: Animation interval in milliseconds

    Example:
        >>> anim = HexScatter(data, q, r, coord_format="axial")
        >>> anim.save("output.mp4")
    """

    def __init__(
        self,
        values: np.ndarray,
        c1: np.ndarray,
        c2: np.ndarray,
        coord_format: CoordFormat = "axial",
        layout: str | None = None,
        figsize: tuple[float, float] = (6, 6),
        cmap: str = "viridis",
        vmin: float | None = None,
        vmax: float | None = None,
        interval: int = 200,
        ax: Axes | None = None,
    ):
        self.values = values
        self.c1 = c1
        self.c2 = c2
        self.coord_format = coord_format
        self.n_frames = values.shape[0]

        is_flat = coord_format in ("zigzag", "flywire")
        effective = layout or ("flat" if is_flat else "pointy")
        _, _, self.x, self.y = resolve_hex(
            c1,
            c2,
            coord_format=coord_format,
            layout=effective,
        )

        if ax is None:
            self.fig, self.ax = plt.subplots(figsize=figsize)
        else:
            self.ax = ax
            self.fig = ax.figure

        self.cmap = cmap
        self.vmin = vmin
        self.vmax = vmax
        self.interval = interval

        self._init_plot()

    def _init_plot(self) -> None:
        """Initialize the plot."""
        self.sc = self.ax.scatter(
            self.x,
            self.y,
            c=self.values[0],
            cmap=self.cmap,
            vmin=self.vmin,
            vmax=self.vmax,
            s=100,
        )
        self.ax.set_aspect("equal")
        self.ax.axis("off")
        plt.colorbar(self.sc, ax=self.ax)

    def update(self, frame: int) -> None:
        """Update animation for given frame."""
        self.sc.set_array(self.values[frame])

    def _create_animation(self) -> FuncAnimation:
        """Create the animation object."""
        return FuncAnimation(
            self.fig,
            self.update,
            frames=self.n_frames,
            interval=self.interval,
            blit=False,
        )

    def save(self, path: str, **kwargs: Any) -> None:
        """Save animation to file."""
        anim = self._create_animation()
        anim.save(path, **kwargs)
        plt.close(self.fig)

    def show(self) -> None:
        """Display animation."""
        self._create_animation()
        plt.show()
Methods:
save(path, **kwargs)

Save animation to file.

Source code in btorch/visualisation/hex/animate.py
def save(self, path: str, **kwargs: Any) -> None:
    """Save animation to file."""
    anim = self._create_animation()
    anim.save(path, **kwargs)
    plt.close(self.fig)
show()

Display animation.

Source code in btorch/visualisation/hex/animate.py
def show(self) -> None:
    """Display animation."""
    self._create_animation()
    plt.show()
update(frame)

Update animation for given frame.

Source code in btorch/visualisation/hex/animate.py
def update(self, frame: int) -> None:
    """Update animation for given frame."""
    self.sc.set_array(self.values[frame])

ReceptiveFieldViewer

Interactive receptive field viewer for connectome analysis.

Source code in btorch/visualisation/hex/receptive_field.py
class ReceptiveFieldViewer:
    """Interactive receptive field viewer for connectome analysis."""

    def __init__(
        self,
        edges: pd.DataFrame,
        target_type: str,
        coord_format: Literal["axial", "zigzag"] = "axial",
        c1_col: str = "u",
        c2_col: str = "v",
        weight_col: str = "weight",
    ):
        """Initialize RF viewer.

        Args:
            edges: Edge dataframe with connectivity
            target_type: Target cell type
            coord_format: Coordinate system
            c1_col: Column name for first coordinate
            c2_col: Column name for second coordinate
            weight_col: Column name for edge weights
        """
        self.edges = edges
        self.target_type = target_type
        self.coord_format = coord_format
        self.c1_col = c1_col
        self.c2_col = c2_col
        self.weight_col = weight_col

    def plot(
        self,
        source: str,
        max_extent: int | None = None,
        **kwargs: Any,
    ) -> Figure:
        """Plot receptive field from source to target.

        Args:
            source: Source cell type
            max_extent: Maximum extent to plot
            **kwargs: Additional arguments for kernel()

        Returns:
            Figure object
        """
        mask = self.edges["target_type"] == self.target_type
        if source:
            mask = mask & (self.edges["source_type"] == source)

        filtered = self.edges[mask]

        if len(filtered) == 0:
            raise ValueError(f"No edges found for {source} -> {self.target_type}")

        c1 = filtered[self.c1_col].to_numpy()
        c2 = filtered[self.c2_col].to_numpy()
        values = filtered[self.weight_col].to_numpy()

        if max_extent is not None:
            from ...utils.hex.distance import radius

            r = radius(c1, c2)
            mask = r <= max_extent
            c1, c2, values = c1[mask], c2[mask], values[mask]

        fig, _ = kernel(c1, c2, values, coord_format=self.coord_format, **kwargs)
        return fig
Methods:
__init__(edges, target_type, coord_format='axial', c1_col='u', c2_col='v', weight_col='weight')

Initialize RF viewer.

Parameters:

Name Type Description Default
edges DataFrame

Edge dataframe with connectivity

required
target_type str

Target cell type

required
coord_format Literal['axial', 'zigzag']

Coordinate system

'axial'
c1_col str

Column name for first coordinate

'u'
c2_col str

Column name for second coordinate

'v'
weight_col str

Column name for edge weights

'weight'
Source code in btorch/visualisation/hex/receptive_field.py
def __init__(
    self,
    edges: pd.DataFrame,
    target_type: str,
    coord_format: Literal["axial", "zigzag"] = "axial",
    c1_col: str = "u",
    c2_col: str = "v",
    weight_col: str = "weight",
):
    """Initialize RF viewer.

    Args:
        edges: Edge dataframe with connectivity
        target_type: Target cell type
        coord_format: Coordinate system
        c1_col: Column name for first coordinate
        c2_col: Column name for second coordinate
        weight_col: Column name for edge weights
    """
    self.edges = edges
    self.target_type = target_type
    self.coord_format = coord_format
    self.c1_col = c1_col
    self.c2_col = c2_col
    self.weight_col = weight_col
plot(source, max_extent=None, **kwargs)

Plot receptive field from source to target.

Parameters:

Name Type Description Default
source str

Source cell type

required
max_extent int | None

Maximum extent to plot

None
**kwargs Any

Additional arguments for kernel()

{}

Returns:

Type Description
Figure

Figure object

Source code in btorch/visualisation/hex/receptive_field.py
def plot(
    self,
    source: str,
    max_extent: int | None = None,
    **kwargs: Any,
) -> Figure:
    """Plot receptive field from source to target.

    Args:
        source: Source cell type
        max_extent: Maximum extent to plot
        **kwargs: Additional arguments for kernel()

    Returns:
        Figure object
    """
    mask = self.edges["target_type"] == self.target_type
    if source:
        mask = mask & (self.edges["source_type"] == source)

    filtered = self.edges[mask]

    if len(filtered) == 0:
        raise ValueError(f"No edges found for {source} -> {self.target_type}")

    c1 = filtered[self.c1_col].to_numpy()
    c2 = filtered[self.c2_col].to_numpy()
    values = filtered[self.weight_col].to_numpy()

    if max_extent is not None:
        from ...utils.hex.distance import radius

        r = radius(c1, c2)
        mask = r <= max_extent
        c1, c2, values = c1[mask], c2[mask], values[mask]

    fig, _ = kernel(c1, c2, values, coord_format=self.coord_format, **kwargs)
    return fig

Functions:

compass(ax, loc='lower left', size=0.15, alignment='vertex', colors=('#66c2a5', '#fc8d62', '#8da0cb'), label_color='#333333', bg_color='white', alpha=0.9, border_color='#cccccc', border_width=0.8)

Draw a hex-direction compass rose as an inset on the axes.

This creates a small map-style compass showing all six axial directions (+q, -q, +r, -r, +s, -s) radiating from a central circle, similar to the style used by Red Blob Games.

Parameters:

Name Type Description Default
ax Axes

Main matplotlib axes.

required
loc str

Compass location, e.g. "lower left", "upper right".

'lower left'
size float

Compass size as fraction of the main axes (0-1).

0.15
alignment str

"vertex" (axes through hex vertices) or "edge" (axes parallel to hex edges).

'vertex'
colors tuple[str, str, str]

Colors for q, r, s axis pairs.

('#66c2a5', '#fc8d62', '#8da0cb')
label_color str

Text color for direction labels.

'#333333'
bg_color str

Background fill color for the compass box.

'white'
alpha float

Background transparency.

0.9
border_color str

Border color for the compass box.

'#cccccc'
border_width float

Border line width.

0.8

Returns:

Type Description
Axes

The inset axes containing the compass.

Source code in btorch/visualisation/hex/static.py
def compass(
    ax: plt.Axes,
    loc: str = "lower left",
    size: float = 0.15,
    alignment: str = "vertex",
    colors: tuple[str, str, str] = ("#66c2a5", "#fc8d62", "#8da0cb"),
    label_color: str = "#333333",
    bg_color: str = "white",
    alpha: float = 0.9,
    border_color: str = "#cccccc",
    border_width: float = 0.8,
) -> plt.Axes:
    """Draw a hex-direction compass rose as an inset on the axes.

    This creates a small map-style compass showing all six axial
    directions (+q, -q, +r, -r, +s, -s) radiating from a central circle,
    similar to the style used by Red Blob Games.

    Args:
        ax: Main matplotlib axes.
        loc: Compass location, e.g. "lower left", "upper right".
        size: Compass size as fraction of the main axes (0-1).
        alignment: "vertex" (axes through hex vertices) or
            "edge" (axes parallel to hex edges).
        colors: Colors for q, r, s axis pairs.
        label_color: Text color for direction labels.
        bg_color: Background fill color for the compass box.
        alpha: Background transparency.
        border_color: Border color for the compass box.
        border_width: Border line width.

    Returns:
        The inset axes containing the compass.
    """
    from matplotlib.patches import Circle, FancyBboxPatch

    inset = ax.inset_axes((0, 0, size, size), transform=ax.transAxes)

    pos_map = {
        "upper left": (0.02, 0.98 - size),
        "upper right": (0.98 - size, 0.98 - size),
        "lower left": (0.02, 0.02),
        "lower right": (0.98 - size, 0.02),
    }
    x0, y0 = pos_map.get(loc, pos_map["lower left"])
    inset.set_position((x0, y0, size, size))

    inset.set_xlim(-1.4, 1.4)
    inset.set_ylim(-1.4, 1.4)
    inset.set_aspect("equal")
    inset.axis("off")

    bbox = FancyBboxPatch(
        (-1.35, -1.35),
        2.7,
        2.7,
        boxstyle="round,pad=0.02,rounding_size=0.15",
        facecolor=bg_color,
        edgecolor=border_color,
        linewidth=border_width,
        alpha=alpha,
        zorder=0,
    )
    inset.add_patch(bbox)

    q_dir = np.array([1.0, 0.0])
    r_dir = np.array([0.5, np.sqrt(3) / 2])
    s_dir = np.array([-0.5, np.sqrt(3) / 2])

    if alignment == "edge":
        angle = np.pi / 6
        rot = np.array(
            [[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]
        )
        q_dir = rot @ q_dir
        r_dir = rot @ r_dir
        s_dir = rot @ s_dir

    directions = [
        (q_dir, "+q", colors[0]),
        (-q_dir, "-q", colors[0]),
        (r_dir, "+r", colors[1]),
        (-r_dir, "-r", colors[1]),
        (s_dir, "+s", colors[2]),
        (-s_dir, "-s", colors[2]),
    ]

    arrow_len = 0.85
    label_offset = 1.15

    for vec, label, color in directions:
        dx, dy = vec * arrow_len
        lx, ly = vec * label_offset

        inset.annotate(
            "",
            xy=(dx, dy),
            xytext=(0, 0),
            arrowprops=dict(
                arrowstyle="-|>",
                color=color,
                lw=1.5,
                mutation_scale=10,
            ),
            zorder=2,
        )

        inset.text(
            lx,
            ly,
            label,
            color=label_color,
            ha="center",
            va="center",
            fontsize=8,
            fontweight="bold",
            zorder=3,
        )

    circle = Circle(
        (0, 0), 0.15, facecolor="white", edgecolor="#888888", linewidth=1, zorder=4
    )
    inset.add_patch(circle)

    return inset

draw_axes(ax, origin=(0.0, 0.0), size=1.0, orientation='pointy', alignment='vertex', colors=('red', 'green', 'blue'), labels=('q', 'r', 's'), linewidth=1.5, head_width=0.3)

Draw 3-axis reference arrows on a hex grid plot.

Parameters:

Name Type Description Default
ax Axes

Matplotlib axes.

required
origin tuple[float, float]

(x, y) position for the axis origin.

(0.0, 0.0)
size float

Length of each arrow in pixel units.

1.0
orientation str

"pointy" or "flat".

'pointy'
alignment str

"vertex" (axes through hex vertices) or "edge" (axes parallel to hex edges).

'vertex'
colors tuple[str, str, str]

Colors for q, r, s arrows.

('red', 'green', 'blue')
labels tuple[str, str, str]

Labels for q, r, s arrows.

('q', 'r', 's')
linewidth float

Arrow line width.

1.5
head_width float

Arrow head width.

0.3
Source code in btorch/visualisation/hex/static.py
def draw_axes(
    ax: plt.Axes,
    origin: tuple[float, float] = (0.0, 0.0),
    size: float = 1.0,
    orientation: str = "pointy",
    alignment: str = "vertex",
    colors: tuple[str, str, str] = ("red", "green", "blue"),
    labels: tuple[str, str, str] = ("q", "r", "s"),
    linewidth: float = 1.5,
    head_width: float = 0.3,
) -> None:
    """Draw 3-axis reference arrows on a hex grid plot.

    Args:
        ax: Matplotlib axes.
        origin: (x, y) position for the axis origin.
        size: Length of each arrow in pixel units.
        orientation: "pointy" or "flat".
        alignment: "vertex" (axes through hex vertices) or
            "edge" (axes parallel to hex edges).
        colors: Colors for q, r, s arrows.
        labels: Labels for q, r, s arrows.
        linewidth: Arrow line width.
        head_width: Arrow head width.
    """
    q_dir, r_dir, s_dir = _hex_axis_directions(
        size=size, orientation=orientation, alignment=alignment
    )

    ox, oy = origin
    for (dx, dy), color, label in zip([q_dir, r_dir, s_dir], colors, labels):
        ax.arrow(
            ox,
            oy,
            dx,
            dy,
            head_width=head_width,
            head_length=head_width * 0.6,
            fc=color,
            ec=color,
            linewidth=linewidth,
            length_includes_head=True,
            zorder=1000,
        )
        ax.text(
            ox + dx * 1.15,
            oy + dy * 1.15,
            label,
            color=color,
            ha="center",
            va="center",
            fontsize=10,
            fontweight="bold",
            zorder=1001,
        )

grid(radius, coord_format='axial', layout=None, annotate=False, size=1.0, orientation='pointy', figsize=(6, 6), ax=None, title=None, axes_alignment=None, show_compass=None)

Coordinate grid with optional labels.

Parameters:

Name Type Description Default
radius int

Grid radius

required
coord_format Literal['axial', 'zigzag']

Coordinate format

'axial'
annotate bool

Whether to annotate coordinates

False
size float

Hexagon size

1.0
orientation Literal['pointy', 'flat']

"pointy" or "flat"

'pointy'
figsize tuple[float, float]

Figure size

(6, 6)
ax Axes | None

Optional axes to plot on

None
title str | None

Plot title

None
axes_alignment str | None

If "vertex" or "edge", draw q/r/s reference axes

None
show_compass str | None

If "vertex" or "edge", draw a hex compass rose inset

None

Returns:

Type Description
tuple[Figure, Axes]

Figure and axes objects

Source code in btorch/visualisation/hex/static.py
def grid(
    radius: int,
    coord_format: Literal["axial", "zigzag"] = "axial",
    layout: str | None = None,
    annotate: bool = False,
    size: float = 1.0,
    orientation: Literal["pointy", "flat"] = "pointy",
    figsize: tuple[float, float] = (6, 6),
    ax: plt.Axes | None = None,
    title: str | None = None,
    axes_alignment: str | None = None,
    show_compass: str | None = None,
) -> tuple[plt.Figure, plt.Axes]:
    """Coordinate grid with optional labels.

    Args:
        radius: Grid radius
        coord_format: Coordinate format
        annotate: Whether to annotate coordinates
        size: Hexagon size
        orientation: "pointy" or "flat"
        figsize: Figure size
        ax: Optional axes to plot on
        title: Plot title
        axes_alignment: If "vertex" or "edge", draw q/r/s reference axes
        show_compass: If "vertex" or "edge", draw a hex compass rose inset

    Returns:
        Figure and axes objects
    """
    from ...utils.hex.coords import disk

    q, r = disk(radius)

    if coord_format == "axial":
        (x, y), eff = _resolve_to_pixel(
            q,
            r,
            "axial",
            size=size,
            orientation=orientation,
            layout=layout,
        )
        labels = [f"({qi},{ri})" for qi, ri in zip(q, r)]
    elif coord_format == "zigzag":
        from ...utils.hex.offset import axial_to_zigzag

        zx, zy = axial_to_zigzag(q, r)
        (x, y), eff = _resolve_to_pixel(zx, zy, "zigzag", size=size, layout=layout)
        labels = [f"({zi[0]},{zi[1]})" for zi in zip(zx, zy)]
    else:
        raise ValueError(f"Unknown coord_format: {coord_format}")

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    hex_orientation = np.pi / 6 if eff in ("flat", "flywire") else 0

    for xi, yi, label in zip(x, y, labels):
        hex_patch = RegularPolygon(
            (xi, yi),
            numVertices=6,
            radius=size * 0.95,
            orientation=hex_orientation,
            facecolor="white",
            edgecolor="gray",
            linewidth=0.5,
        )
        ax.add_patch(hex_patch)

        if annotate:
            ax.text(xi, yi, label, ha="center", va="center", fontsize=6)

    ax.set_aspect("equal")
    ax.set_xlim(x.min() - size, x.max() + size)
    ax.set_ylim(y.min() - size, y.max() + size)

    if title:
        ax.set_title(title)

    if axes_alignment in ("vertex", "edge"):
        draw_axes(
            ax,
            origin=(x.min() + size, y.min() + size),
            size=size * 2,
            orientation=orientation,
            alignment=axes_alignment,
        )

    if show_compass in ("vertex", "edge"):
        compass(ax, alignment=show_compass, loc="lower left")

    ax.axis("off")

    return fig, ax

heatmap(df, dataset, style=None, sizing=None, dpi=72, custom_colorscale=None, title=None, colorbar=True, value_name='value', coord_format='axial', orientation='flat', layout=None, rotation_deg=0.0, include_flywire_hover=True)

Generate an interactive hexagonal heatmap.

Hex polygons are drawn as SVG path shapes in data coordinates — no pixel math, no marker-size estimation. A single invisible scatter trace at hex centres provides hover, colour bar, and optional text labels. Plotly handles all scaling (zoom, resize, export).

Parameters:

Name Type Description Default
df DataFrame

DataFrame with 'p' and 'q' columns plus one or more value columns. Single value column produces a static heatmap; multiple columns produce an animated heatmap with a slider.

required
dataset DataFrame

Reference hex grid ('p', 'q' columns). Background hexes are drawn white for spatial context.

required
style dict | None

Styling overrides — font_type, linecolor, papercolor.

None
sizing dict | None

Size overrides — fig_width, fig_height, hex_line_color, hex_line_width, cbar_thickness, cbar_len, etc.

None
dpi int

Dots per inch for pixel dimension calculations.

72
custom_colorscale list | None

Plotly colorscale (list of [pos, colour] pairs or a named string like "Viridis").

None
title str | None

Optional plot title.

None
colorbar bool

Whether to show colour bar (default True).

True
value_name str

Label for values in hover tooltip.

'value'
coord_format CoordFormat

How to interpret 'p'/'q' columns — any :data:~btorch.utils.hex.resolve.CoordFormat, e.g. "axial", "zigzag", "flywire", or "pixel".

'axial'
orientation Literal['pointy', 'flat']

"flat" or "pointy" hex orientation.

'flat'
layout str | None

Set to "flywire" to use the flywire pixel projection.

None
rotation_deg float

Rotation for flywire layout.

0.0
include_flywire_hover bool

Include axial and zigzag coordinates in hover tooltip (default True).

True

Returns:

Type Description
Figure

Plotly Figure with hexagonal heatmap.

Example

fig = heatmap(data_df, background_df) fig.show()

Source code in btorch/visualisation/hex/interactive.py
def heatmap(
    df: pd.DataFrame,
    dataset: pd.DataFrame,
    style: dict | None = None,
    sizing: dict | None = None,
    dpi: int = 72,
    custom_colorscale: list | None = None,
    title: str | None = None,
    colorbar: bool = True,
    value_name: str = "value",
    coord_format: CoordFormat = "axial",
    orientation: Literal["pointy", "flat"] = "flat",
    layout: str | None = None,
    rotation_deg: float = 0.0,
    include_flywire_hover: bool = True,
) -> go.Figure:
    """Generate an interactive hexagonal heatmap.

    Hex polygons are drawn as SVG path shapes in data coordinates — no
    pixel math, no marker-size estimation.  A single invisible scatter
    trace at hex centres provides hover, colour bar, and optional text
    labels.  Plotly handles all scaling (zoom, resize, export).

    Args:
        df: DataFrame with ``'p'`` and ``'q'`` columns plus one or more
            value columns.  Single value column produces a static heatmap;
            multiple columns produce an animated heatmap with a slider.
        dataset: Reference hex grid (``'p'``, ``'q'`` columns).  Background
            hexes are drawn white for spatial context.
        style: Styling overrides — ``font_type``, ``linecolor``,
            ``papercolor``.
        sizing: Size overrides — ``fig_width``, ``fig_height``,
            ``hex_line_color``, ``hex_line_width``, ``cbar_thickness``,
            ``cbar_len``, etc.
        dpi: Dots per inch for pixel dimension calculations.
        custom_colorscale: Plotly colorscale (list of [pos, colour] pairs
            or a named string like ``"Viridis"``).
        title: Optional plot title.
        colorbar: Whether to show colour bar (default ``True``).
        value_name: Label for values in hover tooltip.
        coord_format: How to interpret ``'p'``/``'q'`` columns —
            any :data:`~btorch.utils.hex.resolve.CoordFormat`, e.g.
            ``"axial"``, ``"zigzag"``, ``"flywire"``, or ``"pixel"``.
        orientation: ``"flat"`` or ``"pointy"`` hex orientation.
        layout: Set to ``"flywire"`` to use the flywire pixel projection.
        rotation_deg: Rotation for flywire layout.
        include_flywire_hover: Include axial and zigzag coordinates in
            hover tooltip (default ``True``).

    Returns:
        Plotly Figure with hexagonal heatmap.

    Example:
        >>> fig = heatmap(data_df, background_df)
        >>> fig.show()
    """
    go = _plotly_go()
    sty = _merge_style(style)
    sz = _merge_sizing(sizing)
    area_w, area_h, f_ticks, f_title = _compute_pixel_dims(sz, dpi)

    bg = dataset.drop_duplicates(subset=["p", "q"])[["p", "q"]].astype(float)
    _, _, _, _, bg_x, bg_y = _resolve_coords(
        bg.p.to_numpy(),
        bg.q.to_numpy(),
        coord_format,
        orientation,
        layout=layout,
        rotation_deg=rotation_deg,
    )
    dq, dr, dzx, dzy, dx, dy = _resolve_coords(
        df.p.to_numpy(),
        df.q.to_numpy(),
        coord_format,
        orientation,
        layout=layout,
        rotation_deg=rotation_deg,
    )
    ctx = _HeatmapContext(
        colorscale=custom_colorscale or _DEFAULT_COLORSCALE,
        vmin=min(0, float(df.values.min())),
        vmax=float(df.values.max()),
        orientation=orientation,
        sty=sty,
        sz=sz,
        f_ticks=f_ticks,
        f_title=f_title,
        value_name=value_name,
        include_flywire_hover=include_flywire_hover,
        bg_xy=(bg_x, bg_y),
        axial=(dq, dr),
        zigzag=(dzx, dzy),
        xy=(dx, dy),
    )

    hex_pad = 1.2  # hex circumradius (1.0) + margin
    x_range = (float(bg_x.min()) - hex_pad, float(bg_x.max()) + hex_pad)
    y_range = (float(bg_y.min()) - hex_pad, float(bg_y.max()) + hex_pad)

    value_cols = [c for c in df.columns if c not in ("p", "q")]
    if len(value_cols) <= 1:
        series = df[value_cols[0]] if value_cols else df.iloc[:, 0]
        fig = _static_heatmap(go, ctx, series, colorbar, area_w, area_h)
    else:
        fig = _animated_heatmap(go, ctx, df, value_cols, colorbar, area_w, area_h)
    _hide_axes(fig, x_range=x_range, y_range=y_range)

    if title:
        fig.update_layout(title=dict(text=title))

    return fig

kernel(c1, c2, values, coord_format='axial', figsize=(1, 1), cmap='seismic', vmin=None, vmax=None, midpoint=None, annotate=False, annotate_coords=False, edgecolor=None, fontsize=5, cbar=False, ax=None)

Plot receptive field kernel on hexagonal lattice.

Parameters:

Name Type Description Default
c1 ndarray

First coordinate

required
c2 ndarray

Second coordinate

required
values ndarray

Kernel values

required
coord_format Literal['axial', 'zigzag']

Coordinate system

'axial'
figsize tuple[float, float]

Figure size

(1, 1)
cmap str

Colormap

'seismic'
vmin float | None

Lower value limit

None
vmax float | None

Upper value limit

None
midpoint float | None

Center value for colormap

None
annotate bool

Whether to annotate values

False
annotate_coords bool

Whether to annotate coordinates

False
edgecolor str | None

Hexagon edge color

None
fontsize int

Font size for annotations

5
cbar bool

Whether to show colorbar

False
ax Axes | None

Optional axes

None

Returns:

Type Description
tuple[Figure, Axes]

Figure and axes objects

Source code in btorch/visualisation/hex/receptive_field.py
def kernel(
    c1: np.ndarray,
    c2: np.ndarray,
    values: np.ndarray,
    coord_format: Literal["axial", "zigzag"] = "axial",
    figsize: tuple[float, float] = (1, 1),
    cmap: str = "seismic",
    vmin: float | None = None,
    vmax: float | None = None,
    midpoint: float | None = None,
    annotate: bool = False,
    annotate_coords: bool = False,
    edgecolor: str | None = None,
    fontsize: int = 5,
    cbar: bool = False,
    ax: Axes | None = None,
) -> tuple[Figure, Axes]:
    """Plot receptive field kernel on hexagonal lattice.

    Args:
        c1: First coordinate
        c2: Second coordinate
        values: Kernel values
        coord_format: Coordinate system
        figsize: Figure size
        cmap: Colormap
        vmin: Lower value limit
        vmax: Upper value limit
        midpoint: Center value for colormap
        annotate: Whether to annotate values
        annotate_coords: Whether to annotate coordinates
        edgecolor: Hexagon edge color
        fontsize: Font size for annotations
        cbar: Whether to show colorbar
        ax: Optional axes

    Returns:
        Figure and axes objects
    """
    if coord_format == "axial":
        x, y = to_pixel(c1, c2)
    elif coord_format == "zigzag":
        from ...utils.hex.offset import zigzag_to_axial

        qz, rz = zigzag_to_axial(c1, c2)
        x, y = to_pixel(qz, rz)
    else:
        raise ValueError(f"Unknown coord_format: {coord_format}")

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    vmin = vmin if vmin is not None else np.nanmin(values)
    vmax = vmax if vmax is not None else np.nanmax(values)

    if midpoint is not None:
        # Symmetric colormap around midpoint
        max_abs = max(abs(vmax - midpoint), abs(vmin - midpoint))
        vmin = midpoint - max_abs
        vmax = midpoint + max_abs

    scatter(
        c1,
        c2,
        values,
        coord_format=coord_format,
        color=HexColorMap(cmap=cmap, vmin=vmin, vmax=vmax),
        ax=ax,
    )

    if annotate or annotate_coords:
        for xi, yi, vi, qi, ri in zip(x, y, values, c1, c2):
            if annotate:
                ax.text(
                    xi, yi, f"{vi:.2f}", ha="center", va="center", fontsize=fontsize
                )
            elif annotate_coords:
                ax.text(
                    xi,
                    yi,
                    f"({int(qi)},{int(ri)})",
                    ha="center",
                    va="center",
                    fontsize=fontsize,
                )

    ax.set_aspect("equal")
    ax.axis("off")

    if cbar:
        sm = ScalarMappable(norm=Normalize(vmin=vmin, vmax=vmax), cmap=cmap)
        plt.colorbar(sm, ax=ax)

    return fig, ax

looming_stimulus(start_coords, all_coords, n_time=4)

Generate expanding stimulus pattern on hex grid.

Creates a sequence of expanding hex regions starting from start_coords, simulating a looming object approaching the retina.

Parameters:

Name Type Description Default
start_coords list[str]

List of "x,y" strings for starting hexes

required
all_coords list[str]

List of all valid "x,y" hex coordinates in grid

required
n_time int

Number of time steps for expansion

4

Returns:

Type Description
list[list[str]]

List of lists, where each inner list contains "x,y" coordinates

list[list[str]]

stimulated at that time step

Example

all_coords = ["0,0", "1,0", "0,2", "-1,0"] looming_stimulus(["0,0"], all_coords, n_time=3) [['0,0'], ['0,0', '1,0', '-1,0', '0,2', '0,-2'], [...]]

Source code in btorch/visualisation/hex/static.py
def looming_stimulus(
    start_coords: list[str], all_coords: list[str], n_time: int = 4
) -> list[list[str]]:
    """Generate expanding stimulus pattern on hex grid.

    Creates a sequence of expanding hex regions starting from start_coords,
    simulating a looming object approaching the retina.

    Args:
        start_coords: List of "x,y" strings for starting hexes
        all_coords: List of all valid "x,y" hex coordinates in grid
        n_time: Number of time steps for expansion

    Returns:
        List of lists, where each inner list contains "x,y" coordinates
        stimulated at that time step

    Example:
        >>> all_coords = ["0,0", "1,0", "0,2", "-1,0"]
        >>> looming_stimulus(["0,0"], all_coords, n_time=3)
        [['0,0'], ['0,0', '1,0', '-1,0', '0,2', '0,-2'], [...]]
    """
    coords = [tuple(map(float, c.split(","))) for c in all_coords]
    x_vals, y_vals = zip(*coords)

    x_sorted = sorted(set(x_vals))
    x_to_rank = {x: i for i, x in enumerate(x_sorted)}
    rank_to_x = {i: x for x, i in x_to_rank.items()}

    y_sorted = sorted(set(y_vals))
    y_to_rank = {y: i for i, y in enumerate(y_sorted)}
    rank_to_y = {i: y for y, i in y_to_rank.items()}

    start = [tuple(map(float, c.split(","))) for c in start_coords]

    stimulus = [start]
    current = start.copy()

    for _ in range(n_time):
        next_hexes = current.copy()
        for x, y in current:
            # Hexes above and below (y ± 2 in double-width)
            if y_to_rank[y] + 2 in rank_to_y:
                next_hexes.append((x, rank_to_y[y_to_rank[y] + 2]))
            if y_to_rank[y] - 2 in rank_to_y:
                next_hexes.append((x, rank_to_y[y_to_rank[y] - 2]))
            # Hexes to the left (x + 1, y ± 1)
            if x_to_rank[x] + 1 in rank_to_x:
                if y_to_rank[y] + 1 in rank_to_y:
                    next_hexes.append(
                        (rank_to_x[x_to_rank[x] + 1], rank_to_y[y_to_rank[y] + 1])
                    )
                if y_to_rank[y] - 1 in rank_to_y:
                    next_hexes.append(
                        (rank_to_x[x_to_rank[x] + 1], rank_to_y[y_to_rank[y] - 1])
                    )
            # Hexes to the right (x - 1, y ± 1)
            if x_to_rank[x] - 1 in rank_to_x:
                if y_to_rank[y] + 1 in rank_to_y:
                    next_hexes.append(
                        (rank_to_x[x_to_rank[x] - 1], rank_to_y[y_to_rank[y] + 1])
                    )
                if y_to_rank[y] - 1 in rank_to_y:
                    next_hexes.append(
                        (rank_to_x[x_to_rank[x] - 1], rank_to_y[y_to_rank[y] - 1])
                    )

        current = list(set(next_hexes))
        stimulus.append(current)

    result = []
    for hex_list in stimulus:
        formatted = []
        for x, y in hex_list:
            x_str = str(int(x)) if x == int(x) else str(x)
            y_str = str(int(y)) if y == int(y) else str(y)
            formatted.append(f"{x_str},{y_str}")
        result.append(formatted)

    return result

quiver(c1, c2, dc1, dc2, coord_format='axial', scale=1.0, *, geometry=None, color=None, reference=None, figsize=(6, 6), ax=None, title=None)

Vector field on hex grid.

Parameters:

Name Type Description Default
c1 ndarray

First coordinate

required
c2 ndarray

Second coordinate

required
dc1 ndarray

First vector component

required
dc2 ndarray

Second vector component

required
coord_format CoordFormat

Any :data:~btorch.utils.hex.resolve.CoordFormat

'axial'
scale float

Vector scale factor

1.0
geometry HexGeometry | None

Pixel layout (size, orientation, rotation); see :class:~btorch.visualisation.hex.options.HexGeometry.

None
color HexColorMap | None

Colormap (and limits) for vector magnitude; see :class:~btorch.visualisation.hex.options.HexColorMap.

None
reference HexReference | None

Reference axes / compass; see :class:~btorch.visualisation.hex.options.HexReference.

None
figsize tuple[float, float]

Figure size (used when ax is None)

(6, 6)
ax Axes | None

Optional axes

None
title str | None

Plot title

None

Returns:

Type Description
tuple[Figure, Axes]

Figure and axes objects

Source code in btorch/visualisation/hex/static.py
def quiver(
    c1: np.ndarray,
    c2: np.ndarray,
    dc1: np.ndarray,
    dc2: np.ndarray,
    coord_format: CoordFormat = "axial",
    scale: float = 1.0,
    *,
    geometry: HexGeometry | None = None,
    color: HexColorMap | None = None,
    reference: HexReference | None = None,
    figsize: tuple[float, float] = (6, 6),
    ax: plt.Axes | None = None,
    title: str | None = None,
) -> tuple[plt.Figure, plt.Axes]:
    """Vector field on hex grid.

    Args:
        c1: First coordinate
        c2: Second coordinate
        dc1: First vector component
        dc2: Second vector component
        coord_format: Any :data:`~btorch.utils.hex.resolve.CoordFormat`
        scale: Vector scale factor
        geometry: Pixel layout (size, orientation, rotation); see
            :class:`~btorch.visualisation.hex.options.HexGeometry`.
        color: Colormap (and limits) for vector magnitude; see
            :class:`~btorch.visualisation.hex.options.HexColorMap`.
        reference: Reference axes / compass; see
            :class:`~btorch.visualisation.hex.options.HexReference`.
        figsize: Figure size (used when ``ax`` is None)
        ax: Optional axes
        title: Plot title

    Returns:
        Figure and axes objects
    """
    geometry = geometry or HexGeometry()
    color = color or HexColorMap()
    reference = reference or HexReference()
    size = geometry.size
    pix = dict(
        size=size,
        orientation=geometry.orientation,
        layout=geometry.layout,
        rotation_deg=geometry.rotation_deg,
    )

    (x, y), _ = _resolve_to_pixel(c1, c2, coord_format, **pix)

    if coord_format == "pixel":
        dx, dy = dc1 * scale, dc2 * scale
    else:
        (tx, ty), _ = _resolve_to_pixel(
            c1 + dc1 * scale, c2 + dc2 * scale, coord_format, **pix
        )
        dx = tx - x
        dy = ty - y

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    magnitudes = np.sqrt(dx**2 + dy**2)
    vmin = color.vmin if color.vmin is not None else np.nanmin(magnitudes)
    vmax = color.vmax if color.vmax is not None else np.nanmax(magnitudes)

    norm = plt.Normalize(vmin=vmin, vmax=vmax)
    colors = plt.get_cmap(color.cmap)(norm(magnitudes))

    ax.quiver(x, y, dx, dy, color=colors, scale_units="xy", angles="xy", scale=1)

    ax.set_aspect("equal")
    ax.set_xlim(x.min() - size * 2, x.max() + size * 2)
    ax.set_ylim(y.min() - size * 2, y.max() + size * 2)
    _decorate(ax, x, y, geometry, reference, title)

    return fig, ax

scatter(c1, c2, values, coord_format='axial', *, geometry=None, color=None, patch=None, reference=None, figsize=(6, 6), ax=None, title=None)

Colored hex scatter.

Parameters:

Name Type Description Default
c1 ndarray

First coordinate (interpreted based on coord_format)

required
c2 ndarray

Second coordinate (interpreted based on coord_format)

required
values ndarray

Color values for each hex

required
coord_format CoordFormat

Any :data:~btorch.utils.hex.resolve.CoordFormat

'axial'
geometry HexGeometry | None

Pixel layout (size, orientation, rotation); see :class:~btorch.visualisation.hex.options.HexGeometry.

None
color HexColorMap | None

Colormap and colour limits; see :class:~btorch.visualisation.hex.options.HexColorMap.

None
patch HexPatchStyle | None

Edge colour/width and alpha; see :class:~btorch.visualisation.hex.options.HexPatchStyle.

None
reference HexReference | None

Reference axes / compass; see :class:~btorch.visualisation.hex.options.HexReference.

None
figsize tuple[float, float]

Figure size (used when ax is None)

(6, 6)
ax Axes | None

Optional axes to plot on

None
title str | None

Plot title

None

Returns:

Type Description
tuple[Figure, Axes]

Figure and axes objects

Source code in btorch/visualisation/hex/static.py
def scatter(
    c1: np.ndarray,
    c2: np.ndarray,
    values: np.ndarray,
    coord_format: CoordFormat = "axial",
    *,
    geometry: HexGeometry | None = None,
    color: HexColorMap | None = None,
    patch: HexPatchStyle | None = None,
    reference: HexReference | None = None,
    figsize: tuple[float, float] = (6, 6),
    ax: plt.Axes | None = None,
    title: str | None = None,
) -> tuple[plt.Figure, plt.Axes]:
    """Colored hex scatter.

    Args:
        c1: First coordinate (interpreted based on coord_format)
        c2: Second coordinate (interpreted based on coord_format)
        values: Color values for each hex
        coord_format: Any :data:`~btorch.utils.hex.resolve.CoordFormat`
        geometry: Pixel layout (size, orientation, rotation); see
            :class:`~btorch.visualisation.hex.options.HexGeometry`.
        color: Colormap and colour limits; see
            :class:`~btorch.visualisation.hex.options.HexColorMap`.
        patch: Edge colour/width and alpha; see
            :class:`~btorch.visualisation.hex.options.HexPatchStyle`.
        reference: Reference axes / compass; see
            :class:`~btorch.visualisation.hex.options.HexReference`.
        figsize: Figure size (used when ``ax`` is None)
        ax: Optional axes to plot on
        title: Plot title

    Returns:
        Figure and axes objects
    """
    geometry = geometry or HexGeometry()
    color = color or HexColorMap()
    patch = patch or HexPatchStyle()
    reference = reference or HexReference()
    size = geometry.size

    (x, y), effective_layout = _resolve_to_pixel(
        c1,
        c2,
        coord_format,
        size=size,
        orientation=geometry.orientation,
        layout=geometry.layout,
        rotation_deg=geometry.rotation_deg,
    )

    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    vmin = color.vmin if color.vmin is not None else np.nanmin(values)
    vmax = color.vmax if color.vmax is not None else np.nanmax(values)

    norm = plt.Normalize(vmin=vmin, vmax=vmax)
    cmap_obj = plt.get_cmap(color.cmap)

    if effective_layout in ("flat", "flywire"):
        hex_orientation = np.pi / 6  # flat top
    else:
        hex_orientation = 0  # pointy top

    for xi, yi, vi in zip(x, y, values):
        face = "white" if np.isnan(vi) else cmap_obj(norm(vi))
        hex_patch = RegularPolygon(
            (xi, yi),
            numVertices=6,
            radius=size * 0.95,  # slight gap between hexes
            orientation=hex_orientation,
            facecolor=face,
            edgecolor=patch.edgecolor,
            linewidth=patch.edgewidth,
            alpha=patch.alpha,
        )
        ax.add_patch(hex_patch)

    ax.set_aspect("equal")
    ax.set_xlim(x.min() - size, x.max() + size)
    ax.set_ylim(y.min() - size, y.max() + size)
    _decorate(ax, x, y, geometry, reference, title)

    return fig, ax

strf(time, rf, c1, c2, coord_format='axial', figsize=(5, 1), fontsize=6, hlines=True, vlines=True)

Plot Spatio-Temporal Receptive Field (STRF).

Parameters:

Name Type Description Default
time ndarray

Time points, shape (n_time,)

required
rf ndarray

Receptive field data, shape (n_time, n_hexes)

required
c1 ndarray

First coordinate

required
c2 ndarray

Second coordinate

required
coord_format Literal['axial', 'zigzag']

Coordinate system

'axial'
figsize tuple[float, float]

Figure size

(5, 1)
fontsize int

Font size

6
hlines bool

Whether to draw horizontal lines

True
vlines bool

Whether to draw vertical lines

True

Returns:

Type Description
tuple[Figure, ndarray]

Figure and axes array

Source code in btorch/visualisation/hex/receptive_field.py
def strf(
    time: np.ndarray,
    rf: np.ndarray,
    c1: np.ndarray,
    c2: np.ndarray,
    coord_format: Literal["axial", "zigzag"] = "axial",
    figsize: tuple[float, float] = (5, 1),
    fontsize: int = 6,
    hlines: bool = True,
    vlines: bool = True,
) -> tuple[Figure, np.ndarray]:
    """Plot Spatio-Temporal Receptive Field (STRF).

    Args:
        time: Time points, shape (n_time,)
        rf: Receptive field data, shape (n_time, n_hexes)
        c1: First coordinate
        c2: Second coordinate
        coord_format: Coordinate system
        figsize: Figure size
        fontsize: Font size
        hlines: Whether to draw horizontal lines
        vlines: Whether to draw vertical lines

    Returns:
        Figure and axes array
    """
    n_time = len(time)
    n_cols = min(n_time, 10)
    n_rows = (n_time + n_cols - 1) // n_cols

    fig, axes = plt.subplots(n_rows, n_cols, figsize=figsize)
    axes = np.array(axes).flatten()

    vmax = np.abs(rf).max()
    vmin = -vmax

    for i, (t, ax) in enumerate(zip(time, axes)):
        kernel(
            c1,
            c2,
            rf[i],
            coord_format=coord_format,
            cmap="seismic",
            vmin=vmin,
            vmax=vmax,
            ax=ax,
        )
        ax.set_title(f"t={t:.2f}", fontsize=fontsize)

    for ax in axes[n_time:]:
        ax.axis("off")

    plt.tight_layout()
    return fig, axes

btorch.visualisation.network

Network graph visualization utilities.

Functions:

plot_network(sparse_mat, ax=None)

Plot a network graph from a sparse connectivity matrix.

Uses NetworkX spring layout to visualize the graph structure. Nodes are colored skyblue, edges are gray.

Parameters:

Name Type Description Default
sparse_mat sparray

Sparse matrix (scipy.sparse) representing connections. Non-zero entries indicate edges.

required
ax Axes | None

Existing axes to plot on. If None, creates new figure.

None

Returns:

Type Description
Figure

Figure containing the network plot.

Raises:

Type Description
ImportError

If networkx is not installed.

Example

from scipy.sparse import random mat = random(50, 50, density=0.1, format="csr") fig = plot_network(mat)

Source code in btorch/visualisation/network.py
def plot_network(sparse_mat: scipy.sparse.sparray, ax: Axes | None = None) -> Figure:
    """Plot a network graph from a sparse connectivity matrix.

    Uses NetworkX spring layout to visualize the graph structure.
    Nodes are colored skyblue, edges are gray.

    Args:
        sparse_mat: Sparse matrix (scipy.sparse) representing connections.
            Non-zero entries indicate edges.
        ax: Existing axes to plot on. If None, creates new figure.

    Returns:
        Figure containing the network plot.

    Raises:
        ImportError: If networkx is not installed.

    Example:
        >>> from scipy.sparse import random
        >>> mat = random(50, 50, density=0.1, format="csr")
        >>> fig = plot_network(mat)
    """
    import matplotlib.pyplot as plt
    import networkx as nx

    G = nx.from_scipy_sparse_array(sparse_mat)
    pos = nx.spring_layout(G)

    if ax is None:
        fig, ax = plt.subplots(figsize=(8, 8))
    else:
        fig = ax.figure

    nx.draw(
        G,
        pos,
        with_labels=True,
        node_color="skyblue",
        edge_color="gray",
        ax=ax,
    )
    ax.set_title("Network Graph")
    return fig

btorch.visualisation.timeseries

Timeseries visualization utilities for spike trains and continuous traces.

This package provides plotting functions for: - Spike raster plots with grouping and styling options - Continuous timeseries traces (voltage, currents) - Frequency spectrum analysis - Log-binned histograms

The raster plot supports neuron grouping, color-coded strips, population firing rates, and event/region annotations.

Layout: raster, traces, spectrum, histogram, neuron_traces and neuron_specs hold the public API; modules prefixed with _ are private implementation details shared between them.

Attributes

__all__ = ['GroupStripOptions', 'NeuronSpec', 'RasterAnnotations', 'RasterGrouping', 'RasterStyle', 'RatePanelOptions', 'SimulationStates', 'SpectrumGrouping', 'SpectrumStyle', 'TracePlotFormat', 'plot_grouped_spectrum', 'plot_log_hist', 'plot_neuron_traces', 'plot_raster', 'plot_spectrum', 'plot_traces'] module-attribute

Classes

GroupStripOptions dataclass

Colour strip beside the raster (also sets the group label side).

Attributes:

Name Type Description
show bool

Draw the strip. With show=False only color_key and side take effect (grouping colour column and label side).

color_key str | None

Column of neurons_df used for strip colours; defaults to RasterGrouping.group_key. A different column gives subgroups.

cmap str

Matplotlib colormap name for top-group and subgroup colours.

layout dict | None

Overrides for the strip geometry and label styling.

legend bool

Add a legend for the group colours.

label_mode Literal['top', 'sub', 'top_sub']

Which labels to print when subgroups are used.

side Literal['left', 'right']

Side of the raster on which strip and labels are drawn.

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class GroupStripOptions:
    """Colour strip beside the raster (also sets the group label side).

    Attributes:
        show: Draw the strip. With ``show=False`` only ``color_key`` and
            ``side`` take effect (grouping colour column and label side).
        color_key: Column of ``neurons_df`` used for strip colours; defaults to
            ``RasterGrouping.group_key``. A different column gives subgroups.
        cmap: Matplotlib colormap name for top-group and subgroup colours.
        layout: Overrides for the strip geometry and label styling.
        legend: Add a legend for the group colours.
        label_mode: Which labels to print when subgroups are used.
        side: Side of the raster on which strip and labels are drawn.
    """

    show: bool = True
    color_key: str | None = None
    cmap: str = "tab10"
    layout: dict | None = None
    legend: bool = True
    label_mode: Literal["top", "sub", "top_sub"] = "top_sub"
    side: Literal["left", "right"] = "right"

NeuronSpec dataclass

Specification for neuron plotting style.

Attributes:

Name Type Description
label str | None

Custom label text

color str | dict[str, str] | None

Main color string or dict of colors for 'voltage', 'asc', 'psc'

linestyle str

Line style string (e.g. '-', '--', ':')

linewidth float

Line width

alpha float

Plot opacity

Source code in btorch/visualisation/timeseries/neuron_specs.py
@dataclass
class NeuronSpec:
    """Specification for neuron plotting style.

    Attributes:
        label: Custom label text
        color: Main color string or dict of colors for 'voltage', 'asc', 'psc'
        linestyle: Line style string (e.g. '-', '--', ':')
        linewidth: Line width
        alpha: Plot opacity
    """

    label: str | None = None
    color: str | dict[str, str] | None = None
    linestyle: str = "-"
    linewidth: float = 0.8
    alpha: float = 1.0
    marker: str | None = None
    markersize: float | None = None

RasterAnnotations dataclass

Events, shaded regions and optional event tracks.

Attributes:

Name Type Description
events Sequence[float] | dict[str, Sequence[float]] | None

Event times, or a dict mapping names to event times.

regions Sequence[tuple[float, float]] | dict[str, Sequence[tuple[float, float]]] | None

(start, end) spans, or a dict mapping names to spans.

show_tracks bool

Draw events/regions as tracks below the raster.

event_kwargs dict | None

Extra keyword arguments for event lines.

region_kwargs dict | None

Extra keyword arguments for region patches.

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class RasterAnnotations:
    """Events, shaded regions and optional event tracks.

    Attributes:
        events: Event times, or a dict mapping names to event times.
        regions: ``(start, end)`` spans, or a dict mapping names to spans.
        show_tracks: Draw events/regions as tracks below the raster.
        event_kwargs: Extra keyword arguments for event lines.
        region_kwargs: Extra keyword arguments for region patches.
    """

    events: Sequence[float] | dict[str, Sequence[float]] | None = None
    regions: (
        Sequence[tuple[float, float]] | dict[str, Sequence[tuple[float, float]]] | None
    ) = None
    show_tracks: bool = False
    event_kwargs: dict | None = None
    region_kwargs: dict | None = None

RasterGrouping dataclass

Neuron grouping, ordering and group separators.

Attributes:

Name Type Description
neurons_df DataFrame | None

Neuron metadata, required for any grouping.

group_key str | None

Column of neurons_df to group neurons by.

group_sort list[str] | None

Explicit group order (unknown groups are ignored).

sort_neurons bool

Reorder neurons by group/subgroup so bands are contiguous; if False the original order is kept.

show_separators bool

Draw lines (and labels) between groups.

separator_style dict | None

Extra keyword arguments for the separator lines.

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class RasterGrouping:
    """Neuron grouping, ordering and group separators.

    Attributes:
        neurons_df: Neuron metadata, required for any grouping.
        group_key: Column of ``neurons_df`` to group neurons by.
        group_sort: Explicit group order (unknown groups are ignored).
        sort_neurons: Reorder neurons by group/subgroup so bands are
            contiguous; if False the original order is kept.
        show_separators: Draw lines (and labels) between groups.
        separator_style: Extra keyword arguments for the separator lines.
    """

    neurons_df: pd.DataFrame | None = None
    group_key: str | None = None
    group_sort: list[str] | None = None
    sort_neurons: bool = True
    show_separators: bool = True
    separator_style: dict | None = None

RasterStyle dataclass

Spike marker appearance.

Attributes:

Name Type Description
spike_color str | dict | Sequence[Any] | None

Default spike colour. A dict maps group names or neuron indices to colours; a sequence gives one colour per neuron.

marker str

Matplotlib marker for spikes.

marker_size float

Marker size in points squared.

neuron_specs dict | list | NeuronSpec | None

Per-neuron styling (dict keyed by neuron index, list, or a single :class:NeuronSpec).

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class RasterStyle:
    """Spike marker appearance.

    Attributes:
        spike_color: Default spike colour. A dict maps group names or neuron
            indices to colours; a sequence gives one colour per neuron.
        marker: Matplotlib marker for spikes.
        marker_size: Marker size in points squared.
        neuron_specs: Per-neuron styling (dict keyed by neuron index, list, or
            a single :class:`NeuronSpec`).
    """

    spike_color: str | dict | Sequence[Any] | None = "black"
    marker: str = "."
    marker_size: float = 5.0
    neuron_specs: dict | list | NeuronSpec | None = None

RatePanelOptions dataclass

Firing-rate panel below the raster.

Attributes:

Name Type Description
total bool | ndarray | Tensor | None

If True compute the population rate; an array of length T (or (T, 1)) is plotted as given.

per_group bool | dict[str, ndarray | Tensor] | ndarray | None

If True compute one rate per group (needs a group key); a dict maps group names to arrays, an array is (T, G) in the order of the resolved groups.

window_ms float

Smoothing window for computed rates, in ms.

Source code in btorch/visualisation/timeseries/raster_options.py
@dataclass(frozen=True, kw_only=True)
class RatePanelOptions:
    """Firing-rate panel below the raster.

    Attributes:
        total: If True compute the population rate; an array of length ``T``
            (or ``(T, 1)``) is plotted as given.
        per_group: If True compute one rate per group (needs a group key); a
            dict maps group names to arrays, an array is ``(T, G)`` in the
            order of the resolved groups.
        window_ms: Smoothing window for computed rates, in ms.
    """

    total: bool | np.ndarray | torch.Tensor | None = False
    per_group: bool | dict[str, np.ndarray | torch.Tensor] | np.ndarray | None = False
    window_ms: float = 10.0

SimulationStates dataclass

Container for simulation state data and configs.

Attributes:

Name Type Description
voltage ndarray | Tensor

Membrane voltage traces (time, neurons) or (time, batch, neurons) if batch dimension present

dt float

Simulation timestep in ms

asc ndarray | Tensor | None

Afterspike current traces (time, neurons), (time, batch, neurons), or (time, batch, neurons, n_asc) for multiple ASC components

psc ndarray | Tensor | None

Total postsynaptic current (time, neurons), (time, batch, neurons), or (time, batch, neurons, n_psc) for multiple PSC components

epsc ndarray | Tensor | None

Excitatory PSC (time, neurons) or (time, batch, neurons)

ipsc ndarray | Tensor | None

Inhibitory PSC (time, neurons) or (time, batch, neurons)

input ndarray | Tensor | None

Input current (time, neurons) or (time, batch, neurons)

spikes ndarray | Tensor | None

Spike trains (time, neurons) or (time, batch, neurons)

v_threshold float | Sequence[float] | ndarray | Tensor | None

Spike threshold voltage(s), scalar or per-neuron

v_reset float | Sequence[float] | ndarray | Tensor | None

Reset voltage(s), scalar or per-neuron

psc_labels Sequence[str] | None

Labels for multi-component PSC (defaults to PSC_<i>)

Source code in btorch/visualisation/timeseries/neuron_specs.py
@dataclass
class SimulationStates:
    """Container for simulation state data and configs.

    Attributes:
        voltage: Membrane voltage traces (time, neurons) or
            (time, batch, neurons) if batch dimension present
        dt: Simulation timestep in ms
        asc: Afterspike current traces (time, neurons), (time, batch, neurons),
            or (time, batch, neurons, n_asc) for multiple ASC components
        psc: Total postsynaptic current (time, neurons), (time, batch, neurons),
            or (time, batch, neurons, n_psc) for multiple PSC components
        epsc: Excitatory PSC (time, neurons) or (time, batch, neurons)
        ipsc: Inhibitory PSC (time, neurons) or (time, batch, neurons)
        input: Input current (time, neurons) or (time, batch, neurons)
        spikes: Spike trains (time, neurons) or (time, batch, neurons)
        v_threshold: Spike threshold voltage(s), scalar or per-neuron
        v_reset: Reset voltage(s), scalar or per-neuron
        psc_labels: Labels for multi-component PSC (defaults to ``PSC_<i>``)
    """

    voltage: np.ndarray | torch.Tensor
    dt: float = 1.0
    asc: np.ndarray | torch.Tensor | None = None
    psc: np.ndarray | torch.Tensor | None = None
    epsc: np.ndarray | torch.Tensor | None = None
    ipsc: np.ndarray | torch.Tensor | None = None
    input: np.ndarray | torch.Tensor | None = None
    spikes: np.ndarray | torch.Tensor | None = None
    v_threshold: float | Sequence[float] | np.ndarray | torch.Tensor | None = None
    v_reset: float | Sequence[float] | np.ndarray | torch.Tensor | None = None
    psc_labels: Sequence[str] | None = None

SpectrumGrouping dataclass

Which neurons belong to which group.

Either give neurons_df plus group_by, or an explicit groups mapping (which takes precedence). With neither, all neurons form one group called "All".

Attributes:

Name Type Description
neurons_df DataFrame | None

Neuron metadata; its index holds neuron indices.

group_by str | None

Column of neurons_df to group neurons by.

groups dict[str, list[int]] | None

Manual {group_label: [neuron_indices]} mapping.

Source code in btorch/visualisation/timeseries/spectrum_options.py
@dataclass(frozen=True, kw_only=True)
class SpectrumGrouping:
    """Which neurons belong to which group.

    Either give ``neurons_df`` plus ``group_by``, or an explicit ``groups``
    mapping (which takes precedence). With neither, all neurons form one
    group called ``"All"``.

    Attributes:
        neurons_df: Neuron metadata; its index holds neuron indices.
        group_by: Column of ``neurons_df`` to group neurons by.
        groups: Manual ``{group_label: [neuron_indices]}`` mapping.
    """

    neurons_df: pd.DataFrame | None = None
    group_by: str | None = None
    groups: dict[str, list[int]] | None = None

SpectrumStyle dataclass

Appearance and figure size of the grouped spectrum.

Attributes:

Name Type Description
show_traces bool

Draw the individual neuron spectra (faint lines).

show_mean bool

Draw the group-mean spectrum.

colors dict[str, str] | None

{group_label: colour}; defaults to the tab10 cycle.

plot_width float

Width of one panel in inches.

plot_height float

Height of one panel in inches.

Source code in btorch/visualisation/timeseries/spectrum_options.py
@dataclass(frozen=True, kw_only=True)
class SpectrumStyle:
    """Appearance and figure size of the grouped spectrum.

    Attributes:
        show_traces: Draw the individual neuron spectra (faint lines).
        show_mean: Draw the group-mean spectrum.
        colors: ``{group_label: colour}``; defaults to the ``tab10`` cycle.
        plot_width: Width of one panel in inches.
        plot_height: Height of one panel in inches.
    """

    show_traces: bool = True
    show_mean: bool = True
    colors: dict[str, str] | None = None
    plot_width: float = 6.0
    plot_height: float = 4.0

TracePlotFormat dataclass

Figure formatting configuration.

Attributes:

Name Type Description
neuron_indices list[int] | None

Specific neuron indices to plot

sample_size int | None

Number of neurons to randomly sample

seed int

Random seed for sampling

show_voltage bool

Whether to show voltage subplot

show_asc bool

Whether to show ASC subplot

show_psc bool

Whether to show PSC subplot

show_spikes_on_voltage bool

Mark spikes on voltage trace

separate_figures bool

Return dict of figures (one per trace type) if True

auto_width bool

Adjust figure width based on simulation duration

colors dict[str, str] | None

Color mapping for different traces

figsize_per_neuron tuple[float, float]

Figure size per neuron row (width, height)

neuron_labels Sequence[str] | Callable[[int], str] | None

Side labels as sequence or callable(neuron_idx) -> str. Default None disables side labels.

neuron_label_position Literal['side', 'top']

Position for neuron labels when enabled. "side" places labels at the right of each neuron slot; "top" places labels above each neuron slot.

neurons_per_row int | None

Number of neurons to place per row in combined mode

batch_idx int | None

Batch index to plot when data has shape (time, batch, neurons). If None and data is 3D, defaults to 0 (first batch sample).

Source code in btorch/visualisation/timeseries/neuron_specs.py
@dataclass
class TracePlotFormat:
    """Figure formatting configuration.

    Attributes:
        neuron_indices: Specific neuron indices to plot
        sample_size: Number of neurons to randomly sample
        seed: Random seed for sampling
        show_voltage: Whether to show voltage subplot
        show_asc: Whether to show ASC subplot
        show_psc: Whether to show PSC subplot
        show_spikes_on_voltage: Mark spikes on voltage trace
        separate_figures: Return dict of figures (one per trace type) if True
        auto_width: Adjust figure width based on simulation duration
        colors: Color mapping for different traces
        figsize_per_neuron: Figure size per neuron row (width, height)
        neuron_labels: Side labels as sequence or callable(neuron_idx) -> str.
            Default None disables side labels.
        neuron_label_position: Position for neuron labels when enabled.
            "side" places labels at the right of each neuron slot; "top"
            places labels above each neuron slot.
        neurons_per_row: Number of neurons to place per row in combined mode
        batch_idx: Batch index to plot when data has shape (time, batch, neurons).
            If None and data is 3D, defaults to 0 (first batch sample).
    """

    neuron_indices: list[int] | None = None
    sample_size: int | None = None
    seed: int = 42
    show_voltage: bool = True
    show_asc: bool = True
    show_psc: bool = True
    show_spikes_on_voltage: bool = True
    separate_figures: bool = False
    auto_width: bool = True
    colors: dict[str, str] | None = None
    figsize_per_neuron: tuple[float, float] = (12, 2.5)
    neuron_labels: Sequence[str] | Callable[[int], str] | None = None
    neuron_label_position: Literal["side", "top"] = "side"
    neuron_specs: list[NeuronSpec | dict] | NeuronSpec | dict | None = None
    neurons_per_row: int | None = None
    batch_idx: int | None = None

Functions:

plot_grouped_spectrum(data, dt=1.0, grouping=None, *, mode='overlay', separate_figures=False, nperseg=None, style=None, title='Grouped Spectrum')

Plot spectrum for multiple groups.

Parameters:

Name Type Description Default
data ndarray | Tensor

(Time, Neurons)

required
dt float

Timestep

1.0
grouping SpectrumGrouping | None

Neuron grouping (metadata column or manual groups); see :class:~btorch.visualisation.timeseries.SpectrumGrouping. Defaults to a single group with all neurons.

None
mode Literal['overlay', 'subplots']

"overlay" (all in one) or "subplots" (rows)

'overlay'
separate_figures bool

Return dict of figs

False
nperseg int | None

Welch segment length passed to :func:plot_spectrum

None
style SpectrumStyle | None

Traces/mean flags, colours and panel size; see :class:~btorch.visualisation.timeseries.SpectrumStyle.

None
title str | None

Title of the overlay figure

'Grouped Spectrum'

Returns:

Type Description
Figure | dict[str, Figure]

A figure, or a dict of figures keyed by group when

Figure | dict[str, Figure]

separate_figures is True.

Source code in btorch/visualisation/timeseries/spectrum.py
def plot_grouped_spectrum(
    data: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    grouping: SpectrumGrouping | None = None,
    *,
    mode: Literal["overlay", "subplots"] = "overlay",
    separate_figures: bool = False,
    nperseg: int | None = None,
    style: SpectrumStyle | None = None,
    title: str | None = "Grouped Spectrum",
) -> Figure | dict[str, Figure]:
    """Plot spectrum for multiple groups.

    Args:
        data: (Time, Neurons)
        dt: Timestep
        grouping: Neuron grouping (metadata column or manual groups); see
            :class:`~btorch.visualisation.timeseries.SpectrumGrouping`.
            Defaults to a single group with all neurons.
        mode: "overlay" (all in one) or "subplots" (rows)
        separate_figures: Return dict of figs
        nperseg: Welch segment length passed to :func:`plot_spectrum`
        style: Traces/mean flags, colours and panel size; see
            :class:`~btorch.visualisation.timeseries.SpectrumStyle`.
        title: Title of the overlay figure

    Returns:
        A figure, or a dict of figures keyed by group when
        ``separate_figures`` is True.
    """
    grouping = grouping or SpectrumGrouping()
    style = style or SpectrumStyle()
    neurons_df, group_by, groups = (
        grouping.neurons_df,
        grouping.group_by,
        grouping.groups,
    )
    show_traces, show_mean, colors = style.show_traces, style.show_mean, style.colors
    plot_width, plot_height = style.plot_width, style.plot_height
    data_np = to_numpy(data)
    if groups is None:
        if neurons_df is None or group_by is None:
            groups = {"All": list(range(data_np.shape[1]))}
        else:
            if group_by not in neurons_df.columns:
                raise ValueError(f"Column {group_by} missing")

            groups = {}
            unique_groups = neurons_df[group_by].unique()
            for g in sorted(unique_groups):
                indices = neurons_df.index[neurons_df[group_by] == g].tolist()
                valid_indices = [i for i in indices if i < data_np.shape[1]]
                if valid_indices:
                    groups[g] = valid_indices

    if colors is None:
        cmap = plt.get_cmap("tab10")
        colors = {g: cmap(i % 10) for i, g in enumerate(groups.keys())}

    if separate_figures:
        figs = {}
        for g_name, indices in groups.items():
            fig, ax = plt.subplots(figsize=(plot_width, plot_height))
            group_data = data_np[:, indices]

            c = colors.get(g_name, "black")
            plot_spectrum(
                group_data,
                dt=dt,
                nperseg=nperseg,
                ax=ax,
                color=c,
                label=str(g_name),
                show_mean=show_mean,
                alpha=0.2 if show_traces else 0.0,
            )
            ax.set_title(f"Spectrum: {g_name}")
            figs[str(g_name)] = fig
        return figs

    elif mode == "subplots":
        n_groups = len(groups)
        fig, axes = plt.subplots(
            n_groups, 1, figsize=(plot_width, plot_height * n_groups), squeeze=False
        )
        axes = axes.flatten()

        for i, (g_name, indices) in enumerate(groups.items()):
            ax = axes[i]
            group_data = data_np[:, indices]
            c = colors.get(g_name, "black")

            plot_spectrum(
                group_data,
                dt=dt,
                nperseg=nperseg,
                ax=ax,
                color=c,
                label=str(g_name),
                show_mean=show_mean,
                alpha=0.2 if show_traces else 0.0,
            )
            ax.set_title(str(g_name))
            ax.legend(loc="upper right")

        plt.tight_layout()
        return fig

    else:  # Overlay
        fig, ax = plt.subplots(figsize=(plot_width, plot_height))

        for g_name, indices in groups.items():
            group_data = data_np[:, indices]
            c = colors.get(g_name, "black")

            plot_spectrum(
                group_data,
                dt=dt,
                nperseg=nperseg,
                ax=ax,
                color=c,
                label=str(g_name),
                show_mean=show_mean,
                alpha=0.1 if show_traces else 0.0,  # lighter alpha for overlay
            )

        ax.set_title(title)
        ax.legend()
        return fig

plot_log_hist(values, ax=None, title='Distribution', xlabel='Value', **kwargs)

Plot log-log histogram with logarithmic binning.

Creates a scatter plot of histogram counts using logarithmically spaced bins. Useful for visualizing heavy-tailed distributions (e.g., power laws).

Parameters:

Name Type Description Default
values ndarray | Tensor

Input values to histogram. Flattened if multidimensional.

required
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None
title str

Plot title.

'Distribution'
xlabel str

X-axis label.

'Value'
**kwargs Any

Additional arguments passed to ax.scatter().

{}

Returns:

Type Description
Axes

Axes containing the log-log histogram.

Example

ax = plot_log_hist(synapse_weights, title="Weight Distribution")

Source code in btorch/visualisation/timeseries/histogram.py
def plot_log_hist(
    values: np.ndarray | torch.Tensor,
    ax: Axes | None = None,
    title: str = "Distribution",
    xlabel: str = "Value",
    **kwargs: Any,
) -> Axes:
    """Plot log-log histogram with logarithmic binning.

    Creates a scatter plot of histogram counts using logarithmically
    spaced bins. Useful for visualizing heavy-tailed distributions
    (e.g., power laws).

    Args:
        values: Input values to histogram. Flattened if multidimensional.
        ax: Existing axes to plot on. Creates new figure if None.
        title: Plot title.
        xlabel: X-axis label.
        **kwargs: Additional arguments passed to ax.scatter().

    Returns:
        Axes containing the log-log histogram.

    Example:
        >>> ax = plot_log_hist(synapse_weights, title="Weight Distribution")
    """
    vals = to_numpy(values)
    hist, bin_centers = compute_log_hist(vals)

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 4))

    ax.scatter(bin_centers, hist, **kwargs)
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set_xlabel(xlabel)
    ax.set_ylabel("Count")
    ax.set_title(title)

    return ax

plot_neuron_traces(states, format=None)

Plot neuron state traces.

Each selected neuron gets a row of subplots showing voltage, ASC and PSC traces. All data goes into states and all presentation options (neuron selection, panels, labels, layout) into format.

Parameters:

Name Type Description Default
states SimulationStates

Simulation state arrays, dt, thresholds and PSC labels (:class:SimulationStates). Arrays are (time, neurons) or (time, batch, neurons); ASC/PSC may add a trailing component axis. If psc has a component axis (n_psc > 1), epsc, ipsc and input must be None.

required
format TracePlotFormat | None

Neuron selection, panel visibility, labels, per-neuron styles and figure layout (:class:TracePlotFormat). Defaults to TracePlotFormat().

None

Returns:

Type Description
Figure | dict[str, Figure]

Figure with neuron trace subplots, or a dict of figures (one per trace

Figure | dict[str, Figure]

type) when format.separate_figures is True.

Raises:

Type Description
ValueError

On invalid shapes, neurons_per_row < 1, conflicting PSC layouts, or a bad batch_idx / threshold length.

Source code in btorch/visualisation/timeseries/neuron_traces.py
def plot_neuron_traces(
    states: SimulationStates,
    format: TracePlotFormat | None = None,
) -> Figure | dict[str, Figure]:
    """Plot neuron state traces.

    Each selected neuron gets a row of subplots showing voltage, ASC and PSC
    traces. All data goes into ``states`` and all presentation options
    (neuron selection, panels, labels, layout) into ``format``.

    Args:
        states: Simulation state arrays, ``dt``, thresholds and PSC labels
            (:class:`SimulationStates`). Arrays are (time, neurons) or
            (time, batch, neurons); ASC/PSC may add a trailing component
            axis. If ``psc`` has a component axis (n_psc > 1), ``epsc``,
            ``ipsc`` and ``input`` must be None.
        format: Neuron selection, panel visibility, labels, per-neuron styles
            and figure layout (:class:`TracePlotFormat`). Defaults to
            ``TracePlotFormat()``.

    Returns:
        Figure with neuron trace subplots, or a dict of figures (one per trace
        type) when ``format.separate_figures`` is True.

    Raises:
        ValueError: On invalid shapes, ``neurons_per_row < 1``, conflicting PSC
            layouts, or a bad ``batch_idx`` / threshold length.
    """
    fmt = format or TracePlotFormat()
    data = _prepare_trace_data(states, fmt.batch_idx)
    n_time, n_neurons = data.voltage.shape
    times = np.arange(n_time) * states.dt
    duration_ms = n_time * states.dt

    neuron_indices = _select_trace_neurons(
        n_neurons, fmt.neuron_indices, fmt.sample_size, fmt.seed
    )
    n_plot = len(neuron_indices)
    neurons_per_row = 1 if fmt.neurons_per_row is None else fmt.neurons_per_row
    if neurons_per_row < 1:
        raise ValueError("neurons_per_row must be >= 1")

    v_thresholds = _resolve_per_neuron_values(
        states.v_threshold, neuron_indices, n_neurons, "v_threshold"
    )
    v_resets = _resolve_per_neuron_values(
        states.v_reset, neuron_indices, n_neurons, "v_reset"
    )

    if fmt.auto_width:
        # ~1 inch per 40 ms, bounded to [10, 30]
        base_width = max(10.0, min(duration_ms * 0.025, 30.0))
    else:
        base_width = fmt.figsize_per_neuron[0]
    height_per_row = fmt.figsize_per_neuron[1]

    colors = fmt.colors or _DEFAULT_TRACE_COLORS
    resolve_label = _make_label_resolver(fmt.neuron_labels)
    kinds = _trace_panel_kinds(fmt, data)

    if fmt.separate_figures:
        return _plot_separate_trace_figures(
            kinds,
            data,
            neuron_indices,
            times,
            colors,
            fmt,
            v_thresholds,
            v_resets,
            resolve_label,
            fmt.neuron_label_position,
            (base_width, height_per_row * n_plot),
            fmt.neuron_specs,
        )

    if not kinds:
        # Nothing requested/available: fall back to the required voltage panel.
        kinds = ["voltage"]

    resolved_labels = [
        resolve_label(plot_idx, neuron_idx)
        for plot_idx, neuron_idx in enumerate(neuron_indices)
    ]
    max_label_len = max((len(label) for label in resolved_labels if label), default=0)
    top_labels = fmt.neuron_label_position == "top"

    grid = _create_trace_grid(
        n_plot,
        len(kinds),
        neurons_per_row,
        top_labels,
        max_label_len,
        base_width,
        height_per_row,
    )
    used_axes = _draw_combined_traces(
        grid,
        kinds,
        data,
        neuron_indices,
        times,
        colors,
        fmt,
        v_thresholds,
        v_resets,
        fmt.neuron_specs,
        resolved_labels,
    )
    _hide_unused_trace_axes(grid, used_axes, n_plot)
    if top_labels and grid.label_axes:
        _widen_for_top_labels(grid)

    right_margin = 0.96 if fmt.neuron_label_position == "side" else 1.0
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        grid.fig.tight_layout(rect=(0.0, 0.0, right_margin, 1.0), w_pad=0.8, h_pad=0.8)
    return grid.fig

plot_raster(spikes, *, dt=None, times=None, ax=None, title=None, xlabel='Time (ms)', ylabel='Neuron Index', style=None, grouping=None, strip=None, rate=None, annotations=None)

Plot spike raster with optional grouping and styling.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix of shape (time, neurons).

required
dt float | None

Time step in ms. Default is 1.0 if times is not provided.

None
times Sequence[float] | None

Explicit time array.

None
ax Axes | None

Axis to plot on. If None, a new figure is created. Ignored (with a warning) when a rate panel is requested.

None
title str | None

Plot title; defaults to a "Fired/Spikes" summary.

None
xlabel str

Label for the x-axis (moved to the rate panel if present).

'Time (ms)'
ylabel str

Label for the y-axis.

'Neuron Index'
style RasterStyle | None

Marker, colour and per-neuron styling (:class:RasterStyle).

None
grouping RasterGrouping | None

Neuron grouping and separators (:class:RasterGrouping).

None
strip GroupStripOptions | None

Group colour strip (:class:GroupStripOptions); None draws no strip.

None
rate RatePanelOptions | None

Firing-rate panel (:class:RatePanelOptions); None draws no panel.

None
annotations RasterAnnotations | None

Events, regions and tracks (:class:RasterAnnotations).

None

Returns:

Type Description
Axes | tuple[Axes, Axes]

ax_raster, or (ax_raster, ax_rate) when a rate panel is drawn.

Raises:

Type Description
ValueError

If spikes is not 2D, or per-group rates are requested without grouping.group_key.

Source code in btorch/visualisation/timeseries/raster.py
def plot_raster(
    spikes: np.ndarray | torch.Tensor,
    *,
    dt: float | None = None,
    times: Sequence[float] | None = None,
    ax: Axes | None = None,
    title: str | None = None,
    xlabel: str = "Time (ms)",
    ylabel: str = "Neuron Index",
    style: RasterStyle | None = None,
    grouping: RasterGrouping | None = None,
    strip: GroupStripOptions | None = None,
    rate: RatePanelOptions | None = None,
    annotations: RasterAnnotations | None = None,
) -> Axes | tuple[Axes, Axes]:
    """Plot spike raster with optional grouping and styling.

    Args:
        spikes: Spike matrix of shape (time, neurons).
        dt: Time step in ms. Default is 1.0 if ``times`` is not provided.
        times: Explicit time array.
        ax: Axis to plot on. If None, a new figure is created. Ignored (with a
            warning) when a rate panel is requested.
        title: Plot title; defaults to a "Fired/Spikes" summary.
        xlabel: Label for the x-axis (moved to the rate panel if present).
        ylabel: Label for the y-axis.
        style: Marker, colour and per-neuron styling (:class:`RasterStyle`).
        grouping: Neuron grouping and separators (:class:`RasterGrouping`).
        strip: Group colour strip (:class:`GroupStripOptions`); None draws no
            strip.
        rate: Firing-rate panel (:class:`RatePanelOptions`); None draws no
            panel.
        annotations: Events, regions and tracks (:class:`RasterAnnotations`).

    Returns:
        ``ax_raster``, or ``(ax_raster, ax_rate)`` when a rate panel is drawn.

    Raises:
        ValueError: If ``spikes`` is not 2D, or per-group rates are requested
            without ``grouping.group_key``.
    """
    style_opts = style or RasterStyle()
    grouping = grouping or RasterGrouping()
    strip = strip or GroupStripOptions(show=False)
    rate = rate or RatePanelOptions()
    annotations = annotations or RasterAnnotations()
    group_key = grouping.group_key
    neurons_df = grouping.neurons_df

    spikes_np = to_numpy(spikes)
    if spikes_np.ndim != 2:
        raise ValueError("spikes must be 2D (time, neurons)")

    n_time, n_neurons = spikes_np.shape
    t = _get_time_axis(n_time, dt, times)

    show_group_rate = _wants_group_rate(rate)
    with_rate_panel = _wants_total_rate(rate) or show_group_rate
    if show_group_rate and group_key is None:
        raise ValueError(
            "RatePanelOptions.per_group requires grouping.group_key (and "
            "neurons_df) so per-group rates can be computed."
        )

    ax_raster, ax_rate = _create_raster_axes(ax, n_neurons, with_rate_panel)
    groups = _resolve_raster_groups(n_neurons, grouping, strip)

    # sorted_indices[0] is plotted at y=0 (bottom).
    idx_map = np.empty(n_neurons)
    idx_map[groups.sorted_indices] = np.arange(len(groups.sorted_indices))

    orig_neuron_indices, spike_times = compute_raster(spikes_np, t)
    plot_neuron_indices = idx_map[orig_neuron_indices]

    spike_style = _resolve_spike_style(
        style_opts, grouping, groups, orig_neuron_indices, n_neurons
    )
    # With a group strip, spikes are drawn later using the strip colours.
    if not strip.show:
        _draw_spikes(ax_raster, spike_times, plot_neuron_indices, spike_style)

    ax_raster.set_xlim(t[0], t[-1])
    ax_raster.set_ylim(-0.5, n_neurons - 0.5)
    ax_raster.set_ylabel(ylabel)
    ax_raster.yaxis.set_major_locator(MaxNLocator(integer=True))

    _draw_raster_annotations(ax_raster, t, n_neurons, annotations)

    spike_count = len(spike_times)
    fired_neurons = len(np.unique(orig_neuron_indices)) if spike_count > 0 else 0
    stats_title = f"Fired {fired_neurons}/{n_neurons}, Spikes {spike_count}"
    ax_raster.set_title(title if title else f"Spike raster {stats_title}")

    if group_key and grouping.show_separators:
        _draw_group_separators(
            ax_raster,
            groups.boundaries,
            n_neurons,
            grouping.separator_style,
            label_groups=not strip.show,
            group_strip_side=strip.side,
        )

    if strip.show:
        strip_colors = _draw_group_strip(
            ax_raster, groups, neurons_df, group_key, strip, n_neurons
        )
        _draw_strip_spikes(
            ax_raster,
            spike_times,
            plot_neuron_indices,
            orig_neuron_indices,
            groups,
            strip_colors,
            spike_style,
            style_opts.marker_size,
        )

    ax_raster.text(
        0.01,
        0.99,
        f"N={spike_count}",
        transform=ax_raster.transAxes,
        ha="left",
        va="top",
        bbox=dict(facecolor="white", alpha=0.7, edgecolor="none"),
        fontsize=8,
    )

    if ax_rate is None:
        ax_raster.set_xlabel(xlabel)
        return ax_raster

    _draw_rate_panel(
        ax_raster,
        ax_rate,
        t,
        spikes_np,
        dt,
        xlabel,
        rate,
        groups,
        style_opts,
        strip,
    )
    return ax_raster, ax_rate

plot_spectrum(data, dt=None, nperseg=None, ax=None, mode='loglog', show_mean=True, title='Frequency Spectrum', color=None, label='Mean', alpha=0.2, mean_linewidth=1.5)

Plot frequency spectrum of timeseries data.

Computes power spectral density using Welch's method and visualizes the frequency content. For 2D input (time, neurons), plots individual traces with optional mean overlay.

Parameters:

Name Type Description Default
data ndarray | Tensor

Input timeseries with shape (time,) or (time, neurons).

required
dt float | None

Sampling interval in ms. Default 1.0.

None
nperseg int | None

Length of FFT segments. Default is min(256, time//4).

None
ax Axes | None

Existing axes to plot on. Creates new figure if None.

None
mode str

Plot scale - "loglog" (default) or "semilogx".

'loglog'
show_mean bool

Whether to overlay the mean spectrum (for 2D data).

True
title str

Plot title.

'Frequency Spectrum'
color str | None

Color for traces. Uses default if None.

None
label str | None

Legend label for mean trace.

'Mean'
alpha float

Opacity for individual traces.

0.2
mean_linewidth float

Line width for mean trace.

1.5

Returns:

Type Description
tuple[ndarray, ndarray, Axes]

Tuple of (frequencies, power_spectrum, axes).

Example

freqs, power, ax = plot_spectrum(spikes, dt=1.0, mode="loglog")

Source code in btorch/visualisation/timeseries/spectrum.py
def plot_spectrum(
    data: np.ndarray | torch.Tensor,
    dt: float | None = None,
    nperseg: int | None = None,
    ax: Axes | None = None,
    mode: str = "loglog",
    show_mean: bool = True,
    title: str = "Frequency Spectrum",
    color: str | None = None,
    label: str | None = "Mean",
    alpha: float = 0.2,
    mean_linewidth: float = 1.5,
) -> tuple[np.ndarray, np.ndarray, Axes]:
    """Plot frequency spectrum of timeseries data.

    Computes power spectral density using Welch's method and visualizes
    the frequency content. For 2D input (time, neurons), plots individual
    traces with optional mean overlay.

    Args:
        data: Input timeseries with shape (time,) or (time, neurons).
        dt: Sampling interval in ms. Default 1.0.
        nperseg: Length of FFT segments. Default is min(256, time//4).
        ax: Existing axes to plot on. Creates new figure if None.
        mode: Plot scale - "loglog" (default) or "semilogx".
        show_mean: Whether to overlay the mean spectrum (for 2D data).
        title: Plot title.
        color: Color for traces. Uses default if None.
        label: Legend label for mean trace.
        alpha: Opacity for individual traces.
        mean_linewidth: Line width for mean trace.

    Returns:
        Tuple of (frequencies, power_spectrum, axes).

    Example:
        >>> freqs, power, ax = plot_spectrum(spikes, dt=1.0, mode="loglog")
    """
    data_np = to_numpy(data)
    if dt is None:
        dt = 1.0

    freqs, power = compute_spectrum(data_np, dt=dt, nperseg=nperseg)

    if ax is None:
        fig, ax = plt.subplots(figsize=(6, 4))

    power_db = 10 * np.log10(power)

    y_data = power if "log" in mode else power_db

    trace_color = color if color else "blue"
    mean_color = color if color else "black"

    if show_mean and data_np.ndim > 1:
        if alpha > 0:
            ax.plot(freqs, y_data, color=trace_color, alpha=alpha, lw=0.5)
        mean_power = y_data.mean(axis=1) if y_data.ndim > 1 else y_data
        ax.plot(freqs, mean_power, color=mean_color, lw=mean_linewidth, label=label)
    else:
        ax.plot(freqs, y_data, color=mean_color, label=label)

    if mode == "loglog":
        ax.set_xscale("log")
        ax.set_yscale("log")
        ax.set_ylabel("Power")
    elif mode == "semilogx":
        ax.set_xscale("log")
        ax.set_ylabel("Power (dB)")

    ax.set_xlabel("Frequency (Hz)")
    ax.set_title(title)

    return freqs, power, ax

plot_traces(data, dt=None, times=None, ax=None, neurons=None, labels=None, colors=None, title=None, xlabel='Time (ms)', ylabel=None, legend=True, alpha=0.8)

Plot continuous timeseries traces.

Parameters

data : array-like Shape (Time, Neurons) or (Time, Neurons, Features). dt : float, optional Time step. times : array-like, optional Explicit time array. ax : Axes, optional Axis to plot on. neurons : list of int or int, optional Indices of neurons to plot. If None, plots all (careful with large N). If int, samples that many neurons randomly. labels : list of str, optional Labels for the legend. colors : list of colors, optional Colors for traces. title : str, optional Plot title.

Returns

Axes

Source code in btorch/visualisation/timeseries/traces.py
def plot_traces(
    data: np.ndarray | torch.Tensor,
    dt: float | None = None,
    times: Sequence[float] | None = None,
    ax: Axes | None = None,
    neurons: Sequence[int] | int | None = None,
    labels: Sequence[str] | str | None = None,
    colors: Sequence[Any] | None = None,
    title: str | None = None,
    xlabel: str = "Time (ms)",
    ylabel: str | None = None,
    legend: bool = True,
    alpha: float = 0.8,
) -> Axes:
    """Plot continuous timeseries traces.

    Parameters
    ----------
    data : array-like
        Shape (Time, Neurons) or (Time, Neurons, Features).
    dt : float, optional
        Time step.
    times : array-like, optional
        Explicit time array.
    ax : Axes, optional
        Axis to plot on.
    neurons : list of int or int, optional
        Indices of neurons to plot. If None, plots all (careful with large N).
        If int, samples that many neurons randomly.
    labels : list of str, optional
        Labels for the legend.
    colors : list of colors, optional
        Colors for traces.
    title : str, optional
        Plot title.

    Returns
    -------
    Axes
    """
    data_np = to_numpy(data)
    t = _get_time_axis(data_np.shape[0], dt, times)

    if data_np.ndim == 2:
        data_np = data_np[:, :, np.newaxis]
    elif data_np.ndim != 3:
        raise ValueError("Data must be 2D (T, N) or 3D (T, N, F)")

    n_neurons = data_np.shape[1]
    if neurons is None:
        neuron_indices = np.arange(n_neurons)
    elif isinstance(neurons, int):
        if neurons >= n_neurons:
            neuron_indices = np.arange(n_neurons)
        else:
            neuron_indices = np.sort(
                np.random.choice(n_neurons, neurons, replace=False)
            )
    else:
        neuron_indices = np.array(neurons)

    n_features = data_np.shape[2]

    if ax is None:
        fig, ax = plt.subplots(figsize=(8, 4))

    if colors is None:
        cmap = plt.get_cmap("turbo", len(neuron_indices))
        colors = [cmap(i) for i in range(len(neuron_indices))]

    for i, idx in enumerate(neuron_indices):
        c = (
            colors[i]
            if isinstance(colors, (list, np.ndarray))
            and len(colors) == len(neuron_indices)
            else None
        )

        for feat in range(n_features):
            trace = data_np[:, idx, feat]

            lbl = None
            if labels is not None:
                if isinstance(labels, str):
                    lbl = f"{labels} {idx}"
                elif len(labels) == len(neuron_indices):
                    lbl = labels[i]
                else:
                    lbl = f"Neuron {idx}"
            else:
                lbl = f"Neuron {idx}"

            if n_features > 1:
                lbl += f" (f{feat})"

            ax.plot(t, trace, label=lbl, color=c, alpha=alpha)

    ax.set_xlabel(xlabel)
    if ylabel:
        ax.set_ylabel(ylabel)
    ax.set_xlim(t[0], t[-1])

    if title:
        ax.set_title(title)

    if legend and len(neuron_indices) <= 20:  # Limit legend clutter
        ax.legend(bbox_to_anchor=(1.05, 1), loc="upper left")

    return ax

btorch.visualisation.tuning

Neuron response curve visualization.

Plotting utilities for f-I (frequency-current) and V-I (voltage-current) curves, commonly used to characterize neuron excitability and response properties.

Functions:

plot_fi_vi_curve(results=None, plot_fi=True, plot_vi=True, get_data_func=None, data_func_kwargs=None, name='fi_vi_curve', file_path=None)

Plot f-I and V-I response curves for neuron characterization.

Generates subplots showing the relationship between input current and firing rate (f-I curve), and input current and membrane voltage traces (V-I curve, displayed as waterfall plot).

Parameters:

Name Type Description Default
results dict | None

Dictionary containing simulation results with keys: - "currents": Input current values, shape (n_steps,) - "frequencies": Firing rates in Hz, shape (n_steps,) - "voltages": Voltage traces, shape (time, n_steps) - "time": Optional time array, shape (time,)

None
plot_fi bool

Whether to plot the f-I curve.

True
plot_vi bool

Whether to plot the V-I waterfall traces.

True
get_data_func Callable | None

Function to generate results if not provided. Called as get_data_func(**data_func_kwargs).

None
data_func_kwargs dict | None

Arguments passed to get_data_func.

None
name str

Base filename for saving (if file_path is provided).

'fi_vi_curve'
file_path str | None

Directory path for saving figure. If None, figure is returned but not saved.

None

Returns:

Type Description
Figure

Figure containing the requested subplots.

Raises:

Type Description
ValueError

If neither results nor get_data_func is provided.

Example

results = { ... "currents": torch.linspace(0, 10, 20), ... "frequencies": firing_rates, ... "voltages": voltage_traces, ... } fig = plot_fi_vi_curve(results, file_path="./output/")

Source code in btorch/visualisation/tuning.py
def plot_fi_vi_curve(
    results: dict | None = None,
    plot_fi: bool = True,
    plot_vi: bool = True,
    get_data_func: Callable | None = None,
    data_func_kwargs: dict | None = None,
    name: str = "fi_vi_curve",
    file_path: str | None = None,
) -> Figure:
    """Plot f-I and V-I response curves for neuron characterization.

    Generates subplots showing the relationship between input current and
    firing rate (f-I curve), and input current and membrane voltage traces
    (V-I curve, displayed as waterfall plot).

    Args:
        results: Dictionary containing simulation results with keys:
            - "currents": Input current values, shape (n_steps,)
            - "frequencies": Firing rates in Hz, shape (n_steps,)
            - "voltages": Voltage traces, shape (time, n_steps)
            - "time": Optional time array, shape (time,)
        plot_fi: Whether to plot the f-I curve.
        plot_vi: Whether to plot the V-I waterfall traces.
        get_data_func: Function to generate results if not provided.
            Called as `get_data_func(**data_func_kwargs)`.
        data_func_kwargs: Arguments passed to `get_data_func`.
        name: Base filename for saving (if file_path is provided).
        file_path: Directory path for saving figure. If None, figure is
            returned but not saved.

    Returns:
        Figure containing the requested subplots.

    Raises:
        ValueError: If neither `results` nor `get_data_func` is provided.

    Example:
        >>> results = {
        ...     "currents": torch.linspace(0, 10, 20),
        ...     "frequencies": firing_rates,
        ...     "voltages": voltage_traces,
        ... }
        >>> fig = plot_fi_vi_curve(results, file_path="./output/")
    """
    if results is None:
        if get_data_func is None:
            raise ValueError("Either 'results' or 'get_data_func' must be provided.")
        results = get_data_func(**(data_func_kwargs or {}))

    currents = results["currents"].detach().cpu().numpy()
    frequencies = results["frequencies"].detach().cpu().numpy()
    voltages = results["voltages"].detach().cpu().numpy()

    num_plots = sum([plot_fi, plot_vi])
    if num_plots == 0:
        raise ValueError("At least one of plot_fi or plot_vi must be True.")

    fig, axes = plt.subplots(1, num_plots, figsize=(6 * num_plots, 5), squeeze=False)
    axes = axes.flatten()
    plot_idx = 0

    if plot_fi:
        ax = axes[plot_idx]
        ax.plot(currents, frequencies, "o-")
        ax.set_xlabel("Input Current")
        ax.set_ylabel("Firing Rate (Hz)")
        ax.set_title("f-I Curve")
        ax.grid(True)
        plot_idx += 1

    if plot_vi:
        ax = axes[plot_idx]

        time = results.get("time")
        if time is not None:
            time = time.detach().cpu().numpy()
        else:
            time = np.arange(voltages.shape[0])

        # Waterfall plot: traces are offset vertically by a fraction of the range.
        v_min = voltages.min()
        v_max = voltages.max()
        v_range = v_max - v_min
        if v_range == 0:
            v_range = 1.0

        offset_step = v_range * 0.2

        num_steps = voltages.shape[1]
        cm = plt.get_cmap("viridis")

        yticks = []
        yticklabels = []

        for i in range(num_steps):
            color = cm(i / num_steps)
            offset = i * offset_step
            ax.plot(
                time, voltages[:, i] + offset, color=color, alpha=0.8, linewidth=1.0
            )

            if i % (max(1, num_steps // 5)) == 0:
                yticks.append(voltages[0, i] + offset)
                yticklabels.append(f"{currents[i]:.1f}")

        ax.set_xlabel("Time (ms)")
        ax.set_ylabel("Membrane Potential (Offset)")
        ax.set_title("Voltage Traces (Waterfall)")

        sm = plt.cm.ScalarMappable(
            cmap=cm, norm=plt.Normalize(vmin=currents.min(), vmax=currents.max())
        )
        cbar = fig.colorbar(sm, ax=ax)
        cbar.set_label("Input Current")

        plot_idx += 1

    plt.tight_layout()
    if file_path is not None:
        fig.savefig(f"{file_path}/{name}.png")
    return fig