Analysis — Dynamic Tools¶
btorch.analysis.dynamic_tools.attractor_dynamics
¶
Functions¶
calculate_kaplan_yorke_dimension(lyapunov_spectrum)
¶
Calculate the Kaplan-Yorke Dimension (D_KY), also known as the Lyapunov Dimension.
Formula: D_KY = k + sum(lambda_i for i=1 to k) / |lambda_{k+1}| where k is the max index such that the sum of the first k exponents is non-negative.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lyapunov_spectrum
|
ndarray
|
Array of Lyapunov exponents, sorted in |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
The Kaplan-Yorke dimension. Returns 0 if the system is stable (all lambda < 0). Returns the number of exponents if the sum of all is positive (unbounded/hyperchaos). |
Source code in btorch/analysis/dynamic_tools/attractor_dynamics.py
calculate_structural_eigenvalue_outliers(weight_matrix, spectral_radius=None)
¶
Analyze the eigenvalues of the weight matrix to identify structural outliers.
According to the circular law, eigenvalues of a random matrix are distributed within a disk of radius R. Outliers outside this radius indicate structural enforcement of specific oscillatory modes (stable dynamics) rather than random chaos.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weight_matrix
|
ndarray
|
The connectivity weight matrix (N x N). |
required |
spectral_radius
|
float
|
The theoretical spectral radius of the random component. If None, it is estimated as std(W) * sqrt(N). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary containing: - 'eigenvalues': All eigenvalues. - 'outliers': Eigenvalues outside the spectral radius. - 'outlier_count': Number of outliers. - 'spectral_radius': The radius used for thresholding. |
Source code in btorch/analysis/dynamic_tools/attractor_dynamics.py
btorch.analysis.dynamic_tools.complexity
¶
Functions¶
calculate_gain_stability_sensitivity(model, dataloader, g_values=None, dt=1.0, device='cuda')
¶
Calculate the Gain-Stability Sensitivity (Susceptibility) slope.
Definition: The slope of the curve of the Maximum Lyapunov Exponent (lambda_max) as a function of global synaptic gain scaling (g).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
The Brain model. |
required | |
dataloader
|
DataLoader providing input. |
required | |
g_values
|
List of gain scaling factors. Default np.linspace(0.5, 5.0, 10). |
None
|
|
dt
|
Simulation time step. |
1.0
|
|
device
|
Device to run on. |
'cuda'
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
float
|
(slope, intercept, g_values, lambda_values) - slope: The slope of lambda_max vs g. - intercept: The intercept of the fit. - g_values: The gain values used. - lambda_values: The computed max Lyapunov exponents. |
Source code in btorch/analysis/dynamic_tools/complexity.py
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 | |
calculate_lyapunov_exponent(spike_train, dt=0.1)
¶
Calculate the maximum Lyapunov exponent for a given spike train.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_train
|
Tensor
|
The spike train data. Shape (time_steps, |
required |
dt
|
float
|
Time bin size in milliseconds. Default is 0.1 ms. |
0.1
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The maximum Lyapunov exponent. |
Source code in btorch/analysis/dynamic_tools/complexity.py
calculate_pcist(response, baseline, threshold_factor=3.0)
¶
Calculate the Perturbational Complexity Index based on State Transitions (PCIst).
Definition: A measure of the spatiotemporal complexity of the network's response to a specific perturbation.
Steps: 1. Perturb (assumed done, input is response). 2. Measure (input is response matrix). 3. Decompose: Perform PCA on the response matrix. 4. Recurrence: Calculate state transitions on the principal components. 5. Sum significant state transitions weighted by the component's Signal-to-Noise ratio.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
response
|
Tensor
|
The network response to perturbation. Shape |
required |
baseline
|
Tensor
|
The baseline |
required |
threshold_factor
|
float
|
Factor of baseline std dev to define |
3.0
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The PCIst score. |
Source code in btorch/analysis/dynamic_tools/complexity.py
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 | |
calculate_ra(spike_initial, spike_final)
¶
Calculate Representation Alignment (RA) using spike data.
RA = Trace(G_final * G_initial) / (||G_final|| * ||G_initial||) where G = S * S^T (Gram matrix of spike activity)
If inputs are 3D tensors, they are assumed to be (batch_size, time_steps, num_neurons) and will be averaged over the time dimension (dim=1) to obtain firing rates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_initial
|
Tensor
|
Initial spike activity. Shape (batch_size, |
required |
|
Tensor
|
Final spike activity. Shape (batch_size, num_neurons) or |
required |
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
The Representation Alignment (RA) score. Low RA -> Rich Regime (Radical restructuring) High RA -> Lazy Regime (Little change in internal structure) |
Source code in btorch/analysis/dynamic_tools/complexity.py
compute_max_lyapunov_exponent(time_series, emb_dim=6, lag=1, tau=1)
¶
Compute the largest Lyapunov exponent of a given time series using the nolds library.
Parameters: - time_series: A 1D numpy array representing the time series data.
Returns: - lyapunov_exponent: The estimated largest Lyapunov exponent.
Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
get_continuous_spiking_rate(spikes, dt, sigma=20.0)
¶
Convert discrete spike trains into continuous firing rates using Gaussian smoothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray or Tensor
|
Spike matrix of shape (time_steps, |
required |
dt
|
float
|
Simulation time step in ms. |
required |
sigma
|
float
|
Standard deviation of the Gaussian kernel in ms. Default 20ms. |
20.0
|
Returns:
| Type | Description |
|---|---|
|
np.ndarray: Continuous firing rate traces of shape (time_steps, n_neurons). |
Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
btorch.analysis.dynamic_tools.criticality
¶
Attributes¶
HAS_NOLDS = True
module-attribute
¶
Functions¶
_fit_distribution(data)
¶
Helper to fit power law distribution using powerlaw package.
Source code in btorch/analysis/dynamic_tools/criticality.py
_fit_scaling(x, y)
¶
Helper to fit power law scaling y = a * x^gamma using curve_fit.
Source code in btorch/analysis/dynamic_tools/criticality.py
_power_law_func(x, a, gamma)
¶
calculate_dfa(spike_train, bin_size=1)
¶
Calculate Detrended Fluctuation Analysis (DFA) exponent alpha.
Meaning of alpha: - 0.5: White noise (no memory) - 0.5 < alpha < 1.0: Long-range memory (fractal structure) - 1.0: 1/f noise (Pink noise) - 1.5: Brownian motion (Random walk)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_train
|
ndarray
|
Binary spike matrix of shape (time_steps, n_neurons). |
required |
bin_size
|
int
|
Width of time bin in number of time steps. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
float |
The DFA exponent alpha. |
Source code in btorch/analysis/dynamic_tools/criticality.py
compute_avalanche_statistics(spike_train, bin_size=1)
¶
Calculate avalanche size (S) and duration (T) distributions and their power-law exponents.
Definition: An avalanche is defined as a continuous sequence of time bins (width bin_size) containing at least one spike, flanked by empty bins.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_train
|
ndarray
|
Binary spike matrix of shape (time_steps, n_neurons). |
required |
bin_size
|
int
|
Width of time bin in number of time steps. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dictionary containing:
- 'tau': Power-law exponent for avalanche size distribution P(S) ~
S^-tau
- 'alpha': Power-law exponent for avalanche duration distribution
P(T) ~ T^-alpha
- 'gamma': Power-law exponent for average size vs duration |
Source code in btorch/analysis/dynamic_tools/criticality.py
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 | |
btorch.analysis.dynamic_tools.ei_balance
¶
E/I balance analysis tools for spiking neural networks.
Functions¶
_compute_eci(I_e, I_i, *, I_ext=None, batch_axis=None, dtype=None)
¶
Source code in btorch/analysis/dynamic_tools/ei_balance.py
_compute_lag_correlation(x, y, *, dt=1.0, max_lag_ms=30.0, batch_axis=None, use_fft=True, dtype=None)
¶
Source code in btorch/analysis/dynamic_tools/ei_balance.py
_cross_correlation_direct(x, y, max_lag, dtype=None)
¶
Direct cross-correlation (simpler for short signals).
Source code in btorch/analysis/dynamic_tools/ei_balance.py
_cross_correlation_fft(x, y, max_lag, dtype=None)
¶
FFT-based cross-correlation.
Source code in btorch/analysis/dynamic_tools/ei_balance.py
compute_eci(I_e, I_i, *, I_ext=None, batch_axis=None, dtype=None)
¶
Compute Excitatory-Inhibitory Cancellation Index (ECI).
ECI measures the degree of cancellation between excitatory and inhibitory currents. ECI = 0 indicates perfect cancellation, ECI = 1 indicates no cancellation.
Formula: ECI = |I_rec + I_ext| / (|I_e| + |I_i|) where I_rec = I_e + I_i
This function is decorated with @use_stats and @use_percentiles.
See use_stats() and
use_percentiles() for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
I_e
|
Tensor | ndarray
|
Excitatory current [T,..., N] |
required |
I_i
|
Tensor | ndarray
|
Inhibitory current [T,..., N]. Note: assumed to be negative (inhibitory). |
required |
I_ext
|
Tensor | ndarray | None
|
External current [T,..., N] (optional) |
None
|
batch_axis
|
tuple[int, ...] | int | None
|
Axes to aggregate over (e.g., trials) in addition to the time axis. If None, averages over all non-neuron dimensions. |
None
|
dtype
|
dtype | dtype | None
|
Data type for aggregation. |
None
|
stat
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See |
required | |
stat_info
|
Additional statistics to compute and store in info dict.
See |
required | |
nan_policy
|
How to handle NaN values ("skip", "warn", "assert").
See |
required | |
inf_policy
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See |
required | |
percentiles
|
Percentile level(s) in [0, 100] to compute.
See |
required |
Returns:
| Name | Type | Description |
|---|---|---|
eci |
Tensor | ndarray
|
ECI values per neuron (shape depends on batch_axis).
If |
info |
Tensor | ndarray
|
Dictionary with additional statistics and optional percentile data. |
Source code in btorch/analysis/dynamic_tools/ei_balance.py
compute_ei_balance(I_e, I_i, *, I_ext=None, dt=1.0, max_lag_ms=30.0, batch_axis=None)
¶
Compute E/I balance metrics including ECI and lag correlation.
This function is decorated with @use_stats and @use_percentiles.
See use_stats() and
use_percentiles() for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
I_e
|
Tensor | ndarray
|
Excitatory current [T, ..., N] |
required |
I_i
|
Tensor | ndarray
|
Inhibitory current [T, ..., N] |
required |
I_ext
|
Tensor | ndarray | None
|
External current [T, ..., N] (optional) |
None
|
dt
|
float
|
Time step in ms |
1.0
|
max_lag_ms
|
float
|
Maximum lag for correlation analysis |
30.0
|
batch_axis
|
tuple[int, ...] | int | None
|
Axes to aggregate over (e.g., trials). If None, averages over all non-time dimensions. |
None
|
stat
|
Aggregation statistic per return position.
See |
required | |
stat_info
|
Additional statistics per position.
See |
required | |
nan_policy
|
How to handle NaN values ("skip", "warn", "assert").
See |
required | |
inf_policy
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See |
required | |
percentiles
|
Percentile level(s) in [0, 100] to compute per position.
See |
required |
Returns:
| Name | Type | Description |
|---|---|---|
eci |
ECI values per neuron |
|
peak_corr |
Peak correlation between E and I currents |
|
best_lag_ms |
Best lag in ms (positive = I lags E) |
|
info |
Dictionary with detailed analysis results |
Source code in btorch/analysis/dynamic_tools/ei_balance.py
compute_lag_correlation(x, y, *, dt=1.0, max_lag_ms=30.0, batch_axis=None, use_fft=True)
¶
Compute lagged cross-correlation between two signals.
Uses FFT-based correlation for efficiency. Returns correlation values and best lag per neuron.
This function is decorated with @use_stats and @use_percentiles.
See use_stats() and
use_percentiles() for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor | ndarray
|
First signal [T, ...] or [T, B, ...] |
required |
y
|
Tensor | ndarray
|
Second signal [T, ...] or [T, B, ...] |
required |
dt
|
float
|
Time step in ms |
1.0
|
max_lag_ms
|
float
|
Maximum lag for correlation in ms |
30.0
|
batch_axis
|
tuple[int, ...] | int | None
|
Axes to aggregate over (e.g., trials). If None, averages over all non-time dimensions. |
None
|
use_fft
|
bool
|
If True, use FFT-based correlation (faster for long signals) |
True
|
stat
|
Aggregation statistic per return position. Can be a single stat
or dict mapping position to stat (e.g., {0: "mean", 1: "median"}).
See |
required | |
stat_info
|
Additional statistics to compute and store in info dict.
Can be a single stat, iterable, or dict mapping position to stat(s).
See |
required | |
nan_policy
|
How to handle NaN values ("skip", "warn", "assert").
See |
required | |
inf_policy
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See |
required | |
percentiles
|
Percentile level(s) in [0, 100] to compute per position.
Can be a single value or dict mapping position to percentile(s).
See |
required |
Returns:
| Name | Type | Description |
|---|---|---|
peak_corr |
Correlation values at best lag per neuron.
If |
|
best_lag_ms |
Best lag in ms per neuron.
If |
|
info |
Dictionary with correlation over lags, best lags, etc. |
Example
Get per-neuron values¶
peak, lag, info = compute_lag_correlation(x, y)
Aggregate: max peak correlation, mean best lag¶
peak_max, lag_mean, info = compute_lag_correlation( x, y, stat={0: "max", 1: "mean"} )
Source code in btorch/analysis/dynamic_tools/ei_balance.py
use_percentiles(func=None, *, value_key='values', default_percentiles=None)
¶
Decorator to add percentiles arg and optionally compute percentiles.
This decorator adds a percentiles parameter to a function that returns
per-neuron values. Percentiles are only computed if percentiles is not None.
Results are stored in info[f"{value_key}_percentile"].
Can also accept a dict mapping return positions to labels for functions returning multiple values (e.g., {1: "eci", 3: "lag"}).
The decorated function should return either: - A tuple of (values, info_dict) where values are per-neuron metrics - Just the per-neuron values (will be wrapped in a tuple with empty dict) - A tuple of multiple values with info as the last element
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable | None
|
The function to decorate (or None if using with parentheses) |
None
|
value_key
|
str | dict[int, str]
|
Key to use in info dict for the percentile result |
'values'
|
Returns:
| Type | Description |
|---|---|
Callable
|
Decorated function with added percentiles parameter |
Example
@use_percentiles
def compute_metric(data, *, percentiles=None):
values = some_computation(data) # per-neuron values
return values, {"raw": values}
# Usage:
values, info = compute_metric(data) # no percentiles computed
values, info = compute_metric(data, percentiles=0.5) # compute median
values, info = compute_metric(
data, percentiles=(0.25, 0.5, 0.75)
) # compute quartiles
Source code in btorch/analysis/statistics.py
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 | |
use_stats(func=None, *, value_key='values', dim=None, default_stat=None, default_stat_info=None, default_nan_policy='skip', default_inf_policy='propagate')
¶
Decorator to add stat and stat_info args for aggregation.
This decorator adds stat, stat_info, nan_policy, and inf_policy
parameters to a function that returns per-neuron values.
stat: If not None, returns the aggregated value instead of per-neuron values. The aggregation is stored in info[f"{value_key}_stat"]. Can be a StatChoice, or a dict mapping return position to label (e.g., {1: "eci", 3: "lag"}) for functions returning multiple values.stat_info: Additional stats to compute and store in info dict without affecting the return value. Can be a single StatChoice, Iterable of StatChoice, a dict mapping position to label(s), or None. If dict, format is {position: stat_or_stats} where stat_or_stats can be a single StatChoice or Iterable of StatChoice.dim: Dimension(s) to aggregate over. Can be:- None: Flatten all dimensions (default)
- int: Aggregate over this dimension for all outputs
- tuple[int, ...]: Aggregate over these dimensions for all outputs
- dict[int, int | tuple[int, ...] | None]: Different dim for each output position (e.g., {0: 1, 1: 2, 2: None, 3: (1, 3, 4)})
nan_policy: How to handle NaN values:- "skip": Ignore NaN values (default)
- "warn": Warn if NaN values found but continue
- "assert": Raise error if NaN values found
inf_policy: How to handle Inf values:- "propagate": Keep Inf values (default)
- "skip": Ignore Inf values
- "warn": Warn if Inf values found but continue
- "assert": Raise error if Inf values found
The decorated function should return either: - A tuple of (values, info_dict) where values are per-neuron metrics - Just the per-neuron values (will be wrapped in a tuple with empty dict) - A tuple of multiple values with info as the last element
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable | None
|
The function to decorate (or None if using with parentheses) |
None
|
value_key
|
str | dict[int, str]
|
Key prefix to use in info dict for stat results |
'values'
|
dim
|
int | tuple[int, ...] | dict[int, int | tuple[int, ...] | None] | None
|
Dimension(s) to aggregate over for each output |
None
|
default_nan_policy
|
Literal['skip', 'warn', 'assert']
|
Default nan_policy for this decorated function |
'skip'
|
default_inf_policy
|
Literal['propagate', 'skip', 'warn', 'assert']
|
Default inf_policy for this decorated function |
'propagate'
|
default_stat
|
StatChoice | dict[int, StatChoice] | None
|
Default stat for this decorated function |
None
|
Returns:
| Type | Description |
|---|---|
Callable
|
Decorated function with added stat, stat_info, nan_policy, and |
Callable
|
inf_policy parameters |
Example
@use_stat
def compute_metric(
data,
*,
stat=None,
stat_info=None,
nan_policy="skip",
inf_policy="propagate",
):
values = some_computation(data) # per-neuron values
return values, {"raw": values}
# Usage:
values, info = compute_metric(data) # returns per-neuron values
mean_val, info = compute_metric(data, stat="mean") # returns aggregated
values, info = compute_metric(
data, stat_info=["mean", "max"]
) # extra stats in info
# Multi-value return with dict stat:
@use_stat
def compute_multiple(data, *, stat=None, stat_info=None):
eci = compute_eci(data) # per-neuron
lag = compute_lag(data) # per-neuron
return eci, lag, {} # multiple values
# Aggregate specific positions with dict stat:
eci_mean, lag_mean, info = compute_multiple(
data, stat={0: "eci", 1: "lag"}
)
Source code in btorch/analysis/statistics.py
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 | |
btorch.analysis.dynamic_tools.lyapunov_dynamics
¶
Functions¶
compute_expansion_to_contraction_ratio(lyapunov_spectrum)
¶
Compute the ratio of expansion to contraction from the Lyapunov spectrum.
Parameters: - lyapunov_spectrum: A list or numpy array of Lyapunov exponents.
Returns: - ratio: The ratio of the sum of positive exponents to the absolute sum of negative exponents.
Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
compute_ks_entropy(time_series, emb_dim=6, lag=1)
¶
Compute the Kolmogorov-Sinai (KS) entropy of a given time series using the nolds library.
Parameters: - time_series: A 1D numpy array representing the time series data.
Returns: - ks_entropy: The estimated KS entropy.
Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
compute_lyapunov_exponent_spectrum(time_series, emb_dim=6, matrix_dim=4, tau=1)
¶
Compute the full Lyapunov spectrum of a given time series using the nolds library.
Parameters: - time_series: A 1D numpy array representing the time series data.
Returns: - lyapunov_spectrum: A list of estimated Lyapunov exponents.
Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
compute_max_lyapunov_exponent(time_series, emb_dim=6, lag=1, tau=1)
¶
Compute the largest Lyapunov exponent of a given time series using the nolds library.
Parameters: - time_series: A 1D numpy array representing the time series data.
Returns: - lyapunov_exponent: The estimated largest Lyapunov exponent.
Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
get_continuous_spiking_rate(spikes, dt, sigma=20.0)
¶
Convert discrete spike trains into continuous firing rates using Gaussian smoothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray or Tensor
|
Spike matrix of shape (time_steps, |
required |
dt
|
float
|
Simulation time step in ms. |
required |
sigma
|
float
|
Standard deviation of the Gaussian kernel in ms. Default 20ms. |
20.0
|
Returns:
| Type | Description |
|---|---|
|
np.ndarray: Continuous firing rate traces of shape (time_steps, n_neurons). |
Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
btorch.analysis.dynamic_tools.micro_scale
¶
Functions¶
calculate_cv_isi(spikes, dt=1.0)
¶
计算群体中每个神经元的CV_ISI,并统计其分布特征。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
(Time, Neurons) 脉冲矩阵 |
required | |
dt
|
仿真步长(ms) |
1.0
|
Returns: dict: {'cv_isi': array, 'mean': float}
Source code in btorch/analysis/dynamic_tools/micro_scale.py
calculate_fr_distribution(spikes, dt=1.0)
¶
计算群体中每个时刻的平均发放率,并统计其分布特征。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
(Time, Neurons) 脉冲矩阵 |
required | |
dt
|
仿真步长(ms) |
1.0
|
Returns: dict: {'rates': array, 'mean': float, 'skew': float, 'kurt': float}
Source code in btorch/analysis/dynamic_tools/micro_scale.py
calculate_spike_distance(spikes, dt=1.0, subset_size=100, seed=None)
¶
计算 SPIKE-distance (Kreuz et al., 2013)。
衡量脉冲序列之间的不同步程度。0表示完全同步。
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
(Time, Neurons) 脉冲矩阵 |
required | |
dt
|
仿真步长(ms) |
1.0
|
|
subset_size
|
随机抽样的神经元数量,用于计算成对距离 |
100
|
Returns: float: 平均 SPIKE-distance
Source code in btorch/analysis/dynamic_tools/micro_scale.py
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 | |
btorch.analysis.dynamic_tools.spiking
¶
Advanced Fano factor methods for spike train analysis.
This module provides methods to compensate for firing rate effects on the Fano factor, implementing:
-
Operational Time Method: Transforms spike trains to a rate-independent reference frame by evaluating Fano factor at normalized rate (λ=1). Reference: Rajdl et al. (2020), Front. Comput. Neurosci.
-
Mean Matching Method: Selects data points where mean spike counts are matched across conditions before computing FF. Reference: Churchland et al. (2010), Nature Neurosci.
-
Model-Based Approaches:
- Modulated Poisson with multiplicative noise (Goris et al., 2014)
- Flexible overdispersion model (Charles et al., 2018)
All methods support both NumPy and PyTorch inputs following the btorch conventions, with GPU acceleration where applicable.
Functions¶
_compute_mean_matching_weights_numpy(means, n_bins=10)
¶
Compute mean-matching weights for each condition/time point.
The mean matching method ensures that the distribution of mean counts
is matched across conditions/times by computing weights that equalize
the histograms.
Args:
means: Array of mean spike counts [n_conditions, n_neurons]
n_bins: Number of bins for mean count histogram
Returns:
Dictionary with weights and matching info
Source code in btorch/analysis/dynamic_tools/spiking.py
_compute_mean_matching_weights_torch(means, n_bins=10)
¶
Torch implementation of mean matching weights.
Source code in btorch/analysis/dynamic_tools/spiking.py
_compute_operational_fano_numpy(spike_data, rate_hz, window_op, dt_ms, batch_axis)
¶
Compute Fano factor in operational time for NumPy arrays.
The operational time approach rescales time by the firing rate: w = λ * t, where λ is the firing rate in Hz.
For a renewal process: F⁽ᵒ⁾ = CV² (independent of rate).
Implementation: We normalize spike counts by rate, effectively computing statistics as if rate = 1 everywhere.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_data
|
ndarray
|
Spike train [T, ...] |
required |
rate_hz
|
ndarray
|
Estimated rate in Hz [T, ...] or scalar |
required |
window_op
|
float
|
Window size in operational time units |
required |
dt_ms
|
float
|
Time step in milliseconds |
required |
batch_axis
|
tuple[int, ...] | None
|
Axes to aggregate across |
required |
Returns:
| Name | Type | Description |
|---|---|---|
fano_op |
ndarray
|
Operational time Fano factor |
info |
dict
|
Computation info |
Source code in btorch/analysis/dynamic_tools/spiking.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 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 | |
_compute_operational_fano_torch(spike_data, rate_hz, window_op, dt_ms, batch_axis)
¶
Compute Fano factor in operational time for Torch tensors.
Source code in btorch/analysis/dynamic_tools/spiking.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 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
_compute_weighted_fano_numpy(spike_counts, weights)
¶
Compute weighted Fano factor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_counts
|
ndarray
|
Spike counts [n_trials, n_neurons] or [n_conditions, n_neurons] |
required |
weights
|
ndarray
|
Weights for each observation |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Weighted Fano factor per neuron |
Source code in btorch/analysis/dynamic_tools/spiking.py
_compute_weighted_fano_torch(spike_counts, weights)
¶
Torch implementation of weighted Fano factor.
Source code in btorch/analysis/dynamic_tools/spiking.py
_estimate_rate_numpy(spike_data, dt_ms, window_ms=None)
¶
Estimate instantaneous firing rate using sliding window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_data
|
ndarray
|
Spike train of shape [T, ...]. First dimension is time. |
required |
dt_ms
|
float
|
Time step in milliseconds. |
required |
window_ms
|
float | None
|
Window size for rate estimation. If None, uses T//20 * dt_ms. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Estimated rate in Hz [T, ...]. |
Source code in btorch/analysis/dynamic_tools/spiking.py
_estimate_rate_torch(spike_data, dt_ms, window_ms=None)
¶
Torch implementation of rate estimation.
Source code in btorch/analysis/dynamic_tools/spiking.py
_flexible_overdispersion_moments(stimulus_drive, noise_std=0.5, nonlinearity='relu')
¶
Compute mean and variance for flexible overdispersion model.
The flexible overdispersion model (Charles et al., 2018): λ_eff = f(g(x) + ε) where f is a nonlinearity.
Different nonlinearities produce different mean-FF relationships: - Rectified-linear: FF decreases with increasing rate - Rectified-squaring: FF ≈ constant - Exponential: FF increases with rate
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stimulus_drive
|
ndarray | Tensor
|
Stimulus-dependent drive g(x) |
required |
noise_std
|
float
|
Standard deviation of additive Gaussian noise ε |
0.5
|
nonlinearity
|
Literal['relu', 'square', 'exp', 'softplus']
|
Type of nonlinearity to apply |
'relu'
|
Returns:
| Name | Type | Description |
|---|---|---|
mean |
ndarray | Tensor
|
Expected spike count |
variance |
ndarray | Tensor
|
Spike count variance |
Source code in btorch/analysis/dynamic_tools/spiking.py
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 | |
_modulated_poisson_moments(lambda_base, gain_mean=1.0, gain_var=0.5)
¶
Compute mean and variance for modulated Poisson model.
The modulated Poisson model (Goris et al., 2014): r ~ Poisson(λ · g) where g is multiplicative gain noise.
Mean: E[r] = λ · E[g] Variance: Var[r] = E[g] · λ + Var[g] · λ²
This produces quadratic mean-variance relationship: Var[r] = E[r] + (Var[g]/E[g]²) · E[r]²
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lambda_base
|
ndarray | Tensor
|
Base firing rate |
required |
gain_mean
|
float
|
Mean of gain distribution (E[g]) |
1.0
|
gain_var
|
float
|
Variance of gain distribution (Var[g]) |
0.5
|
Returns:
| Name | Type | Description |
|---|---|---|
mean |
ndarray | Tensor
|
Expected spike count |
variance |
ndarray | Tensor
|
Spike count variance |
Source code in btorch/analysis/dynamic_tools/spiking.py
compare_fano_methods(spike_data, dt_ms=1.0, **kwargs)
¶
Compare different Fano factor compensation methods.
Computes Fano factor using multiple methods for comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_data
|
ndarray | Tensor
|
Spike train of shape [T, ...]. |
required |
dt_ms
|
float
|
Time step in milliseconds. |
1.0
|
**kwargs
|
Additional arguments passed to methods. |
{}
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with results from each method. |
Source code in btorch/analysis/dynamic_tools/spiking.py
fano_compensated(spike_data, method='operational_time', **kwargs)
¶
Unified interface for compensated Fano factor computation.
This function provides a unified interface to all rate-compensation methods for the Fano factor. The choice of method depends on the experimental design and data characteristics:
- operational_time: Best for comparing variability across different firing rates. Transforms to rate-independent reference frame.
- mean_matching: Best for condition comparisons with overlapping rate distributions. Matches rate histograms before computing FF.
- modulated_poisson: Model-based approach assuming multiplicative gain noise. Good for explaining overdispersion.
- flexible_overdispersion: Model-based approach with flexible nonlinearities. Good for testing different rate-FF relationships.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_data
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
method
|
Literal['operational_time', 'mean_matching', 'modulated_poisson', 'flexible_overdispersion']
|
Compensation method to use. |
'operational_time'
|
**kwargs
|
Method-specific arguments passed to underlying functions. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
fano |
ndarray | Tensor
|
Compensated Fano factor values. |
info |
dict
|
Dictionary with method info and computed statistics. |
Example
Operational time method (recommended for rate comparisons)¶
ff_op, _ = fano_compensated(spikes, method="operational_time")
Mean matching (for condition comparisons)¶
ff_mm, _ = fano_compensated(spikes, method="mean_matching", n_bins=10)
Model-based approach¶
ff_mod, _ = fano_compensated( ... spikes, method="modulated_poisson", ... model_params={"gain_var": 0.5} ... )
Source code in btorch/analysis/dynamic_tools/spiking.py
fano_mean_matching(spike_data, window=None, overlap=0, condition_axis=1, n_bins=10, n_resamples=50, batch_axis=None)
¶
Compute mean-matched Fano factor controlling for rate effects.
The mean matching method (Churchland et al., 2010) ensures that the
distribution of mean spike counts is matched across conditions or time points before computing the Fano factor. This removes artifacts caused by rate changes.
Reference: Churchland et al. (2010) "Stimulus onset quenches neural
variability: a widespread cortical phenomenon", Nature Neurosci.
Args:
spike_data: Spike train of shape [T, n_conditions, ...] or
[T, n_trials, ...]. First dimension is time.
window: Window size for spike counting. If None, uses T//10.
overlap: Overlap between consecutive windows.
condition_axis: Axis representing conditions/trials (default 1).
n_bins: Number of bins for mean count histogram matching.
n_resamples: Number of resampling iterations for stability.
batch_axis: Additional axes to aggregate across.
Returns:
fano_mm: Mean-matched Fano factor values.
info: Dictionary with matching info and computed statistics.
Example:
>>> # spike_data shape: [T, n_conditions, n_neurons]
>>> ff_mm, info = fano_mean_matching(
... spike_data, condition_axis=1, n_bins=10
... )
Source code in btorch/analysis/dynamic_tools/spiking.py
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 | |
fano_model_based(spike_data, window=None, overlap=0, model='modulated_poisson', model_params=None, stimulus_drive=None, batch_axis=None)
¶
Compute model-based Fano factor with rate compensation.
Model-based approaches fit a generative model to the spike data and extract the underlying variability independent of rate effects.
Models: 1. Modulated Poisson (Goris et al., 2014): r ~ Poisson(λ · g) where g is multiplicative gain noise. Produces quadratic mean-variance relationship.
- Flexible Overdispersion (Charles et al., 2018): λ_eff = f(g(x) + ε) with different nonlinearities.
- Rectified-linear: FF decreases with rate
- Rectified-squaring: FF ≈ constant
- Exponential: FF increases with rate
References: - Goris et al. (2014) "Partitioning neuronal variability" - Charles et al. (2018) "Dethroning the Fano factor"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_data
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size for spike counting. If None, uses T//10. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
model
|
Literal['modulated_poisson', 'flexible_overdispersion']
|
Model type to use. |
'modulated_poisson'
|
model_params
|
dict | None
|
Model-specific parameters. |
None
|
stimulus_drive
|
ndarray | Tensor | None
|
Stimulus-dependent drive (required for flexible_overdispersion). |
None
|
batch_axis
|
tuple[int, ...] | None
|
Axes to average across for FF computation. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
fano_model |
ndarray | Tensor
|
Model-based Fano factor values. |
info |
dict
|
Dictionary with model fit info and computed statistics. |
Example
ff_mod, info = fano_model_based( ... spike_data, ... model="modulated_poisson", ... model_params={"gain_mean": 1.0, "gain_var": 0.5} ... )
Source code in btorch/analysis/dynamic_tools/spiking.py
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 1029 1030 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 | |
fano_operational_time(spike_data, window=None, overlap=None, rate_hz=None, dt_ms=1.0, batch_axis=None)
¶
Compute Fano factor in operational time (rate-independent).
The operational time Fano factor transforms the spike train such that
the firing rate equals 1 (normalized), making FF independent of the absolute firing rate. This is the recommended method for comparing variability across conditions with different rates.
For renewal processes, the operational time Fano factor equals the
squared coefficient of variation (CV²) of the ISI distribution.
Reference: Rajdl et al. (2020) "Fano Factor: A Potentially Useful
Information", Front. Comput. Neurosci.
Args:
spike_data: Spike train of shape [T, ...]. First dimension is time.
Values are binary (0/1) or spike counts.
window: Window size in operational time units (default: 1.0).
This is the expected count at rate=1 (i.e., 1 spike expected).
overlap: Not used (kept for API compatibility).
rate_hz: Firing rate in Hz. Can be:
- Scalar: homogeneous rate
- Array [T, ...]: time-varying rate
- None: estimated from data using sliding window
dt_ms: Time step in milliseconds for original time axis.
batch_axis: Axes to average across for FF computation.
Returns:
fano_op: Operational time Fano factor values.
info: Dictionary with operational time info and computed statistics.
Example:
>>> # Compare Fano factors at different rates
>>> spikes_low_rate = generate_poisson_spikes(rate_hz=20, ...)
>>> spikes_high_rate = generate_poisson_spikes(rate_hz=80, ...)
>>> ff_low, _ = fano_operational_time(spikes_low_rate)
>>> ff_high, _ = fano_operational_time(spikes_high_rate)
>>> # Both should be ≈ 1 regardless of rate difference
Source code in btorch/analysis/dynamic_tools/spiking.py
use_percentiles(func=None, *, value_key='values', default_percentiles=None)
¶
Decorator to add percentiles arg and optionally compute percentiles.
This decorator adds a percentiles parameter to a function that returns
per-neuron values. Percentiles are only computed if percentiles is not None.
Results are stored in info[f"{value_key}_percentile"].
Can also accept a dict mapping return positions to labels for functions returning multiple values (e.g., {1: "eci", 3: "lag"}).
The decorated function should return either: - A tuple of (values, info_dict) where values are per-neuron metrics - Just the per-neuron values (will be wrapped in a tuple with empty dict) - A tuple of multiple values with info as the last element
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable | None
|
The function to decorate (or None if using with parentheses) |
None
|
value_key
|
str | dict[int, str]
|
Key to use in info dict for the percentile result |
'values'
|
Returns:
| Type | Description |
|---|---|
Callable
|
Decorated function with added percentiles parameter |
Example
@use_percentiles
def compute_metric(data, *, percentiles=None):
values = some_computation(data) # per-neuron values
return values, {"raw": values}
# Usage:
values, info = compute_metric(data) # no percentiles computed
values, info = compute_metric(data, percentiles=0.5) # compute median
values, info = compute_metric(
data, percentiles=(0.25, 0.5, 0.75)
) # compute quartiles
Source code in btorch/analysis/statistics.py
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 | |
use_stats(func=None, *, value_key='values', dim=None, default_stat=None, default_stat_info=None, default_nan_policy='skip', default_inf_policy='propagate')
¶
Decorator to add stat and stat_info args for aggregation.
This decorator adds stat, stat_info, nan_policy, and inf_policy
parameters to a function that returns per-neuron values.
stat: If not None, returns the aggregated value instead of per-neuron values. The aggregation is stored in info[f"{value_key}_stat"]. Can be a StatChoice, or a dict mapping return position to label (e.g., {1: "eci", 3: "lag"}) for functions returning multiple values.stat_info: Additional stats to compute and store in info dict without affecting the return value. Can be a single StatChoice, Iterable of StatChoice, a dict mapping position to label(s), or None. If dict, format is {position: stat_or_stats} where stat_or_stats can be a single StatChoice or Iterable of StatChoice.dim: Dimension(s) to aggregate over. Can be:- None: Flatten all dimensions (default)
- int: Aggregate over this dimension for all outputs
- tuple[int, ...]: Aggregate over these dimensions for all outputs
- dict[int, int | tuple[int, ...] | None]: Different dim for each output position (e.g., {0: 1, 1: 2, 2: None, 3: (1, 3, 4)})
nan_policy: How to handle NaN values:- "skip": Ignore NaN values (default)
- "warn": Warn if NaN values found but continue
- "assert": Raise error if NaN values found
inf_policy: How to handle Inf values:- "propagate": Keep Inf values (default)
- "skip": Ignore Inf values
- "warn": Warn if Inf values found but continue
- "assert": Raise error if Inf values found
The decorated function should return either: - A tuple of (values, info_dict) where values are per-neuron metrics - Just the per-neuron values (will be wrapped in a tuple with empty dict) - A tuple of multiple values with info as the last element
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable | None
|
The function to decorate (or None if using with parentheses) |
None
|
value_key
|
str | dict[int, str]
|
Key prefix to use in info dict for stat results |
'values'
|
dim
|
int | tuple[int, ...] | dict[int, int | tuple[int, ...] | None] | None
|
Dimension(s) to aggregate over for each output |
None
|
default_nan_policy
|
Literal['skip', 'warn', 'assert']
|
Default nan_policy for this decorated function |
'skip'
|
default_inf_policy
|
Literal['propagate', 'skip', 'warn', 'assert']
|
Default inf_policy for this decorated function |
'propagate'
|
default_stat
|
StatChoice | dict[int, StatChoice] | None
|
Default stat for this decorated function |
None
|
Returns:
| Type | Description |
|---|---|
Callable
|
Decorated function with added stat, stat_info, nan_policy, and |
Callable
|
inf_policy parameters |
Example
@use_stat
def compute_metric(
data,
*,
stat=None,
stat_info=None,
nan_policy="skip",
inf_policy="propagate",
):
values = some_computation(data) # per-neuron values
return values, {"raw": values}
# Usage:
values, info = compute_metric(data) # returns per-neuron values
mean_val, info = compute_metric(data, stat="mean") # returns aggregated
values, info = compute_metric(
data, stat_info=["mean", "max"]
) # extra stats in info
# Multi-value return with dict stat:
@use_stat
def compute_multiple(data, *, stat=None, stat_info=None):
eci = compute_eci(data) # per-neuron
lag = compute_lag(data) # per-neuron
return eci, lag, {} # multiple values
# Aggregate specific positions with dict stat:
eci_mean, lag_mean, info = compute_multiple(
data, stat={0: "eci", 1: "lag"}
)
Source code in btorch/analysis/statistics.py
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 | |