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
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
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
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
GroupStripOptions
dataclass
¶
Colour strip beside the raster (also sets the group label side).
Attributes:
| Name | Type | Description |
|---|---|---|
show |
bool
|
Draw the strip. With |
color_key |
str | None
|
Column of |
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
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
|
|
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
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 |
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
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: |
Source code in btorch/visualisation/timeseries/raster_options.py
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 |
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 |
window_ms |
float
|
Smoothing window for computed rates, in ms. |
Source code in btorch/visualisation/timeseries/raster_options.py
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 |
Source code in btorch/visualisation/timeseries/neuron_specs.py
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
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 |
required |
dataset
|
DataFrame
|
Reference hex grid ( |
required |
style
|
dict | None
|
Styling overrides — |
None
|
sizing
|
dict | None
|
Size overrides — |
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 |
None
|
title
|
str | None
|
Optional plot title. |
None
|
colorbar
|
bool
|
Whether to show colour bar (default |
True
|
value_name
|
str
|
Label for values in hover tooltip. |
'value'
|
coord_format
|
CoordFormat
|
How to interpret |
'axial'
|
orientation
|
Literal['pointy', 'flat']
|
|
'flat'
|
layout
|
str | None
|
Set to |
None
|
rotation_deg
|
float
|
Rotation for flywire layout. |
0.0
|
include_flywire_hover
|
bool
|
Include axial and zigzag coordinates in
hover tooltip (default |
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
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | |
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
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 | |
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 |
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:
Source code in btorch/visualisation/dynamics.py
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
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
|
|
dict
|
|
tuple[Figure, Axes, dict]
|
|
Examples:
>>> fig, ax, results = plot_eigenvalue_spectrum(W)
>>> print(f"Spectral radius: {results['spectral_radius']:.2f}")
Source code in btorch/visualisation/dynamics.py
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
|
|
tuple[Figure, dict]
|
|
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
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:
Source code in btorch/visualisation/dynamics.py
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 |
required |
group_by
|
str
|
Column name in |
required |
kind
|
GroupPlotKind
|
Plot type - "violin", "box", or "ecdf". |
'violin'
|
simple_id_col
|
str
|
Column name for neuron identifiers in |
'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 |
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 |
Example
fig, ax = plot_group_distribution( ... firing_rates, neurons_df, group_by="cell_type", kind="violin" ... )
Source code in btorch/visualisation/aggregation.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
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 |
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
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | |
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
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
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
|
|
tuple[Figure, dict]
|
|
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
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
|
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 |
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
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | |
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
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, |
required |
format
|
TracePlotFormat | None
|
Neuron selection, panel visibility, labels, per-neuron styles
and figure layout (:class: |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
On invalid shapes, |
Source code in btorch/visualisation/timeseries/neuron_traces.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
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 |
None
|
neurons
|
DataFrame | None
|
DataFrame with neuron metadata (required if |
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 |
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
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
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 |
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
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
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 |
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: |
None
|
grouping
|
RasterGrouping | None
|
Neuron grouping and separators (:class: |
None
|
strip
|
GroupStripOptions | None
|
Group colour strip (:class: |
None
|
rate
|
RatePanelOptions | None
|
Firing-rate panel (:class: |
None
|
annotations
|
RasterAnnotations | None
|
Events, regions and tracks (:class: |
None
|
Returns:
| Type | Description |
|---|---|
Axes | tuple[Axes, Axes]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/visualisation/timeseries/raster.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
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
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
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
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
_plot_ecdf(ax, ecdf_by_group, *, group_by, value_name, linewidth)
¶
Source code in btorch/visualisation/aggregation.py
_plot_heatmap_style(ax, traces, time_points, *, cmap)
¶
Source code in btorch/visualisation/aggregation.py
_plot_violin(ax, grouped_values, order, *, alpha)
¶
Source code in btorch/visualisation/aggregation.py
_plot_wave_style(ax, traces, time_points, *, top_n)
¶
Source code in btorch/visualisation/aggregation.py
_resolve_figure_ax(*, ax, figsize)
¶
Source code in btorch/visualisation/aggregation.py
_resolve_neuropil_traces(data, *, mode, agg, connections, neurons, use_polars)
¶
Source code in btorch/visualisation/aggregation.py
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 |
Source code in btorch/analysis/aggregation.py
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
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
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 |
required |
group_by
|
str
|
Column name in |
required |
kind
|
GroupPlotKind
|
Plot type - "violin", "box", or "ecdf". |
'violin'
|
simple_id_col
|
str
|
Column name for neuron identifiers in |
'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 |
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 |
Example
fig, ax = plot_group_distribution( ... firing_rates, neurons_df, group_by="cell_type", kind="violin" ... )
Source code in btorch/visualisation/aggregation.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
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 |
None
|
neurons
|
DataFrame | None
|
DataFrame with neuron metadata (required if |
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 |
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
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 | |
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 |
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
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
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
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
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
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
Functions:¶
_isi_cv_stats(spikes, dt)
¶
Per-neuron ISI CV (NaN below three spikes) and its NaN-aware mean.
_plot_fano_distribution(fano_results, windows, dt)
¶
Plot Fano factor distribution across neurons.
Source code in btorch/visualisation/dynamics.py
_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
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | |
_plot_fano_individual(fano_results, windows, dt, neuron_indices, n_neurons)
¶
Plot Fano factor for individual neurons.
Source code in btorch/visualisation/dynamics.py
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
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 |
Source code in btorch/analysis/aggregation.py
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: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
fano |
StatsResult
|
Fano factor values with shape [...]
(input shape without time dimension).
If |
info |
StatsResult
|
Dictionary with optional computed statistics and percentile data. |
Source code in btorch/analysis/spiking.py
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: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
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 |
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
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
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 | |
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 |
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:
Source code in btorch/visualisation/dynamics.py
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
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
|
|
dict
|
|
tuple[Figure, Axes, dict]
|
|
Examples:
>>> fig, ax, results = plot_eigenvalue_spectrum(W)
>>> print(f"Spectral radius: {results['spectral_radius']:.2f}")
Source code in btorch/visualisation/dynamics.py
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
|
|
tuple[Figure, dict]
|
|
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
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:
Source code in btorch/visualisation/dynamics.py
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 |
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
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | |
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
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
|
|
tuple[Figure, dict]
|
|
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
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
|
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 |
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
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | |
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
|
|
required |
strict
|
bool
|
Accept only |
False
|
name
|
str
|
Argument name used in the |
'data'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
NumPy array (a view of the input when no conversion is needed). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in btorch/utils/array.py
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
HexGeometry
dataclass
¶
How hex coordinates are laid out in pixel space.
Attributes:
| Name | Type | Description |
|---|---|---|
layout |
str | None
|
Explicit pixel layout (e.g. |
size |
float
|
Hexagon size used to convert coordinates to pixels. |
orientation |
Literal['pointy', 'flat']
|
|
rotation_deg |
float
|
Global display rotation in degrees (only applied by
the |
Source code in btorch/visualisation/hex/options.py
HexPatchStyle
dataclass
¶
Appearance of the hexagon patches.
Attributes:
| Name | Type | Description |
|---|---|---|
edgecolor |
str | None
|
Hexagon edge colour ( |
edgewidth |
float
|
Hexagon edge width. |
alpha |
float
|
Transparency (0-1). |
Source code in btorch/visualisation/hex/options.py
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: |
'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
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
HexReference
dataclass
¶
Orientation aids drawn on top of the plot.
Attributes:
| Name | Type | Description |
|---|---|---|
axes_alignment |
Literal['vertex', 'edge'] | None
|
If |
show_compass |
Literal['vertex', 'edge'] | None
|
If |
Source code in btorch/visualisation/hex/options.py
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: |
'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
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
ReceptiveFieldViewer
¶
Interactive receptive field viewer for connectome analysis.
Source code in btorch/visualisation/hex/receptive_field.py
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
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
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
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | |
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
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
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 | |
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 |
required |
dataset
|
DataFrame
|
Reference hex grid ( |
required |
style
|
dict | None
|
Styling overrides — |
None
|
sizing
|
dict | None
|
Size overrides — |
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 |
None
|
title
|
str | None
|
Optional plot title. |
None
|
colorbar
|
bool
|
Whether to show colour bar (default |
True
|
value_name
|
str
|
Label for values in hover tooltip. |
'value'
|
coord_format
|
CoordFormat
|
How to interpret |
'axial'
|
orientation
|
Literal['pointy', 'flat']
|
|
'flat'
|
layout
|
str | None
|
Set to |
None
|
rotation_deg
|
float
|
Rotation for flywire layout. |
0.0
|
include_flywire_hover
|
bool
|
Include axial and zigzag coordinates in
hover tooltip (default |
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
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 | |
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
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
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
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 | |
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: |
'axial'
|
scale
|
float
|
Vector scale factor |
1.0
|
geometry
|
HexGeometry | None
|
Pixel layout (size, orientation, rotation); see
:class: |
None
|
color
|
HexColorMap | None
|
Colormap (and limits) for vector magnitude; see
:class: |
None
|
reference
|
HexReference | None
|
Reference axes / compass; see
:class: |
None
|
figsize
|
tuple[float, float]
|
Figure size (used when |
(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
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | |
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: |
'axial'
|
geometry
|
HexGeometry | None
|
Pixel layout (size, orientation, rotation); see
:class: |
None
|
color
|
HexColorMap | None
|
Colormap and colour limits; see
:class: |
None
|
patch
|
HexPatchStyle | None
|
Edge colour/width and alpha; see
:class: |
None
|
reference
|
HexReference | None
|
Reference axes / compass; see
:class: |
None
|
figsize
|
tuple[float, float]
|
Figure size (used when |
(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
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 | |
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
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
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 |
color_key |
str | None
|
Column of |
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
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
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
|
|
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
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 |
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
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: |
Source code in btorch/visualisation/timeseries/raster_options.py
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 |
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 |
window_ms |
float
|
Smoothing window for computed rates, in ms. |
Source code in btorch/visualisation/timeseries/raster_options.py
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 |
Source code in btorch/visualisation/timeseries/neuron_specs.py
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 |
groups |
dict[str, list[int]] | None
|
Manual |
Source code in btorch/visualisation/timeseries/spectrum_options.py
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
|
|
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
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
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: |
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: |
None
|
style
|
SpectrumStyle | None
|
Traces/mean flags, colours and panel size; see
:class: |
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]
|
|
Source code in btorch/visualisation/timeseries/spectrum.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
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
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, |
required |
format
|
TracePlotFormat | None
|
Neuron selection, panel visibility, labels, per-neuron styles
and figure layout (:class: |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
On invalid shapes, |
Source code in btorch/visualisation/timeseries/neuron_traces.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
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 |
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: |
None
|
grouping
|
RasterGrouping | None
|
Neuron grouping and separators (:class: |
None
|
strip
|
GroupStripOptions | None
|
Group colour strip (:class: |
None
|
rate
|
RatePanelOptions | None
|
Firing-rate panel (:class: |
None
|
annotations
|
RasterAnnotations | None
|
Events, regions and tracks (:class: |
None
|
Returns:
| Type | Description |
|---|---|
Axes | tuple[Axes, Axes]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/visualisation/timeseries/raster.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
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
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
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
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 |
None
|
data_func_kwargs
|
dict | None
|
Arguments passed to |
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 |
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
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | |