Analysis¶
btorch.analysis
¶
Attributes¶
StatChoice = Literal['mean', 'median', 'max', 'min', 'std', 'var', 'argmax', 'argmin', 'cv']
module-attribute
¶
__all__ = ['agg_by_neuropil', 'agg_by_neuron', 'agg_conn', 'build_group_frame', 'group_values', 'group_summary', 'group_ecdf', 'compute_branching_ratio', 'HopDistanceModel', 'compute_ie_ratio', 'indices_to_mask', 'select_on_metric', 'isi_cv', 'fano', 'kurtosis', 'local_variation', 'isi_cv_population', 'fano_population', 'kurtosis_population', 'cv_temporal', 'fano_temporal', 'fano_sweep', 'firing_rate', 'compute_raster', 'compute_log_hist', 'compute_spectrum', 'describe_array', 'suggest_skip_timestep', 'compute_voltage_overshoot', 'StatChoice', 'use_stats', 'use_percentiles']
module-attribute
¶
Classes¶
HopDistanceModel
¶
Fast computation of hop distances in networks using BFS.
Source code in btorch/analysis/connectivity.py
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 | |
Methods:¶
compute_distances(seeds, max_hops=None)
¶
Compute hop distances from seeds to all reachable nodes using BFS.
Source code in btorch/analysis/connectivity.py
hop_statistics(seeds, max_hops=None)
¶
Compute statistics about network reachability by hop distance.
Source code in btorch/analysis/connectivity.py
reconstruct_path(source_node, target_node, distances_df=None)
¶
Reconstruct shortest path from source to target using predecessor info.
Source code in btorch/analysis/connectivity.py
Functions:¶
agg_by_neuron(y, neurons, agg='mean', neuron_type_column='cell_type', **kwargs)
¶
Aggregate data by neuron type.
Source code in btorch/analysis/aggregation.py
agg_by_neuropil(y, neurons=None, connections=None, mode='all_innervated', agg='mean', use_polars=False)
¶
Aggregate activations by neuropil under a validated aggregation mode.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/aggregation.py
agg_conn(y, conn, conn_weight=None, neurons=None, mode='neuron', neuron_type_column='cell_type', agg='mean')
¶
Aggregate connectivity weights by neuropil or neuron-type pairs.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/aggregation.py
build_group_frame(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', dropna=True)
¶
Convert neuron-aligned values to a tidy frame for grouped analyses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
TensorLike
|
Array/tensor shaped |
required |
neurons_df
|
DataFrame
|
DataFrame containing at least |
required |
group_by
|
str
|
Column in |
required |
simple_id_col
|
str
|
Column mapping rows in |
'simple_id'
|
value_name
|
str
|
Name for the output value column. |
'value'
|
dropna
|
bool
|
Drop missing values in group/value columns when |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/aggregation.py
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 | |
compute_branching_ratio(all_counts, k_max=40, *, scatterpoints=False, eps=1e-12, ar1_fallback=True)
¶
Estimate branching ratio via subsampling-invariant MR fitting.
Citation: Wilting, J., & Priesemann, V. (2018). Inferring collective dynamical states from widely unobserved systems. Nature Communications, 9(1), 2325. https://doi.org/10.1038/s41467-018-04725-4
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_counts
|
ndarray | list[ndarray] | list[list[float]] | str
|
One trial, stacked trials, list of trials, or path input. |
required |
k_max
|
int
|
Maximum lag used for the MR fit. |
40
|
scatterpoints
|
bool
|
Keep centered lagged |
False
|
eps
|
float
|
Small stabilizer for divisions and weights. |
1e-12
|
ar1_fallback
|
bool
|
Use AR(1) fallback when MR fit is ill-posed. |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with |
dict
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If input data are invalid or too short. |
RuntimeError
|
If MR and fallback estimation both fail. |
Source code in btorch/analysis/branching.py
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 | |
compute_ie_ratio(excitatory_mat, inhibitory_mat, excitatory_neuron_only=True, neurons=None, warn_strict=True)
¶
Compute inhibitory/excitatory ratio per neuron and whole-brain mean.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/connectivity.py
compute_log_hist(data, bins=1000, edge_pos='mid')
¶
Compute histogram with logarithmically-spaced bins.
Useful for visualizing heavy-tailed distributions like synaptic weights or degree distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
Input data array (must be positive). |
required |
bins
|
int
|
Number of histogram bins. |
1000
|
edge_pos
|
Literal['mid', 'sep']
|
Position to return for bin edges. "mid": Return bin centers (midpoints). "sep": Return bin separators (edges). |
'mid'
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (hist, bin_edges) where hist is the count array and |
tuple
|
bin_edges are the positions (centers or edges based on edge_pos). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data contains non-positive values (required for log scale). |
Source code in btorch/analysis/statistics.py
compute_raster(sp_matrix, times)
¶
Get spike raster plot which displays the spiking activity of a group of neurons over time.
Source code in btorch/analysis/spiking.py
compute_spectrum(y, dt, nperseg=None)
¶
compute_voltage_overshoot(V, mode='threshold_resting', skip_timestep=None, **params)
¶
Quantify voltage stability/overshoot in different ways.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
KeyError
|
If a required threshold parameter ( |
Source code in btorch/analysis/voltage.py
cv_temporal(spikes, dt=1.0, window=100, step=1, batch_axis=None, dtype=None)
¶
Compute CV in sliding temporal windows.
Calculates the coefficient of variation of ISIs within sliding windows over time, giving a time-resolved measure of spike train irregularity.
This function is decorated with @use_stats.
See :func:~btorch.analysis.statistics.use_stats for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. |
required |
dt
|
float
|
Time step in milliseconds. |
1.0
|
window
|
int
|
Size of the sliding window in time steps. |
100
|
step
|
int
|
Step size between consecutive windows. |
1
|
batch_axis
|
BatchAxis
|
Axes to aggregate across (e.g., (1, 2) for trials). |
None
|
dtype
|
dtype | dtype | None
|
Data type for output arrays. If None, uses float64 for NumPy and float32 for Torch. |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-window values.
See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
cv_temporal |
StatsResult
|
CV values for each window. Shape: [n_windows, ...] where n_windows = (T - window) // step + 1. |
info |
StatsResult
|
Dictionary with window boundaries. |
Source code in btorch/analysis/spiking.py
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 | |
describe_array(array, verbose=True)
¶
Compute descriptive statistics for an array.
Computes mean, median, std, min, max, and quartiles, optionally printing them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
ndarray
|
NumPy array to describe (statistics are over all elements). |
required |
verbose
|
bool
|
If True (default), also print the statistics. |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary with keys |
dict[str, float]
|
|
Example
stats = describe_array(np.random.randn(100), verbose=False) sorted(stats) ['max', 'mean', 'median', 'min', 'q25', 'q50', 'q75', 'std']
Source code in btorch/analysis/statistics.py
fano(spikes, window=None, overlap=0, batch_axis=None, dtype=None)
¶
Compute Fano factor for spike trains using optimized cumulative sums.
Supports both NumPy and PyTorch inputs. GPU-friendly operation.
This function is decorated with @use_stats and @use_percentiles.
See :func:~btorch.analysis.statistics.use_stats and
:func:~btorch.analysis.statistics.use_percentiles for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size in time bins (not ms) for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
batch_axis
|
BatchAxis
|
Axes to average across for FF computation (e.g., trials). |
None
|
dtype
|
dtype | dtype | None
|
Data type for accumulation. If None, uses float64 for NumPy and input dtype (or float32 for float16/bfloat16) for Torch. |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
fano |
StatsResult
|
Fano factor values with shape [...]
(input shape without time dimension).
If |
info |
StatsResult
|
Dictionary with optional computed statistics and percentile data. |
Source code in btorch/analysis/spiking.py
fano_population(spikes, window=None, overlap=0)
¶
Compute Fano factor for the pooled population activity.
This computes Fano factor from the summed population spike count, giving a single population-level metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size in time bins (not ms) for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
fano_pop |
StatsResult
|
Single scalar Fano factor for the population. |
info |
StatsResult
|
Dictionary with 'window' and 'n_windows'. |
Source code in btorch/analysis/spiking.py
fano_sweep(spikes, window=None, overlap=0, batch_axis=None, dtype=None)
¶
Compute Fano factor sweeping over window sizes.
This sweeps through window sizes and computes the Fano factor for each, useful for analyzing how variability scales with counting window size.
The window parameter follows numpy.arange semantics: - window=10: windows from 1 to 10 (step=1) - window=(5, 20): windows from 5 to 20 (step=1) - window=(5, 20, 2): windows 5, 7, 9, ..., 19 (step=2) - window=None: defaults to range(1, T//20 + 1, 1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | tuple[int, ...] | None
|
Window size specification following arange convention: - int: stop value (start=1, step=1) - tuple (start, stop): range with step=1 - tuple (start, stop, step): full range specification - None: auto-determine as (1, T//20, 1) |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
batch_axis
|
BatchAxis
|
Axes to average across (e.g., trials). |
None
|
dtype
|
dtype | dtype | None
|
Data type for output arrays. If None, uses float64 for NumPy and float32 for Torch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
fano_sweep |
ndarray | Tensor
|
Fano factor values for each window size. Shape: [n_windows, ...] where n_windows depends on range. |
info |
dict
|
Dictionary with 'window_sizes' array and 'window' spec. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> # Sweep window sizes 1 to 50
>>> fano_sweep(spikes, window=50)
>>> # Sweep window sizes 10, 20, 30, ..., 100
>>> fano_sweep(spikes, window=(10, 101, 10))
>>> # Sweep window sizes 20, 30, 40, 50
>>> fano_sweep(spikes, window=(20, 51, 1))
Source code in btorch/analysis/spiking.py
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 1144 1145 1146 1147 1148 1149 1150 | |
fano_temporal(spikes, window=100, step=1, batch_axis=None)
¶
Compute Fano factor in sliding temporal windows.
Calculates the Fano factor within sliding windows over time, giving a time-resolved measure of spike count variability.
This function is decorated with @use_stats.
See :func:~btorch.analysis.statistics.use_stats for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int
|
Size of the sliding window in time steps for Fano computation. |
100
|
step
|
int
|
Step size between consecutive windows. |
1
|
batch_axis
|
BatchAxis
|
Axes to average across (e.g., trials). |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-window values.
See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
fano_temporal |
StatsResult
|
Fano factor values for each window. Shape: [n_windows, ...] |
info |
StatsResult
|
Dictionary with window boundaries. |
Source code in btorch/analysis/spiking.py
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 | |
firing_rate(spikes, width=4, dt=None, batch_axis=None)
¶
Smooth spikes into firing rates.
Supports input shapes like [T, ...]. If batch_axis is not None, averages over the specified dimensions before smoothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. |
required |
width
|
int | float | None
|
Smoothing window width. If None or 0, no smoothing is applied. |
4
|
dt
|
int | float | None
|
Time step in milliseconds. If None, defaults to 1.0. |
None
|
batch_axis
|
BatchAxis
|
Axes to average over before smoothing (e.g., neurons or trials). Can be int or tuple of ints. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
firing_rates |
ndarray | Tensor
|
Smoothed firing rates with same shape as input (minus averaged axes if batch_axis is specified). |
Source code in btorch/analysis/spiking.py
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 | |
group_ecdf(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', group_order=None, dropna=True)
¶
Compute grouped ECDF points ready for plotting or analysis.
Source code in btorch/analysis/aggregation.py
group_summary(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', group_order=None, dropna=True)
¶
Compute per-group summary statistics from neuron-aligned values.
Source code in btorch/analysis/aggregation.py
group_values(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', group_order=None, dropna=True)
¶
Return grouped value arrays, keyed by group label in plotting order.
Source code in btorch/analysis/aggregation.py
indices_to_mask(indices, shape=None, array=None)
¶
Convert indices to a boolean mask.
For multi-dimensional masks, a 1D index array is treated as
flattened indices. Provide a tuple of index arrays for per-axis
indexing (e.g. the output of :func:numpy.nonzero).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | tuple[ndarray, ...]
|
Index array (flat indices for |
required |
shape
|
tuple[int, ...] | None
|
Shape of the mask. Takes precedence over |
None
|
array
|
ndarray | None
|
Array whose shape is used when |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Boolean array that is |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither |
Source code in btorch/analysis/metrics.py
isi_cv(spikes, dt=1.0, batch_axis=None, dtype=None)
¶
Calculate coefficient of variation of ISIs per neuron.
Supports both NumPy and PyTorch inputs. For GPU tensors, uses a hybrid approach: aggregates on GPU, transfers to CPU for ISI extraction, then returns to GPU.
This function is decorated with @use_stats and @use_percentiles.
See :func:~btorch.analysis.statistics.use_stats and
:func:~btorch.analysis.statistics.use_percentiles for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. Values are binary (0/1) or spike counts. |
required |
dt
|
float
|
Time step in milliseconds for converting ISI to ms. |
1.0
|
batch_axis
|
BatchAxis
|
Axes to aggregate ISIs across (e.g., (1, 2) for trials). If None, computes CV per element in the non-time dimensions. |
None
|
dtype
|
dtype | dtype | None
|
Data type for accumulation. |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
cv_values |
StatsResult
|
CV values reshaped to match input without time dimension.
Shape: [...] (original shape without T, aggregated over batch_axis).
If |
info |
StatsResult
|
Dictionary with 'isi_total' (aggregate ISI statistics), 'isi_stats' (per-neuron statistics), and optional percentile data. |
Source code in btorch/analysis/spiking.py
isi_cv_population(spikes, dt=1.0)
¶
Calculate coefficient of variation of ISIs pooled across all neurons.
This computes CV from the pooled ISI distribution across the entire population, giving a single population-level metric.
This function is decorated with @use_stats.
See :func:~btorch.analysis.statistics.use_stats for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. |
required |
dt
|
float
|
Time step in milliseconds for converting ISI to ms. |
1.0
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return. Default is "cv".
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
Returns:
| Type | Description |
|---|---|
StatsResult
|
A |
StatsResult
|
is the scalar population CV of the pooled ISIs (NaN when the |
StatsResult
|
population emitted fewer than two spikes). With |
StatsResult
|
the raw pooled ISI array in units of |
StatsResult
|
spikes); any other |
StatsResult
|
pooled ISIs under |
StatsResult
|
|
Notes
cv follows the backend convention of
:func:~btorch.analysis.statistics.compute_stats_batch (NumPy:
population std, Torch: unbiased std).
Source code in btorch/analysis/spiking.py
kurtosis(spikes, window=None, overlap=0, fisher=True, batch_axis=None)
¶
Compute kurtosis of spike counts using optimized cumulative sums.
Supports both NumPy and PyTorch inputs. GPU-friendly operation.
This function is decorated with @use_stats and @use_percentiles.
See :func:~btorch.analysis.statistics.use_stats and
:func:~btorch.analysis.statistics.use_percentiles for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size in time bins (not ms) for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
fisher
|
bool
|
If True, return excess kurtosis (subtract 3). |
True
|
batch_axis
|
BatchAxis
|
Axes to average across for kurtosis computation. |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
kurt |
StatsResult
|
Kurtosis values with shape [...]
(input shape without time dimension).
If |
info |
StatsResult
|
Dictionary with optional computed statistics and percentile data. |
Source code in btorch/analysis/spiking.py
kurtosis_population(spikes, window=None, overlap=0, fisher=True)
¶
Compute kurtosis for the pooled population activity.
This computes kurtosis from the summed population spike count, giving a single population-level metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size in time bins (not ms) for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
fisher
|
bool
|
If True, return excess kurtosis (subtract 3). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
kurt_pop |
StatsResult
|
Single scalar kurtosis for the population. |
info |
StatsResult
|
Dictionary with 'window' and 'n_windows'. |
Source code in btorch/analysis/spiking.py
local_variation(spikes, dt=1.0, batch_axis=None)
¶
Calculate Local Variation (LV) of ISIs per neuron.
LV is a measure of spike train irregularity that is less sensitive to slow rate fluctuations than CV. For a Poisson process, LV = 1.
LV = (1/(N-1)) * sum(3*(ISI_i - ISI_{i+1})^2 / (ISI_i + ISI_{i+1})^2)
Supports both NumPy and PyTorch inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. |
required |
dt
|
float
|
Time step in milliseconds. |
1.0
|
batch_axis
|
BatchAxis
|
Axes to aggregate ISIs across (e.g., (1, 2) for trials). |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-neuron values.
See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values.
See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
lv_values |
StatsResult
|
LV values reshaped to match input without time dimension. |
lv_stats |
StatsResult
|
Dictionary with per-neuron LV statistics. |
Source code in btorch/analysis/spiking.py
select_on_metric(metrics, num=None, mode='topk', ret_indices=False)
¶
Select neurons based on a metric array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics
|
ndarray
|
1D per-neuron metric. |
required |
num
|
int | None
|
Number of neurons to select (required for |
None
|
mode
|
Literal['topk', 'any']
|
|
'topk'
|
ret_indices
|
bool
|
If True, return |
False
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, ndarray]
|
Selected neuron indices, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/metrics.py
suggest_skip_timestep(data)
¶
Suggest a burn-in period based on trace length.
Source code in btorch/analysis/voltage.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}_percentiles"] and
info[f"{value_key}_levels"]. The decorated function returns whatever the
wrapped function returns when percentiles is None, otherwise
(*values, info) (see :class:PercentilesDecorated).
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[..., Any] | 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'
|
default_percentiles
|
float | tuple[float, ...] | None
|
Percentiles used when the caller passes none. |
None
|
Returns:
| Type | Description |
|---|---|
PercentilesDecorated | Callable[[Callable[..., Any]], PercentilesDecorated]
|
Decorated function with added percentiles parameter |
Example
@use_percentiles
def compute_metric(data):
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=50) # compute median
values, info = compute_metric(
data, percentiles=(25, 50, 75)
) # compute quartiles
Source code in btorch/analysis/statistics.py
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 | |
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. The decorated
function always returns (*values, info) (see :class:StatsDecorated).
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[..., Any] | 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
|
DimSpec
|
Dimension(s) to aggregate over for each output |
None
|
default_nan_policy
|
NanPolicy
|
Default nan_policy for this decorated function |
'skip'
|
default_inf_policy
|
InfPolicy
|
Default inf_policy for this decorated function |
'propagate'
|
default_stat
|
StatSpec
|
Default stat for this decorated function |
None
|
default_stat_info
|
StatInfoSpec
|
Default stat_info for this decorated function |
None
|
Returns:
| Type | Description |
|---|---|
StatsDecorated | Callable[[Callable[..., Any]], StatsDecorated]
|
Decorated function with added stat, stat_info, nan_policy, and |
StatsDecorated | Callable[[Callable[..., Any]], StatsDecorated]
|
inf_policy parameters |
Example
@use_stats
def compute_metric(
data,
*,
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_stats
def compute_multiple(data):
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
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 | |
btorch.analysis.aggregation
¶
Attributes¶
AggName = Literal['mean', 'sum', 'std']
module-attribute
¶
Reduction names resolved on numpy / torch by the agg_*
helpers.
TensorLike = np.ndarray | torch.Tensor
module-attribute
¶
Functions:¶
_resolve_group_order(frame, group_by, group_order)
¶
Source code in btorch/analysis/aggregation.py
agg_by_neuron(y, neurons, agg='mean', neuron_type_column='cell_type', **kwargs)
¶
Aggregate data by neuron type.
Source code in btorch/analysis/aggregation.py
agg_by_neuropil(y, neurons=None, connections=None, mode='all_innervated', agg='mean', use_polars=False)
¶
Aggregate activations by neuropil under a validated aggregation mode.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/aggregation.py
agg_conn(y, conn, conn_weight=None, neurons=None, mode='neuron', neuron_type_column='cell_type', agg='mean')
¶
Aggregate connectivity weights by neuropil or neuron-type pairs.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/aggregation.py
build_group_frame(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', dropna=True)
¶
Convert neuron-aligned values to a tidy frame for grouped analyses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
TensorLike
|
Array/tensor shaped |
required |
neurons_df
|
DataFrame
|
DataFrame containing at least |
required |
group_by
|
str
|
Column in |
required |
simple_id_col
|
str
|
Column mapping rows in |
'simple_id'
|
value_name
|
str
|
Name for the output value column. |
'value'
|
dropna
|
bool
|
Drop missing values in group/value columns when |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/aggregation.py
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 | |
group_ecdf(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', group_order=None, dropna=True)
¶
Compute grouped ECDF points ready for plotting or analysis.
Source code in btorch/analysis/aggregation.py
group_summary(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', group_order=None, dropna=True)
¶
Compute per-group summary statistics from neuron-aligned values.
Source code in btorch/analysis/aggregation.py
group_values(values, neurons_df, group_by, *, simple_id_col='simple_id', value_name='value', group_order=None, dropna=True)
¶
Return grouped value arrays, keyed by group label in plotting order.
Source code in btorch/analysis/aggregation.py
to_numpy(data, *, strict=False, name='data')
¶
Convert a tensor or array-like to a dense NumPy array.
Torch tensors are detached and moved to CPU; anything else goes through
:func:numpy.asarray.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
Any
|
|
required |
strict
|
bool
|
Accept only |
False
|
name
|
str
|
Argument name used in the |
'data'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
NumPy array (a view of the input when no conversion is needed). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in btorch/utils/array.py
btorch.analysis.branching
¶
Branching-process simulation and MR branching-ratio estimation.
This module provides lightweight simulation helpers and a multiple-regression (MR) estimator for branching ratio under subsampling.
Citation: Wilting, J., & Priesemann, V. (2018). Inferring collective dynamical states from widely unobserved systems. Nature Communications, 9(1), 2325. https://doi.org/10.1038/s41467-018-04725-4
Classes¶
LaggedSlopes
¶
Bases: NamedTuple
Result of :func:compute_lagged_slopes.
Attributes:
| Name | Type | Description |
|---|---|---|
k |
ndarray
|
Lags |
r_k |
ndarray
|
Regression slope per lag, shape |
stderr |
ndarray
|
Standard error of each slope, same shape and |
data_length |
int
|
Total number of samples over all trials minus the first
valid lag; |
mean_activity |
float
|
Mean of the per-trial means; |
xs |
list[ndarray]
|
Centered lagged regressors, one array per valid lag (empty
unless |
ys |
list[ndarray]
|
Centered lagged responses, aligned with |
Source code in btorch/analysis/branching.py
Functions:¶
_ar1_fallback(counts_list, data_length, mean_activity, eps)
¶
Source code in btorch/analysis/branching.py
_to_1d_numeric_array(values)
¶
Source code in btorch/analysis/branching.py
compute_branching_ratio(all_counts, k_max=40, *, scatterpoints=False, eps=1e-12, ar1_fallback=True)
¶
Estimate branching ratio via subsampling-invariant MR fitting.
Citation: Wilting, J., & Priesemann, V. (2018). Inferring collective dynamical states from widely unobserved systems. Nature Communications, 9(1), 2325. https://doi.org/10.1038/s41467-018-04725-4
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_counts
|
ndarray | list[ndarray] | list[list[float]] | str
|
One trial, stacked trials, list of trials, or path input. |
required |
k_max
|
int
|
Maximum lag used for the MR fit. |
40
|
scatterpoints
|
bool
|
Keep centered lagged |
False
|
eps
|
float
|
Small stabilizer for divisions and weights. |
1e-12
|
ar1_fallback
|
bool
|
Use AR(1) fallback when MR fit is ill-posed. |
True
|
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with |
dict
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If input data are invalid or too short. |
RuntimeError
|
If MR and fallback estimation both fail. |
Source code in btorch/analysis/branching.py
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 | |
compute_lagged_slopes(all_counts, k_max, min_points=50, scatterpoints=False, eps=1e-12)
¶
Compute lagged regression slopes r_k for k = 1 .. k_max-1.
For each lag the centered pairs (a[t], a[t+k]) of all trials are
pooled and regressed through the origin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
all_counts
|
list[ndarray]
|
List of 1D count time series (trials). |
required |
k_max
|
int
|
Exclusive upper bound of the lags. |
required |
min_points
|
int
|
Minimum pooled sample count for a lag to be estimated. |
50
|
scatterpoints
|
bool
|
Also return the centered |
False
|
eps
|
float
|
Variance threshold below which a lag is declared degenerate. |
1e-12
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
LaggedSlopes
|
class: |
LaggedSlopes
|
lags are reported as |
|
LaggedSlopes
|
class: |
Source code in btorch/analysis/branching.py
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 | |
input_handler(items)
¶
Normalize supported input forms to list-of-trials arrays.
Raises:
| Type | Description |
|---|---|
ValueError
|
If a numpy array is not a 1D/2D numeric array, a list mixes
types (it must hold only arrays/lists or only |
Source code in btorch/analysis/branching.py
simulate_binomial_subsampling(a_t, alpha, rng=None)
¶
Apply binomial subsampling to count data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a_t
|
ndarray
|
Integer activity time series. |
required |
alpha
|
float
|
Sampling probability in |
required |
rng
|
int | Generator | None
|
Seed or random generator. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Subsampled counts as |
Source code in btorch/analysis/branching.py
simulate_branching(length=10000, m=0.9, activity=100, rng=None)
¶
Simulate a branching process with immigration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
int
|
Number of time points. |
10000
|
m
|
float
|
True branching ratio. |
0.9
|
activity
|
float
|
Target mean activity. |
100
|
rng
|
int | Generator | None
|
Seed or random generator. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Integer count time series of shape |
Source code in btorch/analysis/branching.py
btorch.analysis.clustering
¶
Functions:¶
_euclidean(u, v)
¶
Euclidean distance that tolerates scalar input (for fastdtw).
cluster_traces(traces, threshold=10, linkage_method='average')
¶
Cluster traces of voltages or currents using hierarchical agglomerative clustering with DTW distance.
Source code in btorch/analysis/clustering.py
require(module_name, extra, purpose=None)
¶
Import an optional dependency, or raise ImportError with an install hint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module_name
|
str
|
Dotted module path to import (e.g. |
required |
extra
|
str
|
Name of the btorch extra that provides the module (e.g. |
required |
purpose
|
str | None
|
Optional short description of the feature needing the module. |
None
|
Returns:
| Type | Description |
|---|---|
ModuleType
|
The imported module. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If the module is not installed. |
Source code in btorch/utils/_optional.py
suggest_threshold(linkage_matrix)
¶
Suggest a sensible threshold for hierarchical clustering.
Source code in btorch/analysis/clustering.py
btorch.analysis.connectivity
¶
Connectivity analysis utilities for neural networks.
This module provides tools for analyzing connectivity properties of neural circuits, including:
- Inhibitory/excitatory (IE) ratio computation
- Hop distance analysis using BFS
- Network reachability statistics
- Shortest path reconstruction
Expected DataFrame schemas
neurons DataFrame: - simple_id: Linear neuron index (0..N-1) - root_id: Unique neuron identifier - EI: Excitatory/inhibitory type ("E" or "I")
connections/edges DataFrame: - pre_simple_id: Presynaptic neuron simple_id - post_simple_id: Postsynaptic neuron simple_id - syn_count: Number of synapses (optional)
The HopDistanceModel class provides efficient hop distance computation
using either sparse matrix or edge list representations.
Classes¶
HopDistanceModel
¶
Fast computation of hop distances in networks using BFS.
Source code in btorch/analysis/connectivity.py
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 | |
Methods:¶
compute_distances(seeds, max_hops=None)
¶
Compute hop distances from seeds to all reachable nodes using BFS.
Source code in btorch/analysis/connectivity.py
hop_statistics(seeds, max_hops=None)
¶
Compute statistics about network reachability by hop distance.
Source code in btorch/analysis/connectivity.py
reconstruct_path(source_node, target_node, distances_df=None)
¶
Reconstruct shortest path from source to target using predecessor info.
Source code in btorch/analysis/connectivity.py
Functions:¶
compute_ie_ratio(excitatory_mat, inhibitory_mat, excitatory_neuron_only=True, neurons=None, warn_strict=True)
¶
Compute inhibitory/excitatory ratio per neuron and whole-brain mean.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/connectivity.py
btorch.analysis.metrics
¶
Functions:¶
indices_to_mask(indices, shape=None, array=None)
¶
Convert indices to a boolean mask.
For multi-dimensional masks, a 1D index array is treated as
flattened indices. Provide a tuple of index arrays for per-axis
indexing (e.g. the output of :func:numpy.nonzero).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indices
|
ndarray | tuple[ndarray, ...]
|
Index array (flat indices for |
required |
shape
|
tuple[int, ...] | None
|
Shape of the mask. Takes precedence over |
None
|
array
|
ndarray | None
|
Array whose shape is used when |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Boolean array that is |
Raises:
| Type | Description |
|---|---|
ValueError
|
If neither |
Source code in btorch/analysis/metrics.py
select_on_metric(metrics, num=None, mode='topk', ret_indices=False)
¶
Select neurons based on a metric array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metrics
|
ndarray
|
1D per-neuron metric. |
required |
num
|
int | None
|
Number of neurons to select (required for |
None
|
mode
|
Literal['topk', 'any']
|
|
'topk'
|
ret_indices
|
bool
|
If True, return |
False
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, ndarray]
|
Selected neuron indices, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/metrics.py
btorch.analysis.spiking
¶
Spike train analysis utilities for computing various metrics.
This module provides functions for analyzing spike train data, including:
- ISI (inter-spike interval) statistics: CV, local variation
- Fano factor (spike count variability)
- Kurtosis (spike count distribution shape)
- Population-level metrics (pooled across neurons)
- Temporal windowed analysis
- Firing rate smoothing
All functions support both NumPy arrays and PyTorch tensors, with GPU-optimized implementations where applicable. The time dimension is assumed to be the first dimension (axis=0) for all inputs.
Naming rule
- Bare names (
isi_cv,fano,kurtosis,local_variation, ...) are per-neuron or population statistics: they return arrays (or thestataggregate) together with aninfodict, as(value, info). compute_*names are multi-step pipelines (e.g. smoothing then an estimator, or a simulation) and return their own result types.
Shape conventions
- Input spike trains: [T, ...] where T is time steps, remaining dimensions can be arbitrary (neurons, trials, batches, etc.)
- Per-neuron outputs: [...] (same as input without time dimension)
- Temporal outputs: [n_windows, ...] for sliding window functions
Batch axis behavior
- Most functions support
batch_axisparameter for aggregating across specific dimensions (e.g., trials) before computing metrics - Aggregation is typically done via sum (for spike counts) or mean
The module uses decorators from statistics.py to add optional
aggregation (stat), additional statistics (stat_info), and
percentile computation (percentiles) to many functions.
Attributes¶
BatchAxis = int | tuple[int, ...] | None
module-attribute
¶
Axes (e.g. trials) a spike/current statistic aggregates over before it is
computed; an int is shorthand for a one-element tuple, None keeps all
non-time axes.
StatsResult = tuple[Any, dict[str, Any]]
module-attribute
¶
(value, info) returned by a single-output function wrapped by
:func:use_stats/:func:use_percentiles: value is the per-element array
(or the aggregate if stat is given) and info the statistics dict.
Functions:¶
_check_window(window, overlap, T)
¶
Validate sliding-window arguments.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in btorch/analysis/spiking.py
_cv(spikes, dt=1.0, batch_axis=None, dtype=None)
¶
Source code in btorch/analysis/spiking.py
_cv_numpy(spikes, dt, batch_axis, dtype=None)
¶
NumPy implementation of ISI CV.
Source code in btorch/analysis/spiking.py
_cv_torch(spikes, dt, batch_axis, dtype=None)
¶
Torch implementation of ISI CV with GPU optimization.
Strategy: Aggregate on GPU if needed, transfer to CPU for ISI extraction (more efficient than pure GPU due to divergent control flow), then return.
Note: Uses specified dtype or input dtype for accumulation.
Source code in btorch/analysis/spiking.py
_fano_numpy(spikes, window, overlap, batch_axis, dtype=None)
¶
NumPy implementation of Fano factor.
Source code in btorch/analysis/spiking.py
_fano_population_numpy(spikes, window, overlap, dtype=None)
¶
NumPy implementation of pooled Fano factor.
Source code in btorch/analysis/spiking.py
_fano_population_torch(spikes, window, overlap, dtype=None)
¶
Torch implementation of pooled Fano factor.
Source code in btorch/analysis/spiking.py
_fano_torch(spikes, window, overlap, batch_axis, dtype=None)
¶
Torch implementation of Fano factor (GPU-friendly).
Note: Uses specified dtype or input dtype for accumulation.
Source code in btorch/analysis/spiking.py
_isis_population_numpy(spikes, dt)
¶
Pooled inter-spike intervals across all neurons (NumPy).
Spikes of all neurons are merged into one train; the intervals between
consecutive events (in time units of dt) are returned. Fewer than two
spikes give an empty array, never a sentinel tuple.
Source code in btorch/analysis/spiking.py
_isis_population_torch(spikes, dt)
¶
Pooled inter-spike intervals across all neurons (Torch).
Same contract as :func:_isis_population_numpy; the result is a float32
tensor on the input device (empty for fewer than two spikes).
Source code in btorch/analysis/spiking.py
_kurtosis_numpy(spikes, window, overlap, fisher, batch_axis, dtype=None)
¶
NumPy implementation of kurtosis.
Source code in btorch/analysis/spiking.py
_kurtosis_population_numpy(spikes, window, overlap, fisher)
¶
NumPy implementation of pooled kurtosis.
Source code in btorch/analysis/spiking.py
_kurtosis_population_torch(spikes, window, overlap, fisher)
¶
Torch implementation of pooled kurtosis.
Source code in btorch/analysis/spiking.py
_kurtosis_torch(spikes, window, overlap, fisher, batch_axis)
¶
Torch implementation of kurtosis (GPU-friendly).
Source code in btorch/analysis/spiking.py
_lv_numpy(spikes, dt, batch_axis, dtype=None)
¶
NumPy implementation of Local Variation.
Source code in btorch/analysis/spiking.py
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 | |
_lv_torch(spikes, dt, batch_axis)
¶
Torch implementation of Local Variation with GPU optimization.
Source code in btorch/analysis/spiking.py
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 | |
compute_raster(sp_matrix, times)
¶
Get spike raster plot which displays the spiking activity of a group of neurons over time.
Source code in btorch/analysis/spiking.py
compute_spectrum(y, dt, nperseg=None)
¶
cv_temporal(spikes, dt=1.0, window=100, step=1, batch_axis=None, dtype=None)
¶
Compute CV in sliding temporal windows.
Calculates the coefficient of variation of ISIs within sliding windows over time, giving a time-resolved measure of spike train irregularity.
This function is decorated with @use_stats.
See :func:~btorch.analysis.statistics.use_stats for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. |
required |
dt
|
float
|
Time step in milliseconds. |
1.0
|
window
|
int
|
Size of the sliding window in time steps. |
100
|
step
|
int
|
Step size between consecutive windows. |
1
|
batch_axis
|
BatchAxis
|
Axes to aggregate across (e.g., (1, 2) for trials). |
None
|
dtype
|
dtype | dtype | None
|
Data type for output arrays. If None, uses float64 for NumPy and float32 for Torch. |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-window values.
See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
cv_temporal |
StatsResult
|
CV values for each window. Shape: [n_windows, ...] where n_windows = (T - window) // step + 1. |
info |
StatsResult
|
Dictionary with window boundaries. |
Source code in btorch/analysis/spiking.py
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 | |
fano(spikes, window=None, overlap=0, batch_axis=None, dtype=None)
¶
Compute Fano factor for spike trains using optimized cumulative sums.
Supports both NumPy and PyTorch inputs. GPU-friendly operation.
This function is decorated with @use_stats and @use_percentiles.
See :func:~btorch.analysis.statistics.use_stats and
:func:~btorch.analysis.statistics.use_percentiles for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size in time bins (not ms) for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
batch_axis
|
BatchAxis
|
Axes to average across for FF computation (e.g., trials). |
None
|
dtype
|
dtype | dtype | None
|
Data type for accumulation. If None, uses float64 for NumPy and input dtype (or float32 for float16/bfloat16) for Torch. |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
fano |
StatsResult
|
Fano factor values with shape [...]
(input shape without time dimension).
If |
info |
StatsResult
|
Dictionary with optional computed statistics and percentile data. |
Source code in btorch/analysis/spiking.py
fano_population(spikes, window=None, overlap=0)
¶
Compute Fano factor for the pooled population activity.
This computes Fano factor from the summed population spike count, giving a single population-level metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size in time bins (not ms) for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
fano_pop |
StatsResult
|
Single scalar Fano factor for the population. |
info |
StatsResult
|
Dictionary with 'window' and 'n_windows'. |
Source code in btorch/analysis/spiking.py
fano_sweep(spikes, window=None, overlap=0, batch_axis=None, dtype=None)
¶
Compute Fano factor sweeping over window sizes.
This sweeps through window sizes and computes the Fano factor for each, useful for analyzing how variability scales with counting window size.
The window parameter follows numpy.arange semantics: - window=10: windows from 1 to 10 (step=1) - window=(5, 20): windows from 5 to 20 (step=1) - window=(5, 20, 2): windows 5, 7, 9, ..., 19 (step=2) - window=None: defaults to range(1, T//20 + 1, 1)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | tuple[int, ...] | None
|
Window size specification following arange convention: - int: stop value (start=1, step=1) - tuple (start, stop): range with step=1 - tuple (start, stop, step): full range specification - None: auto-determine as (1, T//20, 1) |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
batch_axis
|
BatchAxis
|
Axes to average across (e.g., trials). |
None
|
dtype
|
dtype | dtype | None
|
Data type for output arrays. If None, uses float64 for NumPy and float32 for Torch. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
fano_sweep |
ndarray | Tensor
|
Fano factor values for each window size. Shape: [n_windows, ...] where n_windows depends on range. |
info |
dict
|
Dictionary with 'window_sizes' array and 'window' spec. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> # Sweep window sizes 1 to 50
>>> fano_sweep(spikes, window=50)
>>> # Sweep window sizes 10, 20, 30, ..., 100
>>> fano_sweep(spikes, window=(10, 101, 10))
>>> # Sweep window sizes 20, 30, 40, 50
>>> fano_sweep(spikes, window=(20, 51, 1))
Source code in btorch/analysis/spiking.py
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 1144 1145 1146 1147 1148 1149 1150 | |
fano_temporal(spikes, window=100, step=1, batch_axis=None)
¶
Compute Fano factor in sliding temporal windows.
Calculates the Fano factor within sliding windows over time, giving a time-resolved measure of spike count variability.
This function is decorated with @use_stats.
See :func:~btorch.analysis.statistics.use_stats for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int
|
Size of the sliding window in time steps for Fano computation. |
100
|
step
|
int
|
Step size between consecutive windows. |
1
|
batch_axis
|
BatchAxis
|
Axes to average across (e.g., trials). |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-window values.
See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
fano_temporal |
StatsResult
|
Fano factor values for each window. Shape: [n_windows, ...] |
info |
StatsResult
|
Dictionary with window boundaries. |
Source code in btorch/analysis/spiking.py
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 | |
firing_rate(spikes, width=4, dt=None, batch_axis=None)
¶
Smooth spikes into firing rates.
Supports input shapes like [T, ...]. If batch_axis is not None, averages over the specified dimensions before smoothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. |
required |
width
|
int | float | None
|
Smoothing window width. If None or 0, no smoothing is applied. |
4
|
dt
|
int | float | None
|
Time step in milliseconds. If None, defaults to 1.0. |
None
|
batch_axis
|
BatchAxis
|
Axes to average over before smoothing (e.g., neurons or trials). Can be int or tuple of ints. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
firing_rates |
ndarray | Tensor
|
Smoothed firing rates with same shape as input (minus averaged axes if batch_axis is specified). |
Source code in btorch/analysis/spiking.py
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 | |
isi_cv(spikes, dt=1.0, batch_axis=None, dtype=None)
¶
Calculate coefficient of variation of ISIs per neuron.
Supports both NumPy and PyTorch inputs. For GPU tensors, uses a hybrid approach: aggregates on GPU, transfers to CPU for ISI extraction, then returns to GPU.
This function is decorated with @use_stats and @use_percentiles.
See :func:~btorch.analysis.statistics.use_stats and
:func:~btorch.analysis.statistics.use_percentiles for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. Values are binary (0/1) or spike counts. |
required |
dt
|
float
|
Time step in milliseconds for converting ISI to ms. |
1.0
|
batch_axis
|
BatchAxis
|
Axes to aggregate ISIs across (e.g., (1, 2) for trials). If None, computes CV per element in the non-time dimensions. |
None
|
dtype
|
dtype | dtype | None
|
Data type for accumulation. |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
cv_values |
StatsResult
|
CV values reshaped to match input without time dimension.
Shape: [...] (original shape without T, aggregated over batch_axis).
If |
info |
StatsResult
|
Dictionary with 'isi_total' (aggregate ISI statistics), 'isi_stats' (per-neuron statistics), and optional percentile data. |
Source code in btorch/analysis/spiking.py
isi_cv_population(spikes, dt=1.0)
¶
Calculate coefficient of variation of ISIs pooled across all neurons.
This computes CV from the pooled ISI distribution across the entire population, giving a single population-level metric.
This function is decorated with @use_stats.
See :func:~btorch.analysis.statistics.use_stats for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. |
required |
dt
|
float
|
Time step in milliseconds for converting ISI to ms. |
1.0
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return. Default is "cv".
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
Returns:
| Type | Description |
|---|---|
StatsResult
|
A |
StatsResult
|
is the scalar population CV of the pooled ISIs (NaN when the |
StatsResult
|
population emitted fewer than two spikes). With |
StatsResult
|
the raw pooled ISI array in units of |
StatsResult
|
spikes); any other |
StatsResult
|
pooled ISIs under |
StatsResult
|
|
Notes
cv follows the backend convention of
:func:~btorch.analysis.statistics.compute_stats_batch (NumPy:
population std, Torch: unbiased std).
Source code in btorch/analysis/spiking.py
kurtosis(spikes, window=None, overlap=0, fisher=True, batch_axis=None)
¶
Compute kurtosis of spike counts using optimized cumulative sums.
Supports both NumPy and PyTorch inputs. GPU-friendly operation.
This function is decorated with @use_stats and @use_percentiles.
See :func:~btorch.analysis.statistics.use_stats and
:func:~btorch.analysis.statistics.use_percentiles for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size in time bins (not ms) for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
fisher
|
bool
|
If True, return excess kurtosis (subtract 3). |
True
|
batch_axis
|
BatchAxis
|
Axes to average across for kurtosis computation. |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute
and store in info dict.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
kurt |
StatsResult
|
Kurtosis values with shape [...]
(input shape without time dimension).
If |
info |
StatsResult
|
Dictionary with optional computed statistics and percentile data. |
Source code in btorch/analysis/spiking.py
kurtosis_population(spikes, window=None, overlap=0, fisher=True)
¶
Compute kurtosis for the pooled population activity.
This computes kurtosis from the summed population spike count, giving a single population-level metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size in time bins (not ms) for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
fisher
|
bool
|
If True, return excess kurtosis (subtract 3). |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
kurt_pop |
StatsResult
|
Single scalar kurtosis for the population. |
info |
StatsResult
|
Dictionary with 'window' and 'n_windows'. |
Source code in btorch/analysis/spiking.py
local_variation(spikes, dt=1.0, batch_axis=None)
¶
Calculate Local Variation (LV) of ISIs per neuron.
LV is a measure of spike train irregularity that is less sensitive to slow rate fluctuations than CV. For a Poisson process, LV = 1.
LV = (1/(N-1)) * sum(3*(ISI_i - ISI_{i+1})^2 / (ISI_i + ISI_{i+1})^2)
Supports both NumPy and PyTorch inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spikes
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. |
required |
dt
|
float
|
Time step in milliseconds. |
1.0
|
batch_axis
|
BatchAxis
|
Axes to aggregate ISIs across (e.g., (1, 2) for trials). |
None
|
Other Parameters:
| Name | Type | Description |
|---|---|---|
stat |
str | None
|
Aggregation statistic to return instead of per-neuron values.
See :func: |
stat_info |
str | list[str] | None
|
Additional statistics to compute.
See :func: |
nan_policy |
str | None
|
How to handle NaN values ("skip", "warn", "assert").
See :func: |
inf_policy |
str | None
|
How to handle Inf values.
See :func: |
percentiles |
float | tuple[float, ...] | None
|
Percentile level(s) in
[0, 100] to compute.
See :func: |
Returns:
| Name | Type | Description |
|---|---|---|
lv_values |
StatsResult
|
LV values reshaped to match input without time dimension. |
lv_stats |
StatsResult
|
Dictionary with per-neuron LV statistics. |
Source code in btorch/analysis/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}_percentiles"] and
info[f"{value_key}_levels"]. The decorated function returns whatever the
wrapped function returns when percentiles is None, otherwise
(*values, info) (see :class:PercentilesDecorated).
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[..., Any] | 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'
|
default_percentiles
|
float | tuple[float, ...] | None
|
Percentiles used when the caller passes none. |
None
|
Returns:
| Type | Description |
|---|---|
PercentilesDecorated | Callable[[Callable[..., Any]], PercentilesDecorated]
|
Decorated function with added percentiles parameter |
Example
@use_percentiles
def compute_metric(data):
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=50) # compute median
values, info = compute_metric(
data, percentiles=(25, 50, 75)
) # compute quartiles
Source code in btorch/analysis/statistics.py
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 | |
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. The decorated
function always returns (*values, info) (see :class:StatsDecorated).
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[..., Any] | 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
|
DimSpec
|
Dimension(s) to aggregate over for each output |
None
|
default_nan_policy
|
NanPolicy
|
Default nan_policy for this decorated function |
'skip'
|
default_inf_policy
|
InfPolicy
|
Default inf_policy for this decorated function |
'propagate'
|
default_stat
|
StatSpec
|
Default stat for this decorated function |
None
|
default_stat_info
|
StatInfoSpec
|
Default stat_info for this decorated function |
None
|
Returns:
| Type | Description |
|---|---|
StatsDecorated | Callable[[Callable[..., Any]], StatsDecorated]
|
Decorated function with added stat, stat_info, nan_policy, and |
StatsDecorated | Callable[[Callable[..., Any]], StatsDecorated]
|
inf_policy parameters |
Example
@use_stats
def compute_metric(
data,
*,
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_stats
def compute_multiple(data):
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
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 | |
btorch.analysis.statistics
¶
Statistical utilities for analysis.
This module provides statistical computation utilities that work with both NumPy arrays and PyTorch tensors, with consistent APIs across both backends.
Key features
- Unified API for common statistics (mean, std, var, median, etc.)
- Configurable NaN and Inf handling policies
- Batch computation optimization (reuses mean/std for CV)
- Decorators for adding aggregation and percentile support
Decorators
use_stats: Addsstat,stat_info,nan_policy,inf_policyargsuse_percentiles: Addspercentilesarg for computing percentiles
Example
from btorch.analysis.statistics import compute_stat, use_stats import numpy as np data = np.random.randn(100, 10) # 100 samples, 10 neurons compute_stat(data, "mean", dim=0) # mean per neuron @use_stats ... def compute_metric(x): return x.mean(axis=0), {} compute_metric(data, stat="median") # returns median instead
Attributes¶
BatchAxis = int | tuple[int, ...] | None
module-attribute
¶
Axes (e.g. trials) a spike/current statistic aggregates over before it is
computed; an int is shorthand for a one-element tuple, None keeps all
non-time axes.
DimSpec = int | tuple[int, ...] | dict[int, int | tuple[int, ...] | None] | None
module-attribute
¶
InfPolicy = Literal['propagate', 'skip', 'warn', 'assert']
module-attribute
¶
MultiStatsResult = tuple[Any, ...]
module-attribute
¶
(*values, info) returned by a multi-output function wrapped by
:func:use_stats/:func:use_percentiles: one entry per wrapped return
position followed by the info dict.
NanPolicy = Literal['skip', 'warn', 'assert']
module-attribute
¶
PercentileSpec = float | tuple[float, ...] | dict[int, float | tuple[float, ...]] | None
module-attribute
¶
StatChoice = Literal['mean', 'median', 'max', 'min', 'std', 'var', 'argmax', 'argmin', 'cv']
module-attribute
¶
StatInfoSpec = StatChoice | Iterable[StatChoice] | dict[int, StatChoice | Iterable[StatChoice]] | None
module-attribute
¶
StatSpec = StatChoice | dict[int, StatChoice] | None
module-attribute
¶
StatsResult = tuple[Any, dict[str, Any]]
module-attribute
¶
(value, info) returned by a single-output function wrapped by
:func:use_stats/:func:use_percentiles: value is the per-element array
(or the aggregate if stat is given) and info the statistics dict.
_NUMPY_REDUCERS = {'mean': lambda v, d: v.mean(axis=d), 'median': lambda v, d: np.median(v, axis=d), 'max': lambda v, d: v.max(axis=d), 'min': lambda v, d: v.min(axis=d), 'std': lambda v, d: v.std(axis=d), 'var': lambda v, d: v.var(axis=d), 'argmax': lambda v, d: v.argmax(axis=d), 'argmin': lambda v, d: v.argmin(axis=d)}
module-attribute
¶
_TORCH_REDUCERS = {'mean': lambda v, d: v.mean(dim=d) if isinstance(d, int) else v.mean(), 'median': lambda v, d: v.median(dim=d).values if isinstance(d, int) else v.median(), 'max': lambda v, d: v.max(dim=d).values if isinstance(d, int) else v.max(), 'min': lambda v, d: v.min(dim=d).values if isinstance(d, int) else v.min(), 'std': lambda v, d: v.std(dim=d) if isinstance(d, int) else v.std(), 'var': lambda v, d: v.var(dim=d) if isinstance(d, int) else v.var(), 'argmax': lambda v, d: v.argmax(dim=d) if isinstance(d, int) else v.argmax(), 'argmin': lambda v, d: v.argmin(dim=d) if isinstance(d, int) else v.argmin()}
module-attribute
¶
Classes¶
PercentilesDecorated
¶
Bases: Protocol
Signature of a function wrapped by :func:use_percentiles.
The arguments of the wrapped function are forwarded unchanged and
percentiles is added. The call returns (*values, info).
Source code in btorch/analysis/statistics.py
StatsDecorated
¶
Bases: Protocol
Signature of a function wrapped by :func:use_stats.
The positional/keyword arguments of the wrapped function are forwarded
unchanged; stat, stat_info, nan_policy and inf_policy are
added. The call always returns (*values, info).
Source code in btorch/analysis/statistics.py
_Outputs
¶
Resolve per-position values, info keys and dims of a decorated result.
Source code in btorch/analysis/statistics.py
Functions:¶
_apply_value_policy(values, *, name, policy, detect)
¶
Apply a NaN/Inf policy (name is "NaN" or "Inf").
detect is isnan/isinf of the matching backend. Offending
elements are dropped for "skip" and "warn" (which also warns).
Source code in btorch/analysis/statistics.py
_percentile_key(value_key, pos)
¶
Info-key prefix of output pos used by :func:use_percentiles.
Source code in btorch/analysis/statistics.py
_unpack_result(result, value_key)
¶
Unpack function result into values tuple and info dict.
Handles the logic for detecting whether the last element of a tuple result is an info dict or an actual return value.
When value_key is a dict, we know exactly how many values to expect (max position + 1). Only treat the last element as info if there's an extra element beyond what's expected.
When value_key is a string, use the original heuristic: if the last element is a dict, treat it as info.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
Any
|
The return value from a decorated function |
required |
value_key
|
str | dict[int, str]
|
The value_key from the decorator (str or dict) |
required |
Returns:
| Type | Description |
|---|---|
tuple[tuple[Any, ...], dict]
|
Tuple of (values_tuple, info_dict) |
Source code in btorch/analysis/statistics.py
compute_log_hist(data, bins=1000, edge_pos='mid')
¶
Compute histogram with logarithmically-spaced bins.
Useful for visualizing heavy-tailed distributions like synaptic weights or degree distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
ndarray
|
Input data array (must be positive). |
required |
bins
|
int
|
Number of histogram bins. |
1000
|
edge_pos
|
Literal['mid', 'sep']
|
Position to return for bin edges. "mid": Return bin centers (midpoints). "sep": Return bin separators (edges). |
'mid'
|
Returns:
| Type | Description |
|---|---|
tuple
|
Tuple of (hist, bin_edges) where hist is the count array and |
tuple
|
bin_edges are the positions (centers or edges based on edge_pos). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data contains non-positive values (required for log scale). |
Source code in btorch/analysis/statistics.py
compute_percentiles(values, percentiles)
¶
Compute percentiles of values.
Works with both numpy arrays and PyTorch tensors, preserving the input type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ndarray | Tensor
|
Input array or tensor |
required |
percentiles
|
float | tuple[float, ...]
|
Percentile level(s) in [0, 100] range (e.g., 50 for median) |
required |
Returns:
| Type | Description |
|---|---|
dict[str, list[float] | tuple[float, ...]]
|
Dictionary with "levels" and "percentiles" keys |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any requested percentile is outside |
Source code in btorch/analysis/statistics.py
compute_stat(values, stat, *, nan_policy='skip', inf_policy='propagate', dim=None)
¶
Compute a single statistic on an array or tensor.
Works with both numpy arrays and PyTorch tensors, preserving the input type.
See :func:compute_stats_batch for the shared implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ndarray | Tensor
|
Input array or tensor |
required |
stat
|
StatChoice
|
Statistic to compute |
required |
nan_policy
|
NanPolicy
|
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 |
'skip'
|
inf_policy
|
InfPolicy
|
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 |
'propagate'
|
dim
|
int | tuple[int, ...] | None
|
Dimension(s) to aggregate over. If None, flattens all dimensions. |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
Computed statistic value |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Example
import numpy as np data = np.random.randn(100) compute_stat(data, "mean") 0.1
Source code in btorch/analysis/statistics.py
compute_stats_batch(values, stats, *, nan_policy='skip', inf_policy='propagate', dim=None)
¶
Compute multiple statistics efficiently on an array or tensor.
This function optimizes computation by reusing mean and std calculations when computing cv (coefficient of variation).
Works with both numpy arrays and PyTorch tensors, preserving the input type.
Torch results with a single element become Python scalars; NumPy results
are returned as produced by NumPy. Note that std/var/cv follow
each backend's native convention (torch: unbiased, NumPy: population).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ndarray | Tensor
|
Input array or tensor |
required |
stats
|
Iterable[StatChoice]
|
Statistics to compute |
required |
nan_policy
|
NanPolicy
|
How to handle NaN values |
'skip'
|
inf_policy
|
InfPolicy
|
How to handle Inf values |
'propagate'
|
dim
|
int | tuple[int, ...] | None
|
Dimension(s) to aggregate over. If None, flattens all dimensions. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict mapping each stat to its computed value |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a stat is unknown or a policy is |
Example
import numpy as np data = np.random.randn(100) compute_stats_batch(data, ["mean", "std", "cv"])
Source code in btorch/analysis/statistics.py
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 | |
describe_array(array, verbose=True)
¶
Compute descriptive statistics for an array.
Computes mean, median, std, min, max, and quartiles, optionally printing them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
ndarray
|
NumPy array to describe (statistics are over all elements). |
required |
verbose
|
bool
|
If True (default), also print the statistics. |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dictionary with keys |
dict[str, float]
|
|
Example
stats = describe_array(np.random.randn(100), verbose=False) sorted(stats) ['max', 'mean', 'median', 'min', 'q25', 'q50', 'q75', 'std']
Source code in btorch/analysis/statistics.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}_percentiles"] and
info[f"{value_key}_levels"]. The decorated function returns whatever the
wrapped function returns when percentiles is None, otherwise
(*values, info) (see :class:PercentilesDecorated).
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[..., Any] | 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'
|
default_percentiles
|
float | tuple[float, ...] | None
|
Percentiles used when the caller passes none. |
None
|
Returns:
| Type | Description |
|---|---|
PercentilesDecorated | Callable[[Callable[..., Any]], PercentilesDecorated]
|
Decorated function with added percentiles parameter |
Example
@use_percentiles
def compute_metric(data):
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=50) # compute median
values, info = compute_metric(
data, percentiles=(25, 50, 75)
) # compute quartiles
Source code in btorch/analysis/statistics.py
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 | |
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. The decorated
function always returns (*values, info) (see :class:StatsDecorated).
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[..., Any] | 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
|
DimSpec
|
Dimension(s) to aggregate over for each output |
None
|
default_nan_policy
|
NanPolicy
|
Default nan_policy for this decorated function |
'skip'
|
default_inf_policy
|
InfPolicy
|
Default inf_policy for this decorated function |
'propagate'
|
default_stat
|
StatSpec
|
Default stat for this decorated function |
None
|
default_stat_info
|
StatInfoSpec
|
Default stat_info for this decorated function |
None
|
Returns:
| Type | Description |
|---|---|
StatsDecorated | Callable[[Callable[..., Any]], StatsDecorated]
|
Decorated function with added stat, stat_info, nan_policy, and |
StatsDecorated | Callable[[Callable[..., Any]], StatsDecorated]
|
inf_policy parameters |
Example
@use_stats
def compute_metric(
data,
*,
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_stats
def compute_multiple(data):
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
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 | |
btorch.analysis.voltage
¶
Functions:¶
compute_voltage_overshoot(V, mode='threshold_resting', skip_timestep=None, **params)
¶
Quantify voltage stability/overshoot in different ways.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
KeyError
|
If a required threshold parameter ( |
Source code in btorch/analysis/voltage.py
suggest_skip_timestep(data)
¶
Suggest a burn-in period based on trace length.