Skip to content

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
class HopDistanceModel:
    """Fast computation of hop distances in networks using BFS."""

    def __init__(
        self,
        edges: pd.DataFrame | None = None,
        adjacency: sparse.sparray | None = None,
        node_mapping: dict | None = None,
        source: str = "source",
        target: str = "target",
    ):
        if edges is None and adjacency is None:
            raise ValueError("Must provide either edges DataFrame or adjacency matrix")

        if adjacency is not None:
            self.adjacency = adjacency.tocsr()
            self.use_sparse = True
            if node_mapping is None:
                self.node_mapping = {i: i for i in range(adjacency.shape[0])}
                self.reverse_mapping = {i: i for i in range(adjacency.shape[0])}
            else:
                self.node_mapping = node_mapping
                self.reverse_mapping = {v: k for k, v in node_mapping.items()}
            self.n_nodes = adjacency.shape[0]
        else:
            self.edges = edges.copy()
            self.source = source
            self.target = target
            self.use_sparse = False

            for col in (source, target):
                if col not in edges.columns:
                    raise ValueError(f'edges must contain "{col}" column')

            all_nodes = np.unique(
                np.concatenate([edges[source].values, edges[target].values])
            )
            self.node_mapping = {node: idx for idx, node in enumerate(all_nodes)}
            self.reverse_mapping = {
                idx: node for node, idx in self.node_mapping.items()
            }
            self.n_nodes = len(all_nodes)

            self._build_adjacency_dict()

    def _build_adjacency_dict(self):
        """Build adjacency dictionary for fast neighbor lookup."""
        self.adj_dict = {}
        for _, row in self.edges.iterrows():
            src_idx = self.node_mapping[row[self.source]]
            tgt_idx = self.node_mapping[row[self.target]]

            if src_idx not in self.adj_dict:
                self.adj_dict[src_idx] = []
            self.adj_dict[src_idx].append(tgt_idx)

        for node in self.adj_dict:
            self.adj_dict[node] = np.array(self.adj_dict[node], dtype=np.int32)

    def compute_distances(
        self, seeds: list[int | str], max_hops: int | None = None
    ) -> pd.DataFrame:
        """Compute hop distances from seeds to all reachable nodes using
        BFS."""
        seed_indices = [self.node_mapping.get(seed, None) for seed in seeds]
        missing = [s for s in seeds if s not in self.node_mapping]
        if len(missing) != 0:
            warnings.warn(f"Seeds not found in network: {missing}", stacklevel=2)
            seed_indices = [s for s in seed_indices if s is not None]

        distances = np.full(self.n_nodes, -1, dtype=np.int32)
        predecessors = np.full(self.n_nodes, -1, dtype=np.int32)

        queue = deque()
        for seed_idx in seed_indices:
            distances[seed_idx] = 0
            predecessors[seed_idx] = seed_idx
            queue.append(seed_idx)

        while queue:
            current_idx = queue.popleft()
            current_dist = distances[current_idx]

            if max_hops is not None and current_dist >= max_hops:
                continue

            if self.use_sparse:
                neighbors = self.adjacency[[current_idx]].indices.flatten()
            else:
                neighbors = self.adj_dict.get(current_idx, np.array([], dtype=np.int32))

            for neighbor_idx in neighbors:
                if distances[neighbor_idx] == -1:
                    distances[neighbor_idx] = current_dist + 1
                    predecessors[neighbor_idx] = current_idx
                    queue.append(neighbor_idx)

        reachable_mask = distances >= 0
        result_nodes = [
            self.reverse_mapping[idx] for idx in np.where(reachable_mask)[0]
        ]
        result_distances = distances[reachable_mask]
        result_predecessors = [
            self.reverse_mapping[predecessors[idx]]
            for idx in np.where(reachable_mask)[0]
        ]

        return pd.DataFrame(
            {
                "node": result_nodes,
                "distance": result_distances,
                "predecessor": result_predecessors,
            }
        )

    def hop_statistics(
        self, seeds: list[int | str], max_hops: int | None = None
    ) -> pd.DataFrame:
        """Compute statistics about network reachability by hop distance."""
        distances_df = self.compute_distances(seeds, max_hops)

        if distances_df.empty:
            return pd.DataFrame(
                columns=[
                    "hops",
                    "nodes_count",
                    "nodes_percentage",
                    "cumulative_count",
                    "cumulative_percentage",
                ]
            )

        hop_counts = distances_df["distance"].value_counts().sort_index()

        stats = []
        cumulative = 0
        for hops in range(hop_counts.index.min(), hop_counts.index.max() + 1):
            count = hop_counts.get(hops, 0)
            cumulative += count

            stats.append(
                {
                    "hops": hops,
                    "nodes_count": count,
                    "nodes_percentage": 100.0 * count / self.n_nodes,
                    "cumulative_count": cumulative,
                    "cumulative_percentage": 100.0 * cumulative / self.n_nodes,
                }
            )

        return pd.DataFrame(stats)

    def reconstruct_path(
        self,
        source_node: int | str,
        target_node: int | str,
        distances_df: pd.DataFrame | None = None,
    ) -> list[int | str]:
        """Reconstruct shortest path from source to target using predecessor
        info."""
        if distances_df is None:
            distances_df = self.compute_distances([source_node])

        target_row = distances_df[distances_df["node"] == target_node]
        if target_row.empty:
            return []

        path = []
        current = target_node
        predecessors_dict = dict(zip(distances_df["node"], distances_df["predecessor"]))

        while current != source_node:
            path.append(current)
            if current not in predecessors_dict:
                return []
            current = predecessors_dict[current]

        path.append(source_node)
        return path[::-1]
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
def compute_distances(
    self, seeds: list[int | str], max_hops: int | None = None
) -> pd.DataFrame:
    """Compute hop distances from seeds to all reachable nodes using
    BFS."""
    seed_indices = [self.node_mapping.get(seed, None) for seed in seeds]
    missing = [s for s in seeds if s not in self.node_mapping]
    if len(missing) != 0:
        warnings.warn(f"Seeds not found in network: {missing}", stacklevel=2)
        seed_indices = [s for s in seed_indices if s is not None]

    distances = np.full(self.n_nodes, -1, dtype=np.int32)
    predecessors = np.full(self.n_nodes, -1, dtype=np.int32)

    queue = deque()
    for seed_idx in seed_indices:
        distances[seed_idx] = 0
        predecessors[seed_idx] = seed_idx
        queue.append(seed_idx)

    while queue:
        current_idx = queue.popleft()
        current_dist = distances[current_idx]

        if max_hops is not None and current_dist >= max_hops:
            continue

        if self.use_sparse:
            neighbors = self.adjacency[[current_idx]].indices.flatten()
        else:
            neighbors = self.adj_dict.get(current_idx, np.array([], dtype=np.int32))

        for neighbor_idx in neighbors:
            if distances[neighbor_idx] == -1:
                distances[neighbor_idx] = current_dist + 1
                predecessors[neighbor_idx] = current_idx
                queue.append(neighbor_idx)

    reachable_mask = distances >= 0
    result_nodes = [
        self.reverse_mapping[idx] for idx in np.where(reachable_mask)[0]
    ]
    result_distances = distances[reachable_mask]
    result_predecessors = [
        self.reverse_mapping[predecessors[idx]]
        for idx in np.where(reachable_mask)[0]
    ]

    return pd.DataFrame(
        {
            "node": result_nodes,
            "distance": result_distances,
            "predecessor": result_predecessors,
        }
    )
hop_statistics(seeds, max_hops=None)

Compute statistics about network reachability by hop distance.

Source code in btorch/analysis/connectivity.py
def hop_statistics(
    self, seeds: list[int | str], max_hops: int | None = None
) -> pd.DataFrame:
    """Compute statistics about network reachability by hop distance."""
    distances_df = self.compute_distances(seeds, max_hops)

    if distances_df.empty:
        return pd.DataFrame(
            columns=[
                "hops",
                "nodes_count",
                "nodes_percentage",
                "cumulative_count",
                "cumulative_percentage",
            ]
        )

    hop_counts = distances_df["distance"].value_counts().sort_index()

    stats = []
    cumulative = 0
    for hops in range(hop_counts.index.min(), hop_counts.index.max() + 1):
        count = hop_counts.get(hops, 0)
        cumulative += count

        stats.append(
            {
                "hops": hops,
                "nodes_count": count,
                "nodes_percentage": 100.0 * count / self.n_nodes,
                "cumulative_count": cumulative,
                "cumulative_percentage": 100.0 * cumulative / self.n_nodes,
            }
        )

    return pd.DataFrame(stats)
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
def reconstruct_path(
    self,
    source_node: int | str,
    target_node: int | str,
    distances_df: pd.DataFrame | None = None,
) -> list[int | str]:
    """Reconstruct shortest path from source to target using predecessor
    info."""
    if distances_df is None:
        distances_df = self.compute_distances([source_node])

    target_row = distances_df[distances_df["node"] == target_node]
    if target_row.empty:
        return []

    path = []
    current = target_node
    predecessors_dict = dict(zip(distances_df["node"], distances_df["predecessor"]))

    while current != source_node:
        path.append(current)
        if current not in predecessors_dict:
            return []
        current = predecessors_dict[current]

    path.append(source_node)
    return path[::-1]

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
def agg_by_neuron(
    y,
    neurons: pd.DataFrame,
    agg: AggName = "mean",
    neuron_type_column: str = "cell_type",
    **kwargs,
) -> dict:
    """Aggregate data by neuron type."""
    agg_func = getattr(np, agg) if isinstance(y, np.ndarray) else getattr(torch, agg)
    ret = {}
    for neuron_type, group in neurons.groupby(
        neuron_type_column, dropna=True, **kwargs
    ):
        ret[neuron_type] = agg_func(y[..., group.simple_id.to_numpy()], -1)
    return ret

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 mode="top_innervated" and neurons is None, if mode="all_innervated" and connections is None, or if mode is not one of the two supported values.

Source code in btorch/analysis/aggregation.py
def agg_by_neuropil(
    y,
    neurons: pd.DataFrame | None = None,
    connections: pd.DataFrame | None = None,
    mode: Literal["top_innervated", "all_innervated"] = "all_innervated",
    agg: AggName = "mean",
    use_polars: bool = False,
) -> tuple[dict, dict]:
    """Aggregate activations by neuropil under a validated aggregation mode.

    Raises:
        ValueError: If ``mode="top_innervated"`` and ``neurons`` is None, if
            ``mode="all_innervated"`` and ``connections`` is None, or if
            ``mode`` is not one of the two supported values.
    """
    agg_func = getattr(np, agg) if isinstance(y, np.ndarray) else getattr(torch, agg)
    if use_polars:
        # polars is an accelerator (``pip install "btorch[fast]"``): without it
        # the numpy/torch path below gives identical results, only slower.
        try:
            import polars as pl
        except ImportError:
            use_polars = False

    if mode == "top_innervated":
        if neurons is None:
            raise ValueError("neurons must be provided for top_innervated mode")
        tmp = neurons[["group", "simple_id"]].copy()
        tmp = tmp[tmp["simple_id"] < y.shape[-1]]
        pre_ret: dict = {}
        post_ret: dict = {}

        if use_polars:
            tmp["pre"] = tmp["group"].str.split(".").str[0]
            tmp["post"] = tmp["group"].str.split(".").str[-1]
            ptbl = pl.from_pandas(tmp)

            pre_groups = ptbl.group_by("pre", maintain_order=True).agg(
                pl.col("simple_id")
            )
            for row in pre_groups.iter_rows(named=True):
                sid = np.asarray(row["simple_id"], dtype=int)
                pre_ret[row["pre"]] = agg_func(y[..., sid], -1)

            post_groups = ptbl.group_by("post", maintain_order=True).agg(
                pl.col("simple_id")
            )
            for row in post_groups.iter_rows(named=True):
                sid = np.asarray(row["simple_id"], dtype=int)
                post_ret[row["post"]] = agg_func(y[..., sid], -1)
        else:
            tmp["pre"] = tmp["group"].apply(lambda x: x.split(".")[0])
            tmp["post"] = tmp["group"].apply(lambda x: x.split(".")[-1])
            for pre, group in tmp.groupby("pre", dropna=True):
                pre_ret[pre] = agg_func(y[..., group.simple_id], -1)
            for post, group in tmp.groupby("post", dropna=True):
                post_ret[post] = agg_func(y[..., group.simple_id], -1)
        return pre_ret, post_ret
    if mode == "all_innervated":
        if connections is None:
            raise ValueError("connections must be provided for all_innervated mode")
        tmp = connections[["pre_simple_id", "post_simple_id", "neuropil"]]
        tmp = tmp[
            (tmp["pre_simple_id"] < y.shape[-1]) & (tmp["post_simple_id"] < y.shape[-1])
        ]
        pre_ret: dict = {}
        post_ret: dict = {}

        if use_polars:
            ptbl = pl.from_pandas(tmp)
            groups = ptbl.group_by("neuropil", maintain_order=True).agg(
                pl.col("pre_simple_id"), pl.col("post_simple_id")
            )
            for row in groups.iter_rows(named=True):
                neuropil = row["neuropil"]
                pre_ids = np.asarray(row["pre_simple_id"], dtype=int)
                post_ids = np.asarray(row["post_simple_id"], dtype=int)
                pre_ret[neuropil] = agg_func(y[..., pre_ids], -1)
                post_ret[neuropil] = agg_func(y[..., post_ids], -1)
        else:
            for neuropil, group in tmp.groupby("neuropil", dropna=True):
                pre_ret[neuropil] = agg_func(y[..., group.pre_simple_id.to_numpy()], -1)
                post_ret[neuropil] = agg_func(
                    y[..., group.post_simple_id.to_numpy()], -1
                )
        return pre_ret, post_ret

    raise ValueError(
        "Invalid `mode` for `agg_by_neuropil`. "
        "Expected one of: {'top_innervated', 'all_innervated'}."
    )

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 mode="neuron" and neurons is None, or if mode is not "neuropil" or "neuron".

Source code in btorch/analysis/aggregation.py
def agg_conn(
    y,
    conn: pd.DataFrame,
    conn_weight: scipy.sparse.sparray | None = None,
    neurons: pd.DataFrame | None = None,
    mode: Literal["neuropil", "neuron"] = "neuron",
    neuron_type_column: str = "cell_type",
    agg: AggName = "mean",
) -> pd.Series:
    """Aggregate connectivity weights by neuropil or neuron-type pairs.

    Raises:
        ValueError: If ``mode="neuron"`` and ``neurons`` is None, or if
            ``mode`` is not ``"neuropil"`` or ``"neuron"``.
    """
    if conn_weight is not None:
        conn_weight = conn_weight.tocoo()
        conn = conn.merge(
            pd.DataFrame(
                {
                    "pre_simple_id": conn_weight.row,
                    "post_simple_id": conn_weight.col,
                    "weight": conn_weight.data,
                }
            ),
            how="left",
            on=["pre_simple_id", "post_simple_id"],
        )
    if mode == "neuropil":
        return conn.groupby("neuropil")["weight"].agg(agg)
    if mode == "neuron":
        if neurons is None:
            raise ValueError("neurons must be provided for neuron mode")
        conn = conn.merge(
            neurons[["simple_id", neuron_type_column]].rename(
                columns={
                    "simple_id": "pre_simple_id",
                    neuron_type_column: f"pre_{neuron_type_column}",
                }
            ),
            how="left",
            on="pre_simple_id",
        )
        conn = conn.merge(
            neurons[["simple_id", neuron_type_column]].rename(
                columns={
                    "simple_id": "post_simple_id",
                    neuron_type_column: f"post_{neuron_type_column}",
                }
            ),
            how="left",
            on="post_simple_id",
        )
        return conn.groupby(
            [f"pre_{neuron_type_column}", f"post_{neuron_type_column}"]
        )["weight"].agg(agg)

    raise ValueError(
        "Invalid `mode` for `agg_conn`. Expected one of: {'neuropil', 'neuron'}."
    )

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 [N] or [..., N] where the last axis is neuron. All leading dimensions are flattened into independent samples (e.g., trials, conditions, or time points).

required
neurons_df DataFrame

DataFrame containing at least simple_id_col and group_by.

required
group_by str

Column in neurons_df used as grouping key.

required
simple_id_col str

Column mapping rows in neurons_df to neuron index in values.

'simple_id'
value_name str

Name for the output value column.

'value'
dropna bool

Drop missing values in group/value columns when True.

True

Raises:

Type Description
ValueError

If values is 0-d; if simple_id_col or group_by is missing from neurons_df; if no neuron metadata remains after dropping missing groups; if simple_id_col has duplicates, is not numeric, or contains ids outside [0, N - 1]; or if no values remain after dropping missing entries.

Source code in btorch/analysis/aggregation.py
def build_group_frame(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    dropna: bool = True,
) -> pd.DataFrame:
    """Convert neuron-aligned values to a tidy frame for grouped analyses.

    Args:
        values: Array/tensor shaped `[N]` or `[..., N]` where the last axis is
            neuron. All leading dimensions are flattened into independent
            samples (e.g., trials, conditions, or time points).
        neurons_df: DataFrame containing at least `simple_id_col` and `group_by`.
        group_by: Column in `neurons_df` used as grouping key.
        simple_id_col: Column mapping rows in `neurons_df` to neuron index in
            `values`.
        value_name: Name for the output value column.
        dropna: Drop missing values in group/value columns when `True`.

    Raises:
        ValueError: If ``values`` is 0-d; if ``simple_id_col`` or ``group_by`` is
            missing from ``neurons_df``; if no neuron metadata remains after
            dropping missing groups; if ``simple_id_col`` has duplicates, is not
            numeric, or contains ids outside ``[0, N - 1]``; or if no values
            remain after dropping missing entries.
    """
    y = to_numpy(values, strict=True, name="values")
    if y.ndim < 1:
        raise ValueError("`values` must have at least one dimension.")

    if simple_id_col not in neurons_df.columns:
        raise ValueError(f"Missing `{simple_id_col}` in `neurons_df`.")
    if group_by not in neurons_df.columns:
        raise ValueError(f"Missing `{group_by}` in `neurons_df`.")

    metadata = neurons_df.loc[:, [simple_id_col, group_by]].copy()
    if dropna:
        metadata = metadata.dropna(subset=[group_by])
    if metadata.empty:
        raise ValueError("No neuron metadata available after filtering.")

    if metadata[simple_id_col].duplicated().any():
        raise ValueError(f"`{simple_id_col}` must be unique in `neurons_df`.")

    try:
        simple_ids = pd.to_numeric(metadata[simple_id_col], errors="raise").to_numpy(
            dtype=np.int64
        )
    except (ValueError, TypeError, OverflowError) as exc:
        raise ValueError(f"`{simple_id_col}` must be numeric.") from exc

    n_neurons = y.shape[-1]
    out_of_range = (simple_ids < 0) | (simple_ids >= n_neurons)
    if np.any(out_of_range):
        bad_ids = simple_ids[out_of_range]
        raise ValueError(
            f"Found `{simple_id_col}` outside [0, {n_neurons - 1}]: {bad_ids.tolist()}"
        )

    selected = y[..., simple_ids]
    n_samples = int(np.prod(selected.shape[:-1], dtype=np.int64))
    n_samples = max(1, n_samples)

    flattened = selected.reshape(n_samples, len(simple_ids))
    group_labels = metadata[group_by].to_numpy()

    frame = pd.DataFrame(
        {
            group_by: np.repeat(group_labels, n_samples),
            value_name: flattened.T.reshape(-1),
        }
    )

    if dropna:
        frame = frame.dropna(subset=[value_name])
    if frame.empty:
        raise ValueError("No values available after filtering.")

    return frame

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 x and y samples in result.

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 branching_ratio, naive_branching_ratio, k,

dict

r_k, stderr and fit metadata.

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
def compute_branching_ratio(
    all_counts: np.ndarray | list[np.ndarray] | list[list[float]] | str,
    k_max: int = 40,
    *,
    scatterpoints: bool = False,
    eps: float = 1e-12,
    ar1_fallback: bool = True,
) -> dict:
    """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

    Args:
        all_counts: One trial, stacked trials, list of trials, or path input.
        k_max: Maximum lag used for the MR fit.
        scatterpoints: Keep centered lagged ``x`` and ``y`` samples in result.
        eps: Small stabilizer for divisions and weights.
        ar1_fallback: Use AR(1) fallback when MR fit is ill-posed.

    Returns:
        Dictionary with ``branching_ratio``, ``naive_branching_ratio``, ``k``,
        ``r_k``, ``stderr`` and fit metadata.

    Raises:
        ValueError: If input data are invalid or too short.
        RuntimeError: If MR and fallback estimation both fail.
    """
    counts_list = input_handler(all_counts)

    k_max = int(max(2, k_max))

    shortest = min(len(c) for c in counts_list)
    max_possible = min(k_max, shortest - 1)
    if max_possible < 1:
        raise ValueError("Time series too short for branching-ratio estimation")

    k, r_k_raw, stderr_raw, data_length, mean_activity, xs, ys = compute_lagged_slopes(
        counts_list,
        max_possible + 1,
        scatterpoints=scatterpoints,
        eps=eps,
    )

    r_k = np.asarray(r_k_raw, dtype=np.float64)
    stderr = np.asarray(stderr_raw, dtype=np.float64)

    valid = np.isfinite(r_k) & np.isfinite(stderr) & (r_k > 0) & (stderr > 0)
    if np.sum(valid) < 2:
        if ar1_fallback:
            result = _ar1_fallback(counts_list, data_length, mean_activity, eps)
            if scatterpoints:
                result["xs"] = xs
                result["ys"] = ys
            return result
        raise RuntimeError("Insufficient valid r_k values for MR estimation")

    k_valid = k[valid].astype(np.float64)
    r_valid = np.clip(r_k[valid], 1e-12, 1e12)
    stderr_valid = stderr[valid]

    y = np.log(r_valid)
    w = 1.0 / (stderr_valid + eps)
    w = w / np.mean(w)

    slope, intercept = np.polyfit(k_valid, y, 1, w=w)
    m_hat = float(np.exp(slope))
    a_fit = float(np.exp(intercept))

    if not np.isfinite(m_hat) or m_hat <= 0:
        raise RuntimeError("Fitted branching ratio is non-positive or invalid")

    result = {
        "branching_ratio": m_hat,
        "a_fit": a_fit,
        "autocorrelationtime": float(-1.0 / np.log(m_hat))
        if (m_hat > 0 and m_hat != 1.0)
        else np.inf,
        "naive_branching_ratio": float(r_k[0]) if len(r_k) > 0 else np.nan,
        "k": k,
        "r_k": r_k,
        "stderr": stderr,
        "fit_slope": float(slope),
        "fit_intercept": float(intercept),
        "fit_points_used": int(np.sum(valid)),
        "data_length": data_length,
        "mean_activity": mean_activity,
    }
    if scatterpoints:
        result["xs"] = xs
        result["ys"] = ys
    return result

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 excitatory_neuron_only is True and neurons is None.

Source code in btorch/analysis/connectivity.py
def compute_ie_ratio(
    excitatory_mat: sparray,
    inhibitory_mat: sparray,
    excitatory_neuron_only: bool = True,
    neurons: pd.DataFrame | None = None,
    warn_strict: bool = True,
) -> tuple[float, np.ndarray]:
    """Compute inhibitory/excitatory ratio per neuron and whole-brain mean.

    Raises:
        ValueError: If ``excitatory_neuron_only`` is True and ``neurons`` is
            None.
    """
    if excitatory_neuron_only:
        if neurons is None:
            raise ValueError("`neurons` must be provided when excitatory_neuron_only")

    sum_inhibitory = inhibitory_mat.sum(axis=0).astype(float)
    sum_excitatory = excitatory_mat.sum(axis=0).astype(float)

    # neurons that have zero inputs from both e and i connections are likely input,
    # so don't warn on them
    input_indices = (sum_excitatory == 0) & (sum_inhibitory == 0)

    sum_excitatory[sum_excitatory == 0] = np.nan
    if excitatory_neuron_only:
        sum_excitatory[neurons[neurons.EI == "E"].simple_id.to_numpy()] = np.nan

    ie_ratios = sum_inhibitory / sum_excitatory

    if warn_strict:
        nan_indices = (np.isnan(ie_ratios) & ~input_indices).nonzero()[0]
        if nan_indices.size > 0:
            warnings.warn(
                f"IE ratio contains NaN values at indices {nan_indices}",
                stacklevel=2,
            )

        inf_indices = np.isinf(ie_ratios).nonzero()[0]
        if inf_indices.size > 0:
            warnings.warn(
                f"IE ratio contains Inf values at indices {inf_indices}",
                stacklevel=2,
            )

    ie_ratios = np.where(np.isinf(ie_ratios), np.nan, ie_ratios)
    ie_ratio_whole_brain: float = np.nanmean(ie_ratios[ie_ratios != 0])

    return ie_ratio_whole_brain, ie_ratios

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
def compute_log_hist(
    data: np.ndarray,
    bins: int = 1000,
    edge_pos: Literal["mid", "sep"] = "mid",
) -> tuple:
    """Compute histogram with logarithmically-spaced bins.

    Useful for visualizing heavy-tailed distributions like synaptic weights
    or degree distributions.

    Args:
        data: Input data array (must be positive).
        bins: Number of histogram bins.
        edge_pos: Position to return for bin edges.
            "mid": Return bin centers (midpoints).
            "sep": Return bin separators (edges).

    Returns:
        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:
        ValueError: If data contains non-positive values (required for log scale).
    """
    bin_edges = np.logspace(np.log10(np.min(data)), np.log10(np.max(data)), num=bins)
    hist, edges = np.histogram(data, bins=bin_edges)
    if edge_pos == "mid":
        bin_edges = 0.5 * (edges[:-1] + edges[1:])
    return hist, bin_edges

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
def compute_raster(
    sp_matrix: np.ndarray, times: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
    """Get spike raster plot which displays the spiking activity of a group of
    neurons over time."""
    times = np.asarray(times)
    elements = np.where(sp_matrix > 0.0)
    index = elements[1]
    time = times[elements[0]]
    return index, time

compute_spectrum(y, dt, nperseg=None)

Source code in btorch/analysis/spiking.py
def compute_spectrum(
    y: np.ndarray, dt: float, nperseg: int | None = None
) -> tuple[np.ndarray, np.ndarray]:
    from scipy.signal import welch

    freqs, Y_mag = welch(y, fs=1 / dt, nperseg=nperseg, axis=0)
    return freqs, Y_mag

compute_voltage_overshoot(V, mode='threshold_resting', skip_timestep=None, **params)

Quantify voltage stability/overshoot in different ways.

Raises:

Type Description
ValueError

If mode is not one of "std", "mse_threshold" or "threshold_resting".

KeyError

If a required threshold parameter (V_th, and V_reset for "threshold_resting") is missing from params.

Source code in btorch/analysis/voltage.py
def compute_voltage_overshoot(
    V: np.ndarray | torch.Tensor,
    mode: Literal["std", "mse_threshold", "threshold_resting"] = "threshold_resting",
    skip_timestep: int | None = None,
    **params: float,
) -> np.ndarray | torch.Tensor:
    """Quantify voltage stability/overshoot in different ways.

    Raises:
        ValueError: If ``mode`` is not one of ``"std"``, ``"mse_threshold"`` or
            ``"threshold_resting"``.
        KeyError: If a required threshold parameter (``V_th``, and ``V_reset``
            for ``"threshold_resting"``) is missing from ``params``.
    """
    is_numpy = isinstance(V, np.ndarray)
    V = V.astype(np.float32) if is_numpy else V.to(torch.float32)

    if skip_timestep is None:
        skip_timestep = suggest_skip_timestep(V)

    V_slice = V[skip_timestep:]
    if mode == "std":
        return V_slice.std(0)

    elif mode == "mse_threshold":
        V_th = params["V_th"]
        return (
            (V_slice - V_th).pow(2).mean(0)
            if not is_numpy
            else np.mean((V_slice - V_th) ** 2, axis=0)
        )

    elif mode == "threshold_resting":
        V_th = params["V_th"]
        V_reset = params["V_reset"]
        n_scale = params.get("n_scale", 3)

        scale = V_th - V_reset

        upper = V_th + n_scale * scale
        lower = V_reset - n_scale * scale

        mask = (V_slice > upper) | (V_slice < lower)
        return mask.astype(np.float32).mean(0) if is_numpy else mask.float().mean(0)

    else:
        raise ValueError(f"Unsupported mode: {mode}")

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values. See :func:~btorch.analysis.statistics.use_stats.

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
@use_stats(value_key="cv_temporal", dim=1)
def cv_temporal(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    window: int = 100,
    step: int = 1,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train array of shape [T, ...]. First dimension is time.
        dt: Time step in milliseconds.
        window: Size of the sliding window in time steps.
        step: Step size between consecutive windows.
        batch_axis: Axes to aggregate across (e.g., (1, 2) for trials).
        dtype: Data type for output arrays. If None, uses float64 for NumPy
            and float32 for Torch.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-window values.
            See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values.
            See :func:`~btorch.analysis.statistics.use_stats`.

    Returns:
        cv_temporal: CV values for each window. Shape: [n_windows, ...]
            where n_windows = (T - window) // step + 1.
        info: Dictionary with window boundaries.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)

    T = spikes.shape[0]
    n_windows = (T - window) // step + 1

    # Determine output dtype
    if isinstance(spikes, torch.Tensor):
        out_dtype = dtype if dtype is not None else torch.float32
        cv_values = torch.full(
            (n_windows,) + spikes.shape[1:],
            float("nan"),
            dtype=out_dtype,
            device=spikes.device,
        )
    else:
        out_dtype = dtype if dtype is not None else float
        cv_values = np.full((n_windows,) + spikes.shape[1:], np.nan, dtype=out_dtype)

    for i in range(n_windows):
        start = i * step
        end = start + window
        if end > T:
            break

        window_data = spikes[start:end]

        cv_window, _ = _cv(window_data, dt, batch_axis, dtype)
        cv_values[i] = cv_window

    window_starts = np.arange(n_windows) * step * dt
    window_ends = window_starts + window * dt

    info = {
        "window": window,
        "step": step,
        "window_starts_ms": window_starts,
        "window_ends_ms": window_ends,
    }
    return cv_values, info

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 mean, median, std, min, max,

dict[str, float]

q25, q50 and q75.

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
def describe_array(array: np.ndarray, verbose: bool = True) -> dict[str, float]:
    """Compute descriptive statistics for an array.

    Computes mean, median, std, min, max, and quartiles, optionally printing
    them.

    Args:
        array: NumPy array to describe (statistics are over all elements).
        verbose: If True (default), also print the statistics.

    Returns:
        Dictionary with keys ``mean``, ``median``, ``std``, ``min``, ``max``,
        ``q25``, ``q50`` and ``q75``.

    Example:
        >>> stats = describe_array(np.random.randn(100), verbose=False)
        >>> sorted(stats)
        ['max', 'mean', 'median', 'min', 'q25', 'q50', 'q75', 'std']
    """
    q25, q50, q75 = np.percentile(array, [25, 50, 75])  # q50 equals the median
    stats = {
        "mean": float(np.mean(array)),
        "median": float(np.median(array)),
        "std": float(np.std(array)),
        "min": float(np.min(array)),
        "max": float(np.max(array)),
        "q25": float(q25),
        "q50": float(q50),
        "q75": float(q75),
    }

    if verbose:
        print(f"Mean: {stats['mean']}")
        print(f"Median: {stats['median']}")
        print(f"Standard Deviation: {stats['std']}")
        print(f"Min: {stats['min']}")
        print(f"Max: {stats['max']}")
        print(f"25th Percentile (Q1): {stats['q25']}")
        print(f"50th Percentile (Q2/Median): {stats['q50']}")
        print(f"75th Percentile (Q3): {stats['q75']}")
    return stats

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

Returns:

Name Type Description
fano StatsResult

Fano factor values with shape [...] (input shape without time dimension). If stat is provided, returns the aggregated statistic instead.

info StatsResult

Dictionary with optional computed statistics and percentile data.

Source code in btorch/analysis/spiking.py
@use_percentiles(value_key="fano")
@use_stats(value_key="fano")
def fano(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses full duration T.
        overlap: Overlap between consecutive windows.
        batch_axis: Axes to average across for FF computation (e.g., trials).
        dtype: Data type for accumulation. If None, uses float64 for NumPy
            and input dtype (or float32 for float16/bfloat16) for Torch.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        fano: Fano factor values with shape [...]
            (input shape without time dimension).
            If `stat` is provided, returns the aggregated statistic instead.
        info: Dictionary with optional computed statistics and percentile data.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    if window is None:
        # Default window size to get ~10 bins for variance computation
        # Need at least 2 bins for valid variance with unbiased=True
        window = max(1, spikes.shape[0] // 10)
    if isinstance(spikes, torch.Tensor):
        return _fano_torch(spikes, window, overlap, batch_axis, dtype)
    else:
        return _fano_numpy(spikes, window, overlap, batch_axis, dtype)

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
def fano_population(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
) -> StatsResult:
    """Compute Fano factor for the pooled population activity.

    This computes Fano factor from the summed population spike count,
    giving a single population-level metric.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses full duration T.
        overlap: Overlap between consecutive windows.

    Returns:
        fano_pop: Single scalar Fano factor for the population.
        info: Dictionary with 'window' and 'n_windows'.
    """
    if isinstance(spikes, torch.Tensor):
        return _fano_population_torch(spikes, window, overlap)
    else:
        return _fano_population_numpy(spikes, window, overlap)

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 window is not an int or a 2/3-tuple, step is not positive, start is below 1, stop exceeds T + 1, or the range contains no window size.

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
def fano_sweep(
    spikes: np.ndarray | torch.Tensor,
    window: int | tuple[int, ...] | None = None,
    overlap: int = 0,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> tuple[np.ndarray | torch.Tensor, dict]:
    """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)

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: 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)
        overlap: Overlap between consecutive windows.
        batch_axis: Axes to average across (e.g., trials).
        dtype: Data type for output arrays. If None, uses float64 for NumPy
            and float32 for Torch.

    Returns:
        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.

    Raises:
        ValueError: If ``window`` is not an int or a 2/3-tuple, ``step`` is not
            positive, ``start`` is below 1, ``stop`` exceeds ``T + 1``, or the
            range contains no window size.

    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))
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    T = spikes.shape[0]

    # Parse window specification following arange semantics
    if window is None:
        start, stop, step = 1, T // 20 + 1, 1
    elif isinstance(window, int):
        start, stop, step = 1, window + 1, 1
    elif len(window) == 2:
        start, stop, step = window[0], window[1], 1
    elif len(window) == 3:
        start, stop, step = window[0], window[1], window[2]
    else:
        raise ValueError("window must be int, (start, stop), or (start, stop, step)")

    if step <= 0:
        raise ValueError("step must be positive")
    if start < 1:
        raise ValueError("start must be >= 1")
    if stop > T + 1:
        raise ValueError(f"stop must be <= T+1 ({T + 1})")

    window_sizes = np.arange(start, stop, step)
    n_windows = len(window_sizes)

    if n_windows == 0:
        raise ValueError("window range produces no valid window sizes")

    if isinstance(spikes, torch.Tensor):
        device = spikes.device
        out = torch.zeros(
            (n_windows,) + spikes.shape[1:], device=device, dtype=torch.float64
        )
        for i, w in enumerate(window_sizes):
            fano_val, _ = _fano_torch(spikes, int(w), overlap, batch_axis)
            out[i] = fano_val
    else:
        out = np.zeros((n_windows,) + spikes.shape[1:])
        for i, w in enumerate(window_sizes):
            fano_val, _ = _fano_numpy(spikes, int(w), overlap, batch_axis)
            out[i] = fano_val

    info = {
        "window": (start, stop, step),
        "window_sizes": window_sizes,
        "n_windows": n_windows,
    }
    return out, info

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values. See :func:~btorch.analysis.statistics.use_stats.

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
@use_stats(value_key="fano_temporal", dim=1)
def fano_temporal(
    spikes: np.ndarray | torch.Tensor,
    window: int = 100,
    step: int = 1,
    batch_axis: BatchAxis = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Size of the sliding window in time steps for Fano computation.
        step: Step size between consecutive windows.
        batch_axis: Axes to average across (e.g., trials).

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-window values.
            See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values.
            See :func:`~btorch.analysis.statistics.use_stats`.

    Returns:
        fano_temporal: Fano factor values for each window. Shape: [n_windows, ...]
        info: Dictionary with window boundaries.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    T = spikes.shape[0]
    n_windows = (T - window) // step + 1

    if isinstance(spikes, torch.Tensor):
        fano_values = torch.full(
            (n_windows,) + spikes.shape[1:],
            float("nan"),
            dtype=torch.float64,
            device=spikes.device,
        )
    else:
        fano_values = np.full((n_windows,) + spikes.shape[1:], np.nan, dtype=float)

    for i in range(n_windows):
        start = i * step
        end = start + window
        if end > T:
            break

        window_data = spikes[start:end]
        bin = max(1, window_data.shape[0] // 10)

        if isinstance(window_data, torch.Tensor):
            fano_window, _ = _fano_torch(window_data, bin, 0, batch_axis)
            fano_values[i] = fano_window
        else:
            fano_window, _ = _fano_numpy(window_data, bin, 0, batch_axis)
            fano_values[i] = fano_window

    window_starts = np.arange(n_windows) * step
    window_ends = window_starts + window

    info = {
        "window": window,
        "step": step,
        "window_starts": window_starts,
        "window_ends": window_ends,
    }
    return fano_values, info

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
def firing_rate(
    spikes: np.ndarray | torch.Tensor,
    width: int | float | None = 4,
    dt: int | float | None = None,
    batch_axis: BatchAxis = None,
) -> np.ndarray | torch.Tensor:
    """Smooth spikes into firing rates.

    Supports input shapes like [T, ...].
    If batch_axis is not None, averages over the specified dimensions before
    smoothing.

    Args:
        spikes: Spike train array of shape [T, ...].
        width: Smoothing window width. If None or 0, no smoothing is applied.
        dt: Time step in milliseconds. If None, defaults to 1.0.
        batch_axis: Axes to average over before smoothing (e.g., neurons or
            trials). Can be int or tuple of ints.

    Returns:
        firing_rates: Smoothed firing rates with same shape as input (minus
            averaged axes if batch_axis is specified).
    """
    if dt is None:
        dt = 1.0

    if batch_axis is not None:
        # Normalize to a tuple for consistent handling
        if isinstance(batch_axis, int):
            batch_axis = (batch_axis,)
        if isinstance(spikes, np.ndarray):
            spikes = spikes.mean(axis=tuple(batch_axis))
        else:
            spikes = spikes.mean(dim=tuple(batch_axis))

    if width is None or width == 0:
        return spikes / dt

    width1 = int(width // 2) * 2 + 1

    if isinstance(spikes, np.ndarray):
        if spikes.dtype == np.float16:
            spikes = spikes.astype(np.float32)
        window = np.ones(width1, dtype=float) / width1
        # Convolve along time axis (0) for all other dimensions
        out = convolve1d(spikes, window, axis=0, mode="constant", cval=0.0)
        return out / dt

    else:
        # torch implementation for arbitrary dimensions [T, *others]
        orig_shape = spikes.shape
        T = orig_shape[0]

        # Flatten others to treat as batches for conv1d: [T, B] -> [B, 1, T]
        x = spikes.reshape(T, -1).T.unsqueeze(1)

        window = torch.ones(width1, device=spikes.device, dtype=spikes.dtype) / width1
        weight = window.view(1, 1, -1)

        y = torch.conv1d(x, weight, padding="same")

        # [B, 1, T] -> [B, T] -> [T, B] -> [T, *others]
        return y.squeeze(1).T.reshape(orig_shape) / dt

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
def group_ecdf(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
) -> dict[object, pd.DataFrame]:
    """Compute grouped ECDF points ready for plotting or analysis."""
    grouped = group_values(
        values,
        neurons_df,
        group_by,
        simple_id_col=simple_id_col,
        value_name=value_name,
        group_order=group_order,
        dropna=dropna,
    )

    ret: dict[object, pd.DataFrame] = {}
    for group, vals in grouped.items():
        x = np.sort(vals)
        y = np.arange(1, len(x) + 1, dtype=float) / len(x)
        ret[group] = pd.DataFrame({value_name: x, "ecdf": y})
    return ret

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
def group_summary(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
) -> pd.DataFrame:
    """Compute per-group summary statistics from neuron-aligned values."""
    grouped = group_values(
        values,
        neurons_df,
        group_by,
        simple_id_col=simple_id_col,
        value_name=value_name,
        group_order=group_order,
        dropna=dropna,
    )

    rows = []
    for group, vals in grouped.items():
        rows.append(
            {
                group_by: group,
                "n": int(vals.size),
                "mean": float(np.mean(vals)),
                "std": float(np.std(vals)),
                "min": float(np.min(vals)),
                "q25": float(np.quantile(vals, 0.25)),
                "median": float(np.median(vals)),
                "q75": float(np.quantile(vals, 0.75)),
                "max": float(np.max(vals)),
            }
        )

    return pd.DataFrame(rows)

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
def group_values(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
) -> dict[object, np.ndarray]:
    """Return grouped value arrays, keyed by group label in plotting order."""
    frame = build_group_frame(
        values,
        neurons_df,
        group_by,
        simple_id_col=simple_id_col,
        value_name=value_name,
        dropna=dropna,
    )
    order = _resolve_group_order(frame, group_by, group_order)
    return {
        group: frame.loc[frame[group_by] == group, value_name].to_numpy(dtype=float)
        for group in order
    }

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 ndim > 1 masks) or a tuple of per-axis index arrays.

required
shape tuple[int, ...] | None

Shape of the mask. Takes precedence over array.

None
array ndarray | None

Array whose shape is used when shape is not given.

None

Returns:

Type Description
ndarray

Boolean array that is True at indices.

Raises:

Type Description
ValueError

If neither shape nor array is given.

Source code in btorch/analysis/metrics.py
def indices_to_mask(
    indices: np.ndarray | tuple[np.ndarray, ...],
    shape: tuple[int, ...] | None = None,
    array: np.ndarray | None = None,
) -> np.ndarray:
    """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`).

    Args:
        indices: Index array (flat indices for ``ndim > 1`` masks) or a tuple
            of per-axis index arrays.
        shape: Shape of the mask. Takes precedence over ``array``.
        array: Array whose shape is used when ``shape`` is not given.

    Returns:
        Boolean array that is ``True`` at ``indices``.

    Raises:
        ValueError: If neither ``shape`` nor ``array`` is given.
    """
    if shape is None and array is None:
        raise ValueError("Either `shape` or `array` must be provided")
    mask = (
        np.zeros(shape, dtype=bool)
        if shape is not None
        else np.zeros_like(array, dtype=bool)
    )
    indices_arr = np.asarray(indices)
    if mask.ndim > 1 and indices_arr.ndim == 1 and not isinstance(indices, tuple):
        mask.flat[indices_arr] = True
    else:
        mask[indices] = True
    return mask

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

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 stat is provided, returns the aggregated statistic instead.

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
@use_percentiles(value_key="cv")
@use_stats(value_key="cv")
def isi_cv(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train array of shape [T, ...]. First dimension is time.
            Values are binary (0/1) or spike counts.
        dt: Time step in milliseconds for converting ISI to ms.
        batch_axis: Axes to aggregate ISIs across (e.g., (1, 2) for trials).
            If None, computes CV per element in the non-time dimensions.
        dtype: Data type for accumulation.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        cv_values: CV values reshaped to match input without time dimension.
            Shape: [...] (original shape without T, aggregated over batch_axis).
            If `stat` is provided, returns the aggregated statistic instead.
        info: Dictionary with 'isi_total' (aggregate ISI statistics),
            'isi_stats' (per-neuron statistics), and optional percentile data.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    return _cv(spikes, dt, batch_axis, dtype)

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

Returns:

Type Description
StatsResult

A (value, info) tuple. With the default stat="cv", value

StatsResult

is the scalar population CV of the pooled ISIs (NaN when the

StatsResult

population emitted fewer than two spikes). With stat=None it is

StatsResult

the raw pooled ISI array in units of dt (empty for fewer than two

StatsResult

spikes); any other stat aggregates that array. info holds the

StatsResult

pooled ISIs under "isi_population" and the aggregate under

StatsResult

"isi_population_<stat>".

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
@use_stats(value_key="isi_population", default_stat="cv")
def isi_cv_population(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train array of shape [T, ...]. First dimension is time.
        dt: Time step in milliseconds for converting ISI to ms.

    Keyword Args:
        stat (str | None): Aggregation statistic to return. Default is "cv".
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.

    Returns:
        A ``(value, info)`` tuple. With the default ``stat="cv"``, ``value``
        is the scalar population CV of the pooled ISIs (NaN when the
        population emitted fewer than two spikes). With ``stat=None`` it is
        the raw pooled ISI array in units of ``dt`` (empty for fewer than two
        spikes); any other ``stat`` aggregates that array. ``info`` holds the
        pooled ISIs under ``"isi_population"`` and the aggregate under
        ``"isi_population_<stat>"``.

    Notes:
        ``cv`` follows the backend convention of
        :func:`~btorch.analysis.statistics.compute_stats_batch` (NumPy:
        population std, Torch: unbiased std).
    """
    if isinstance(spikes, torch.Tensor):
        return _isis_population_torch(spikes, dt)
    else:
        return _isis_population_numpy(spikes, dt)

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

Returns:

Name Type Description
kurt StatsResult

Kurtosis values with shape [...] (input shape without time dimension). If stat is provided, returns the aggregated statistic instead.

info StatsResult

Dictionary with optional computed statistics and percentile data.

Source code in btorch/analysis/spiking.py
@use_percentiles(value_key="kurtosis")
@use_stats(value_key="kurtosis")
def kurtosis(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
    fisher: bool = True,
    batch_axis: BatchAxis = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses full duration T.
        overlap: Overlap between consecutive windows.
        fisher: If True, return excess kurtosis (subtract 3).
        batch_axis: Axes to average across for kurtosis computation.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        kurt: Kurtosis values with shape [...]
            (input shape without time dimension).
            If `stat` is provided, returns the aggregated statistic instead.
        info: Dictionary with optional computed statistics and percentile data.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    if window is None:
        # Default window size to get ~10 bins for variance computation
        # Need at least 2 bins for valid variance with unbiased=True
        window = max(1, spikes.shape[0] // 10)
    if isinstance(spikes, torch.Tensor):
        return _kurtosis_torch(spikes, window, overlap, fisher, batch_axis)
    else:
        return _kurtosis_numpy(spikes, window, overlap, fisher, batch_axis)

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
def kurtosis_population(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
    fisher: bool = True,
) -> StatsResult:
    """Compute kurtosis for the pooled population activity.

    This computes kurtosis from the summed population spike count,
    giving a single population-level metric.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses full duration T.
        overlap: Overlap between consecutive windows.
        fisher: If True, return excess kurtosis (subtract 3).

    Returns:
        kurt_pop: Single scalar kurtosis for the population.
        info: Dictionary with 'window' and 'n_windows'.
    """
    if isinstance(spikes, torch.Tensor):
        return _kurtosis_population_torch(spikes, window, overlap, fisher)
    else:
        return _kurtosis_population_numpy(spikes, window, overlap, fisher)

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values. See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

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(value_key="lv")
@use_stats(value_key="lv")
def local_variation(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    batch_axis: BatchAxis = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train array of shape [T, ...]. First dimension is time.
        dt: Time step in milliseconds.
        batch_axis: Axes to aggregate ISIs across (e.g., (1, 2) for trials).

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values.
            See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        lv_values: LV values reshaped to match input without time dimension.
        lv_stats: Dictionary with per-neuron LV statistics.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    if isinstance(spikes, torch.Tensor):
        return _lv_torch(spikes, dt, batch_axis)
    else:
        return _lv_numpy(spikes, dt, batch_axis)

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 "topk"; an optional cap, sampled at random, for "any").

None
mode Literal['topk', 'any']

"topk" selects the num largest entries, "any" the non-zero entries.

'topk'
ret_indices bool

If True, return (indices, mask) instead of indices.

False

Returns:

Type Description
ndarray | tuple[ndarray, ndarray]

Selected neuron indices, or (indices, mask) if ret_indices.

Raises:

Type Description
ValueError

If mode is unsupported or num is missing for "topk".

Source code in btorch/analysis/metrics.py
def select_on_metric(
    metrics: np.ndarray,
    num: int | None = None,
    mode: Literal["topk", "any"] = "topk",
    ret_indices: bool = False,
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
    """Select neurons based on a metric array.

    Args:
        metrics: 1D per-neuron metric.
        num: Number of neurons to select (required for ``"topk"``; an optional
            cap, sampled at random, for ``"any"``).
        mode: ``"topk"`` selects the ``num`` largest entries, ``"any"`` the
            non-zero entries.
        ret_indices: If True, return ``(indices, mask)`` instead of indices.

    Returns:
        Selected neuron indices, or ``(indices, mask)`` if ``ret_indices``.

    Raises:
        ValueError: If ``mode`` is unsupported or ``num`` is missing for
            ``"topk"``.
    """
    if mode == "topk":
        if num is None:
            raise ValueError("`num` must be provided when mode is 'topk'")
        ret = np.argpartition(metrics, -num)[-num:]
    elif mode == "any":
        ret = metrics.nonzero()[0]
        if num is not None and len(ret) > num:
            ret = np.random.choice(ret, num, replace=False)
    else:
        raise ValueError(f"Unsupported mode {mode}")

    if ret_indices:
        return ret, indices_to_mask(ret, array=metrics)
    else:
        return ret

suggest_skip_timestep(data)

Suggest a burn-in period based on trace length.

Source code in btorch/analysis/voltage.py
def suggest_skip_timestep(data: np.ndarray | torch.Tensor) -> int:
    """Suggest a burn-in period based on trace length."""
    skip_timestep = data.shape[0] // 8
    if skip_timestep < 100:
        skip_timestep = 0
    if skip_timestep > 1000:
        skip_timestep = 1000
    return skip_timestep

use_percentiles(func=None, /, *, value_key='values', default_percentiles=None)

use_percentiles(
    func: Callable[..., Any],
) -> PercentilesDecorated
use_percentiles(
    func: None = None,
    /,
    *,
    value_key: str | dict[int, str] = ...,
    default_percentiles: float
    | tuple[float, ...]
    | None = ...,
) -> Callable[[Callable[..., Any]], PercentilesDecorated]

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
def use_percentiles(
    func: Callable[..., Any] | None = None,
    /,
    *,
    value_key: str | dict[int, str] = "values",
    default_percentiles: float | tuple[float, ...] | None = None,
) -> PercentilesDecorated | Callable[[Callable[..., Any]], PercentilesDecorated]:
    """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

    Args:
        func: The function to decorate (or None if using with parentheses)
        value_key: Key to use in info dict for the percentile result
        default_percentiles: Percentiles used when the caller passes none.

    Returns:
        Decorated function with added percentiles parameter

    Example:
        ```python
        @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
        ```
    """

    def decorator(f: Callable[..., Any]) -> PercentilesDecorated:
        @wraps(f)
        def wrapper(
            *args: Any,
            percentiles: PercentileSpec = default_percentiles,
            **kwargs: Any,
        ) -> tuple[Any, ...]:
            result = f(*args, **kwargs)
            if percentiles is None:
                return result

            values_tuple, info = _unpack_result(result, value_key)
            outputs = _Outputs(values_tuple, value_key)
            updated_info = dict(info or {})

            # Resolve ``{position: (info key prefix, percentile levels)}``.
            if isinstance(percentiles, dict):
                # Different percentiles for different return values
                targets = {
                    pos: (_percentile_key(value_key, pos), levels)
                    for pos, levels in percentiles.items()
                }
            elif isinstance(value_key, dict):
                # One percentiles value applied to every labelled output
                targets = {
                    pos: (label, percentiles) for pos, label in value_key.items()
                }
            else:
                targets = {0: (value_key, percentiles)}

            for pos, (key_name, levels) in targets.items():
                perc = compute_percentiles(outputs.get(pos), levels)
                updated_info[f"{key_name}_percentiles"] = perc["percentiles"]
                updated_info[f"{key_name}_levels"] = perc["levels"]

            return (*values_tuple, updated_info)

        return wrapper

    if func is None:
        return decorator
    return decorator(func)

use_stats(func=None, /, *, value_key='values', dim=None, default_stat=None, default_stat_info=None, default_nan_policy='skip', default_inf_policy='propagate')

use_stats(func: Callable[..., Any]) -> StatsDecorated
use_stats(
    func: None = None,
    /,
    *,
    value_key: str | dict[int, str] = ...,
    dim: DimSpec = ...,
    default_stat: StatSpec = ...,
    default_stat_info: StatInfoSpec = ...,
    default_nan_policy: NanPolicy = ...,
    default_inf_policy: InfPolicy = ...,
) -> Callable[[Callable[..., Any]], StatsDecorated]

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
def use_stats(
    func: Callable[..., Any] | None = None,
    /,
    *,
    value_key: str | dict[int, str] = "values",
    dim: DimSpec = None,
    default_stat: StatSpec = None,
    default_stat_info: StatInfoSpec = None,
    default_nan_policy: NanPolicy = "skip",
    default_inf_policy: InfPolicy = "propagate",
) -> StatsDecorated | Callable[[Callable[..., Any]], StatsDecorated]:
    """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

    Args:
        func: The function to decorate (or None if using with parentheses)
        value_key: Key prefix to use in info dict for stat results
        dim: Dimension(s) to aggregate over for each output
        default_nan_policy: Default nan_policy for this decorated function
        default_inf_policy: Default inf_policy for this decorated function
        default_stat: Default stat for this decorated function
        default_stat_info: Default stat_info for this decorated function

    Returns:
        Decorated function with added stat, stat_info, nan_policy, and
        inf_policy parameters

    Example:
        ```python
        @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"}
        )
        ```
    """

    def decorator(f: Callable[..., Any]) -> StatsDecorated:
        # Inspect the wrapped function to determine what arguments it accepts
        sig = inspect.signature(f)
        f_accepts_nan_policy = "nan_policy" in sig.parameters
        f_accepts_inf_policy = "inf_policy" in sig.parameters

        @wraps(f)
        def wrapper(
            *args: Any,
            stat: StatSpec = default_stat,
            stat_info: StatInfoSpec = default_stat_info,
            nan_policy: NanPolicy | None = None,
            inf_policy: InfPolicy | None = None,
            **kwargs: Any,
        ) -> tuple[Any, ...]:
            # Use effective policies (passed value > decorator default)
            nan_pol = nan_policy if nan_policy is not None else default_nan_policy
            inf_pol = inf_policy if inf_policy is not None else default_inf_policy
            policies = {"nan_policy": nan_pol, "inf_policy": inf_pol}

            # Pass policies to the wrapped function if it accepts them
            if f_accepts_nan_policy:
                kwargs["nan_policy"] = nan_pol
            if f_accepts_inf_policy:
                kwargs["inf_policy"] = inf_pol

            values_tuple, info = _unpack_result(f(*args, **kwargs), value_key)
            outputs = _Outputs(values_tuple, value_key, dim)
            updated_info = dict(info or {})

            if stat is not None:
                # A single stat applies to output 0; a dict maps position->stat.
                stat_map = stat if isinstance(stat, dict) else {0: stat}
                aggregated = []
                for pos, choice in stat_map.items():
                    values = outputs.get(pos)
                    key_name = outputs.key(pos)
                    stat_value = compute_stat(
                        values, choice, dim=outputs.dim_for(pos), **policies
                    )
                    aggregated.append(stat_value)
                    updated_info[key_name] = values
                    updated_info[f"{key_name}_{choice}"] = stat_value
                return (*aggregated, updated_info)

            if stat_info is not None:
                # A bare spec applies to output 0; a dict maps position->spec.
                info_map = stat_info if isinstance(stat_info, dict) else {0: stat_info}
                for pos, spec in info_map.items():
                    names = [spec] if isinstance(spec, str) else list(spec)
                    key_name = outputs.key(pos)
                    batch = compute_stats_batch(
                        outputs.get(pos), names, dim=outputs.dim_for(pos), **policies
                    )
                    for name in names:
                        updated_info[f"{key_name}_{name}"] = batch[str(name)]

            # Original values with the (possibly extended) info
            return (*values_tuple, updated_info)

        return wrapper

    if func is None:
        return decorator
    return decorator(func)

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
def _resolve_group_order(
    frame: pd.DataFrame,
    group_by: str,
    group_order: Sequence | None,
) -> list[object]:
    if group_order is None:
        return list(pd.unique(frame[group_by]))

    requested = list(group_order)
    available = set(frame[group_by].tolist())
    missing = [group for group in requested if group not in available]
    if missing:
        raise ValueError(f"`group_order` contains unknown groups: {missing}")
    return requested

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
def agg_by_neuron(
    y,
    neurons: pd.DataFrame,
    agg: AggName = "mean",
    neuron_type_column: str = "cell_type",
    **kwargs,
) -> dict:
    """Aggregate data by neuron type."""
    agg_func = getattr(np, agg) if isinstance(y, np.ndarray) else getattr(torch, agg)
    ret = {}
    for neuron_type, group in neurons.groupby(
        neuron_type_column, dropna=True, **kwargs
    ):
        ret[neuron_type] = agg_func(y[..., group.simple_id.to_numpy()], -1)
    return ret

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 mode="top_innervated" and neurons is None, if mode="all_innervated" and connections is None, or if mode is not one of the two supported values.

Source code in btorch/analysis/aggregation.py
def agg_by_neuropil(
    y,
    neurons: pd.DataFrame | None = None,
    connections: pd.DataFrame | None = None,
    mode: Literal["top_innervated", "all_innervated"] = "all_innervated",
    agg: AggName = "mean",
    use_polars: bool = False,
) -> tuple[dict, dict]:
    """Aggregate activations by neuropil under a validated aggregation mode.

    Raises:
        ValueError: If ``mode="top_innervated"`` and ``neurons`` is None, if
            ``mode="all_innervated"`` and ``connections`` is None, or if
            ``mode`` is not one of the two supported values.
    """
    agg_func = getattr(np, agg) if isinstance(y, np.ndarray) else getattr(torch, agg)
    if use_polars:
        # polars is an accelerator (``pip install "btorch[fast]"``): without it
        # the numpy/torch path below gives identical results, only slower.
        try:
            import polars as pl
        except ImportError:
            use_polars = False

    if mode == "top_innervated":
        if neurons is None:
            raise ValueError("neurons must be provided for top_innervated mode")
        tmp = neurons[["group", "simple_id"]].copy()
        tmp = tmp[tmp["simple_id"] < y.shape[-1]]
        pre_ret: dict = {}
        post_ret: dict = {}

        if use_polars:
            tmp["pre"] = tmp["group"].str.split(".").str[0]
            tmp["post"] = tmp["group"].str.split(".").str[-1]
            ptbl = pl.from_pandas(tmp)

            pre_groups = ptbl.group_by("pre", maintain_order=True).agg(
                pl.col("simple_id")
            )
            for row in pre_groups.iter_rows(named=True):
                sid = np.asarray(row["simple_id"], dtype=int)
                pre_ret[row["pre"]] = agg_func(y[..., sid], -1)

            post_groups = ptbl.group_by("post", maintain_order=True).agg(
                pl.col("simple_id")
            )
            for row in post_groups.iter_rows(named=True):
                sid = np.asarray(row["simple_id"], dtype=int)
                post_ret[row["post"]] = agg_func(y[..., sid], -1)
        else:
            tmp["pre"] = tmp["group"].apply(lambda x: x.split(".")[0])
            tmp["post"] = tmp["group"].apply(lambda x: x.split(".")[-1])
            for pre, group in tmp.groupby("pre", dropna=True):
                pre_ret[pre] = agg_func(y[..., group.simple_id], -1)
            for post, group in tmp.groupby("post", dropna=True):
                post_ret[post] = agg_func(y[..., group.simple_id], -1)
        return pre_ret, post_ret
    if mode == "all_innervated":
        if connections is None:
            raise ValueError("connections must be provided for all_innervated mode")
        tmp = connections[["pre_simple_id", "post_simple_id", "neuropil"]]
        tmp = tmp[
            (tmp["pre_simple_id"] < y.shape[-1]) & (tmp["post_simple_id"] < y.shape[-1])
        ]
        pre_ret: dict = {}
        post_ret: dict = {}

        if use_polars:
            ptbl = pl.from_pandas(tmp)
            groups = ptbl.group_by("neuropil", maintain_order=True).agg(
                pl.col("pre_simple_id"), pl.col("post_simple_id")
            )
            for row in groups.iter_rows(named=True):
                neuropil = row["neuropil"]
                pre_ids = np.asarray(row["pre_simple_id"], dtype=int)
                post_ids = np.asarray(row["post_simple_id"], dtype=int)
                pre_ret[neuropil] = agg_func(y[..., pre_ids], -1)
                post_ret[neuropil] = agg_func(y[..., post_ids], -1)
        else:
            for neuropil, group in tmp.groupby("neuropil", dropna=True):
                pre_ret[neuropil] = agg_func(y[..., group.pre_simple_id.to_numpy()], -1)
                post_ret[neuropil] = agg_func(
                    y[..., group.post_simple_id.to_numpy()], -1
                )
        return pre_ret, post_ret

    raise ValueError(
        "Invalid `mode` for `agg_by_neuropil`. "
        "Expected one of: {'top_innervated', 'all_innervated'}."
    )

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 mode="neuron" and neurons is None, or if mode is not "neuropil" or "neuron".

Source code in btorch/analysis/aggregation.py
def agg_conn(
    y,
    conn: pd.DataFrame,
    conn_weight: scipy.sparse.sparray | None = None,
    neurons: pd.DataFrame | None = None,
    mode: Literal["neuropil", "neuron"] = "neuron",
    neuron_type_column: str = "cell_type",
    agg: AggName = "mean",
) -> pd.Series:
    """Aggregate connectivity weights by neuropil or neuron-type pairs.

    Raises:
        ValueError: If ``mode="neuron"`` and ``neurons`` is None, or if
            ``mode`` is not ``"neuropil"`` or ``"neuron"``.
    """
    if conn_weight is not None:
        conn_weight = conn_weight.tocoo()
        conn = conn.merge(
            pd.DataFrame(
                {
                    "pre_simple_id": conn_weight.row,
                    "post_simple_id": conn_weight.col,
                    "weight": conn_weight.data,
                }
            ),
            how="left",
            on=["pre_simple_id", "post_simple_id"],
        )
    if mode == "neuropil":
        return conn.groupby("neuropil")["weight"].agg(agg)
    if mode == "neuron":
        if neurons is None:
            raise ValueError("neurons must be provided for neuron mode")
        conn = conn.merge(
            neurons[["simple_id", neuron_type_column]].rename(
                columns={
                    "simple_id": "pre_simple_id",
                    neuron_type_column: f"pre_{neuron_type_column}",
                }
            ),
            how="left",
            on="pre_simple_id",
        )
        conn = conn.merge(
            neurons[["simple_id", neuron_type_column]].rename(
                columns={
                    "simple_id": "post_simple_id",
                    neuron_type_column: f"post_{neuron_type_column}",
                }
            ),
            how="left",
            on="post_simple_id",
        )
        return conn.groupby(
            [f"pre_{neuron_type_column}", f"post_{neuron_type_column}"]
        )["weight"].agg(agg)

    raise ValueError(
        "Invalid `mode` for `agg_conn`. Expected one of: {'neuropil', 'neuron'}."
    )

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 [N] or [..., N] where the last axis is neuron. All leading dimensions are flattened into independent samples (e.g., trials, conditions, or time points).

required
neurons_df DataFrame

DataFrame containing at least simple_id_col and group_by.

required
group_by str

Column in neurons_df used as grouping key.

required
simple_id_col str

Column mapping rows in neurons_df to neuron index in values.

'simple_id'
value_name str

Name for the output value column.

'value'
dropna bool

Drop missing values in group/value columns when True.

True

Raises:

Type Description
ValueError

If values is 0-d; if simple_id_col or group_by is missing from neurons_df; if no neuron metadata remains after dropping missing groups; if simple_id_col has duplicates, is not numeric, or contains ids outside [0, N - 1]; or if no values remain after dropping missing entries.

Source code in btorch/analysis/aggregation.py
def build_group_frame(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    dropna: bool = True,
) -> pd.DataFrame:
    """Convert neuron-aligned values to a tidy frame for grouped analyses.

    Args:
        values: Array/tensor shaped `[N]` or `[..., N]` where the last axis is
            neuron. All leading dimensions are flattened into independent
            samples (e.g., trials, conditions, or time points).
        neurons_df: DataFrame containing at least `simple_id_col` and `group_by`.
        group_by: Column in `neurons_df` used as grouping key.
        simple_id_col: Column mapping rows in `neurons_df` to neuron index in
            `values`.
        value_name: Name for the output value column.
        dropna: Drop missing values in group/value columns when `True`.

    Raises:
        ValueError: If ``values`` is 0-d; if ``simple_id_col`` or ``group_by`` is
            missing from ``neurons_df``; if no neuron metadata remains after
            dropping missing groups; if ``simple_id_col`` has duplicates, is not
            numeric, or contains ids outside ``[0, N - 1]``; or if no values
            remain after dropping missing entries.
    """
    y = to_numpy(values, strict=True, name="values")
    if y.ndim < 1:
        raise ValueError("`values` must have at least one dimension.")

    if simple_id_col not in neurons_df.columns:
        raise ValueError(f"Missing `{simple_id_col}` in `neurons_df`.")
    if group_by not in neurons_df.columns:
        raise ValueError(f"Missing `{group_by}` in `neurons_df`.")

    metadata = neurons_df.loc[:, [simple_id_col, group_by]].copy()
    if dropna:
        metadata = metadata.dropna(subset=[group_by])
    if metadata.empty:
        raise ValueError("No neuron metadata available after filtering.")

    if metadata[simple_id_col].duplicated().any():
        raise ValueError(f"`{simple_id_col}` must be unique in `neurons_df`.")

    try:
        simple_ids = pd.to_numeric(metadata[simple_id_col], errors="raise").to_numpy(
            dtype=np.int64
        )
    except (ValueError, TypeError, OverflowError) as exc:
        raise ValueError(f"`{simple_id_col}` must be numeric.") from exc

    n_neurons = y.shape[-1]
    out_of_range = (simple_ids < 0) | (simple_ids >= n_neurons)
    if np.any(out_of_range):
        bad_ids = simple_ids[out_of_range]
        raise ValueError(
            f"Found `{simple_id_col}` outside [0, {n_neurons - 1}]: {bad_ids.tolist()}"
        )

    selected = y[..., simple_ids]
    n_samples = int(np.prod(selected.shape[:-1], dtype=np.int64))
    n_samples = max(1, n_samples)

    flattened = selected.reshape(n_samples, len(simple_ids))
    group_labels = metadata[group_by].to_numpy()

    frame = pd.DataFrame(
        {
            group_by: np.repeat(group_labels, n_samples),
            value_name: flattened.T.reshape(-1),
        }
    )

    if dropna:
        frame = frame.dropna(subset=[value_name])
    if frame.empty:
        raise ValueError("No values available after filtering.")

    return frame

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
def group_ecdf(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
) -> dict[object, pd.DataFrame]:
    """Compute grouped ECDF points ready for plotting or analysis."""
    grouped = group_values(
        values,
        neurons_df,
        group_by,
        simple_id_col=simple_id_col,
        value_name=value_name,
        group_order=group_order,
        dropna=dropna,
    )

    ret: dict[object, pd.DataFrame] = {}
    for group, vals in grouped.items():
        x = np.sort(vals)
        y = np.arange(1, len(x) + 1, dtype=float) / len(x)
        ret[group] = pd.DataFrame({value_name: x, "ecdf": y})
    return ret

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
def group_summary(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
) -> pd.DataFrame:
    """Compute per-group summary statistics from neuron-aligned values."""
    grouped = group_values(
        values,
        neurons_df,
        group_by,
        simple_id_col=simple_id_col,
        value_name=value_name,
        group_order=group_order,
        dropna=dropna,
    )

    rows = []
    for group, vals in grouped.items():
        rows.append(
            {
                group_by: group,
                "n": int(vals.size),
                "mean": float(np.mean(vals)),
                "std": float(np.std(vals)),
                "min": float(np.min(vals)),
                "q25": float(np.quantile(vals, 0.25)),
                "median": float(np.median(vals)),
                "q75": float(np.quantile(vals, 0.75)),
                "max": float(np.max(vals)),
            }
        )

    return pd.DataFrame(rows)

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
def group_values(
    values: TensorLike,
    neurons_df: pd.DataFrame,
    group_by: str,
    *,
    simple_id_col: str = "simple_id",
    value_name: str = "value",
    group_order: Sequence | None = None,
    dropna: bool = True,
) -> dict[object, np.ndarray]:
    """Return grouped value arrays, keyed by group label in plotting order."""
    frame = build_group_frame(
        values,
        neurons_df,
        group_by,
        simple_id_col=simple_id_col,
        value_name=value_name,
        dropna=dropna,
    )
    order = _resolve_group_order(frame, group_by, group_order)
    return {
        group: frame.loc[frame[group_by] == group, value_name].to_numpy(dtype=float)
        for group in order
    }

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

torch.Tensor, np.ndarray or array-like.

required
strict bool

Accept only torch.Tensor and np.ndarray and raise :class:TypeError for anything else (lists, scalars, ...).

False
name str

Argument name used in the strict error message.

'data'

Returns:

Type Description
ndarray

NumPy array (a view of the input when no conversion is needed).

Raises:

Type Description
TypeError

If strict and data is not a tensor or ndarray.

Source code in btorch/utils/array.py
def to_numpy(data: Any, *, strict: bool = False, name: str = "data") -> np.ndarray:
    """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`.

    Args:
        data: ``torch.Tensor``, ``np.ndarray`` or array-like.
        strict: Accept only ``torch.Tensor`` and ``np.ndarray`` and raise
            :class:`TypeError` for anything else (lists, scalars, ...).
        name: Argument name used in the ``strict`` error message.

    Returns:
        NumPy array (a view of the input when no conversion is needed).

    Raises:
        TypeError: If ``strict`` and ``data`` is not a tensor or ndarray.
    """
    if isinstance(data, torch.Tensor):
        return data.detach().cpu().numpy()
    if strict and not isinstance(data, np.ndarray):
        raise TypeError(f"`{name}` must be a numpy array or torch tensor.")
    return np.asarray(data)

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 1 .. k_max-1, shape (k_max-1,), int.

r_k ndarray

Regression slope per lag, shape (k_max-1,). NaN marks a lag that could not be estimated (no trial is longer than k, fewer than min_points samples, or variance <= eps).

stderr ndarray

Standard error of each slope, same shape and NaN marking as r_k.

data_length int

Total number of samples over all trials minus the first valid lag; 0 when no lag is valid.

mean_activity float

Mean of the per-trial means; NaN when no lag is valid.

xs list[ndarray]

Centered lagged regressors, one array per valid lag (empty unless scatterpoints=True; skipped lags are omitted, so index i is not lag k[i]).

ys list[ndarray]

Centered lagged responses, aligned with xs.

Source code in btorch/analysis/branching.py
class LaggedSlopes(NamedTuple):
    """Result of :func:`compute_lagged_slopes`.

    Attributes:
        k: Lags ``1 .. k_max-1``, shape ``(k_max-1,)``, ``int``.
        r_k: Regression slope per lag, shape ``(k_max-1,)``. ``NaN`` marks a
            lag that could not be estimated (no trial is longer than ``k``,
            fewer than ``min_points`` samples, or variance ``<= eps``).
        stderr: Standard error of each slope, same shape and ``NaN`` marking
            as ``r_k``.
        data_length: Total number of samples over all trials minus the first
            valid lag; ``0`` when no lag is valid.
        mean_activity: Mean of the per-trial means; ``NaN`` when no lag is
            valid.
        xs: Centered lagged regressors, one array per *valid* lag (empty
            unless ``scatterpoints=True``; skipped lags are omitted, so index
            ``i`` is not lag ``k[i]``).
        ys: Centered lagged responses, aligned with ``xs``.
    """

    k: np.ndarray
    r_k: np.ndarray
    stderr: np.ndarray
    data_length: int
    mean_activity: float
    xs: list[np.ndarray]
    ys: list[np.ndarray]

Functions:

_ar1_fallback(counts_list, data_length, mean_activity, eps)

Source code in btorch/analysis/branching.py
def _ar1_fallback(
    counts_list: list[np.ndarray], data_length: int, mean_activity: float, eps: float
) -> dict:
    x0 = []
    x1 = []
    for c in counts_list:
        if len(c) > 1:
            x0.append(c[:-1] - c[:-1].mean())
            x1.append(c[1:] - c[1:].mean())

    if not x0:
        raise RuntimeError("Insufficient data for AR(1) fallback")

    x0_cat = np.concatenate(x0)
    x1_cat = np.concatenate(x1)
    var0 = np.mean(x0_cat * x0_cat)
    if var0 <= eps:
        raise RuntimeError("Insufficient variance for AR(1) fallback")

    br_hat = float(np.mean(x0_cat * x1_cat) / var0)
    return {
        "branching_ratio": br_hat,
        "a_fit": np.nan,
        "autocorrelationtime": float(-1.0 / np.log(br_hat)) if br_hat > 0 else np.nan,
        "naive_branching_ratio": br_hat,
        "k": np.array([1], dtype=int),
        "r_k": np.array([br_hat], dtype=np.float64),
        "stderr": np.array([np.nan], dtype=np.float64),
        "fit_slope": np.nan,
        "fit_intercept": np.nan,
        "fit_points_used": 1,
        "data_length": data_length,
        "mean_activity": mean_activity,
        "note": "AR1 fallback used (insufficient valid MR points)",
    }

_to_1d_numeric_array(values)

Source code in btorch/analysis/branching.py
def _to_1d_numeric_array(values: np.ndarray | list[float] | list[int]) -> np.ndarray:
    arr = np.asarray(values, dtype=np.float64)
    if arr.ndim != 1:
        raise ValueError("Each trial must be a 1D numeric array")
    if arr.size == 0:
        raise ValueError("Empty trials are not supported")
    if not np.all(np.isfinite(arr)):
        raise ValueError("Input contains non-finite values")
    return arr

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 x and y samples in result.

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 branching_ratio, naive_branching_ratio, k,

dict

r_k, stderr and fit metadata.

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
def compute_branching_ratio(
    all_counts: np.ndarray | list[np.ndarray] | list[list[float]] | str,
    k_max: int = 40,
    *,
    scatterpoints: bool = False,
    eps: float = 1e-12,
    ar1_fallback: bool = True,
) -> dict:
    """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

    Args:
        all_counts: One trial, stacked trials, list of trials, or path input.
        k_max: Maximum lag used for the MR fit.
        scatterpoints: Keep centered lagged ``x`` and ``y`` samples in result.
        eps: Small stabilizer for divisions and weights.
        ar1_fallback: Use AR(1) fallback when MR fit is ill-posed.

    Returns:
        Dictionary with ``branching_ratio``, ``naive_branching_ratio``, ``k``,
        ``r_k``, ``stderr`` and fit metadata.

    Raises:
        ValueError: If input data are invalid or too short.
        RuntimeError: If MR and fallback estimation both fail.
    """
    counts_list = input_handler(all_counts)

    k_max = int(max(2, k_max))

    shortest = min(len(c) for c in counts_list)
    max_possible = min(k_max, shortest - 1)
    if max_possible < 1:
        raise ValueError("Time series too short for branching-ratio estimation")

    k, r_k_raw, stderr_raw, data_length, mean_activity, xs, ys = compute_lagged_slopes(
        counts_list,
        max_possible + 1,
        scatterpoints=scatterpoints,
        eps=eps,
    )

    r_k = np.asarray(r_k_raw, dtype=np.float64)
    stderr = np.asarray(stderr_raw, dtype=np.float64)

    valid = np.isfinite(r_k) & np.isfinite(stderr) & (r_k > 0) & (stderr > 0)
    if np.sum(valid) < 2:
        if ar1_fallback:
            result = _ar1_fallback(counts_list, data_length, mean_activity, eps)
            if scatterpoints:
                result["xs"] = xs
                result["ys"] = ys
            return result
        raise RuntimeError("Insufficient valid r_k values for MR estimation")

    k_valid = k[valid].astype(np.float64)
    r_valid = np.clip(r_k[valid], 1e-12, 1e12)
    stderr_valid = stderr[valid]

    y = np.log(r_valid)
    w = 1.0 / (stderr_valid + eps)
    w = w / np.mean(w)

    slope, intercept = np.polyfit(k_valid, y, 1, w=w)
    m_hat = float(np.exp(slope))
    a_fit = float(np.exp(intercept))

    if not np.isfinite(m_hat) or m_hat <= 0:
        raise RuntimeError("Fitted branching ratio is non-positive or invalid")

    result = {
        "branching_ratio": m_hat,
        "a_fit": a_fit,
        "autocorrelationtime": float(-1.0 / np.log(m_hat))
        if (m_hat > 0 and m_hat != 1.0)
        else np.inf,
        "naive_branching_ratio": float(r_k[0]) if len(r_k) > 0 else np.nan,
        "k": k,
        "r_k": r_k,
        "stderr": stderr,
        "fit_slope": float(slope),
        "fit_intercept": float(intercept),
        "fit_points_used": int(np.sum(valid)),
        "data_length": data_length,
        "mean_activity": mean_activity,
    }
    if scatterpoints:
        result["xs"] = xs
        result["ys"] = ys
    return result

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 x/y samples per lag.

False
eps float

Variance threshold below which a lag is declared degenerate.

1e-12

Returns:

Name Type Description
A LaggedSlopes

class:LaggedSlopes named tuple (unpackable as a 7-tuple). Failed

LaggedSlopes

lags are reported as NaN in r_k/stderr; see

LaggedSlopes

class:LaggedSlopes for every member and sentinel.

Source code in btorch/analysis/branching.py
def compute_lagged_slopes(
    all_counts: list[np.ndarray],
    k_max: int,
    min_points: int = 50,
    scatterpoints: bool = False,
    eps: float = 1e-12,
) -> LaggedSlopes:
    """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.

    Args:
        all_counts: List of 1D count time series (trials).
        k_max: Exclusive upper bound of the lags.
        min_points: Minimum pooled sample count for a lag to be estimated.
        scatterpoints: Also return the centered ``x``/``y`` samples per lag.
        eps: Variance threshold below which a lag is declared degenerate.

    Returns:
        A :class:`LaggedSlopes` named tuple (unpackable as a 7-tuple). Failed
        lags are reported as ``NaN`` in ``r_k``/``stderr``; see
        :class:`LaggedSlopes` for every member and sentinel.
    """
    k_arr = np.arange(1, k_max, dtype=int)
    r_k = np.zeros(len(k_arr), dtype=np.float64)
    stderr = np.zeros(len(k_arr), dtype=np.float64)

    xs: list[np.ndarray] = []
    ys: list[np.ndarray] = []

    for idx, k in enumerate(k_arr):
        x_concat = []
        y_concat = []
        for counts in all_counts:
            if counts.size <= k:
                continue
            x_block = counts[:-k]
            y_block = counts[k:]
            x_block = x_block - x_block.mean()
            y_block = y_block - y_block.mean()
            x_concat.append(x_block)
            y_concat.append(y_block)

        if not x_concat:
            r_k[idx] = np.nan
            stderr[idx] = np.nan
            continue

        x = np.concatenate(x_concat)
        y = np.concatenate(y_concat)
        n_samples = x.size

        if n_samples < min_points:
            r_k[idx] = np.nan
            stderr[idx] = np.nan
            continue

        cov = np.mean(x * y)
        var0 = np.mean(x * x)
        if var0 <= eps:
            r_k[idx] = np.nan
            stderr[idx] = np.nan
            continue

        slope = cov / var0
        prod = x * y
        stderr_prod = prod.std(ddof=1) / np.sqrt(n_samples)
        stderr_slope = stderr_prod / (var0 + eps)

        r_k[idx] = slope
        stderr[idx] = stderr_slope

        if scatterpoints:
            xs.append(x.copy())
            ys.append(y.copy())

    valid_idx = np.where(~np.isnan(r_k))[0]
    if valid_idx.size:
        first = valid_idx[0]
        data_length = int(np.sum([len(a) for a in all_counts]) - k_arr[first])
        mean_activity = float(np.mean([c.mean() for c in all_counts]))
    else:
        data_length = 0
        mean_activity = np.nan

    return LaggedSlopes(k_arr, r_k, stderr, data_length, mean_activity, xs, ys)

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 .npy paths), the input type is not recognized, or a trial is not 1D, is empty or contains non-finite values.

Source code in btorch/analysis/branching.py
def input_handler(items: object) -> list[np.ndarray]:
    """Normalize supported input forms to list-of-trials arrays.

    Raises:
        ValueError: If a numpy array is not a 1D/2D numeric array, a list mixes
            types (it must hold only arrays/lists or only ``.npy`` paths), the
            input type is not recognized, or a trial is not 1D, is empty or
            contains non-finite values.
    """
    if isinstance(items, np.ndarray):
        if items.ndim == 1 and items.dtype.kind in "iuf":
            return [_to_1d_numeric_array(items)]
        if items.ndim == 2 and items.dtype.kind in "iuf":
            return [_to_1d_numeric_array(row) for row in items]
        raise ValueError("Unsupported numpy array input")
    if isinstance(items, list):
        if all(isinstance(x, (np.ndarray, list)) for x in items):
            return [_to_1d_numeric_array(x) for x in items]
        if all(isinstance(x, str) for x in items):
            return [_to_1d_numeric_array(np.load(x)) for x in items]
        raise ValueError("List of mixed types not supported")
    if isinstance(items, str):
        return [_to_1d_numeric_array(np.load(items))]
    raise ValueError("Input type not recognized")

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 [0, 1].

required
rng int | Generator | None

Seed or random generator.

None

Returns:

Type Description
ndarray

Subsampled counts as float for compatibility with existing tests.

Source code in btorch/analysis/branching.py
def simulate_binomial_subsampling(
    a_t: np.ndarray,
    alpha: float,
    rng: int | np.random.Generator | None = None,
) -> np.ndarray:
    """Apply binomial subsampling to count data.

    Args:
        a_t: Integer activity time series.
        alpha: Sampling probability in ``[0, 1]``.
        rng: Seed or random generator.

    Returns:
        Subsampled counts as ``float`` for compatibility with existing tests.
    """
    rng = np.random.default_rng(rng)
    counts = np.asarray(a_t, dtype=np.int64)
    out = rng.binomial(counts, alpha)
    return out.astype(float)

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 (length,).

Source code in btorch/analysis/branching.py
def simulate_branching(
    length: int = 10000,
    m: float = 0.9,
    activity: float = 100,
    rng: int | np.random.Generator | None = None,
) -> np.ndarray:
    """Simulate a branching process with immigration.

    Args:
        length: Number of time points.
        m: True branching ratio.
        activity: Target mean activity.
        rng: Seed or random generator.

    Returns:
        Integer count time series of shape ``(length,)``.
    """
    rng = np.random.default_rng(rng)
    h = activity * (1 - m)
    a_t = np.empty(length, dtype=np.int64)
    a_t[0] = rng.poisson(lam=activity)
    for t in range(1, length):
        tmp = rng.poisson(lam=h)
        if a_t[t - 1] > 0 and m > 0:
            tmp += rng.poisson(lam=m * a_t[t - 1])
        a_t[t] = tmp
    return a_t

btorch.analysis.clustering

Functions:

_euclidean(u, v)

Euclidean distance that tolerates scalar input (for fastdtw).

Source code in btorch/analysis/clustering.py
def _euclidean(u: np.ndarray | float, v: np.ndarray | float) -> float:
    """Euclidean distance that tolerates scalar input (for fastdtw)."""
    u = np.atleast_1d(np.asarray(u))
    v = np.atleast_1d(np.asarray(v))
    return _scipy_euclidean(u, v)

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
def cluster_traces(
    traces: Sequence[np.ndarray],
    threshold: float = 10,
    linkage_method: str = "average",
) -> tuple[dict[int, list[int]], np.ndarray, np.ndarray, np.ndarray]:
    """Cluster traces of voltages or currents using hierarchical agglomerative
    clustering with DTW distance."""
    fastdtw = require("fastdtw", "analysis", "DTW clustering").fastdtw
    num_traces = len(traces)

    distance_matrix = np.zeros((num_traces, num_traces))
    for i in range(num_traces):
        for j in range(num_traces):
            distance, _ = fastdtw(traces[i], traces[j], dist=_euclidean)
            distance_matrix[i, j] = distance

    # DTW may introduce tiny numerical asymmetry; enforce symmetry
    # so scipy.spatial.distance.squareform accepts the matrix.
    distance_matrix = (distance_matrix + distance_matrix.T) / 2

    Z = linkage(squareform(distance_matrix), method=linkage_method)
    clusters = fcluster(Z, t=threshold, criterion="distance")

    cluster_indices = {}
    for idx, cluster_id in enumerate(clusters):
        if cluster_id not in cluster_indices:
            cluster_indices[cluster_id] = []
        cluster_indices[cluster_id].append(idx)

    return cluster_indices, clusters, Z, distance_matrix

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. "plotly.graph_objects").

required
extra str

Name of the btorch extra that provides the module (e.g. "viz").

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
def require(module_name: str, extra: str, purpose: str | None = None) -> ModuleType:
    """Import an optional dependency, or raise ImportError with an install
    hint.

    Args:
        module_name: Dotted module path to import (e.g. ``"plotly.graph_objects"``).
        extra: Name of the btorch extra that provides the module (e.g. ``"viz"``).
        purpose: Optional short description of the feature needing the module.

    Returns:
        The imported module.

    Raises:
        ImportError: If the module is not installed.
    """
    try:
        return importlib.import_module(module_name)
    except ImportError as e:
        what = f" for {purpose}" if purpose else ""
        raise ImportError(
            f"'{module_name.split('.')[0]}' is required{what} but is not "
            f'installed. Install it with: pip install "btorch[{extra}]"'
        ) from e

suggest_threshold(linkage_matrix)

Suggest a sensible threshold for hierarchical clustering.

Source code in btorch/analysis/clustering.py
def suggest_threshold(linkage_matrix: np.ndarray) -> float:
    """Suggest a sensible threshold for hierarchical clustering."""
    sorted_distances = sorted(linkage_matrix[:, 2], reverse=True)
    diffs = np.abs(np.diff(sorted_distances))
    potential_elbows = np.where(diffs > np.mean(diffs))[0] + 1

    if len(potential_elbows) == 0:
        suggested_threshold = sorted_distances[-1]
    else:
        first_elbow = potential_elbows[0]
        suggested_threshold = sorted_distances[first_elbow]

    return suggested_threshold

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
class HopDistanceModel:
    """Fast computation of hop distances in networks using BFS."""

    def __init__(
        self,
        edges: pd.DataFrame | None = None,
        adjacency: sparse.sparray | None = None,
        node_mapping: dict | None = None,
        source: str = "source",
        target: str = "target",
    ):
        if edges is None and adjacency is None:
            raise ValueError("Must provide either edges DataFrame or adjacency matrix")

        if adjacency is not None:
            self.adjacency = adjacency.tocsr()
            self.use_sparse = True
            if node_mapping is None:
                self.node_mapping = {i: i for i in range(adjacency.shape[0])}
                self.reverse_mapping = {i: i for i in range(adjacency.shape[0])}
            else:
                self.node_mapping = node_mapping
                self.reverse_mapping = {v: k for k, v in node_mapping.items()}
            self.n_nodes = adjacency.shape[0]
        else:
            self.edges = edges.copy()
            self.source = source
            self.target = target
            self.use_sparse = False

            for col in (source, target):
                if col not in edges.columns:
                    raise ValueError(f'edges must contain "{col}" column')

            all_nodes = np.unique(
                np.concatenate([edges[source].values, edges[target].values])
            )
            self.node_mapping = {node: idx for idx, node in enumerate(all_nodes)}
            self.reverse_mapping = {
                idx: node for node, idx in self.node_mapping.items()
            }
            self.n_nodes = len(all_nodes)

            self._build_adjacency_dict()

    def _build_adjacency_dict(self):
        """Build adjacency dictionary for fast neighbor lookup."""
        self.adj_dict = {}
        for _, row in self.edges.iterrows():
            src_idx = self.node_mapping[row[self.source]]
            tgt_idx = self.node_mapping[row[self.target]]

            if src_idx not in self.adj_dict:
                self.adj_dict[src_idx] = []
            self.adj_dict[src_idx].append(tgt_idx)

        for node in self.adj_dict:
            self.adj_dict[node] = np.array(self.adj_dict[node], dtype=np.int32)

    def compute_distances(
        self, seeds: list[int | str], max_hops: int | None = None
    ) -> pd.DataFrame:
        """Compute hop distances from seeds to all reachable nodes using
        BFS."""
        seed_indices = [self.node_mapping.get(seed, None) for seed in seeds]
        missing = [s for s in seeds if s not in self.node_mapping]
        if len(missing) != 0:
            warnings.warn(f"Seeds not found in network: {missing}", stacklevel=2)
            seed_indices = [s for s in seed_indices if s is not None]

        distances = np.full(self.n_nodes, -1, dtype=np.int32)
        predecessors = np.full(self.n_nodes, -1, dtype=np.int32)

        queue = deque()
        for seed_idx in seed_indices:
            distances[seed_idx] = 0
            predecessors[seed_idx] = seed_idx
            queue.append(seed_idx)

        while queue:
            current_idx = queue.popleft()
            current_dist = distances[current_idx]

            if max_hops is not None and current_dist >= max_hops:
                continue

            if self.use_sparse:
                neighbors = self.adjacency[[current_idx]].indices.flatten()
            else:
                neighbors = self.adj_dict.get(current_idx, np.array([], dtype=np.int32))

            for neighbor_idx in neighbors:
                if distances[neighbor_idx] == -1:
                    distances[neighbor_idx] = current_dist + 1
                    predecessors[neighbor_idx] = current_idx
                    queue.append(neighbor_idx)

        reachable_mask = distances >= 0
        result_nodes = [
            self.reverse_mapping[idx] for idx in np.where(reachable_mask)[0]
        ]
        result_distances = distances[reachable_mask]
        result_predecessors = [
            self.reverse_mapping[predecessors[idx]]
            for idx in np.where(reachable_mask)[0]
        ]

        return pd.DataFrame(
            {
                "node": result_nodes,
                "distance": result_distances,
                "predecessor": result_predecessors,
            }
        )

    def hop_statistics(
        self, seeds: list[int | str], max_hops: int | None = None
    ) -> pd.DataFrame:
        """Compute statistics about network reachability by hop distance."""
        distances_df = self.compute_distances(seeds, max_hops)

        if distances_df.empty:
            return pd.DataFrame(
                columns=[
                    "hops",
                    "nodes_count",
                    "nodes_percentage",
                    "cumulative_count",
                    "cumulative_percentage",
                ]
            )

        hop_counts = distances_df["distance"].value_counts().sort_index()

        stats = []
        cumulative = 0
        for hops in range(hop_counts.index.min(), hop_counts.index.max() + 1):
            count = hop_counts.get(hops, 0)
            cumulative += count

            stats.append(
                {
                    "hops": hops,
                    "nodes_count": count,
                    "nodes_percentage": 100.0 * count / self.n_nodes,
                    "cumulative_count": cumulative,
                    "cumulative_percentage": 100.0 * cumulative / self.n_nodes,
                }
            )

        return pd.DataFrame(stats)

    def reconstruct_path(
        self,
        source_node: int | str,
        target_node: int | str,
        distances_df: pd.DataFrame | None = None,
    ) -> list[int | str]:
        """Reconstruct shortest path from source to target using predecessor
        info."""
        if distances_df is None:
            distances_df = self.compute_distances([source_node])

        target_row = distances_df[distances_df["node"] == target_node]
        if target_row.empty:
            return []

        path = []
        current = target_node
        predecessors_dict = dict(zip(distances_df["node"], distances_df["predecessor"]))

        while current != source_node:
            path.append(current)
            if current not in predecessors_dict:
                return []
            current = predecessors_dict[current]

        path.append(source_node)
        return path[::-1]
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
def compute_distances(
    self, seeds: list[int | str], max_hops: int | None = None
) -> pd.DataFrame:
    """Compute hop distances from seeds to all reachable nodes using
    BFS."""
    seed_indices = [self.node_mapping.get(seed, None) for seed in seeds]
    missing = [s for s in seeds if s not in self.node_mapping]
    if len(missing) != 0:
        warnings.warn(f"Seeds not found in network: {missing}", stacklevel=2)
        seed_indices = [s for s in seed_indices if s is not None]

    distances = np.full(self.n_nodes, -1, dtype=np.int32)
    predecessors = np.full(self.n_nodes, -1, dtype=np.int32)

    queue = deque()
    for seed_idx in seed_indices:
        distances[seed_idx] = 0
        predecessors[seed_idx] = seed_idx
        queue.append(seed_idx)

    while queue:
        current_idx = queue.popleft()
        current_dist = distances[current_idx]

        if max_hops is not None and current_dist >= max_hops:
            continue

        if self.use_sparse:
            neighbors = self.adjacency[[current_idx]].indices.flatten()
        else:
            neighbors = self.adj_dict.get(current_idx, np.array([], dtype=np.int32))

        for neighbor_idx in neighbors:
            if distances[neighbor_idx] == -1:
                distances[neighbor_idx] = current_dist + 1
                predecessors[neighbor_idx] = current_idx
                queue.append(neighbor_idx)

    reachable_mask = distances >= 0
    result_nodes = [
        self.reverse_mapping[idx] for idx in np.where(reachable_mask)[0]
    ]
    result_distances = distances[reachable_mask]
    result_predecessors = [
        self.reverse_mapping[predecessors[idx]]
        for idx in np.where(reachable_mask)[0]
    ]

    return pd.DataFrame(
        {
            "node": result_nodes,
            "distance": result_distances,
            "predecessor": result_predecessors,
        }
    )
hop_statistics(seeds, max_hops=None)

Compute statistics about network reachability by hop distance.

Source code in btorch/analysis/connectivity.py
def hop_statistics(
    self, seeds: list[int | str], max_hops: int | None = None
) -> pd.DataFrame:
    """Compute statistics about network reachability by hop distance."""
    distances_df = self.compute_distances(seeds, max_hops)

    if distances_df.empty:
        return pd.DataFrame(
            columns=[
                "hops",
                "nodes_count",
                "nodes_percentage",
                "cumulative_count",
                "cumulative_percentage",
            ]
        )

    hop_counts = distances_df["distance"].value_counts().sort_index()

    stats = []
    cumulative = 0
    for hops in range(hop_counts.index.min(), hop_counts.index.max() + 1):
        count = hop_counts.get(hops, 0)
        cumulative += count

        stats.append(
            {
                "hops": hops,
                "nodes_count": count,
                "nodes_percentage": 100.0 * count / self.n_nodes,
                "cumulative_count": cumulative,
                "cumulative_percentage": 100.0 * cumulative / self.n_nodes,
            }
        )

    return pd.DataFrame(stats)
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
def reconstruct_path(
    self,
    source_node: int | str,
    target_node: int | str,
    distances_df: pd.DataFrame | None = None,
) -> list[int | str]:
    """Reconstruct shortest path from source to target using predecessor
    info."""
    if distances_df is None:
        distances_df = self.compute_distances([source_node])

    target_row = distances_df[distances_df["node"] == target_node]
    if target_row.empty:
        return []

    path = []
    current = target_node
    predecessors_dict = dict(zip(distances_df["node"], distances_df["predecessor"]))

    while current != source_node:
        path.append(current)
        if current not in predecessors_dict:
            return []
        current = predecessors_dict[current]

    path.append(source_node)
    return path[::-1]

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 excitatory_neuron_only is True and neurons is None.

Source code in btorch/analysis/connectivity.py
def compute_ie_ratio(
    excitatory_mat: sparray,
    inhibitory_mat: sparray,
    excitatory_neuron_only: bool = True,
    neurons: pd.DataFrame | None = None,
    warn_strict: bool = True,
) -> tuple[float, np.ndarray]:
    """Compute inhibitory/excitatory ratio per neuron and whole-brain mean.

    Raises:
        ValueError: If ``excitatory_neuron_only`` is True and ``neurons`` is
            None.
    """
    if excitatory_neuron_only:
        if neurons is None:
            raise ValueError("`neurons` must be provided when excitatory_neuron_only")

    sum_inhibitory = inhibitory_mat.sum(axis=0).astype(float)
    sum_excitatory = excitatory_mat.sum(axis=0).astype(float)

    # neurons that have zero inputs from both e and i connections are likely input,
    # so don't warn on them
    input_indices = (sum_excitatory == 0) & (sum_inhibitory == 0)

    sum_excitatory[sum_excitatory == 0] = np.nan
    if excitatory_neuron_only:
        sum_excitatory[neurons[neurons.EI == "E"].simple_id.to_numpy()] = np.nan

    ie_ratios = sum_inhibitory / sum_excitatory

    if warn_strict:
        nan_indices = (np.isnan(ie_ratios) & ~input_indices).nonzero()[0]
        if nan_indices.size > 0:
            warnings.warn(
                f"IE ratio contains NaN values at indices {nan_indices}",
                stacklevel=2,
            )

        inf_indices = np.isinf(ie_ratios).nonzero()[0]
        if inf_indices.size > 0:
            warnings.warn(
                f"IE ratio contains Inf values at indices {inf_indices}",
                stacklevel=2,
            )

    ie_ratios = np.where(np.isinf(ie_ratios), np.nan, ie_ratios)
    ie_ratio_whole_brain: float = np.nanmean(ie_ratios[ie_ratios != 0])

    return ie_ratio_whole_brain, ie_ratios

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 ndim > 1 masks) or a tuple of per-axis index arrays.

required
shape tuple[int, ...] | None

Shape of the mask. Takes precedence over array.

None
array ndarray | None

Array whose shape is used when shape is not given.

None

Returns:

Type Description
ndarray

Boolean array that is True at indices.

Raises:

Type Description
ValueError

If neither shape nor array is given.

Source code in btorch/analysis/metrics.py
def indices_to_mask(
    indices: np.ndarray | tuple[np.ndarray, ...],
    shape: tuple[int, ...] | None = None,
    array: np.ndarray | None = None,
) -> np.ndarray:
    """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`).

    Args:
        indices: Index array (flat indices for ``ndim > 1`` masks) or a tuple
            of per-axis index arrays.
        shape: Shape of the mask. Takes precedence over ``array``.
        array: Array whose shape is used when ``shape`` is not given.

    Returns:
        Boolean array that is ``True`` at ``indices``.

    Raises:
        ValueError: If neither ``shape`` nor ``array`` is given.
    """
    if shape is None and array is None:
        raise ValueError("Either `shape` or `array` must be provided")
    mask = (
        np.zeros(shape, dtype=bool)
        if shape is not None
        else np.zeros_like(array, dtype=bool)
    )
    indices_arr = np.asarray(indices)
    if mask.ndim > 1 and indices_arr.ndim == 1 and not isinstance(indices, tuple):
        mask.flat[indices_arr] = True
    else:
        mask[indices] = True
    return mask

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 "topk"; an optional cap, sampled at random, for "any").

None
mode Literal['topk', 'any']

"topk" selects the num largest entries, "any" the non-zero entries.

'topk'
ret_indices bool

If True, return (indices, mask) instead of indices.

False

Returns:

Type Description
ndarray | tuple[ndarray, ndarray]

Selected neuron indices, or (indices, mask) if ret_indices.

Raises:

Type Description
ValueError

If mode is unsupported or num is missing for "topk".

Source code in btorch/analysis/metrics.py
def select_on_metric(
    metrics: np.ndarray,
    num: int | None = None,
    mode: Literal["topk", "any"] = "topk",
    ret_indices: bool = False,
) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
    """Select neurons based on a metric array.

    Args:
        metrics: 1D per-neuron metric.
        num: Number of neurons to select (required for ``"topk"``; an optional
            cap, sampled at random, for ``"any"``).
        mode: ``"topk"`` selects the ``num`` largest entries, ``"any"`` the
            non-zero entries.
        ret_indices: If True, return ``(indices, mask)`` instead of indices.

    Returns:
        Selected neuron indices, or ``(indices, mask)`` if ``ret_indices``.

    Raises:
        ValueError: If ``mode`` is unsupported or ``num`` is missing for
            ``"topk"``.
    """
    if mode == "topk":
        if num is None:
            raise ValueError("`num` must be provided when mode is 'topk'")
        ret = np.argpartition(metrics, -num)[-num:]
    elif mode == "any":
        ret = metrics.nonzero()[0]
        if num is not None and len(ret) > num:
            ret = np.random.choice(ret, num, replace=False)
    else:
        raise ValueError(f"Unsupported mode {mode}")

    if ret_indices:
        return ret, indices_to_mask(ret, array=metrics)
    else:
        return ret

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 the stat aggregate) together with an info dict, 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_axis parameter 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 window is not in [1, T] or overlap is not smaller than window.

Source code in btorch/analysis/spiking.py
def _check_window(window: int, overlap: int, T: int) -> None:
    """Validate sliding-window arguments.

    Raises:
        ValueError: If ``window`` is not in ``[1, T]`` or ``overlap`` is not
            smaller than ``window``.
    """
    if not 1 <= window <= T:
        raise ValueError(f"window must be in [1, T={T}], got {window}")
    if overlap >= window:
        raise ValueError(
            f"overlap must be smaller than window, got overlap={overlap}, "
            f"window={window}"
        )

_cv(spikes, dt=1.0, batch_axis=None, dtype=None)

Source code in btorch/analysis/spiking.py
def _cv(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
):
    if isinstance(spikes, torch.Tensor):
        return _cv_torch(spikes, dt, batch_axis, dtype)
    else:
        return _cv_numpy(spikes, dt, batch_axis, dtype)

_cv_numpy(spikes, dt, batch_axis, dtype=None)

NumPy implementation of ISI CV.

Source code in btorch/analysis/spiking.py
def _cv_numpy(
    spikes: np.ndarray,
    dt: float,
    batch_axis: tuple[int, ...] | None,
    dtype: np.dtype | None = None,
):
    """NumPy implementation of ISI CV."""
    orig_shape = spikes.shape
    T = orig_shape[0]

    # Aggregate across batch dimensions if specified
    if batch_axis is not None:
        axes_to_sum = tuple(batch_axis)
        spike_aggregated = np.sum(spikes, axis=axes_to_sum, keepdims=False)
        work_shape = (T,) + spike_aggregated.shape[1:]
    else:
        spike_aggregated = spikes
        work_shape = orig_shape

    flat_data = spike_aggregated.reshape(T, -1)
    n_flat = flat_data.shape[1]

    # Vectorized spike extraction
    t_idx, n_idx = np.where(flat_data > 0)
    n_spikes_all = np.bincount(n_idx, minlength=n_flat)

    # Sort by neuron index primarily, then time secondarily
    sort_order = np.lexsort((t_idx, n_idx))
    t_sorted = t_idx[sort_order]
    n_sorted = n_idx[sort_order]

    diffs = np.diff(t_sorted) * dt

    # Valid ISIs are those where the neuron index didn't change
    valid_mask = n_sorted[:-1] == n_sorted[1:]
    valid_isis = diffs[valid_mask]
    valid_n = n_sorted[:-1][valid_mask]

    # Fast aggregation for CV calculation
    count_isi = np.bincount(valid_n, minlength=n_flat)
    sum_isi = np.bincount(valid_n, weights=valid_isis, minlength=n_flat)
    sum_isi_sq = np.bincount(valid_n, weights=valid_isis**2, minlength=n_flat)

    with np.errstate(divide="ignore", invalid="ignore"):
        mean_isi_arr = sum_isi / count_isi
        var_isi_arr = (sum_isi_sq / count_isi) - mean_isi_arr**2
        std_isi_arr = np.sqrt(np.maximum(var_isi_arr, 0.0))
        cv_values_flat = std_isi_arr / mean_isi_arr

    # NaN out neurons with < 2 ISIs (need at least 2 spikes for 1 ISI),
    # and 2 ISI to compute cv
    cv_values_flat[count_isi < 2] = np.nan
    cv_values = cv_values_flat.reshape(work_shape[1:])
    return cv_values, {
        "spike_count": n_spikes_all,
        "isi_mean": mean_isi_arr,
        "isi_std": std_isi_arr,
        "isi_var": var_isi_arr,
    }

_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
def _cv_torch(
    spikes: torch.Tensor,
    dt: float,
    batch_axis: tuple[int, ...] | None,
    dtype: torch.dtype | None = 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.
    """
    device = spikes.device
    orig_shape = spikes.shape
    T = orig_shape[0]

    # Aggregate across batch dimensions if specified
    if batch_axis is not None:
        spike_aggregated = torch.sum(spikes, dim=batch_axis, keepdim=False)
        work_shape = (T,) + spike_aggregated.shape[1:]
    else:
        spike_aggregated = spikes
        work_shape = orig_shape

    # For ISI extraction, CPU is more efficient due to sequential nature
    spike_cpu = spike_aggregated.cpu()
    T = spike_cpu.shape[0]
    flat_data = spike_cpu.reshape(T, -1)
    n_flat = flat_data.shape[1]

    # Vectorized spike extraction on CPU
    t_idx, n_idx = torch.nonzero(flat_data, as_tuple=True)
    n_spikes_all = torch.bincount(n_idx, minlength=n_flat)

    # Sort by neuron, then time (torch.lexsort doesn't exist,
    #   use argsort on packed values)
    # Pack: neuron * (T+1) + time ensures sorting by neuron first, then time
    packed = n_idx * (T + 1) + t_idx
    sort_order = torch.argsort(packed, stable=True)
    t_sorted = t_idx[sort_order].float() * dt
    n_sorted = n_idx[sort_order]

    isis = torch.diff(t_sorted)
    valid_mask = n_sorted[:-1] == n_sorted[1:]
    valid_isis = isis[valid_mask]
    valid_n = n_sorted[:-1][valid_mask]

    # Aggregate per neuron
    count_isi = torch.bincount(valid_n, minlength=n_flat).float()
    sum_isi = torch.bincount(valid_n, weights=valid_isis, minlength=n_flat)
    sum_isi_sq = torch.bincount(valid_n, weights=valid_isis**2, minlength=n_flat)
    mean_isi_arr = sum_isi / (count_isi + 1e-12)
    var_isi_arr = (sum_isi_sq / (count_isi + 1e-12)) - mean_isi_arr**2
    std_isi_arr = torch.sqrt(torch.clamp(var_isi_arr, min=0.0))
    cv_values_flat = std_isi_arr / (mean_isi_arr + 1e-12)

    cv_values_flat[count_isi < 2] = float("nan")

    cv_values = cv_values_flat.reshape(work_shape[1:]).to(device)
    mean_isi_arr = mean_isi_arr.reshape(work_shape[1:]).to(device)
    std_isi_arr = std_isi_arr.reshape(work_shape[1:]).to(device)
    var_isi_arr = var_isi_arr.reshape(work_shape[1:]).to(device)
    n_spikes_all = n_spikes_all.reshape(work_shape[1:]).to(device)
    return cv_values, {
        "spike_count": n_spikes_all,
        "isi_mean": mean_isi_arr,
        "isi_std": std_isi_arr,
        "isi_var": var_isi_arr,
    }

_fano_numpy(spikes, window, overlap, batch_axis, dtype=None)

NumPy implementation of Fano factor.

Source code in btorch/analysis/spiking.py
def _fano_numpy(
    spikes: np.ndarray,
    window: int | None,
    overlap: int,
    batch_axis: tuple[int, ...] | None,
    dtype: np.dtype | None = None,
):
    """NumPy implementation of Fano factor."""
    orig_shape = spikes.shape
    T = orig_shape[0]

    if window is None:
        # Default window size to get ~10 bins for variance computation
        # Need at least 2 bins for valid variance with ddof=1
        window = max(1, T // 10)

    _check_window(window, overlap, T)

    step = window - overlap

    # Average across batch dimensions if specified
    if batch_axis is not None:
        spikes = np.mean(spikes, axis=batch_axis, keepdims=False)

    flat_spike = spikes.reshape(T, -1)
    n_flat = flat_spike.shape[1]

    # VECTORIZED WINDOWING via Cumulative Sum
    # dtype=None lets numpy use its default (float64)
    cumsum_spike = np.zeros((T + 1, n_flat), dtype=dtype)
    np.cumsum(flat_spike, axis=0, dtype=dtype, out=cumsum_spike[1:])

    t_starts = np.arange(0, T - window + 1, step)
    t_ends = t_starts + window
    counts = cumsum_spike[t_ends] - cumsum_spike[t_starts]

    mean_counts = counts.mean(axis=0)
    var_counts = counts.var(axis=0, ddof=1)

    fano = np.zeros(n_flat, dtype=dtype)
    valid = np.isfinite(mean_counts) & (mean_counts > 0) & np.isfinite(var_counts)
    if np.any(valid):
        fano[valid] = var_counts[valid] / mean_counts[valid]

    fano_result = fano.reshape(spikes.shape[1:])
    return fano_result, {}

_fano_population_numpy(spikes, window, overlap, dtype=None)

NumPy implementation of pooled Fano factor.

Source code in btorch/analysis/spiking.py
def _fano_population_numpy(
    spikes: np.ndarray, window: int | None, overlap: int, dtype: np.dtype | None = None
) -> tuple[np.ndarray, dict]:
    """NumPy implementation of pooled Fano factor."""
    T = spikes.shape[0]

    if window is None:
        window = T

    _check_window(window, overlap, T)

    step = window - overlap

    # Pool across all non-time dimensions
    flat_spike = spikes.reshape(T, -1)

    # Sum across all neurons to get population spike count
    pop_counts = flat_spike.sum(axis=1)

    # VECTORIZED WINDOWING via Cumulative Sum
    # dtype=None lets numpy use its default (float64)
    cumsum = np.zeros(T + 1, dtype=dtype)
    np.cumsum(pop_counts, dtype=dtype, out=cumsum[1:])

    t_starts = np.arange(0, T - window + 1, step)
    t_ends = t_starts + window
    counts = cumsum[t_ends] - cumsum[t_starts]

    mean_counts = counts.mean()
    var_counts = counts.var(ddof=1)

    fano_pop = var_counts / mean_counts if mean_counts > 0 else np.nan

    return np.array(fano_pop), {"window": window, "n_windows": len(counts)}

_fano_population_torch(spikes, window, overlap, dtype=None)

Torch implementation of pooled Fano factor.

Source code in btorch/analysis/spiking.py
def _fano_population_torch(
    spikes: torch.Tensor,
    window: int | None,
    overlap: int,
    dtype: torch.dtype | None = None,
) -> tuple[torch.Tensor, dict]:
    """Torch implementation of pooled Fano factor."""
    device = spikes.device
    T = spikes.shape[0]

    if window is None:
        window = T

    _check_window(window, overlap, T)

    step = window - overlap

    # Pool across all non-time dimensions
    flat_spike = spikes.reshape(T, -1)

    # Sum across all neurons to get population spike count
    pop_counts = flat_spike.sum(dim=1)

    # Use specified dtype or default to float64
    accum_dtype = dtype if dtype is not None else torch.float64

    # Vectorized windowing via cumulative sum
    cumsum = torch.zeros(T + 1, device=device, dtype=accum_dtype)
    cumsum[1:] = torch.cumsum(pop_counts, dim=0)

    t_starts = torch.arange(0, T - window + 1, step, device=device)
    t_ends = t_starts + window
    counts = cumsum[t_ends] - cumsum[t_starts]

    mean_counts = counts.mean().item()
    var_counts = counts.var(unbiased=True).item()

    fano_pop = var_counts / mean_counts if mean_counts > 0 else float("nan")

    return torch.tensor(fano_pop, device=device), {
        "window": window,
        "n_windows": len(counts),
    }

_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
def _fano_torch(
    spikes: torch.Tensor,
    window: int,
    overlap: int,
    batch_axis: tuple[int, ...] | None,
    dtype: torch.dtype | None = None,
):
    """Torch implementation of Fano factor (GPU-friendly).

    Note: Uses specified dtype or input dtype for accumulation.
    """
    device = spikes.device
    orig_shape = spikes.shape
    T = orig_shape[0]

    _check_window(window, overlap, T)

    step = window - overlap

    # Cast to specified dtype or preserve input dtype for accumulation
    if dtype is not None:
        spike_work = spikes.to(dtype)
    elif spikes.dtype in (torch.float16, torch.bfloat16):
        spike_work = spikes.float()
    else:
        spike_work = spikes

    if batch_axis is not None:
        spike_work = torch.mean(spike_work, dim=batch_axis, keepdim=False)

    flat_spike = spike_work.reshape(T, -1)
    n_flat = flat_spike.shape[1]

    # Determine accumulator dtype
    accum_dtype = dtype if dtype is not None else spike_work.dtype

    # Vectorized windowing via cumulative sum (very GPU-friendly)
    cumsum_spike = torch.zeros(T + 1, n_flat, device=device, dtype=accum_dtype)
    cumsum_spike[1:] = torch.cumsum(flat_spike, dim=0)

    t_starts = torch.arange(0, T - window + 1, step, device=device)
    t_ends = t_starts + window
    counts = cumsum_spike[t_ends] - cumsum_spike[t_starts]

    mean_counts = counts.mean(dim=0)
    var_counts = counts.var(dim=0, unbiased=True)

    fano = torch.zeros(n_flat, device=device, dtype=accum_dtype)
    valid = torch.isfinite(mean_counts) & (mean_counts > 0) & torch.isfinite(var_counts)
    if valid.any():
        fano[valid] = var_counts[valid] / mean_counts[valid]

    # Use spike_work.shape which accounts for batch_axis aggregation
    fano_result = fano.reshape(spike_work.shape[1:])
    return fano_result, {}

_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
def _isis_population_numpy(spikes: np.ndarray, dt: float) -> np.ndarray:
    """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.
    """
    flat_data = spikes.reshape(spikes.shape[0], -1)
    # np.where scans row-major, so the time indices are already sorted.
    t_idx = np.where(flat_data > 0)[0].astype(np.float64) * dt
    return np.diff(t_idx)

_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
def _isis_population_torch(spikes: torch.Tensor, dt: float) -> torch.Tensor:
    """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).
    """
    # ISI extraction is done on CPU, the result goes back to the input device.
    flat_data = spikes.cpu().reshape(spikes.shape[0], -1)
    # nonzero scans row-major, so the time indices are already sorted.
    t_idx = torch.nonzero(flat_data, as_tuple=True)[0].float() * dt
    return torch.diff(t_idx).to(spikes.device)

_kurtosis_numpy(spikes, window, overlap, fisher, batch_axis, dtype=None)

NumPy implementation of kurtosis.

Source code in btorch/analysis/spiking.py
def _kurtosis_numpy(
    spikes: np.ndarray,
    window: int,
    overlap: int,
    fisher: bool,
    batch_axis: tuple[int, ...] | None,
    dtype: np.dtype | None = None,
):
    """NumPy implementation of kurtosis."""
    orig_shape = spikes.shape
    T = orig_shape[0]

    _check_window(window, overlap, T)

    step = window - overlap

    # Average across batch dimensions if specified
    if batch_axis is not None:
        spikes = np.mean(spikes, axis=batch_axis, keepdims=False)

    flat_spike = spikes.reshape(T, -1)
    n_flat = flat_spike.shape[1]

    # VECTORIZED WINDOWING via Cumulative Sum
    # dtype=None lets numpy use its default (float64)
    cumsum_spike = np.zeros((T + 1, n_flat), dtype=dtype)
    np.cumsum(flat_spike, axis=0, dtype=dtype, out=cumsum_spike[1:])

    t_starts = np.arange(0, T - window + 1, step)
    t_ends = t_starts + window
    counts = cumsum_spike[t_ends] - cumsum_spike[t_starts]

    m1 = counts.mean(axis=0)
    m2 = counts.var(axis=0, ddof=1)
    m4 = np.mean((counts - m1) ** 4, axis=0)

    eps = 1e-12
    kurt = m4 / (m2 + eps) ** 2

    if fisher:
        kurt = kurt - 3.0

    # Use spikes.shape which accounts for batch_axis aggregation (modified in place)
    kurt_result = kurt.reshape(spikes.shape[1:])
    return kurt_result, {}

_kurtosis_population_numpy(spikes, window, overlap, fisher)

NumPy implementation of pooled kurtosis.

Source code in btorch/analysis/spiking.py
def _kurtosis_population_numpy(
    spikes: np.ndarray, window: int | None, overlap: int, fisher: bool
) -> tuple[np.ndarray, dict]:
    """NumPy implementation of pooled kurtosis."""
    T = spikes.shape[0]

    if window is None:
        window = T

    _check_window(window, overlap, T)

    step = window - overlap

    # Pool across all non-time dimensions
    flat_spike = spikes.reshape(T, -1)

    # Sum across all neurons to get population spike count
    pop_counts = flat_spike.sum(axis=1)

    # VECTORIZED WINDOWING via Cumulative Sum
    cumsum = np.zeros(T + 1, dtype=np.float64)
    np.cumsum(pop_counts, dtype=np.float64, out=cumsum[1:])

    t_starts = np.arange(0, T - window + 1, step)
    t_ends = t_starts + window
    counts = cumsum[t_ends] - cumsum[t_starts]

    m1 = counts.mean()
    m2 = counts.var(ddof=1)
    m4 = np.mean((counts - m1) ** 4)

    eps = 1e-12
    kurt = m4 / (m2 + eps) ** 2

    if fisher:
        kurt = kurt - 3.0

    return np.array(kurt), {"window": window, "n_windows": len(counts)}

_kurtosis_population_torch(spikes, window, overlap, fisher)

Torch implementation of pooled kurtosis.

Source code in btorch/analysis/spiking.py
def _kurtosis_population_torch(
    spikes: torch.Tensor, window: int | None, overlap: int, fisher: bool
) -> tuple[torch.Tensor, dict]:
    """Torch implementation of pooled kurtosis."""
    device = spikes.device
    T = spikes.shape[0]

    if window is None:
        window = T

    _check_window(window, overlap, T)

    step = window - overlap

    # Pool across all non-time dimensions
    flat_spike = spikes.reshape(T, -1)

    # Sum across all neurons to get population spike count
    pop_counts = flat_spike.sum(dim=1)

    # Vectorized windowing via cumulative sum
    cumsum = torch.zeros(T + 1, device=device, dtype=torch.float64)
    cumsum[1:] = torch.cumsum(pop_counts, dim=0)

    t_starts = torch.arange(0, T - window + 1, step, device=device)
    t_ends = t_starts + window
    counts = cumsum[t_ends] - cumsum[t_starts]

    m1 = counts.mean()
    m2 = counts.var(unbiased=True)
    m4 = torch.mean((counts - m1) ** 4)

    eps = 1e-12
    kurt = m4 / (m2 + eps) ** 2

    if fisher:
        kurt = kurt - 3.0

    kurt_val = kurt.item() if isinstance(kurt, torch.Tensor) else kurt
    return torch.tensor(kurt_val, device=device), {
        "window": window,
        "n_windows": len(counts),
    }

_kurtosis_torch(spikes, window, overlap, fisher, batch_axis)

Torch implementation of kurtosis (GPU-friendly).

Source code in btorch/analysis/spiking.py
def _kurtosis_torch(
    spikes: torch.Tensor,
    window: int,
    overlap: int,
    fisher: bool,
    batch_axis: tuple[int, ...] | None,
):
    """Torch implementation of kurtosis (GPU-friendly)."""
    device = spikes.device
    orig_shape = spikes.shape
    T = orig_shape[0]

    _check_window(window, overlap, T)

    step = window - overlap

    # Cast to float64 for accumulation accuracy
    if spikes.dtype in (torch.float16, torch.float32):
        spike_work = spikes.double()
    else:
        spike_work = spikes

    if batch_axis is not None:
        spike_work = torch.mean(spike_work, dim=tuple(batch_axis), keepdim=False)

    flat_spike = spike_work.reshape(T, -1)
    n_flat = flat_spike.shape[1]

    # Vectorized windowing via cumulative sum
    cumsum_spike = torch.zeros(T + 1, n_flat, device=device, dtype=torch.float64)
    cumsum_spike[1:] = torch.cumsum(flat_spike, dim=0)

    t_starts = torch.arange(0, T - window + 1, step, device=device)
    t_ends = t_starts + window
    counts = cumsum_spike[t_ends] - cumsum_spike[t_starts]

    m1 = counts.mean(dim=0)
    m2 = counts.var(dim=0, unbiased=True)
    m4 = torch.mean((counts - m1) ** 4, dim=0)

    eps = 1e-12
    kurt = m4 / (m2 + eps) ** 2

    if fisher:
        kurt = kurt - 3.0

    # Use spike_work.shape which accounts for batch_axis aggregation
    kurt_result = kurt.reshape(spike_work.shape[1:])
    return kurt_result, {}

_lv_numpy(spikes, dt, batch_axis, dtype=None)

NumPy implementation of Local Variation.

Source code in btorch/analysis/spiking.py
def _lv_numpy(
    spikes: np.ndarray,
    dt: float,
    batch_axis: tuple[int, ...] | None,
    dtype: np.dtype | None = None,
):
    """NumPy implementation of Local Variation."""
    orig_shape = spikes.shape
    T = orig_shape[0]

    # Aggregate across batch dimensions if specified
    if batch_axis is not None:
        spike_aggregated = np.sum(spikes, axis=batch_axis, keepdims=False)
        work_shape = (T,) + spike_aggregated.shape[1:]
    else:
        spike_aggregated = spikes
        work_shape = orig_shape

    flat_data = spike_aggregated.reshape(T, -1)
    n_flat = flat_data.shape[1]

    t_idx, n_idx = np.where(flat_data > 0)

    # Sort by neuron, then time
    sort_order = np.lexsort((t_idx, n_idx))
    t_sorted = t_idx[sort_order].astype(np.float64) * dt
    n_sorted = n_idx[sort_order]

    isis = np.diff(t_sorted)

    # Valid consecutive ISI pairs (same neuron for 3 consecutive spikes)
    valid_mask = (n_sorted[:-2] == n_sorted[1:-1]) & (n_sorted[1:-1] == n_sorted[2:])

    isi_i = isis[:-1][valid_mask]
    isi_j = isis[1:][valid_mask]
    valid_n = n_sorted[:-2][valid_mask]

    # LV formula: 3*(ISI_i - ISI_{i+1})^2 / (ISI_i + ISI_{i+1})^2
    sum_isis = isi_i + isi_j
    diff_isis = isi_i - isi_j
    lv_terms = 3.0 * (diff_isis**2) / (sum_isis**2 + 1e-12)

    # Count valid pairs per neuron
    count_pairs = np.bincount(valid_n, minlength=n_flat)
    sum_lv = np.bincount(valid_n, weights=lv_terms, minlength=n_flat)

    with np.errstate(divide="ignore", invalid="ignore"):
        lv_values_flat = sum_lv / count_pairs

    # NaN for neurons with insufficient ISI pairs
    lv_values_flat[count_pairs < 1] = np.nan

    lv_stats = {}
    for i in range(n_flat):
        if count_pairs[i] < 1:
            lv_stats[i] = {"n_pairs": 0, "lv": np.nan}
        else:
            lv_stats[i] = {
                "n_pairs": int(count_pairs[i]),
                "lv": float(lv_values_flat[i]),
            }

    lv_values = lv_values_flat.reshape(work_shape[1:])
    return lv_values, lv_stats

_lv_torch(spikes, dt, batch_axis)

Torch implementation of Local Variation with GPU optimization.

Source code in btorch/analysis/spiking.py
def _lv_torch(
    spikes: torch.Tensor,
    dt: float,
    batch_axis: tuple[int, ...] | None,
):
    """Torch implementation of Local Variation with GPU optimization."""
    device = spikes.device
    orig_shape = spikes.shape
    T = orig_shape[0]

    # Aggregate across batch dimensions if specified
    if batch_axis is not None:
        axes_to_sum = tuple(batch_axis)
        spike_aggregated = torch.sum(spikes, dim=axes_to_sum, keepdim=False)
        work_shape = (T,) + spike_aggregated.shape[1:]
    else:
        spike_aggregated = spikes
        work_shape = orig_shape

    # Transfer to CPU for ISI extraction
    spike_cpu = spike_aggregated.cpu()
    T = spike_cpu.shape[0]
    flat_data = spike_cpu.reshape(T, -1)
    n_flat = flat_data.shape[1]

    t_idx, n_idx = torch.nonzero(flat_data, as_tuple=True)

    # Sort by neuron, then time (torch.lexsort doesn't exist,
    #   use argsort on packed values)
    packed = n_idx * (T + 1) + t_idx
    sort_order = torch.argsort(packed, stable=True)
    t_sorted = t_idx[sort_order].float() * dt
    n_sorted = n_idx[sort_order]

    isis = torch.diff(t_sorted)

    # Valid consecutive ISI pairs (same neuron for 3 consecutive spikes)
    valid_mask = (n_sorted[:-2] == n_sorted[1:-1]) & (n_sorted[1:-1] == n_sorted[2:])

    isi_i = isis[:-1][valid_mask]
    isi_j = isis[1:][valid_mask]
    valid_n = n_sorted[:-2][valid_mask]

    # LV formula
    sum_isis = isi_i + isi_j
    diff_isis = isi_i - isi_j
    lv_terms = 3.0 * (diff_isis**2) / (sum_isis**2 + 1e-12)

    # Aggregate per neuron
    count_pairs = torch.bincount(valid_n, minlength=n_flat).float()
    sum_lv = torch.bincount(valid_n, weights=lv_terms, minlength=n_flat)

    with torch.no_grad():
        lv_values_flat = sum_lv / (count_pairs + 1e-12)

    lv_values_flat[count_pairs < 1] = float("nan")

    lv_stats = {}
    for i in range(n_flat):
        if count_pairs[i].item() < 1:
            lv_stats[i] = {"n_pairs": 0, "lv": float("nan")}
        else:
            lv_stats[i] = {
                "n_pairs": int(count_pairs[i].item()),
                "lv": float(lv_values_flat[i].item()),
            }

    lv_values = lv_values_flat.reshape(work_shape[1:]).to(device)
    return lv_values, lv_stats

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
def compute_raster(
    sp_matrix: np.ndarray, times: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
    """Get spike raster plot which displays the spiking activity of a group of
    neurons over time."""
    times = np.asarray(times)
    elements = np.where(sp_matrix > 0.0)
    index = elements[1]
    time = times[elements[0]]
    return index, time

compute_spectrum(y, dt, nperseg=None)

Source code in btorch/analysis/spiking.py
def compute_spectrum(
    y: np.ndarray, dt: float, nperseg: int | None = None
) -> tuple[np.ndarray, np.ndarray]:
    from scipy.signal import welch

    freqs, Y_mag = welch(y, fs=1 / dt, nperseg=nperseg, axis=0)
    return freqs, Y_mag

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values. See :func:~btorch.analysis.statistics.use_stats.

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
@use_stats(value_key="cv_temporal", dim=1)
def cv_temporal(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    window: int = 100,
    step: int = 1,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train array of shape [T, ...]. First dimension is time.
        dt: Time step in milliseconds.
        window: Size of the sliding window in time steps.
        step: Step size between consecutive windows.
        batch_axis: Axes to aggregate across (e.g., (1, 2) for trials).
        dtype: Data type for output arrays. If None, uses float64 for NumPy
            and float32 for Torch.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-window values.
            See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values.
            See :func:`~btorch.analysis.statistics.use_stats`.

    Returns:
        cv_temporal: CV values for each window. Shape: [n_windows, ...]
            where n_windows = (T - window) // step + 1.
        info: Dictionary with window boundaries.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)

    T = spikes.shape[0]
    n_windows = (T - window) // step + 1

    # Determine output dtype
    if isinstance(spikes, torch.Tensor):
        out_dtype = dtype if dtype is not None else torch.float32
        cv_values = torch.full(
            (n_windows,) + spikes.shape[1:],
            float("nan"),
            dtype=out_dtype,
            device=spikes.device,
        )
    else:
        out_dtype = dtype if dtype is not None else float
        cv_values = np.full((n_windows,) + spikes.shape[1:], np.nan, dtype=out_dtype)

    for i in range(n_windows):
        start = i * step
        end = start + window
        if end > T:
            break

        window_data = spikes[start:end]

        cv_window, _ = _cv(window_data, dt, batch_axis, dtype)
        cv_values[i] = cv_window

    window_starts = np.arange(n_windows) * step * dt
    window_ends = window_starts + window * dt

    info = {
        "window": window,
        "step": step,
        "window_starts_ms": window_starts,
        "window_ends_ms": window_ends,
    }
    return cv_values, info

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

Returns:

Name Type Description
fano StatsResult

Fano factor values with shape [...] (input shape without time dimension). If stat is provided, returns the aggregated statistic instead.

info StatsResult

Dictionary with optional computed statistics and percentile data.

Source code in btorch/analysis/spiking.py
@use_percentiles(value_key="fano")
@use_stats(value_key="fano")
def fano(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses full duration T.
        overlap: Overlap between consecutive windows.
        batch_axis: Axes to average across for FF computation (e.g., trials).
        dtype: Data type for accumulation. If None, uses float64 for NumPy
            and input dtype (or float32 for float16/bfloat16) for Torch.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        fano: Fano factor values with shape [...]
            (input shape without time dimension).
            If `stat` is provided, returns the aggregated statistic instead.
        info: Dictionary with optional computed statistics and percentile data.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    if window is None:
        # Default window size to get ~10 bins for variance computation
        # Need at least 2 bins for valid variance with unbiased=True
        window = max(1, spikes.shape[0] // 10)
    if isinstance(spikes, torch.Tensor):
        return _fano_torch(spikes, window, overlap, batch_axis, dtype)
    else:
        return _fano_numpy(spikes, window, overlap, batch_axis, dtype)

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
def fano_population(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
) -> StatsResult:
    """Compute Fano factor for the pooled population activity.

    This computes Fano factor from the summed population spike count,
    giving a single population-level metric.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses full duration T.
        overlap: Overlap between consecutive windows.

    Returns:
        fano_pop: Single scalar Fano factor for the population.
        info: Dictionary with 'window' and 'n_windows'.
    """
    if isinstance(spikes, torch.Tensor):
        return _fano_population_torch(spikes, window, overlap)
    else:
        return _fano_population_numpy(spikes, window, overlap)

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 window is not an int or a 2/3-tuple, step is not positive, start is below 1, stop exceeds T + 1, or the range contains no window size.

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
def fano_sweep(
    spikes: np.ndarray | torch.Tensor,
    window: int | tuple[int, ...] | None = None,
    overlap: int = 0,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> tuple[np.ndarray | torch.Tensor, dict]:
    """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)

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: 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)
        overlap: Overlap between consecutive windows.
        batch_axis: Axes to average across (e.g., trials).
        dtype: Data type for output arrays. If None, uses float64 for NumPy
            and float32 for Torch.

    Returns:
        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.

    Raises:
        ValueError: If ``window`` is not an int or a 2/3-tuple, ``step`` is not
            positive, ``start`` is below 1, ``stop`` exceeds ``T + 1``, or the
            range contains no window size.

    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))
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    T = spikes.shape[0]

    # Parse window specification following arange semantics
    if window is None:
        start, stop, step = 1, T // 20 + 1, 1
    elif isinstance(window, int):
        start, stop, step = 1, window + 1, 1
    elif len(window) == 2:
        start, stop, step = window[0], window[1], 1
    elif len(window) == 3:
        start, stop, step = window[0], window[1], window[2]
    else:
        raise ValueError("window must be int, (start, stop), or (start, stop, step)")

    if step <= 0:
        raise ValueError("step must be positive")
    if start < 1:
        raise ValueError("start must be >= 1")
    if stop > T + 1:
        raise ValueError(f"stop must be <= T+1 ({T + 1})")

    window_sizes = np.arange(start, stop, step)
    n_windows = len(window_sizes)

    if n_windows == 0:
        raise ValueError("window range produces no valid window sizes")

    if isinstance(spikes, torch.Tensor):
        device = spikes.device
        out = torch.zeros(
            (n_windows,) + spikes.shape[1:], device=device, dtype=torch.float64
        )
        for i, w in enumerate(window_sizes):
            fano_val, _ = _fano_torch(spikes, int(w), overlap, batch_axis)
            out[i] = fano_val
    else:
        out = np.zeros((n_windows,) + spikes.shape[1:])
        for i, w in enumerate(window_sizes):
            fano_val, _ = _fano_numpy(spikes, int(w), overlap, batch_axis)
            out[i] = fano_val

    info = {
        "window": (start, stop, step),
        "window_sizes": window_sizes,
        "n_windows": n_windows,
    }
    return out, info

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values. See :func:~btorch.analysis.statistics.use_stats.

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
@use_stats(value_key="fano_temporal", dim=1)
def fano_temporal(
    spikes: np.ndarray | torch.Tensor,
    window: int = 100,
    step: int = 1,
    batch_axis: BatchAxis = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Size of the sliding window in time steps for Fano computation.
        step: Step size between consecutive windows.
        batch_axis: Axes to average across (e.g., trials).

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-window values.
            See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values.
            See :func:`~btorch.analysis.statistics.use_stats`.

    Returns:
        fano_temporal: Fano factor values for each window. Shape: [n_windows, ...]
        info: Dictionary with window boundaries.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    T = spikes.shape[0]
    n_windows = (T - window) // step + 1

    if isinstance(spikes, torch.Tensor):
        fano_values = torch.full(
            (n_windows,) + spikes.shape[1:],
            float("nan"),
            dtype=torch.float64,
            device=spikes.device,
        )
    else:
        fano_values = np.full((n_windows,) + spikes.shape[1:], np.nan, dtype=float)

    for i in range(n_windows):
        start = i * step
        end = start + window
        if end > T:
            break

        window_data = spikes[start:end]
        bin = max(1, window_data.shape[0] // 10)

        if isinstance(window_data, torch.Tensor):
            fano_window, _ = _fano_torch(window_data, bin, 0, batch_axis)
            fano_values[i] = fano_window
        else:
            fano_window, _ = _fano_numpy(window_data, bin, 0, batch_axis)
            fano_values[i] = fano_window

    window_starts = np.arange(n_windows) * step
    window_ends = window_starts + window

    info = {
        "window": window,
        "step": step,
        "window_starts": window_starts,
        "window_ends": window_ends,
    }
    return fano_values, info

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
def firing_rate(
    spikes: np.ndarray | torch.Tensor,
    width: int | float | None = 4,
    dt: int | float | None = None,
    batch_axis: BatchAxis = None,
) -> np.ndarray | torch.Tensor:
    """Smooth spikes into firing rates.

    Supports input shapes like [T, ...].
    If batch_axis is not None, averages over the specified dimensions before
    smoothing.

    Args:
        spikes: Spike train array of shape [T, ...].
        width: Smoothing window width. If None or 0, no smoothing is applied.
        dt: Time step in milliseconds. If None, defaults to 1.0.
        batch_axis: Axes to average over before smoothing (e.g., neurons or
            trials). Can be int or tuple of ints.

    Returns:
        firing_rates: Smoothed firing rates with same shape as input (minus
            averaged axes if batch_axis is specified).
    """
    if dt is None:
        dt = 1.0

    if batch_axis is not None:
        # Normalize to a tuple for consistent handling
        if isinstance(batch_axis, int):
            batch_axis = (batch_axis,)
        if isinstance(spikes, np.ndarray):
            spikes = spikes.mean(axis=tuple(batch_axis))
        else:
            spikes = spikes.mean(dim=tuple(batch_axis))

    if width is None or width == 0:
        return spikes / dt

    width1 = int(width // 2) * 2 + 1

    if isinstance(spikes, np.ndarray):
        if spikes.dtype == np.float16:
            spikes = spikes.astype(np.float32)
        window = np.ones(width1, dtype=float) / width1
        # Convolve along time axis (0) for all other dimensions
        out = convolve1d(spikes, window, axis=0, mode="constant", cval=0.0)
        return out / dt

    else:
        # torch implementation for arbitrary dimensions [T, *others]
        orig_shape = spikes.shape
        T = orig_shape[0]

        # Flatten others to treat as batches for conv1d: [T, B] -> [B, 1, T]
        x = spikes.reshape(T, -1).T.unsqueeze(1)

        window = torch.ones(width1, device=spikes.device, dtype=spikes.dtype) / width1
        weight = window.view(1, 1, -1)

        y = torch.conv1d(x, weight, padding="same")

        # [B, 1, T] -> [B, T] -> [T, B] -> [T, *others]
        return y.squeeze(1).T.reshape(orig_shape) / dt

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

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 stat is provided, returns the aggregated statistic instead.

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
@use_percentiles(value_key="cv")
@use_stats(value_key="cv")
def isi_cv(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    batch_axis: BatchAxis = None,
    dtype: np.dtype | torch.dtype | None = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train array of shape [T, ...]. First dimension is time.
            Values are binary (0/1) or spike counts.
        dt: Time step in milliseconds for converting ISI to ms.
        batch_axis: Axes to aggregate ISIs across (e.g., (1, 2) for trials).
            If None, computes CV per element in the non-time dimensions.
        dtype: Data type for accumulation.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        cv_values: CV values reshaped to match input without time dimension.
            Shape: [...] (original shape without T, aggregated over batch_axis).
            If `stat` is provided, returns the aggregated statistic instead.
        info: Dictionary with 'isi_total' (aggregate ISI statistics),
            'isi_stats' (per-neuron statistics), and optional percentile data.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    return _cv(spikes, dt, batch_axis, dtype)

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

Returns:

Type Description
StatsResult

A (value, info) tuple. With the default stat="cv", value

StatsResult

is the scalar population CV of the pooled ISIs (NaN when the

StatsResult

population emitted fewer than two spikes). With stat=None it is

StatsResult

the raw pooled ISI array in units of dt (empty for fewer than two

StatsResult

spikes); any other stat aggregates that array. info holds the

StatsResult

pooled ISIs under "isi_population" and the aggregate under

StatsResult

"isi_population_<stat>".

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
@use_stats(value_key="isi_population", default_stat="cv")
def isi_cv_population(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train array of shape [T, ...]. First dimension is time.
        dt: Time step in milliseconds for converting ISI to ms.

    Keyword Args:
        stat (str | None): Aggregation statistic to return. Default is "cv".
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.

    Returns:
        A ``(value, info)`` tuple. With the default ``stat="cv"``, ``value``
        is the scalar population CV of the pooled ISIs (NaN when the
        population emitted fewer than two spikes). With ``stat=None`` it is
        the raw pooled ISI array in units of ``dt`` (empty for fewer than two
        spikes); any other ``stat`` aggregates that array. ``info`` holds the
        pooled ISIs under ``"isi_population"`` and the aggregate under
        ``"isi_population_<stat>"``.

    Notes:
        ``cv`` follows the backend convention of
        :func:`~btorch.analysis.statistics.compute_stats_batch` (NumPy:
        population std, Torch: unbiased std).
    """
    if isinstance(spikes, torch.Tensor):
        return _isis_population_torch(spikes, dt)
    else:
        return _isis_population_numpy(spikes, dt)

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute and store in info dict. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values ("propagate", "skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

Returns:

Name Type Description
kurt StatsResult

Kurtosis values with shape [...] (input shape without time dimension). If stat is provided, returns the aggregated statistic instead.

info StatsResult

Dictionary with optional computed statistics and percentile data.

Source code in btorch/analysis/spiking.py
@use_percentiles(value_key="kurtosis")
@use_stats(value_key="kurtosis")
def kurtosis(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
    fisher: bool = True,
    batch_axis: BatchAxis = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses full duration T.
        overlap: Overlap between consecutive windows.
        fisher: If True, return excess kurtosis (subtract 3).
        batch_axis: Axes to average across for kurtosis computation.

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            Options: "mean", "median", "max", "min", "std", "var", "argmax",
            "argmin", "cv". See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute
            and store in info dict.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values ("propagate", "skip", "warn",
            "assert"). See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        kurt: Kurtosis values with shape [...]
            (input shape without time dimension).
            If `stat` is provided, returns the aggregated statistic instead.
        info: Dictionary with optional computed statistics and percentile data.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    if window is None:
        # Default window size to get ~10 bins for variance computation
        # Need at least 2 bins for valid variance with unbiased=True
        window = max(1, spikes.shape[0] // 10)
    if isinstance(spikes, torch.Tensor):
        return _kurtosis_torch(spikes, window, overlap, fisher, batch_axis)
    else:
        return _kurtosis_numpy(spikes, window, overlap, fisher, batch_axis)

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
def kurtosis_population(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
    fisher: bool = True,
) -> StatsResult:
    """Compute kurtosis for the pooled population activity.

    This computes kurtosis from the summed population spike count,
    giving a single population-level metric.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses full duration T.
        overlap: Overlap between consecutive windows.
        fisher: If True, return excess kurtosis (subtract 3).

    Returns:
        kurt_pop: Single scalar kurtosis for the population.
        info: Dictionary with 'window' and 'n_windows'.
    """
    if isinstance(spikes, torch.Tensor):
        return _kurtosis_population_torch(spikes, window, overlap, fisher)
    else:
        return _kurtosis_population_numpy(spikes, window, overlap, fisher)

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:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | None

Additional statistics to compute. See :func:~btorch.analysis.statistics.use_stats.

nan_policy str | None

How to handle NaN values ("skip", "warn", "assert"). See :func:~btorch.analysis.statistics.use_stats.

inf_policy str | None

How to handle Inf values. See :func:~btorch.analysis.statistics.use_stats.

percentiles float | tuple[float, ...] | None

Percentile level(s) in [0, 100] to compute. See :func:~btorch.analysis.statistics.use_percentiles.

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(value_key="lv")
@use_stats(value_key="lv")
def local_variation(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    batch_axis: BatchAxis = None,
) -> StatsResult:
    """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.

    Args:
        spikes: Spike train array of shape [T, ...]. First dimension is time.
        dt: Time step in milliseconds.
        batch_axis: Axes to aggregate ISIs across (e.g., (1, 2) for trials).

    Keyword Args:
        stat (str | None): Aggregation statistic to return instead of per-neuron values.
            See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | None): Additional statistics to compute.
            See :func:`~btorch.analysis.statistics.use_stats`.
        nan_policy (str | None): How to handle NaN values ("skip", "warn", "assert").
            See :func:`~btorch.analysis.statistics.use_stats`.
        inf_policy (str | None): How to handle Inf values.
            See :func:`~btorch.analysis.statistics.use_stats`.
        percentiles (float | tuple[float, ...] | None): Percentile level(s) in
            [0, 100] to compute.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        lv_values: LV values reshaped to match input without time dimension.
        lv_stats: Dictionary with per-neuron LV statistics.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    if isinstance(spikes, torch.Tensor):
        return _lv_torch(spikes, dt, batch_axis)
    else:
        return _lv_numpy(spikes, dt, batch_axis)

use_percentiles(func=None, /, *, value_key='values', default_percentiles=None)

use_percentiles(
    func: Callable[..., Any],
) -> PercentilesDecorated
use_percentiles(
    func: None = None,
    /,
    *,
    value_key: str | dict[int, str] = ...,
    default_percentiles: float
    | tuple[float, ...]
    | None = ...,
) -> Callable[[Callable[..., Any]], PercentilesDecorated]

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
def use_percentiles(
    func: Callable[..., Any] | None = None,
    /,
    *,
    value_key: str | dict[int, str] = "values",
    default_percentiles: float | tuple[float, ...] | None = None,
) -> PercentilesDecorated | Callable[[Callable[..., Any]], PercentilesDecorated]:
    """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

    Args:
        func: The function to decorate (or None if using with parentheses)
        value_key: Key to use in info dict for the percentile result
        default_percentiles: Percentiles used when the caller passes none.

    Returns:
        Decorated function with added percentiles parameter

    Example:
        ```python
        @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
        ```
    """

    def decorator(f: Callable[..., Any]) -> PercentilesDecorated:
        @wraps(f)
        def wrapper(
            *args: Any,
            percentiles: PercentileSpec = default_percentiles,
            **kwargs: Any,
        ) -> tuple[Any, ...]:
            result = f(*args, **kwargs)
            if percentiles is None:
                return result

            values_tuple, info = _unpack_result(result, value_key)
            outputs = _Outputs(values_tuple, value_key)
            updated_info = dict(info or {})

            # Resolve ``{position: (info key prefix, percentile levels)}``.
            if isinstance(percentiles, dict):
                # Different percentiles for different return values
                targets = {
                    pos: (_percentile_key(value_key, pos), levels)
                    for pos, levels in percentiles.items()
                }
            elif isinstance(value_key, dict):
                # One percentiles value applied to every labelled output
                targets = {
                    pos: (label, percentiles) for pos, label in value_key.items()
                }
            else:
                targets = {0: (value_key, percentiles)}

            for pos, (key_name, levels) in targets.items():
                perc = compute_percentiles(outputs.get(pos), levels)
                updated_info[f"{key_name}_percentiles"] = perc["percentiles"]
                updated_info[f"{key_name}_levels"] = perc["levels"]

            return (*values_tuple, updated_info)

        return wrapper

    if func is None:
        return decorator
    return decorator(func)

use_stats(func=None, /, *, value_key='values', dim=None, default_stat=None, default_stat_info=None, default_nan_policy='skip', default_inf_policy='propagate')

use_stats(func: Callable[..., Any]) -> StatsDecorated
use_stats(
    func: None = None,
    /,
    *,
    value_key: str | dict[int, str] = ...,
    dim: DimSpec = ...,
    default_stat: StatSpec = ...,
    default_stat_info: StatInfoSpec = ...,
    default_nan_policy: NanPolicy = ...,
    default_inf_policy: InfPolicy = ...,
) -> Callable[[Callable[..., Any]], StatsDecorated]

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
def use_stats(
    func: Callable[..., Any] | None = None,
    /,
    *,
    value_key: str | dict[int, str] = "values",
    dim: DimSpec = None,
    default_stat: StatSpec = None,
    default_stat_info: StatInfoSpec = None,
    default_nan_policy: NanPolicy = "skip",
    default_inf_policy: InfPolicy = "propagate",
) -> StatsDecorated | Callable[[Callable[..., Any]], StatsDecorated]:
    """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

    Args:
        func: The function to decorate (or None if using with parentheses)
        value_key: Key prefix to use in info dict for stat results
        dim: Dimension(s) to aggregate over for each output
        default_nan_policy: Default nan_policy for this decorated function
        default_inf_policy: Default inf_policy for this decorated function
        default_stat: Default stat for this decorated function
        default_stat_info: Default stat_info for this decorated function

    Returns:
        Decorated function with added stat, stat_info, nan_policy, and
        inf_policy parameters

    Example:
        ```python
        @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"}
        )
        ```
    """

    def decorator(f: Callable[..., Any]) -> StatsDecorated:
        # Inspect the wrapped function to determine what arguments it accepts
        sig = inspect.signature(f)
        f_accepts_nan_policy = "nan_policy" in sig.parameters
        f_accepts_inf_policy = "inf_policy" in sig.parameters

        @wraps(f)
        def wrapper(
            *args: Any,
            stat: StatSpec = default_stat,
            stat_info: StatInfoSpec = default_stat_info,
            nan_policy: NanPolicy | None = None,
            inf_policy: InfPolicy | None = None,
            **kwargs: Any,
        ) -> tuple[Any, ...]:
            # Use effective policies (passed value > decorator default)
            nan_pol = nan_policy if nan_policy is not None else default_nan_policy
            inf_pol = inf_policy if inf_policy is not None else default_inf_policy
            policies = {"nan_policy": nan_pol, "inf_policy": inf_pol}

            # Pass policies to the wrapped function if it accepts them
            if f_accepts_nan_policy:
                kwargs["nan_policy"] = nan_pol
            if f_accepts_inf_policy:
                kwargs["inf_policy"] = inf_pol

            values_tuple, info = _unpack_result(f(*args, **kwargs), value_key)
            outputs = _Outputs(values_tuple, value_key, dim)
            updated_info = dict(info or {})

            if stat is not None:
                # A single stat applies to output 0; a dict maps position->stat.
                stat_map = stat if isinstance(stat, dict) else {0: stat}
                aggregated = []
                for pos, choice in stat_map.items():
                    values = outputs.get(pos)
                    key_name = outputs.key(pos)
                    stat_value = compute_stat(
                        values, choice, dim=outputs.dim_for(pos), **policies
                    )
                    aggregated.append(stat_value)
                    updated_info[key_name] = values
                    updated_info[f"{key_name}_{choice}"] = stat_value
                return (*aggregated, updated_info)

            if stat_info is not None:
                # A bare spec applies to output 0; a dict maps position->spec.
                info_map = stat_info if isinstance(stat_info, dict) else {0: stat_info}
                for pos, spec in info_map.items():
                    names = [spec] if isinstance(spec, str) else list(spec)
                    key_name = outputs.key(pos)
                    batch = compute_stats_batch(
                        outputs.get(pos), names, dim=outputs.dim_for(pos), **policies
                    )
                    for name in names:
                        updated_info[f"{key_name}_{name}"] = batch[str(name)]

            # Original values with the (possibly extended) info
            return (*values_tuple, updated_info)

        return wrapper

    if func is None:
        return decorator
    return decorator(func)

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: Adds stat, stat_info, nan_policy, inf_policy args
  • use_percentiles: Adds percentiles arg for computing percentiles
Policy options
  • nan_policy: "skip" (default), "warn", "assert"
  • inf_policy: "propagate" (default), "skip", "warn", "assert"
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
class PercentilesDecorated(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)``.
    """

    def __call__(
        self,
        *args: Any,
        percentiles: PercentileSpec = ...,
        **kwargs: Any,
    ) -> tuple[Any, ...]: ...

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
class StatsDecorated(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)``.
    """

    def __call__(
        self,
        *args: Any,
        stat: StatSpec = ...,
        stat_info: StatInfoSpec = ...,
        nan_policy: NanPolicy | None = ...,
        inf_policy: InfPolicy | None = ...,
        **kwargs: Any,
    ) -> tuple[Any, ...]: ...

_Outputs

Resolve per-position values, info keys and dims of a decorated result.

Source code in btorch/analysis/statistics.py
class _Outputs:
    """Resolve per-position values, info keys and dims of a decorated
    result."""

    def __init__(
        self,
        values: tuple[Any, ...],
        value_key: str | dict[int, str],
        dim: DimSpec = None,
    ) -> None:
        self.values = values
        self.value_key = value_key
        self.dim = dim

    def get(self, pos: int) -> Any:
        if pos < 0 or pos >= len(self.values):
            raise IndexError(
                f"Position {pos} out of range for return tuple "
                f"of length {len(self.values)}"
            )
        return self.values[pos]

    def key(self, pos: int) -> str:
        """Info-key prefix of output ``pos`` used by :func:`use_stats`."""
        if isinstance(self.value_key, dict):
            return self.value_key.get(pos, f"values{pos}")
        if len(self.values) > 1:
            return f"{self.value_key}{pos}"
        return self.value_key

    def dim_for(self, pos: int) -> int | tuple[int, ...] | None:
        if isinstance(self.dim, dict):
            return self.dim.get(pos, None)
        return self.dim
Methods:
key(pos)

Info-key prefix of output pos used by :func:use_stats.

Source code in btorch/analysis/statistics.py
def key(self, pos: int) -> str:
    """Info-key prefix of output ``pos`` used by :func:`use_stats`."""
    if isinstance(self.value_key, dict):
        return self.value_key.get(pos, f"values{pos}")
    if len(self.values) > 1:
        return f"{self.value_key}{pos}"
    return self.value_key

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
def _apply_value_policy(
    values: np.ndarray | torch.Tensor,
    *,
    name: str,
    policy: str,
    detect: Callable[[Any], Any],
) -> np.ndarray | torch.Tensor:
    """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).
    """
    if policy == "propagate":
        return values
    bad = detect(values)
    if not bad.any():
        return values
    if policy == "assert":
        raise ValueError(f"{name} values found in input")
    if policy == "warn":
        warnings.warn(f"{name} values found in input", UserWarning, stacklevel=4)
    return values[~bad]

_percentile_key(value_key, pos)

Info-key prefix of output pos used by :func:use_percentiles.

Source code in btorch/analysis/statistics.py
def _percentile_key(value_key: str | dict[int, str], pos: int) -> str:
    """Info-key prefix of output ``pos`` used by :func:`use_percentiles`."""
    if isinstance(value_key, dict):
        return value_key.get(pos, f"values{pos}")
    return f"{value_key}{pos}"

_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
def _unpack_result(
    result: Any, value_key: str | dict[int, str]
) -> tuple[tuple[Any, ...], dict]:
    """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.

    Args:
        result: The return value from a decorated function
        value_key: The value_key from the decorator (str or dict)

    Returns:
        Tuple of (values_tuple, info_dict)
    """
    if isinstance(result, tuple):
        if isinstance(value_key, dict):
            # Dict value_key: only extract info if there's an extra element
            expected_values = max(value_key.keys()) + 1
            if len(result) > expected_values and isinstance(result[-1], dict):
                return result[:-1], result[-1]
            else:
                return result, {}
        else:
            # String value_key: original heuristic
            if len(result) >= 2 and isinstance(result[-1], dict):
                return result[:-1], result[-1]
            else:
                return result, {}
    else:
        return (result,), {}

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
def compute_log_hist(
    data: np.ndarray,
    bins: int = 1000,
    edge_pos: Literal["mid", "sep"] = "mid",
) -> tuple:
    """Compute histogram with logarithmically-spaced bins.

    Useful for visualizing heavy-tailed distributions like synaptic weights
    or degree distributions.

    Args:
        data: Input data array (must be positive).
        bins: Number of histogram bins.
        edge_pos: Position to return for bin edges.
            "mid": Return bin centers (midpoints).
            "sep": Return bin separators (edges).

    Returns:
        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:
        ValueError: If data contains non-positive values (required for log scale).
    """
    bin_edges = np.logspace(np.log10(np.min(data)), np.log10(np.max(data)), num=bins)
    hist, edges = np.histogram(data, bins=bin_edges)
    if edge_pos == "mid":
        bin_edges = 0.5 * (edges[:-1] + edges[1:])
    return hist, bin_edges

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 [0, 100].

Source code in btorch/analysis/statistics.py
def compute_percentiles(
    values: np.ndarray | torch.Tensor,
    percentiles: float | tuple[float, ...],
) -> dict[str, list[float] | tuple[float, ...]]:
    """Compute percentiles of values.

    Works with both numpy arrays and PyTorch tensors, preserving the input type.

    Args:
        values: Input array or tensor
        percentiles: Percentile level(s) in [0, 100] range (e.g., 50 for median)

    Returns:
        Dictionary with "levels" and "percentiles" keys

    Raises:
        ValueError: If any requested percentile is outside ``[0, 100]``.
    """
    # Normalize percentiles to a tuple
    if isinstance(percentiles, (int, float)):
        levels = (float(percentiles),)
    else:
        levels = tuple(float(p) for p in percentiles)

    # Validate levels
    for p in levels:
        if not 0 <= p <= 100:
            raise ValueError(f"Percentile must be in [0, 100], got {p}")

    if isinstance(values, torch.Tensor):
        # Use torch.quantile for tensor inputs (preserves device/dtype)
        values_flat = values.flatten()
        if values_flat.dtype == torch.float16:
            values_flat = values_flat.to(torch.float32)
        # torch.quantile takes quantiles in [0, 1] range directly
        perc_values = torch.quantile(
            values_flat,
            torch.tensor([p / 100 for p in levels], device=values.device),
        ).tolist()
    else:
        # Use numpy for array inputs
        values_flat = np.asarray(values).flatten()
        perc_values = [np.percentile(values_flat, p) for p in levels]

    return {
        "levels": levels,
        "percentiles": perc_values,
    }

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 stat is unknown or a policy is "assert" and the offending values are present.

Example

import numpy as np data = np.random.randn(100) compute_stat(data, "mean") 0.1

Source code in btorch/analysis/statistics.py
def compute_stat(
    values: np.ndarray | torch.Tensor,
    stat: StatChoice,
    *,
    nan_policy: NanPolicy = "skip",
    inf_policy: InfPolicy = "propagate",
    dim: int | tuple[int, ...] | None = None,
) -> Any:
    """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.

    Args:
        values: Input array or tensor
        stat: Statistic to compute
        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
        dim: Dimension(s) to aggregate over. If None, flattens all dimensions.

    Returns:
        Computed statistic value

    Raises:
        ValueError: If ``stat`` is unknown or a policy is ``"assert"`` and the
            offending values are present.

    Example:
        >>> import numpy as np
        >>> data = np.random.randn(100)
        >>> compute_stat(data, "mean")
        0.1
    """
    return compute_stats_batch(
        values, [stat], nan_policy=nan_policy, inf_policy=inf_policy, dim=dim
    )[stat]

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 "assert" and the offending values are present.

Example

import numpy as np data = np.random.randn(100) compute_stats_batch(data, ["mean", "std", "cv"])

Source code in btorch/analysis/statistics.py
def compute_stats_batch(
    values: np.ndarray | torch.Tensor,
    stats: Iterable[StatChoice],
    *,
    nan_policy: NanPolicy = "skip",
    inf_policy: InfPolicy = "propagate",
    dim: int | tuple[int, ...] | None = None,
) -> dict[str, Any]:
    """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).

    Args:
        values: Input array or tensor
        stats: Statistics to compute
        nan_policy: How to handle NaN values
        inf_policy: How to handle Inf values
        dim: Dimension(s) to aggregate over. If None, flattens all dimensions.

    Returns:
        Dict mapping each stat to its computed value

    Raises:
        ValueError: If a stat is unknown or a policy is ``"assert"`` and the
            offending values are present.

    Example:
        >>> import numpy as np
        >>> data = np.random.randn(100)
        >>> compute_stats_batch(data, ["mean", "std", "cv"])
        {'mean': 0.1, 'std': 1.0, 'cv': 10.0}
    """
    stats = [str(s) for s in stats]
    for name in stats:
        if name != "cv" and name not in _NUMPY_REDUCERS:
            raise ValueError(f"Unknown stat: {name}")

    is_tensor = isinstance(values, torch.Tensor)
    nan_detect, inf_detect = (
        (torch.isnan, torch.isinf) if is_tensor else (np.isnan, np.isinf)
    )
    values = _apply_value_policy(
        values, name="NaN", policy=nan_policy, detect=nan_detect
    )
    values = _apply_value_policy(
        values, name="Inf", policy=inf_policy, detect=inf_detect
    )
    if dim is None:
        values = values.flatten()
        dim = 0
        if (values.numel() if is_tensor else values.size) == 0:
            # Nothing left to aggregate (e.g. fewer than two spikes): every
            # statistic is undefined, so report NaN instead of warning/raising.
            return {name: float("nan") for name in stats}

    reducers = _TORCH_REDUCERS if is_tensor else _NUMPY_REDUCERS
    cache: dict[str, Any] = {}

    def reduce(name: str) -> Any:
        # mean/std are shared between their own request and ``cv``.
        if name not in cache:
            cache[name] = reducers[name](values, dim)
        return cache[name]

    results: dict[str, Any] = {}
    for name in stats:
        value = (
            reduce("std") / (reduce("mean") + 1e-10) if name == "cv" else reduce(name)
        )
        if is_tensor and value.numel() == 1:
            value = value.item()
        results[name] = value
    return results

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 mean, median, std, min, max,

dict[str, float]

q25, q50 and q75.

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
def describe_array(array: np.ndarray, verbose: bool = True) -> dict[str, float]:
    """Compute descriptive statistics for an array.

    Computes mean, median, std, min, max, and quartiles, optionally printing
    them.

    Args:
        array: NumPy array to describe (statistics are over all elements).
        verbose: If True (default), also print the statistics.

    Returns:
        Dictionary with keys ``mean``, ``median``, ``std``, ``min``, ``max``,
        ``q25``, ``q50`` and ``q75``.

    Example:
        >>> stats = describe_array(np.random.randn(100), verbose=False)
        >>> sorted(stats)
        ['max', 'mean', 'median', 'min', 'q25', 'q50', 'q75', 'std']
    """
    q25, q50, q75 = np.percentile(array, [25, 50, 75])  # q50 equals the median
    stats = {
        "mean": float(np.mean(array)),
        "median": float(np.median(array)),
        "std": float(np.std(array)),
        "min": float(np.min(array)),
        "max": float(np.max(array)),
        "q25": float(q25),
        "q50": float(q50),
        "q75": float(q75),
    }

    if verbose:
        print(f"Mean: {stats['mean']}")
        print(f"Median: {stats['median']}")
        print(f"Standard Deviation: {stats['std']}")
        print(f"Min: {stats['min']}")
        print(f"Max: {stats['max']}")
        print(f"25th Percentile (Q1): {stats['q25']}")
        print(f"50th Percentile (Q2/Median): {stats['q50']}")
        print(f"75th Percentile (Q3): {stats['q75']}")
    return stats

use_percentiles(func=None, /, *, value_key='values', default_percentiles=None)

use_percentiles(
    func: Callable[..., Any],
) -> PercentilesDecorated
use_percentiles(
    func: None = None,
    /,
    *,
    value_key: str | dict[int, str] = ...,
    default_percentiles: float
    | tuple[float, ...]
    | None = ...,
) -> Callable[[Callable[..., Any]], PercentilesDecorated]

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
def use_percentiles(
    func: Callable[..., Any] | None = None,
    /,
    *,
    value_key: str | dict[int, str] = "values",
    default_percentiles: float | tuple[float, ...] | None = None,
) -> PercentilesDecorated | Callable[[Callable[..., Any]], PercentilesDecorated]:
    """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

    Args:
        func: The function to decorate (or None if using with parentheses)
        value_key: Key to use in info dict for the percentile result
        default_percentiles: Percentiles used when the caller passes none.

    Returns:
        Decorated function with added percentiles parameter

    Example:
        ```python
        @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
        ```
    """

    def decorator(f: Callable[..., Any]) -> PercentilesDecorated:
        @wraps(f)
        def wrapper(
            *args: Any,
            percentiles: PercentileSpec = default_percentiles,
            **kwargs: Any,
        ) -> tuple[Any, ...]:
            result = f(*args, **kwargs)
            if percentiles is None:
                return result

            values_tuple, info = _unpack_result(result, value_key)
            outputs = _Outputs(values_tuple, value_key)
            updated_info = dict(info or {})

            # Resolve ``{position: (info key prefix, percentile levels)}``.
            if isinstance(percentiles, dict):
                # Different percentiles for different return values
                targets = {
                    pos: (_percentile_key(value_key, pos), levels)
                    for pos, levels in percentiles.items()
                }
            elif isinstance(value_key, dict):
                # One percentiles value applied to every labelled output
                targets = {
                    pos: (label, percentiles) for pos, label in value_key.items()
                }
            else:
                targets = {0: (value_key, percentiles)}

            for pos, (key_name, levels) in targets.items():
                perc = compute_percentiles(outputs.get(pos), levels)
                updated_info[f"{key_name}_percentiles"] = perc["percentiles"]
                updated_info[f"{key_name}_levels"] = perc["levels"]

            return (*values_tuple, updated_info)

        return wrapper

    if func is None:
        return decorator
    return decorator(func)

use_stats(func=None, /, *, value_key='values', dim=None, default_stat=None, default_stat_info=None, default_nan_policy='skip', default_inf_policy='propagate')

use_stats(func: Callable[..., Any]) -> StatsDecorated
use_stats(
    func: None = None,
    /,
    *,
    value_key: str | dict[int, str] = ...,
    dim: DimSpec = ...,
    default_stat: StatSpec = ...,
    default_stat_info: StatInfoSpec = ...,
    default_nan_policy: NanPolicy = ...,
    default_inf_policy: InfPolicy = ...,
) -> Callable[[Callable[..., Any]], StatsDecorated]

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
def use_stats(
    func: Callable[..., Any] | None = None,
    /,
    *,
    value_key: str | dict[int, str] = "values",
    dim: DimSpec = None,
    default_stat: StatSpec = None,
    default_stat_info: StatInfoSpec = None,
    default_nan_policy: NanPolicy = "skip",
    default_inf_policy: InfPolicy = "propagate",
) -> StatsDecorated | Callable[[Callable[..., Any]], StatsDecorated]:
    """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

    Args:
        func: The function to decorate (or None if using with parentheses)
        value_key: Key prefix to use in info dict for stat results
        dim: Dimension(s) to aggregate over for each output
        default_nan_policy: Default nan_policy for this decorated function
        default_inf_policy: Default inf_policy for this decorated function
        default_stat: Default stat for this decorated function
        default_stat_info: Default stat_info for this decorated function

    Returns:
        Decorated function with added stat, stat_info, nan_policy, and
        inf_policy parameters

    Example:
        ```python
        @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"}
        )
        ```
    """

    def decorator(f: Callable[..., Any]) -> StatsDecorated:
        # Inspect the wrapped function to determine what arguments it accepts
        sig = inspect.signature(f)
        f_accepts_nan_policy = "nan_policy" in sig.parameters
        f_accepts_inf_policy = "inf_policy" in sig.parameters

        @wraps(f)
        def wrapper(
            *args: Any,
            stat: StatSpec = default_stat,
            stat_info: StatInfoSpec = default_stat_info,
            nan_policy: NanPolicy | None = None,
            inf_policy: InfPolicy | None = None,
            **kwargs: Any,
        ) -> tuple[Any, ...]:
            # Use effective policies (passed value > decorator default)
            nan_pol = nan_policy if nan_policy is not None else default_nan_policy
            inf_pol = inf_policy if inf_policy is not None else default_inf_policy
            policies = {"nan_policy": nan_pol, "inf_policy": inf_pol}

            # Pass policies to the wrapped function if it accepts them
            if f_accepts_nan_policy:
                kwargs["nan_policy"] = nan_pol
            if f_accepts_inf_policy:
                kwargs["inf_policy"] = inf_pol

            values_tuple, info = _unpack_result(f(*args, **kwargs), value_key)
            outputs = _Outputs(values_tuple, value_key, dim)
            updated_info = dict(info or {})

            if stat is not None:
                # A single stat applies to output 0; a dict maps position->stat.
                stat_map = stat if isinstance(stat, dict) else {0: stat}
                aggregated = []
                for pos, choice in stat_map.items():
                    values = outputs.get(pos)
                    key_name = outputs.key(pos)
                    stat_value = compute_stat(
                        values, choice, dim=outputs.dim_for(pos), **policies
                    )
                    aggregated.append(stat_value)
                    updated_info[key_name] = values
                    updated_info[f"{key_name}_{choice}"] = stat_value
                return (*aggregated, updated_info)

            if stat_info is not None:
                # A bare spec applies to output 0; a dict maps position->spec.
                info_map = stat_info if isinstance(stat_info, dict) else {0: stat_info}
                for pos, spec in info_map.items():
                    names = [spec] if isinstance(spec, str) else list(spec)
                    key_name = outputs.key(pos)
                    batch = compute_stats_batch(
                        outputs.get(pos), names, dim=outputs.dim_for(pos), **policies
                    )
                    for name in names:
                        updated_info[f"{key_name}_{name}"] = batch[str(name)]

            # Original values with the (possibly extended) info
            return (*values_tuple, updated_info)

        return wrapper

    if func is None:
        return decorator
    return decorator(func)

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 mode is not one of "std", "mse_threshold" or "threshold_resting".

KeyError

If a required threshold parameter (V_th, and V_reset for "threshold_resting") is missing from params.

Source code in btorch/analysis/voltage.py
def compute_voltage_overshoot(
    V: np.ndarray | torch.Tensor,
    mode: Literal["std", "mse_threshold", "threshold_resting"] = "threshold_resting",
    skip_timestep: int | None = None,
    **params: float,
) -> np.ndarray | torch.Tensor:
    """Quantify voltage stability/overshoot in different ways.

    Raises:
        ValueError: If ``mode`` is not one of ``"std"``, ``"mse_threshold"`` or
            ``"threshold_resting"``.
        KeyError: If a required threshold parameter (``V_th``, and ``V_reset``
            for ``"threshold_resting"``) is missing from ``params``.
    """
    is_numpy = isinstance(V, np.ndarray)
    V = V.astype(np.float32) if is_numpy else V.to(torch.float32)

    if skip_timestep is None:
        skip_timestep = suggest_skip_timestep(V)

    V_slice = V[skip_timestep:]
    if mode == "std":
        return V_slice.std(0)

    elif mode == "mse_threshold":
        V_th = params["V_th"]
        return (
            (V_slice - V_th).pow(2).mean(0)
            if not is_numpy
            else np.mean((V_slice - V_th) ** 2, axis=0)
        )

    elif mode == "threshold_resting":
        V_th = params["V_th"]
        V_reset = params["V_reset"]
        n_scale = params.get("n_scale", 3)

        scale = V_th - V_reset

        upper = V_th + n_scale * scale
        lower = V_reset - n_scale * scale

        mask = (V_slice > upper) | (V_slice < lower)
        return mask.astype(np.float32).mean(0) if is_numpy else mask.float().mean(0)

    else:
        raise ValueError(f"Unsupported mode: {mode}")

suggest_skip_timestep(data)

Suggest a burn-in period based on trace length.

Source code in btorch/analysis/voltage.py
def suggest_skip_timestep(data: np.ndarray | torch.Tensor) -> int:
    """Suggest a burn-in period based on trace length."""
    skip_timestep = data.shape[0] // 8
    if skip_timestep < 100:
        skip_timestep = 0
    if skip_timestep > 1000:
        skip_timestep = 1000
    return skip_timestep