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,
plot_group_violin,
plot_group_box,
plot_group_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, hexmap):
- Graph layout: plot_network
- Hexagonal heatmaps: hex_heatmap
Tuning plots (tuning):
- Response curves: [plot_fi_vi_curve][btorch.visualisation.tuning.plot_fi_vi_curve]
Attributes¶
__all__ = ['hex_heatmap', 'plot_network', 'plot_group_box', 'plot_group_distribution', 'plot_group_ecdf', 'plot_group_violin', 'plot_neuropil_timeseries_overview', 'plot_neuropil_timeseries_panels', 'plot_log_hist', 'plot_raster', 'plot_spectrum', 'plot_traces', 'plot_neuron_traces', 'SimulationStates', 'TracePlotFormat', '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
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 |
Source code in btorch/visualisation/timeseries.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.py
Functions¶
hex_heatmap(df, dataset, style=None, sizing=None, dpi=72, custom_colorscale=None)
¶
Generate an interactive hexagonal heatmap.
Visualizes data on a hexagonal grid layout. Single-column data produces a static heatmap; multi-column DataFrames produce an animated heatmap with a slider to navigate through timepoints or conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
Series | DataFrame
|
Data to visualize. Single Series for static plot, or DataFrame with multiple columns for animated plot (one frame per column). Must have 'p' and 'q' columns representing hex grid coordinates. |
required |
dataset
|
DataFrame
|
Reference dataset defining the full hex grid background. Used to render empty hexagons for spatial context. |
required |
style
|
dict | None
|
Styling options dict with keys: - "font_type": Font family (default: "arial") - "markerlinecolor": Marker line color - "linecolor": Axis/line color (default: "black") - "papercolor": Background color (default: "rgba(255,255,255,255)") |
None
|
sizing
|
dict | None
|
Size configuration dict with keys: - "fig_width", "fig_height": Figure dimensions in mm - "markersize": Hexagon marker size (default: 16) - "cbar_thickness", "cbar_len": Colorbar dimensions |
None
|
dpi
|
int
|
Dots per inch for pixel calculations (default: 72). |
72
|
custom_colorscale
|
list | None
|
Custom Plotly colorscale. Default is white-to-blue. |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
Plotly Figure with hexagonal heatmap. Static for Series input, |
Figure
|
animated with slider for DataFrame input. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
Static heatmap¶
fig = hex_heatmap(data_series, background_dataset) fig.show()
Animated heatmap with timepoints¶
fig = hex_heatmap(timepoint_df, background_dataset) fig.write_html("animated_hexmap.html")
Source code in btorch/visualisation/hexmap.py
14 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 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 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 | |
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. |
Example
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
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 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 | |
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
|
Additional arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
Figure
|
Figure with DFA summary and interpretation guide. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If spikes are not provided. |
Example
fig = plot_dfa_analysis(spikes, bin_size=10)
Source code in btorch/visualisation/dynamics.py
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 462 463 464 465 466 467 468 469 470 471 472 473 474 | |
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]
|
|
Example
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]
|
|
Example
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. |
Example
data = (slope, intercept, g_vals, lyap_vals) fig, ax = plot_gain_stability(data)
Source code in btorch/visualisation/dynamics.py
plot_group_box(values, neurons_df, group_by, **kwargs)
¶
Convenience wrapper for plot_group_distribution(..., kind='box').
Source code in btorch/visualisation/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_group_ecdf(values, neurons_df, group_by, **kwargs)
¶
Convenience wrapper for plot_group_distribution(..., kind='ecdf').
Source code in btorch/visualisation/aggregation.py
plot_group_violin(values, neurons_df, group_by, **kwargs)
¶
Convenience wrapper for plot_group_distribution(...,
kind='violin').
Source code in btorch/visualisation/aggregation.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
|
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. |
Example
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
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 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 | |
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
|
Union[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
|
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.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. |
Example
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, ax=None)
¶
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
|
ax
|
Axes | None
|
Unused parameter (kept for API compatibility). |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
Tuple of (figure, stats) where stats is a dict with keys: |
dict
|
|
tuple[Figure, dict]
|
|
Example
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
|
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 |
Example
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
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 229 230 231 232 233 | |
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
|
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=None, format=None, voltage=None, dt=1.0, asc=None, psc=None, epsc=None, ipsc=None, input=None, psc_labels=None, spikes=None, v_threshold=None, v_reset=None, neuron_indices=None, sample_size=None, seed=42, show_voltage=True, show_asc=True, show_psc=True, neuron_labels=None, neuron_label_position='side', neuron_specs=None, neurons_df=None, separate_figures=False, auto_width=True, neurons_per_row=None, batch_idx=None)
¶
Plot neuron state traces with flexible interface.
Supports both dataclass and plain argument interfaces. Each neuron gets a row of subplots showing voltage, ASC, and PSC traces.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
states
|
SimulationStates | DataFrame | None
|
SimulationStates dataclass with all state data |
None
|
format
|
TracePlotFormat | None
|
TracePlotFormat dataclass with formatting options |
None
|
voltage
|
ndarray | Tensor | None
|
Voltage traces (time, neurons) or (time, batch, neurons) |
None
|
dt
|
float
|
Timestep in ms |
1.0
|
asc
|
ndarray | Tensor | None
|
Afterspike current traces (time, neurons), (time, batch, neurons), or (time, batch, neurons, n_asc) for multiple ASC components |
None
|
psc
|
ndarray | Tensor | None
|
Postsynaptic current traces (time, neurons), (time, batch, neurons), or (time, batch, neurons, n_psc) for multiple PSC components. If psc has additional dims (n_psc > 1), epsc, ipsc, and input should be None. |
None
|
epsc
|
ndarray | Tensor | None
|
Excitatory PSC traces (time, neurons) or (time, batch, neurons) |
None
|
ipsc
|
ndarray | Tensor | None
|
Inhibitory PSC traces (time, neurons) or (time, batch, neurons) |
None
|
input
|
ndarray | Tensor | None
|
Input current traces (time, neurons) or (time, batch, neurons) |
None
|
psc_labels
|
Sequence[str] | None
|
Labels for PSC components when psc has shape (time, neurons, n_psc) or (time, batch, neurons, n_psc). If None, defaults to ["PSC_0", "PSC_1", ...]. |
None
|
spikes
|
ndarray | Tensor | None
|
Spike trains (time, neurons) or (time, batch, neurons) |
None
|
v_threshold
|
float | Sequence[float] | ndarray | Tensor | None
|
Spike threshold(s), scalar or per-neuron values |
None
|
v_reset
|
float | Sequence[float] | ndarray | Tensor | None
|
Reset voltage reference line(s), scalar or per-neuron values |
None
|
neuron_indices
|
list[int] | None
|
Specific neurons to plot |
None
|
sample_size
|
int | None
|
Number of neurons to randomly sample |
None
|
seed
|
int
|
Random seed for sampling |
42
|
show_voltage
|
bool
|
Show voltage subplot |
True
|
show_asc
|
bool
|
Show ASC subplot |
True
|
show_psc
|
bool
|
Show PSC subplot |
True
|
neuron_labels
|
Sequence[str] | Callable[[int], str] | None
|
Side labels as sequence or callable(neuron_idx) -> str. Default None disables side labels. |
None
|
neuron_label_position
|
Literal['side', 'top']
|
Position for neuron labels when enabled. "side" or "top". |
'side'
|
neuron_specs
|
list[NeuronSpec | dict] | NeuronSpec | dict | None
|
Specifications for per-neuron styling (scalar or list) |
None
|
neurons_df
|
DataFrame | None
|
DataFrame with neuron metadata for labels |
None
|
separate_figures
|
bool
|
Return dict of figures (one per trace type) |
False
|
auto_width
|
bool
|
Adjust width based on duration |
True
|
neurons_per_row
|
int | None
|
Number of neurons per row in combined figure |
None
|
batch_idx
|
int | None
|
Batch index to plot when data has shape (time, batch, neurons). If None and data is 3D, defaults to 0. |
None
|
Returns:
| Type | Description |
|---|---|
Figure | dict[str, Figure]
|
Figure with neuron trace subplots OR dict of Figures |
Source code in btorch/visualisation/timeseries.py
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 | |
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
|
Literal['mean', 'sum', 'std']
|
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
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 266 267 268 269 270 271 | |
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
|
Literal['mean', 'sum', 'std']
|
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
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 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 | |
plot_raster(spikes, dt=None, times=None, ax=None, neurons_df=None, group_key=None, group_sort=None, spike_color='black', marker='.', marker_size=5.0, neuron_specs=None, show_group_separators=True, separator_style=None, title=None, xlabel='Time (ms)', ylabel='Neuron Index', rate=False, group_rate=False, rate_window_ms=10.0, show_group_strip=False, group_color_key=None, strip_cmap='tab10', group_strip_kwargs=None, group_strip_legend=True, group_label_mode='top_sub', group_strip_side='right', sort_neurons=True, events=None, regions=None, show_tracks=False, event_kwargs=None, region_kwargs=None)
¶
Plot spike raster with optional grouping and styling.
Parameters¶
spikes : np.ndarray or torch.Tensor Spike matrix of shape (time, neurons). dt : float, optional Time step in ms. Default is 1.0 if times is not provided. times : array-like, optional Explicit time array. ax : matplotlib.axes.Axes, optional Axis to plot on. If None, a new figure is created. neurons_df : pd.DataFrame, optional Dataframe containing neuron metadata, required for grouping. group_key : str, optional Column name in neurons_df to group neurons by. group_sort : list[str], optional Specific order for the groups. spike_color : str or dict or sequence, optional Default color for spikes. Can be a dict mapping group names or neuron indices to colors, or a per-neuron color sequence. marker : str Marker type. marker_size : float Size of the markers. neuron_specs : dict, list, or NeuronSpec, optional Specific styling per neuron. show_group_separators : bool Whether to draw lines separating groups. separator_style : dict, optional Arguments for separator lines (color, linewidth, etc.). title : str, optional Plot title. xlabel : str Label for x-axis. ylabel : str Label for y-axis. rate : bool or array-like, optional If True, compute and plot the population firing rate. If array-like, use it directly with length matching the time axis. group_rate : bool or dict or array-like, optional If True, compute and plot per-group firing rates when grouping is available. If dict, map group names to per-group rate arrays. If array-like, interpret as (T, G) in the order of resolved groups. rate_window_ms : float Window size for firing rate smoothing in ms. show_group_strip : bool If True, draw a colorbar-like group strip on the side. group_color_key : str, optional Column name in neurons_df to color the group strip. Defaults to group_key. strip_cmap : str Matplotlib colormap name used to derive both top-group and subgroup colors. group_strip_kwargs : dict, optional Additional options for colorbar layout and labels. group_strip_legend : bool If True, add a legend for group colors. group_label_mode : {"top", "sub", "top_sub"} Label mode for the colorbar when using subgroups. group_strip_side : {"left", "right"} Side on which to draw the group strip and labels. sort_neurons : bool If True (default), neurons are reordered by group and subgroup so bands are continuous. If False, original order is preserved.
Returns¶
ax or (ax_raster, ax_rate) The axis object(s).
Source code in btorch/visualisation/timeseries.py
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 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 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 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 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 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 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 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 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 | |
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
|
Union[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.py
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 | |
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.py
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 | |