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', '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', '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
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | |
Functions¶
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.
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.
Source code in btorch/analysis/aggregation.py
branching_ratio(all_counts, k_max=40, *, maxslopes=None, 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
|
maxslopes
|
int | None
|
Legacy synonym for |
None
|
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
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
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
|
Source code in btorch/analysis/aggregation.py
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.
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
|
Input data array (must be positive). |
required | |
bins
|
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 of (hist, bin_edges) where hist is the count array and |
|
|
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)
¶
cv_temporal(spike_data, dt_ms=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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_data
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. |
required |
dt_ms
|
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
|
tuple[int, ...] | int | None
|
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
|
Returns:
| Name | Type | Description |
|---|---|---|
cv_temporal |
CV values for each window. Shape: [n_windows, ...] where n_windows = (T - window) // step + 1. |
|
info |
Dictionary with window boundaries. |
Source code in btorch/analysis/spiking.py
describe_array(array)
¶
Print descriptive statistics for a 1D array.
Displays mean, median, std, min, max, and quartiles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
array
|
ndarray
|
1D NumPy array to describe. |
required |
Example
describe_array(np.random.randn(100)) Mean: 0.05 Median: 0.12 ...
Source code in btorch/analysis/statistics.py
fano(spike, 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 use_stats() and
use_percentiles() for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
batch_axis
|
tuple[int, ...] | int | None
|
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
|
stat
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See |
required | |
stat_info
|
Additional statistics to compute and store in info dict.
See |
required | |
nan_policy
|
How to handle NaN values ("skip", "warn", "assert").
See |
required | |
inf_policy
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See |
required | |
percentiles
|
Percentile level(s) in [0, 100] to compute.
See |
required |
Returns:
| Name | Type | Description |
|---|---|---|
fano |
Fano factor values with shape [...]
(input shape without time dimension).
If |
|
info |
Dictionary with optional computed statistics and percentile data. |
Source code in btorch/analysis/spiking.py
fano_population(spike, 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 |
|---|---|---|---|
spike
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size for spike counting. If None, uses full duration T. |
None
|
overlap
|
int
|
Overlap between consecutive windows. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
fano_pop |
Single scalar Fano factor for the population. |
|
info |
Dictionary with 'window' and 'n_windows'. |
Source code in btorch/analysis/spiking.py
fano_sweep(spike, 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 |
|---|---|---|---|
spike
|
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
|
tuple[int, ...] | int | None
|
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 |
Fano factor values for each window size. Shape: [n_windows, ...] where n_windows depends on range. |
|
info |
Dictionary with 'window_sizes' array and 'window' spec. |
Examples:
>>> # Sweep window sizes 1 to 50
>>> fano_sweep(spike, window=50)
>>> # Sweep window sizes 10, 20, 30, ..., 100
>>> fano_sweep(spike, window=(10, 101, 10))
>>> # Sweep window sizes 20, 30, 40, 50
>>> fano_sweep(spike, window=(20, 51, 1))
Source code in btorch/analysis/spiking.py
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 | |
fano_temporal(spike, 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.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike
|
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
|
tuple[int, ...] | None
|
Axes to average across (e.g., trials). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
fano_temporal |
Fano factor values for each window. Shape: [n_windows, ...] |
|
info |
Dictionary with window boundaries. |
Source code in btorch/analysis/spiking.py
firing_rate(spikes, width=4, dt=None, axis=None)
¶
Smooth spikes into firing rates.
Supports input shapes like [T, ...]. If 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
|
axis
|
int | Sequence[int] | None
|
Axes to average over before smoothing. Can be int or tuple of ints. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
firing_rates |
Smoothed firing rates with same shape as input (minus averaged axes if axis is specified). |
Source code in btorch/analysis/spiking.py
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 | |
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 an array of 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.
Source code in btorch/analysis/metrics.py
isi_cv(spike_data, dt_ms=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 use_stats() and
use_percentiles() for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_data
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. Values are binary (0/1) or spike counts. |
required |
dt_ms
|
float
|
Time step in milliseconds for converting ISI to ms. |
1.0
|
batch_axis
|
tuple[int, ...] | int | None
|
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
|
stat
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See |
required | |
stat_info
|
Additional statistics to compute and store in info dict.
See |
required | |
nan_policy
|
How to handle NaN values ("skip", "warn", "assert").
See |
required | |
inf_policy
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See |
required | |
percentiles
|
Percentile level(s) in [0, 100] to compute.
See |
required |
Returns:
| Name | Type | Description |
|---|---|---|
cv_values |
CV values reshaped to match input without time dimension.
Shape: [...] (original shape without T, aggregated over batch_axis).
If |
|
info |
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(spike_data, dt_ms=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 use_stats() for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike_data
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. |
required |
dt_ms
|
float
|
Time step in milliseconds for converting ISI to ms. |
1.0
|
stat
|
Aggregation statistic to return. Default is "cv".
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See |
required | |
stat_info
|
Additional statistics to compute and store in info dict.
See |
required | |
nan_policy
|
How to handle NaN values ("skip", "warn", "assert").
See |
required | |
inf_policy
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See |
required |
Returns:
| Name | Type | Description |
|---|---|---|
cv_pop |
Single scalar CV value for the population, or aggregated
statistic if |
|
info |
Dictionary with computed statistics. |
Source code in btorch/analysis/spiking.py
kurtosis(spike, 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 use_stats() and
use_percentiles() for detailed usage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spike
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size 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
|
tuple[int, ...] | int | None
|
Axes to average across for kurtosis computation. |
None
|
stat
|
Aggregation statistic to return instead of per-neuron values.
Options: "mean", "median", "max", "min", "std", "var", "argmax",
"argmin", "cv". See |
required | |
stat_info
|
Additional statistics to compute and store in info dict.
See |
required | |
nan_policy
|
How to handle NaN values ("skip", "warn", "assert").
See |
required | |
inf_policy
|
How to handle Inf values ("propagate", "skip", "warn",
"assert"). See |
required | |
percentiles
|
Percentile level(s) in [0, 100] to compute.
See |
required |
Returns:
| Name | Type | Description |
|---|---|---|
kurt |
Kurtosis values with shape [...]
(input shape without time dimension).
If |
|
info |
Dictionary with optional computed statistics and percentile data. |
Source code in btorch/analysis/spiking.py
kurtosis_population(spike, 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 |
|---|---|---|---|
spike
|
ndarray | Tensor
|
Spike train of shape [T, ...]. First dimension is time. |
required |
window
|
int | None
|
Window size 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 |
Single scalar kurtosis for the population. |
|
info |
Dictionary with 'window' and 'n_windows'. |
Source code in btorch/analysis/spiking.py
local_variation(spike_data, dt_ms=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 |
|---|---|---|---|
spike_data
|
ndarray | Tensor
|
Spike train array of shape [T, ...]. First dimension is time. |
required |
dt_ms
|
float
|
Time step in milliseconds. |
1.0
|
batch_axis
|
tuple[int, ...] | None
|
Axes to aggregate ISIs across (e.g., (1, 2) for trials). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
lv_values |
LV values reshaped to match input without time dimension. |
|
lv_stats |
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.
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}_percentile"].
Can also accept a dict mapping return positions to labels for functions returning multiple values (e.g., {1: "eci", 3: "lag"}).
The decorated function should return either: - A tuple of (values, info_dict) where values are per-neuron metrics - Just the per-neuron values (will be wrapped in a tuple with empty dict) - A tuple of multiple values with info as the last element
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable | None
|
The function to decorate (or None if using with parentheses) |
None
|
value_key
|
str | dict[int, str]
|
Key to use in info dict for the percentile result |
'values'
|
Returns:
| Type | Description |
|---|---|
Callable
|
Decorated function with added percentiles parameter |
Example
@use_percentiles
def compute_metric(data, *, percentiles=None):
values = some_computation(data) # per-neuron values
return values, {"raw": values}
# Usage:
values, info = compute_metric(data) # no percentiles computed
values, info = compute_metric(data, percentiles=0.5) # compute median
values, info = compute_metric(
data, percentiles=(0.25, 0.5, 0.75)
) # compute quartiles
Source code in btorch/analysis/statistics.py
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 | |
use_stats(func=None, *, value_key='values', dim=None, default_stat=None, default_stat_info=None, default_nan_policy='skip', default_inf_policy='propagate')
¶
Decorator to add stat and stat_info args for aggregation.
This decorator adds stat, stat_info, nan_policy, and inf_policy
parameters to a function that returns per-neuron values.
stat: If not None, returns the aggregated value instead of per-neuron values. The aggregation is stored in info[f"{value_key}_stat"]. Can be a StatChoice, or a dict mapping return position to label (e.g., {1: "eci", 3: "lag"}) for functions returning multiple values.stat_info: Additional stats to compute and store in info dict without affecting the return value. Can be a single StatChoice, Iterable of StatChoice, a dict mapping position to label(s), or None. If dict, format is {position: stat_or_stats} where stat_or_stats can be a single StatChoice or Iterable of StatChoice.dim: Dimension(s) to aggregate over. Can be:- None: Flatten all dimensions (default)
- int: Aggregate over this dimension for all outputs
- tuple[int, ...]: Aggregate over these dimensions for all outputs
- dict[int, int | tuple[int, ...] | None]: Different dim for each output position (e.g., {0: 1, 1: 2, 2: None, 3: (1, 3, 4)})
nan_policy: How to handle NaN values:- "skip": Ignore NaN values (default)
- "warn": Warn if NaN values found but continue
- "assert": Raise error if NaN values found
inf_policy: How to handle Inf values:- "propagate": Keep Inf values (default)
- "skip": Ignore Inf values
- "warn": Warn if Inf values found but continue
- "assert": Raise error if Inf values found
The decorated function should return either: - A tuple of (values, info_dict) where values are per-neuron metrics - Just the per-neuron values (will be wrapped in a tuple with empty dict) - A tuple of multiple values with info as the last element
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
func
|
Callable | None
|
The function to decorate (or None if using with parentheses) |
None
|
value_key
|
str | dict[int, str]
|
Key prefix to use in info dict for stat results |
'values'
|
dim
|
int | tuple[int, ...] | dict[int, int | tuple[int, ...] | None] | None
|
Dimension(s) to aggregate over for each output |
None
|
default_nan_policy
|
Literal['skip', 'warn', 'assert']
|
Default nan_policy for this decorated function |
'skip'
|
default_inf_policy
|
Literal['propagate', 'skip', 'warn', 'assert']
|
Default inf_policy for this decorated function |
'propagate'
|
default_stat
|
StatChoice | dict[int, StatChoice] | None
|
Default stat for this decorated function |
None
|
Returns:
| Type | Description |
|---|---|
Callable
|
Decorated function with added stat, stat_info, nan_policy, and |
Callable
|
inf_policy parameters |
Example
@use_stat
def compute_metric(
data,
*,
stat=None,
stat_info=None,
nan_policy="skip",
inf_policy="propagate",
):
values = some_computation(data) # per-neuron values
return values, {"raw": values}
# Usage:
values, info = compute_metric(data) # returns per-neuron values
mean_val, info = compute_metric(data, stat="mean") # returns aggregated
values, info = compute_metric(
data, stat_info=["mean", "max"]
) # extra stats in info
# Multi-value return with dict stat:
@use_stat
def compute_multiple(data, *, stat=None, stat_info=None):
eci = compute_eci(data) # per-neuron
lag = compute_lag(data) # per-neuron
return eci, lag, {} # multiple values
# Aggregate specific positions with dict stat:
eci_mean, lag_mean, info = compute_multiple(
data, stat={0: "eci", 1: "lag"}
)
Source code in btorch/analysis/statistics.py
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 | |
voltage_overshoot(V, mode='threshold_resting', skip_timestep=None, **params)
¶
Quantify voltage stability/overshoot in different ways.