Skip to content

Analysis — Dynamic Tools

btorch.analysis.dynamic_tools.attractor_dynamics

Classes

EigenvalueOutliers

Bases: TypedDict

Result of :func:compute_structural_eigenvalue_outliers.

Source code in btorch/analysis/dynamic_tools/attractor_dynamics.py
class EigenvalueOutliers(TypedDict):
    """Result of :func:`compute_structural_eigenvalue_outliers`."""

    eigenvalues: np.ndarray  # complex, shape (N,)
    max_eigenvalue: float  # largest eigenvalue magnitude |lambda| (0.0 if N == 0)
    outliers: np.ndarray  # complex eigenvalues with |lambda| > spectral_radius
    outlier_count: int
    spectral_radius: float  # bulk radius used as the threshold

Functions:

compute_kaplan_yorke_dimension(lyapunov_spectrum)

Calculate the Kaplan-Yorke Dimension (D_KY), also known as the Lyapunov Dimension.

Formula: D_KY = k + sum(lambda_i for i=1 to k) / |lambda_{k+1}| where k is the max index such that the sum of the first k exponents is non-negative.

Parameters:

Name Type Description Default
lyapunov_spectrum ndarray

Array of Lyapunov exponents, sorted in descending order.

required

Returns:

Name Type Description
float float

The Kaplan-Yorke dimension. Returns 0 if the system is stable (all lambda < 0). Returns the number of exponents if the sum of all is positive (unbounded/hyperchaos). A stable or fully expanding spectrum is a valid result, not a failure; no NaN sentinel is used (an empty spectrum gives 0.0).

Source code in btorch/analysis/dynamic_tools/attractor_dynamics.py
def compute_kaplan_yorke_dimension(lyapunov_spectrum: np.ndarray) -> float:
    """Calculate the Kaplan-Yorke Dimension (D_KY), also known as the Lyapunov
    Dimension.

    Formula: D_KY = k + sum(lambda_i for i=1 to k) / |lambda_{k+1}|
    where k is the max index such that the sum of the first k exponents is non-negative.

    Args:
        lyapunov_spectrum (np.ndarray): Array of Lyapunov exponents, sorted in
            descending order.

    Returns:
        float: The Kaplan-Yorke dimension. Returns 0 if the system is stable
            (all lambda < 0). Returns the number of exponents if the sum of all
            is positive (unbounded/hyperchaos). A stable or fully expanding
            spectrum is a valid result, not a failure; no NaN sentinel is
            used (an empty spectrum gives 0.0).
    """
    ls = np.sort(lyapunov_spectrum)[::-1]

    n = len(ls)

    cum_sum = np.cumsum(ls)

    # k: last index whose cumulative sum is still non-negative.
    positive_sums = np.where(cum_sum >= 0)[0]

    if len(positive_sums) == 0:
        # All cumulative sums are negative.
        # This usually means the first exponent is negative (stable fixed point).
        return 0.0

    k = positive_sums[-1]

    if k == n - 1:
        return float(n)

    # 0-based k is the last summed index, so the integer part is k + 1.
    sum_lambda = cum_sum[k]
    lambda_next = ls[k + 1]

    if lambda_next == 0:
        # Guard against division by zero (lambda_{k+1} is normally negative).
        return float(k + 1)

    d_ky = (k + 1) + sum_lambda / abs(lambda_next)

    return d_ky

compute_structural_eigenvalue_outliers(weight_matrix, spectral_radius=None)

Analyze the eigenvalues of the weight matrix to identify structural outliers.

According to the circular law, eigenvalues of a random matrix are distributed within a disk of radius R. Outliers outside this radius indicate structural enforcement of specific oscillatory modes (stable dynamics) rather than random chaos.

Parameters:

Name Type Description Default
weight_matrix ndarray

The connectivity weight matrix (N x N).

required
spectral_radius float

The theoretical spectral radius of the random component. If None, it is estimated as std(W) * sqrt(N).

None

Returns:

Name Type Description
EigenvalueOutliers EigenvalueOutliers

Dictionary containing: - 'eigenvalues': All eigenvalues. - 'max_eigenvalue': Largest eigenvalue magnitude. - 'outliers': Eigenvalues outside the spectral radius. - 'outlier_count': Number of outliers. - 'spectral_radius': The radius used for thresholding. There is no NaN failure return; invalid input raises.

Raises:

Type Description
ValueError

If weight_matrix is not square.

Source code in btorch/analysis/dynamic_tools/attractor_dynamics.py
def compute_structural_eigenvalue_outliers(
    weight_matrix: np.ndarray, spectral_radius: float | None = None
) -> EigenvalueOutliers:
    """Analyze the eigenvalues of the weight matrix to identify structural
    outliers.

    According to the circular law, eigenvalues of a random matrix are distributed
    within a disk of radius R. Outliers outside this radius indicate structural
    enforcement of specific oscillatory modes (stable dynamics) rather than
    random chaos.

    Args:
        weight_matrix (np.ndarray): The connectivity weight matrix (N x N).
        spectral_radius (float, optional): The theoretical spectral radius of the
            random component. If None, it is estimated as std(W) * sqrt(N).

    Returns:
        EigenvalueOutliers: Dictionary containing:
            - 'eigenvalues': All eigenvalues.
            - 'max_eigenvalue': Largest eigenvalue magnitude.
            - 'outliers': Eigenvalues outside the spectral radius.
            - 'outlier_count': Number of outliers.
            - 'spectral_radius': The radius used for thresholding.
            There is no NaN failure return; invalid input raises.

    Raises:
        ValueError: If ``weight_matrix`` is not square.
    """
    W = np.array(weight_matrix)
    N = W.shape[0]

    if W.shape[0] != W.shape[1]:
        raise ValueError("Weight matrix must be square.")

    eigenvalues = np.linalg.eigvals(W)

    if spectral_radius is None:
        # Circular law: W_ij ~ N(0, sigma^2) gives bulk radius sigma * sqrt(N).
        sigma = np.std(W)
        spectral_radius = sigma * np.sqrt(N)

    magnitudes = np.abs(eigenvalues)
    outlier_indices = np.where(magnitudes > spectral_radius)[0]
    outliers = eigenvalues[outlier_indices]

    return {
        "eigenvalues": eigenvalues,
        "max_eigenvalue": np.max(magnitudes) if len(magnitudes) > 0 else 0.0,
        "outliers": outliers,
        "outlier_count": len(outliers),
        "spectral_radius": spectral_radius,  # Bulk Radius (Threshold)
    }

btorch.analysis.dynamic_tools.complexity

Functions:

compute_continuous_spiking_rate(spikes, dt, sigma=20.0)

Convert discrete spike trains into continuous firing rates using Gaussian smoothing.

The output follows the input type: a torch.Tensor input gives a float64 tensor on the input device, anything else a float64 NumPy array. The smoothing itself runs in SciPy on the CPU.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix of shape (time_steps, n_neurons).

required
dt float

Simulation time step in ms.

required
sigma float

Standard deviation of the Gaussian kernel in ms. Default 20 ms.

20.0

Returns:

Type Description
ndarray | Tensor

Continuous firing rate traces of shape (time_steps, n_neurons),

ndarray | Tensor

as a tensor for tensor input and as an array otherwise.

ndarray | Tensor

There is no NaN failure return; NaN/inf in the input propagate.

Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
def compute_continuous_spiking_rate(
    spikes: np.ndarray | torch.Tensor,
    dt: float,
    sigma: float = 20.0,
) -> np.ndarray | torch.Tensor:
    """Convert discrete spike trains into continuous firing rates using
    Gaussian smoothing.

    The output follows the input type: a ``torch.Tensor`` input gives a
    ``float64`` tensor on the input device, anything else a ``float64`` NumPy
    array. The smoothing itself runs in SciPy on the CPU.

    Args:
        spikes: Spike matrix of shape ``(time_steps, n_neurons)``.
        dt: Simulation time step in ms.
        sigma: Standard deviation of the Gaussian kernel in ms. Default 20 ms.

    Returns:
        Continuous firing rate traces of shape ``(time_steps, n_neurons)``,
        as a tensor for tensor input and as an array otherwise.
        There is no NaN failure return; NaN/inf in the input propagate.
    """
    # sigma is in ms, dt in ms: convert to bins
    sigma_bins = sigma / dt

    rates = gaussian_filter1d(to_numpy(spikes).astype(float), sigma=sigma_bins, axis=0)

    if isinstance(spikes, torch.Tensor):
        return torch.from_numpy(rates).to(spikes.device)
    return rates

compute_gain_stability_sensitivity(model, dataloader, g_values=None, dt=1.0, device='cuda')

Calculate the Gain-Stability Sensitivity (Susceptibility) slope.

Definition: The slope of the curve of the Maximum Lyapunov Exponent (lambda_max) as a function of global synaptic gain scaling (g).

The model must expose model.brain.synapse.linear (the recurrent connection whose weights are scaled) and model.brain.neuron. The scaled tensor is linear.weight for dense layers, and linear.weight.value (per-edge weights) or linear.weight.scale (grouped weights) for a :class:~btorch.models.connection.SparseConnection. The model weights are always restored, even if the sweep raises.

Parameters:

Name Type Description Default
model Module

The Brain model.

required
dataloader DataLoader

DataLoader providing input.

required
g_values ndarray | None

Array of gain scaling factors. Default np.linspace(0.5, 5.0, 10).

None
dt float

Simulation time step.

1.0
device str

Device to run on.

'cuda'

Returns:

Name Type Description
tuple tuple[float, float, ndarray, ndarray]

(slope, intercept, g_values, lambda_values) - slope: The slope of lambda_max vs g (NaN if fewer than two finite lambda values were obtained). - intercept: The intercept of the fit (NaN as above). - g_values: The gain values used. - lambda_values: The computed max Lyapunov exponents; NaN for gains where the estimate failed.

Raises:

Type Description
AttributeError

If the model lacks brain.synapse.linear or the layer has no scalable weight tensor.

ValueError

If the dataloader is empty.

Source code in btorch/analysis/dynamic_tools/complexity.py
def compute_gain_stability_sensitivity(
    model: torch.nn.Module,
    dataloader: torch.utils.data.DataLoader,
    g_values: np.ndarray | None = None,
    dt: float = 1.0,
    device: str = "cuda",
) -> tuple[float, float, np.ndarray, np.ndarray]:
    """Calculate the Gain-Stability Sensitivity (Susceptibility) slope.

    Definition: The slope of the curve of the Maximum Lyapunov Exponent (lambda_max)
    as a function of global synaptic gain scaling (g).

    The model must expose ``model.brain.synapse.linear`` (the recurrent
    connection whose weights are scaled) and ``model.brain.neuron``. The scaled
    tensor is ``linear.weight`` for dense layers, and ``linear.weight.value``
    (per-edge weights) or ``linear.weight.scale`` (grouped weights) for a
    :class:`~btorch.models.connection.SparseConnection`. The model weights are
    always restored, even if the sweep raises.

    Args:
        model: The Brain model.
        dataloader: DataLoader providing input.
        g_values: Array of gain scaling factors. Default np.linspace(0.5, 5.0, 10).
        dt: Simulation time step.
        device: Device to run on.

    Returns:
        tuple: (slope, intercept, g_values, lambda_values)
            - slope: The slope of lambda_max vs g (NaN if fewer than two
              finite lambda values were obtained).
            - intercept: The intercept of the fit (NaN as above).
            - g_values: The gain values used.
            - lambda_values: The computed max Lyapunov exponents; NaN for gains
              where the estimate failed.

    Raises:
        AttributeError: If the model lacks ``brain.synapse.linear`` or the
            layer has no scalable weight tensor.
        ValueError: If the dataloader is empty.
    """
    # Local import: btorch.models is heavy and only needed for this routine.
    from btorch.models import functional, init

    if g_values is None:
        g_values = np.linspace(0.5, 5.0, 10)
    g_values = np.asarray(g_values, dtype=float)

    # Assuming model is Brain, model.brain is RecurrentNN, model.brain.synapse
    # is Synapse and model.brain.synapse.linear is the layer.
    model.eval()
    model.to(device)

    # Resolved after the device move: moving a module replaces its buffers.
    try:
        weight = model.brain.synapse.linear.weight
    except AttributeError as e:
        raise AttributeError(
            "model must expose model.brain.synapse.linear with a weight"
        ) from e
    if not isinstance(weight, torch.Tensor):
        # Weight module of a SparseConnection: per-edge values or group scales.
        weight = getattr(weight, "value", getattr(weight, "scale", None))
    if not isinstance(weight, torch.Tensor):
        raise AttributeError("model.brain.synapse.linear has no scalable weight tensor")
    original_weight = weight.detach().clone()

    try:
        batch = next(iter(dataloader))
    except StopIteration:
        raise ValueError("dataloader is empty") from None

    inputs = batch["input"]
    # inputs: (Batch, Time, ...) -> (Time, Batch, ...)
    inputs = inputs.transpose(0, 1).to(device)

    # We can use the first sample in the batch.
    input_sample = inputs[:, 0:1, ...]  # Keep batch dim 1

    lambda_values = []
    try:
        for g in g_values:
            with torch.no_grad():
                weight.copy_(original_weight * g)

            functional.reset_net(model, batch_size=1, device=device)
            init.uniform_v_(model.brain.neuron, set_reset_value=True)

            with torch.no_grad():
                _, brain_out = model(input_sample)
                spikes = brain_out["neuron"]["spike"]  # (Time, Batch, Neurons)

            # spikes: (Time, 1, Neurons) -> (Time, Neurons)
            spikes_sq = spikes.squeeze(1)

            rates = to_numpy(compute_continuous_spiking_rate(spikes_sq, dt=dt))

            # Mean population rate for LE calculation
            mean_rate = rates.mean(axis=1)

            # Compute LE; nolds raises ValueError/RuntimeError on degenerate
            # series (e.g. too short or constant). Record NaN, not a fake 0.
            try:
                le = compute_max_lyapunov_exponent(mean_rate)
            except (ValueError, RuntimeError, ArithmeticError) as e:
                warnings.warn(f"Lyapunov exponent failed for g={g}: {e}", stacklevel=2)
                le = float("nan")

            lambda_values.append(le)
    finally:
        # Restore weights even if the sweep raised
        with torch.no_grad():
            weight.copy_(original_weight)

    lambda_arr = np.asarray(lambda_values, dtype=float)

    # Fit line: lambda = slope * g + intercept, ignoring NaN/Inf entries
    valid = np.isfinite(lambda_arr)
    if np.sum(valid) < 2:
        warnings.warn(
            "Fewer than two finite Lyapunov exponents; slope is NaN", stacklevel=2
        )
        return float("nan"), float("nan"), g_values, lambda_arr

    slope, intercept = np.polyfit(g_values[valid], lambda_arr[valid], 1)

    return float(slope), float(intercept), g_values, lambda_arr

compute_lyapunov_exponent_from_spikes(spike_train, dt=0.1)

Calculate the maximum Lyapunov exponent for a given spike train.

Pipeline: smooth the spikes into rates, average over neurons and pass the resulting 1-D series to :func:compute_max_lyapunov_exponent, which is the one to use when you already have a 1-D series and want to set embedding arguments.

Parameters:

Name Type Description Default
spike_train Tensor

The spike train data. Shape (time_steps, num_neurons).

required
dt float

Time bin size in milliseconds. Default is 0.1 ms.

0.1

Returns:

Name Type Description
float float

The maximum Lyapunov exponent. Failure return: whatever :func:compute_max_lyapunov_exponent (nolds.lyap_r) yields for a degenerate series; this function adds no NaN sentinel of its own.

Raises:

Type Description
ValueError

If spike_train is not 2D.

Source code in btorch/analysis/dynamic_tools/complexity.py
def compute_lyapunov_exponent_from_spikes(
    spike_train: torch.Tensor, dt: float = 0.1
) -> float:
    """Calculate the maximum Lyapunov exponent for a given spike train.

    Pipeline: smooth the spikes into rates, average over neurons and pass the
    resulting 1-D series to :func:`compute_max_lyapunov_exponent`, which is the
    one to use when you already have a 1-D series and want to set embedding
    arguments.

    Args:
        spike_train (torch.Tensor): The spike train data. Shape
            ``(time_steps, num_neurons)``.
        dt (float): Time bin size in milliseconds. Default is 0.1 ms.

    Returns:
        float: The maximum Lyapunov exponent. Failure return: whatever
            :func:`compute_max_lyapunov_exponent` (``nolds.lyap_r``) yields for
            a degenerate series; this function adds no NaN sentinel of its own.

    Raises:
        ValueError: If ``spike_train`` is not 2D.
    """
    if spike_train.ndim != 2:
        raise ValueError(
            "spike_train must be a 2D tensor with shape (time_steps, num_neurons)"
        )

    # Small Gaussian bandwidth (ms): the dynamics live on a fine timescale.
    bandwidth = 5.0
    continuous_rate = to_numpy(
        compute_continuous_spiking_rate(spike_train, dt, bandwidth)
    )

    # nolds needs a 1-D series: use the mean population rate.
    mean_rate = continuous_rate.mean(axis=1)
    lyapunov_exponent = compute_max_lyapunov_exponent(mean_rate)

    return lyapunov_exponent

compute_max_lyapunov_exponent(time_series, emb_dim=6, lag=1, tau=1)

Compute the largest Lyapunov exponent of a given time series using the nolds library.

Parameters:

Name Type Description Default
time_series ndarray

A 1D numpy array representing the time series data.

required
emb_dim int

Embedding dimension. Default 6.

6
lag int

Lag between samples. Default 1.

1
tau int

Time delay. Default 1.

1

Returns:

Type Description
float

The estimated largest Lyapunov exponent. No NaN sentinel is added

float

here; degenerate series give whatever nolds.lyap_r returns.

Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
def compute_max_lyapunov_exponent(
    time_series: np.ndarray,
    emb_dim: int = 6,
    lag: int = 1,
    tau: int = 1,
) -> float:
    """Compute the largest Lyapunov exponent of a given time series using the
    nolds library.

    Args:
        time_series: A 1D numpy array representing the time series data.
        emb_dim: Embedding dimension. Default 6.
        lag: Lag between samples. Default 1.
        tau: Time delay. Default 1.

    Returns:
        The estimated largest Lyapunov exponent. No NaN sentinel is added
        here; degenerate series give whatever ``nolds.lyap_r`` returns.
    """
    nolds = require("nolds", "analysis", "Lyapunov/entropy estimation")
    lyapunov_exponent = nolds.lyap_r(time_series, emb_dim=emb_dim, lag=lag, tau=tau)
    return lyapunov_exponent

compute_pcist(response, baseline, threshold_factor=3.0)

Calculate the Perturbational Complexity Index based on State Transitions (PCIst).

Definition: A measure of the spatiotemporal complexity of the network's response to a specific perturbation.

Steps: 1. Perturb (assumed done, input is response). 2. Measure (input is response matrix). 3. Decompose: Perform PCA on the response matrix. 4. Recurrence: Calculate state transitions on the principal components. 5. Sum significant state transitions weighted by the component's Signal-to-Noise ratio.

Parameters:

Name Type Description Default
response Tensor

The network response to perturbation. Shape (time_steps, num_neurons).

required
baseline Tensor

The baseline activity before perturbation. Shape (time_steps_base, num_neurons).

required
threshold_factor float

Factor of baseline std dev to define significant state excursion. Default 3.0.

3.0

Returns:

Name Type Description
float float

The PCIst score, or NaN (with a warning) if the SVD of the response fails to converge.

Source code in btorch/analysis/dynamic_tools/complexity.py
def compute_pcist(
    response: torch.Tensor, baseline: torch.Tensor, threshold_factor: float = 3.0
) -> float:
    """Calculate the Perturbational Complexity Index based on State Transitions
    (PCIst).

    Definition: A measure of the spatiotemporal complexity of the network's
    response to a specific perturbation.

    Steps:
    1. Perturb (assumed done, input is response).
    2. Measure (input is response matrix).
    3. Decompose: Perform PCA on the response matrix.
    4. Recurrence: Calculate state transitions on the principal components.
    5. Sum significant state transitions weighted by the component's
    Signal-to-Noise ratio.

    Args:
        response (torch.Tensor): The network response to perturbation. Shape
            ``(time_steps, num_neurons)``.
        baseline (torch.Tensor): The baseline activity before perturbation.
            Shape ``(time_steps_base, num_neurons)``.
        threshold_factor (float): Factor of baseline std dev to define
            significant state excursion. Default 3.0.

    Returns:
        float: The PCIst score, or NaN (with a warning) if the SVD of the
            response fails to converge.
    """
    if not isinstance(response, torch.Tensor):
        response = torch.tensor(response, dtype=torch.float32)
    if not isinstance(baseline, torch.Tensor):
        baseline = torch.tensor(baseline, dtype=torch.float32)

    response = response.float()
    baseline = baseline.float()

    # Handle batch dimension: if 3D, calculate mean PCIst over batch or raise
    # error? For simplicity, if 3D, we assume (batch, time, neurons) and
    # calculate average PCIst.
    if response.ndim == 3:
        batch_size = response.shape[0]
        pcist_values = []
        for i in range(batch_size):
            b_sample = baseline[i] if baseline.ndim == 3 else baseline
            pcist_values.append(compute_pcist(response[i], b_sample, threshold_factor))
        return sum(pcist_values) / len(pcist_values)

    mean_base = baseline.mean(dim=0)
    response_centered = response - mean_base
    baseline_centered = baseline - mean_base

    # 2. PCA on Response
    # We use SVD for PCA: X = U S V^T. Principal components (scores) are X V = U S.
    # response_centered shape: (T, N)
    try:
        # full_matrices=False ensures we get min(T, N) components
        U, S, Vh = torch.linalg.svd(response_centered, full_matrices=False)
    except RuntimeError as e:
        # SVD did not converge (e.g. non-finite input). Report NaN rather than
        # a fake score of 0.0, which would be indistinguishable from "no
        # complexity".
        warnings.warn(f"SVD failed in compute_pcist, returning NaN: {e}", stacklevel=2)
        return float("nan")

    V = Vh.T  # (N, K)

    # Project data onto Principal Components
    # Scores shape: (T, K)
    scores_response = torch.matmul(response_centered, V)
    scores_baseline = torch.matmul(baseline_centered, V)

    # SNR = Variance(Response) / Variance(Baseline)
    # Add epsilon to avoid division by zero
    var_response = scores_response.var(dim=0)
    var_baseline = scores_baseline.var(dim=0)

    epsilon = 1e-9
    snr = var_response / (var_baseline + epsilon)

    # A state transition is defined as crossing a threshold defined by baseline noise.
    # Threshold for component k: threshold_factor * std(baseline_k)

    std_baseline = scores_baseline.std(dim=0)
    thresholds = threshold_factor * std_baseline  # (K,)

    # We are looking for "significant excursions"
    # Shape: (T, K)
    active_states = (torch.abs(scores_response) > thresholds.unsqueeze(0)).float()

    # Count transitions: change from 0 to 1 or 1 to 0
    # diff along time dimension
    transitions = torch.abs(active_states[1:] - active_states[:-1])

    num_transitions = transitions.sum(dim=0)  # (K,)

    # Transitions weighted by each component's SNR (no SNR < 1 filtering).
    pcist_score = (num_transitions * snr).sum()

    return pcist_score.item()

compute_ra(spike_initial, spike_final)

Calculate Representation Alignment (RA) using spike data.

RA = Trace(G_final * G_initial) / (||G_final|| * ||G_initial||) where G = S * S^T (Gram matrix of spike activity)

If inputs are 3D tensors, they are assumed to be (batch_size, time_steps, num_neurons) and will be averaged over the time dimension (dim=1) to obtain firing rates.

Parameters:

Name Type Description Default
spike_initial Tensor

Initial spike activity. Shape (batch_size, num_neurons) or (batch_size, time_steps, num_neurons).

required
spike_final Tensor

Final spike activity. Shape (batch_size, num_neurons) or (batch_size, time_steps, num_neurons).

required

Returns:

Name Type Description
float float

The Representation Alignment (RA) score. Low RA -> Rich Regime (Radical restructuring) High RA -> Lazy Regime (Little change in internal structure) Failure return: float("nan") (with a warning) when either Gram matrix is all zeros (no spikes), so the alignment is undefined.

Source code in btorch/analysis/dynamic_tools/complexity.py
def compute_ra(spike_initial: torch.Tensor, spike_final: torch.Tensor) -> float:
    """Calculate Representation Alignment (RA) using spike data.

    RA = Trace(G_final * G_initial) / (||G_final|| * ||G_initial||)
    where G = S * S^T (Gram matrix of spike activity)

    If inputs are 3D tensors, they are assumed to be (batch_size, time_steps,
    num_neurons) and will be averaged over the time dimension (dim=1) to obtain
    firing rates.

    Args:
        spike_initial (torch.Tensor): Initial spike activity. Shape
            ``(batch_size, num_neurons)`` or
            ``(batch_size, time_steps, num_neurons)``.
        spike_final (torch.Tensor): Final spike activity. Shape
            ``(batch_size, num_neurons)`` or
            ``(batch_size, time_steps, num_neurons)``.

    Returns:
        float: The Representation Alignment (RA) score.
               Low RA -> Rich Regime (Radical restructuring)
               High RA -> Lazy Regime (Little change in internal structure)
            Failure return: ``float("nan")`` (with a warning) when either
            Gram matrix is all zeros (no spikes), so the alignment is
            undefined.
    """
    if not isinstance(spike_initial, torch.Tensor):
        spike_initial = torch.tensor(spike_initial, dtype=torch.float32)
    if not isinstance(spike_final, torch.Tensor):
        spike_final = torch.tensor(spike_final, dtype=torch.float32)

    spike_initial = spike_initial.float()
    spike_final = spike_final.float()

    # Handle 3D input: (batch, time, neurons) -> (batch, neurons)
    if spike_initial.ndim == 3:
        spike_initial = spike_initial.mean(dim=1)
    if spike_final.ndim == 3:
        spike_final = spike_final.mean(dim=1)

    # 1. Compute Gram matrix G = S * S^T
    # Shape: (batch_size, batch_size)
    g_initial = torch.matmul(spike_initial, spike_initial.T)
    g_final = torch.matmul(spike_final, spike_final.T)

    # 2. Calculate Trace(G_final * G_initial)
    # Trace(A @ B) = sum(element-wise product of A and B^T)
    # Since G is symmetric, G^T = G, so this is sum(G_final * G_initial)
    product = torch.matmul(g_final, g_initial)
    numerator = torch.trace(product)

    # Assuming Frobenius norm as is standard for matrix alignment
    norm_initial = torch.norm(g_initial, p="fro")
    norm_final = torch.norm(g_final, p="fro")

    if norm_initial == 0 or norm_final == 0:
        # Silent activity: alignment is undefined, report NaN (not a fake 0).
        warnings.warn(
            "compute_ra: all-zero spike activity, alignment is undefined; "
            "returning NaN",
            stacklevel=2,
        )
        return float("nan")

    ra = numerator / (norm_final * norm_initial)

    return ra.item()

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.dynamic_tools.criticality

Classes

AvalancheStatistics

Bases: TypedDict

Result of :func:compute_avalanche_statistics (keys are always all present; unestimable quantities are NaN/None).

Source code in btorch/analysis/dynamic_tools/criticality.py
class AvalancheStatistics(TypedDict):
    """Result of :func:`compute_avalanche_statistics` (keys are always all
    present; unestimable quantities are NaN/None)."""

    tau: float
    alpha: float
    gamma: float
    gamma_pred: float
    CCC: float
    sizes: np.ndarray
    durations: np.ndarray
    avg_size_by_duration: tuple[np.ndarray, np.ndarray]
    gamma_stats: dict[str, Any] | None
    fit_S: Any | None  # powerlaw.Fit
    fit_T: Any | None  # powerlaw.Fit

Functions:

_criticality_consistency(tau, alpha, gamma)

Return (gamma_pred, CCC); NaN where undefined.

gamma_pred = (alpha - 1) / (tau - 1) (needs tau != 1) and CCC = 1 - |gamma - gamma_pred| / gamma (needs gamma != 0).

Source code in btorch/analysis/dynamic_tools/criticality.py
def _criticality_consistency(
    tau: float, alpha: float, gamma: float
) -> tuple[float, float]:
    """Return ``(gamma_pred, CCC)``; NaN where undefined.

    ``gamma_pred = (alpha - 1) / (tau - 1)`` (needs ``tau != 1``) and
    ``CCC = 1 - |gamma - gamma_pred| / gamma`` (needs ``gamma != 0``).
    """
    if np.isnan(tau) or np.isnan(alpha) or np.isnan(gamma) or tau == 1:
        return np.nan, np.nan
    gamma_pred = (alpha - 1) / (tau - 1)
    ccc = 1 - abs(gamma - gamma_pred) / gamma if gamma != 0 else np.nan
    return gamma_pred, ccc

_extract_avalanches(activity)

Sizes (total spikes) and durations (bins) of runs of active bins.

Source code in btorch/analysis/dynamic_tools/criticality.py
def _extract_avalanches(activity: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """Sizes (total spikes) and durations (bins) of runs of active bins."""
    # Pad with False so runs touching the boundaries get a start and an end.
    padded = np.concatenate(([False], activity > 0, [False]))
    diff = np.diff(padded.astype(int))
    starts = np.where(diff == 1)[0]
    ends = np.where(diff == -1)[0]  # exclusive

    sizes = np.array([activity[s:e].sum() for s, e in zip(starts, ends)])
    durations = np.array([e - s for s, e in zip(starts, ends)])
    return sizes, durations

_fit_distribution(data)

Fit a discrete power law with the powerlaw package.

Returns:

Type Description
float

(alpha, fit); (np.nan, None) when there are fewer than 10

Any | None

samples or the fit fails (a warning is emitted for failures).

Source code in btorch/analysis/dynamic_tools/criticality.py
def _fit_distribution(data: np.ndarray) -> tuple[float, Any | None]:
    """Fit a discrete power law with the ``powerlaw`` package.

    Returns:
        ``(alpha, fit)``; ``(np.nan, None)`` when there are fewer than 10
        samples or the fit fails (a warning is emitted for failures).
    """
    if len(data) < 10:
        return np.nan, None
    powerlaw = require("powerlaw", "analysis", "power-law fitting")
    try:
        # discrete=True because sizes/durations are counts (integers)
        fit = powerlaw.Fit(data, discrete=True, verbose=False)
        return fit.alpha, fit
    except (ValueError, RuntimeError, FloatingPointError, ZeroDivisionError) as e:
        warnings.warn(f"Failed to fit power law distribution: {e}", stacklevel=2)
        return np.nan, None

_fit_scaling(x, y)

Fit the power law scaling y = a * x^gamma using curve_fit.

Returns:

Type Description
float

(gamma, stats) with stats a dict (r_squared, popt,

dict[str, Any] | None

pcov); (np.nan, None) when there are fewer than 3 points or

tuple[float, dict[str, Any] | None]

the fit fails (a warning is emitted for failures).

Source code in btorch/analysis/dynamic_tools/criticality.py
def _fit_scaling(
    x: np.ndarray, y: np.ndarray
) -> tuple[float, dict[str, Any] | None]:
    """Fit the power law scaling y = a * x^gamma using curve_fit.

    Returns:
        ``(gamma, stats)`` with ``stats`` a dict (``r_squared``, ``popt``,
        ``pcov``); ``(np.nan, None)`` when there are fewer than 3 points or
        the fit fails (a warning is emitted for failures).
    """
    if len(x) < 3:
        return np.nan, None

    try:
        # Initial guess: a=1, gamma=1.5. curve_fit raises RuntimeError when it
        # fails to converge and ValueError on invalid/NaN input.
        popt, pcov = curve_fit(_power_law_func, x, y, p0=[1, 1.5], maxfev=2000)
    except (RuntimeError, ValueError) as e:
        warnings.warn(f"Failed to fit scaling relation: {e}", stacklevel=2)
        return np.nan, None

    gamma = popt[1]
    residuals = y - _power_law_func(x, *popt)
    ss_res = np.sum(residuals**2)
    ss_tot = np.sum((y - np.mean(y)) ** 2)
    # A constant ``y`` has no variance to explain; report NaN instead of 0/0.
    r_squared = 1 - (ss_res / ss_tot) if ss_tot > 0 else np.nan

    stats = {"r_squared": r_squared, "popt": popt, "pcov": pcov}
    return gamma, stats

_mean_size_by_duration(sizes, durations)

Average avalanche size per distinct duration, <S>(T).

Grouped with bincount over the integer durations; empty arrays when there is no avalanche.

Source code in btorch/analysis/dynamic_tools/criticality.py
def _mean_size_by_duration(
    sizes: np.ndarray, durations: np.ndarray
) -> tuple[np.ndarray, np.ndarray]:
    """Average avalanche size per distinct duration, ``<S>(T)``.

    Grouped with ``bincount`` over the integer durations; empty arrays when
    there is no avalanche.
    """
    if len(durations) == 0:
        return np.array([], dtype=int), np.array([], dtype=float)
    counts = np.bincount(durations)
    sum_sizes = np.bincount(durations, weights=sizes)
    mask = counts > 0
    return np.arange(len(counts))[mask], sum_sizes[mask] / counts[mask]

_population_activity(spike_train, bin_size)

Population spike count per bin, (T,) or (T // bin_size,).

A 2D (time_steps, n_neurons) input is summed over neurons, a 1D input is taken as the activity already. Trailing steps that do not fill a whole bin are dropped.

Source code in btorch/analysis/dynamic_tools/criticality.py
def _population_activity(spike_train: np.ndarray, bin_size: int) -> np.ndarray:
    """Population spike count per bin, ``(T,)`` or ``(T // bin_size,)``.

    A 2D ``(time_steps, n_neurons)`` input is summed over neurons, a 1D input
    is taken as the activity already. Trailing steps that do not fill a whole
    bin are dropped.
    """
    activity = spike_train.sum(axis=1) if spike_train.ndim == 2 else spike_train
    if bin_size > 1:
        n_bins = len(activity) // bin_size
        activity = activity[: n_bins * bin_size].reshape(-1, bin_size).sum(axis=1)
    return activity

_power_law_func(x, a, gamma)

Source code in btorch/analysis/dynamic_tools/criticality.py
def _power_law_func(
    x: np.ndarray, a: float, gamma: float
) -> np.ndarray:
    return a * np.power(x, gamma)

compute_avalanche_statistics(spike_train, bin_size=1)

Calculate avalanche size (S) and duration (T) distributions and their power-law exponents.

Definition: An avalanche is defined as a continuous sequence of time bins (width bin_size) containing at least one spike, flanked by empty bins.

Parameters:

Name Type Description Default
spike_train ndarray

Binary spike matrix of shape (time_steps, n_neurons).

required
bin_size int

Width of time bin in number of time steps.

1

Returns:

Name Type Description
AvalancheStatistics AvalancheStatistics

Dictionary containing: - 'tau': Power-law exponent for avalanche size distribution P(S) ~ S^-tau - 'alpha': Power-law exponent for avalanche duration distribution P(T) ~ T^-alpha - 'gamma': Power-law exponent for average size vs duration (T) ~ T^gamma - 'gamma_pred': Predicted gamma based on tau and alpha: (alpha-1)/(tau-1) - 'CCC': Criticality Consistency Coefficient: 1 - |gamma - gamma_pred| / gamma - 'sizes': List of avalanche sizes - 'durations': List of avalanche durations - 'avg_size_by_duration': Tuple (unique_durations, mean_sizes); empty arrays when no avalanche was found - 'gamma_stats': Dict with 'r_squared', 'popt', 'pcov' of the scaling fit, or None - 'fit_S': powerlaw.Fit object for sizes, or None - 'fit_T': powerlaw.Fit object for durations, or None

Raises:

Type Description
ValueError

If spike_train is not 2D.

Notes

The result always has the same keys. When a quantity cannot be estimated (fewer than 10 avalanches, failed fit) its exponent is np.nan and the associated fit object / stats are None; a :class:UserWarning is emitted.

Source code in btorch/analysis/dynamic_tools/criticality.py
def compute_avalanche_statistics(
    spike_train: np.ndarray, bin_size: int = 1
) -> AvalancheStatistics:
    """Calculate avalanche size (S) and duration (T) distributions and their
    power-law exponents.

    Definition: An avalanche is defined as a continuous sequence of time bins
    (width bin_size) containing at least one spike, flanked by empty bins.

    Args:
        spike_train (np.ndarray): Binary spike matrix of shape (time_steps, n_neurons).
        bin_size (int): Width of time bin in number of time steps.

    Returns:
        AvalancheStatistics: Dictionary containing:
            - 'tau': Power-law exponent for avalanche size distribution P(S) ~
              S^-tau
            - 'alpha': Power-law exponent for avalanche duration distribution
              P(T) ~ T^-alpha
            - 'gamma': Power-law exponent for average size vs duration <S>(T) ~
              T^gamma
            - 'gamma_pred': Predicted gamma based on tau and alpha:
              (alpha-1)/(tau-1)
            - 'CCC': Criticality Consistency Coefficient: 1 - |gamma -
              gamma_pred| / gamma
            - 'sizes': List of avalanche sizes
            - 'durations': List of avalanche durations
            - 'avg_size_by_duration': Tuple (unique_durations, mean_sizes);
              empty arrays when no avalanche was found
            - 'gamma_stats': Dict with 'r_squared', 'popt', 'pcov' of the
              scaling fit, or None
            - 'fit_S': powerlaw.Fit object for sizes, or None
            - 'fit_T': powerlaw.Fit object for durations, or None

    Raises:
        ValueError: If ``spike_train`` is not 2D.

    Notes:
        The result always has the same keys. When a quantity cannot be
        estimated (fewer than 10 avalanches, failed fit) its exponent is
        ``np.nan`` and the associated fit object / stats are ``None``; a
        :class:`UserWarning` is emitted.
    """
    spike_train = np.array(spike_train)
    if spike_train.ndim != 2:
        raise ValueError("spike_train must be a 2D matrix (time_steps, n_neurons)")

    activity = _population_activity(spike_train, bin_size)
    sizes, durations = _extract_avalanches(activity)
    unique_durations, mean_sizes = _mean_size_by_duration(sizes, durations)

    results: AvalancheStatistics = {
        "sizes": sizes,
        "durations": durations,
        "tau": np.nan,
        "alpha": np.nan,
        "gamma": np.nan,
        "gamma_pred": np.nan,
        "CCC": np.nan,
        "fit_S": None,
        "fit_T": None,
        "avg_size_by_duration": (unique_durations, mean_sizes),
        "gamma_stats": None,
    }

    if len(sizes) < 10:
        warnings.warn(
            f"Not enough avalanches to fit power law. Found {len(sizes)} avalanches.",
            stacklevel=2,
        )
        return results

    # Power laws by MLE (powerlaw package); <S>(T) ~ T^gamma by least squares.
    results["tau"], results["fit_S"] = _fit_distribution(sizes)
    results["alpha"], results["fit_T"] = _fit_distribution(durations)
    results["gamma"], results["gamma_stats"] = _fit_scaling(
        unique_durations, mean_sizes
    )
    results["gamma_pred"], results["CCC"] = _criticality_consistency(
        results["tau"], results["alpha"], results["gamma"]
    )
    return results

compute_dfa(spike_train, bin_size=1)

Calculate Detrended Fluctuation Analysis (DFA) exponent alpha.

Meaning of alpha: - 0.5: White noise (no memory) - 0.5 < alpha < 1.0: Long-range memory (fractal structure) - 1.0: 1/f noise (Pink noise) - 1.5: Brownian motion (Random walk)

Parameters:

Name Type Description Default
spike_train ndarray

Binary spike matrix of shape (time_steps, n_neurons).

required
bin_size int

Width of time bin in number of time steps.

1

Returns:

Name Type Description
float float

The DFA exponent alpha, or np.nan (with a warning) when

float

the computation fails.

Source code in btorch/analysis/dynamic_tools/criticality.py
def compute_dfa(spike_train: np.ndarray, bin_size: int = 1) -> float:
    """Calculate Detrended Fluctuation Analysis (DFA) exponent alpha.

    Meaning of alpha:
    - 0.5: White noise (no memory)
    - 0.5 < alpha < 1.0: Long-range memory (fractal structure)
    - 1.0: 1/f noise (Pink noise)
    - 1.5: Brownian motion (Random walk)

    Args:
        spike_train (np.ndarray): Binary spike matrix of shape (time_steps, n_neurons).
        bin_size (int): Width of time bin in number of time steps.

    Returns:
        float: The DFA exponent alpha, or ``np.nan`` (with a warning) when
        the computation fails.
    """
    nolds = require("nolds", "analysis", "DFA analysis")

    spike_train = np.array(spike_train)

    population_activity = _population_activity(spike_train, bin_size)

    # nolds.dfa takes the raw series (it integrates internally).
    try:
        alpha = nolds.dfa(population_activity)
        return alpha
    except (ValueError, RuntimeError, AssertionError, FloatingPointError) as e:
        warnings.warn(f"Failed to calculate DFA: {e}", stacklevel=2)
        return np.nan

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

btorch.analysis.dynamic_tools.ei_balance

E/I balance analysis tools for spiking neural networks.

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.

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.

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:

_compute_lag_correlation(x, y, *, dt=1.0, max_lag_ms=30.0, batch_axis=None, use_fft=True, dtype=None)

Source code in btorch/analysis/dynamic_tools/ei_balance.py
def _compute_lag_correlation(
    x: torch.Tensor | np.ndarray,
    y: torch.Tensor | np.ndarray,
    *,
    dt: float = 1.0,
    max_lag_ms: float = 30.0,
    batch_axis: BatchAxis = None,
    use_fft: bool = True,
    dtype: torch.dtype | np.dtype | None = None,
):
    if max_lag_ms < dt:
        raise ValueError(f"max_lag_ms ({max_lag_ms}) must be >= dt ({dt})")
    if isinstance(x, torch.Tensor):
        y = torch.as_tensor(y, dtype=x.dtype, device=x.device)
    else:
        y = y.numpy(force=True) if isinstance(y, torch.Tensor) else np.asarray(y)

    is_torch = isinstance(x, torch.Tensor)
    T = x.shape[0]
    n_neurons = x.shape[-1]
    lag_bins = int(max_lag_ms / dt)
    max_lag = min(lag_bins, T - 1)

    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)

    # Common reshape logic (works for both torch and numpy)
    x_3d = x.reshape(T, -1, n_neurons)
    y_3d = y.reshape(T, -1, n_neurons)
    flat_x = x_3d.reshape(T, -1)
    flat_y = y_3d.reshape(T, -1)

    if use_fft or T > 100:
        corr_flat = _cross_correlation_fft(flat_x, flat_y, max_lag, dtype)
    else:
        corr_flat = _cross_correlation_direct(flat_x, flat_y, max_lag, dtype)

    n_lags = corr_flat.shape[0]
    corr_3d = corr_flat.reshape(n_lags, -1, n_neurons)

    if is_torch:
        compute_dtype = _torch_dtype(dtype)
        if batch_axis is not None:
            corr_agg = corr_3d.mean(dim=1, dtype=compute_dtype)
        else:
            corr_agg = corr_3d.reshape(n_lags, -1)

        peak_corr, best_lag_idx = torch.max(corr_agg, dim=0)
        max_lag_actual = min(lag_bins, T - 1)
        best_lags = best_lag_idx - max_lag_actual
        best_lag_ms = best_lags * dt

        info = {
            "corr_over_lags": corr_agg,
            "lag_values_ms": torch.arange(
                -max_lag_actual, max_lag_actual + 1, device=x.device
            )
            * dt,
        }
        return peak_corr, best_lag_ms, info
    else:
        compute_dtype = _numpy_dtype(dtype)
        if batch_axis is not None:
            corr_agg = corr_3d.mean(axis=1, dtype=compute_dtype)
        else:
            corr_agg = corr_3d.reshape(n_lags, -1)

        best_lag_idx = np.argmax(corr_agg, axis=0)
        peak_corr = corr_agg[best_lag_idx, np.arange(corr_agg.shape[1])]
        max_lag_actual = min(lag_bins, T - 1)
        best_lags = best_lag_idx - max_lag_actual
        if compute_dtype is None:
            best_lag_ms = best_lags * dt
            lag_values_ms = np.arange(-max_lag_actual, max_lag_actual + 1) * dt
        else:
            best_lag_ms = best_lags.astype(compute_dtype, copy=False) * np.asarray(
                dt, dtype=compute_dtype
            )
            lag_values_ms = np.arange(
                -max_lag_actual, max_lag_actual + 1, dtype=compute_dtype
            ) * np.asarray(dt, dtype=compute_dtype)

        info = {
            "corr_over_lags": corr_agg,
            "lag_values_ms": lag_values_ms,
        }
        return peak_corr, best_lag_ms, info

_cross_correlation_direct(x, y, max_lag, dtype=None)

Direct cross-correlation (simpler for short signals).

Source code in btorch/analysis/dynamic_tools/ei_balance.py
def _cross_correlation_direct(
    x: torch.Tensor | np.ndarray,
    y: torch.Tensor | np.ndarray,
    max_lag: int,
    dtype: torch.dtype | np.dtype | None = None,
) -> torch.Tensor | np.ndarray:
    """Direct cross-correlation (simpler for short signals)."""
    is_torch = isinstance(x, torch.Tensor)
    T, N = x.shape

    if is_torch:
        device = x.device
        compute_dtype = _torch_dtype(dtype)
        if compute_dtype is not None:
            x = x.to(dtype=compute_dtype)
            y = y.to(dtype=compute_dtype)
        # Normalize
        x_mean = x.mean(dim=0, keepdim=True, dtype=compute_dtype)
        y_mean = y.mean(dim=0, keepdim=True, dtype=compute_dtype)
        x_std = x.std(dim=0, keepdim=True) + torch.finfo(x.dtype).eps
        y_std = y.std(dim=0, keepdim=True) + torch.finfo(y.dtype).eps
        x_norm = (x - x_mean) / x_std
        y_norm = (y - y_mean) / y_std
        max_lag_actual = min(max_lag, T - 1)
        n_lags = 2 * max_lag_actual + 1
        corr = torch.zeros(n_lags, N, device=device, dtype=x.dtype)
        for i, lag in enumerate(range(-max_lag_actual, max_lag_actual + 1)):
            if lag < 0:
                c = (x_norm[:lag] * y_norm[-lag:]).mean(dim=0, dtype=compute_dtype)
            elif lag > 0:
                c = (x_norm[lag:] * y_norm[:-lag]).mean(dim=0, dtype=compute_dtype)
            else:
                c = (x_norm * y_norm).mean(dim=0, dtype=compute_dtype)
            corr[i, :] = c
        return corr
    else:
        compute_dtype = _numpy_dtype(dtype)
        if compute_dtype is not None:
            x = x.astype(compute_dtype, copy=False)
            y = y.astype(compute_dtype, copy=False)
        # Normalize
        x_norm = (x - x.mean(axis=0, dtype=compute_dtype)) / (
            x.std(axis=0, dtype=compute_dtype) + np.finfo(x.dtype).eps
        )
        y_norm = (y - y.mean(axis=0, dtype=compute_dtype)) / (
            y.std(axis=0, dtype=compute_dtype) + np.finfo(y.dtype).eps
        )
        n_lags = 2 * max_lag + 1
        corr = []
        for i, lag in enumerate(range(-max_lag, max_lag + 1)):
            if lag < 0:
                c = (x_norm[:lag] * y_norm[-lag:]).mean(axis=0, dtype=compute_dtype)
            elif lag > 0:
                c = (x_norm[lag:] * y_norm[:-lag]).mean(axis=0, dtype=compute_dtype)
            else:
                c = (x_norm * y_norm).mean(axis=0, dtype=compute_dtype)
            corr.append(c)
        return np.stack(corr, axis=0)

_cross_correlation_fft(x, y, max_lag, dtype=None)

FFT-based cross-correlation.

Source code in btorch/analysis/dynamic_tools/ei_balance.py
def _cross_correlation_fft(
    x: torch.Tensor | np.ndarray,
    y: torch.Tensor | np.ndarray,
    max_lag: int,
    dtype: torch.dtype | np.dtype | None = None,
) -> torch.Tensor | np.ndarray:
    """FFT-based cross-correlation."""
    is_torch = isinstance(x, torch.Tensor)
    T, N = x.shape
    n_fft = 2 * T

    if is_torch:
        compute_dtype = _torch_dtype(dtype)
        fft_dtype = compute_dtype
        if fft_dtype is None and x.dtype in {torch.float16, torch.bfloat16}:
            fft_dtype = torch.float32
        if fft_dtype is not None:
            x = x.to(dtype=fft_dtype)
            y = y.to(dtype=fft_dtype)
        x_demean = x - x.mean(dim=0, keepdim=True, dtype=fft_dtype)
        y_demean = y - y.mean(dim=0, keepdim=True, dtype=fft_dtype)
        X = torch.fft.rfft(x_demean, n=n_fft, dim=0)
        Y = torch.fft.rfft(y_demean, n=n_fft, dim=0)
        cross_spec = X * Y.conj()
        corr_full = torch.fft.irfft(cross_spec, n=n_fft, dim=0)
        x_std = x.std(dim=0, keepdim=True) + torch.finfo(x.dtype).eps
        y_std = y.std(dim=0, keepdim=True) + torch.finfo(y.dtype).eps
        corr_norm = corr_full / (x_std * y_std * T)
        max_lag_actual = min(max_lag, T - 1)
        neg_lags = corr_norm[-max_lag_actual:, :]
        pos_lags = corr_norm[: max_lag_actual + 1, :]
        return torch.cat([neg_lags, pos_lags], dim=0)
    else:
        compute_dtype = _numpy_dtype(dtype)
        if compute_dtype is not None:
            x = x.astype(compute_dtype, copy=False)
            y = y.astype(compute_dtype, copy=False)
        # Demean and compute FFT
        x_demean = x - x.mean(axis=0, keepdims=True, dtype=compute_dtype)
        y_demean = y - y.mean(axis=0, keepdims=True, dtype=compute_dtype)
        X = np.fft.rfft(x_demean, n=n_fft, axis=0)
        Y = np.fft.rfft(y_demean, n=n_fft, axis=0)
        cross_spec = X * np.conj(Y)
        corr_full = np.fft.irfft(cross_spec, n=n_fft, axis=0)
        # Normalize
        eps = np.finfo(x.dtype).eps
        x_std = x.std(axis=0, keepdims=True, dtype=compute_dtype) + eps
        y_std = y.std(axis=0, keepdims=True, dtype=compute_dtype) + eps
        corr_norm = corr_full / (x_std * y_std * T)
        if compute_dtype is not None:
            corr_norm = corr_norm.astype(compute_dtype, copy=False)
        neg_lags = corr_norm[-max_lag:, :]
        pos_lags = corr_norm[: max_lag + 1, :]
        return np.concatenate([neg_lags, pos_lags], axis=0)

_numpy_dtype(dtype)

Source code in btorch/analysis/dynamic_tools/ei_balance.py
def _numpy_dtype(dtype: torch.dtype | np.dtype | None) -> np.dtype | None:
    if dtype is None:
        return None
    if isinstance(dtype, torch.dtype):
        return np.dtype(str(dtype).removeprefix("torch."))
    return np.dtype(dtype)

_torch_dtype(dtype)

Source code in btorch/analysis/dynamic_tools/ei_balance.py
def _torch_dtype(dtype: torch.dtype | np.dtype | None) -> torch.dtype | None:
    if isinstance(dtype, torch.dtype) or dtype is None:
        return dtype
    return torch.from_numpy(np.empty((), dtype=dtype)).dtype

compute_eci(I_e, I_i, *, I_ext=None, batch_axis=None, dtype=None)

Compute Excitatory-Inhibitory Cancellation Index (ECI).

ECI measures the degree of cancellation between excitatory and inhibitory currents. ECI = 0 indicates perfect cancellation, ECI = 1 indicates no cancellation.

Formula: ECI = |I_rec + I_ext| / (|I_e| + |I_i|) where I_rec = I_e + I_i

This function is decorated with @use_stats and @use_percentiles. See :func:~btorch.analysis.statistics.use_stats and :func:~btorch.analysis.statistics.use_percentiles for detailed usage.

Parameters:

Name Type Description Default
I_e Tensor | ndarray

Excitatory current [T,..., N]

required
I_i Tensor | ndarray

Inhibitory current [T,..., N]. Note: assumed to be negative (inhibitory).

required
I_ext Tensor | ndarray | None

External current [T,..., N] (optional)

None
batch_axis BatchAxis

Axes to aggregate over (e.g., trials) in addition to the time axis. If None, averages over all non-neuron dimensions.

None
dtype dtype | dtype | None

Data type for aggregation.

None

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
eci StatsResult

ECI values per neuron (shape depends on batch_axis). If stat is provided, returns the aggregated statistic instead.

info StatsResult

Dictionary with additional statistics and optional percentile data.

Source code in btorch/analysis/dynamic_tools/ei_balance.py
@use_percentiles(value_key="eci")
@use_stats(value_key="eci")
def compute_eci(
    I_e: torch.Tensor | np.ndarray,
    I_i: torch.Tensor | np.ndarray,
    *,
    I_ext: torch.Tensor | np.ndarray | None = None,
    batch_axis: BatchAxis = None,
    dtype: torch.dtype | np.dtype | None = None,
) -> StatsResult:
    """Compute Excitatory-Inhibitory Cancellation Index (ECI).

    ECI measures the degree of cancellation between excitatory and inhibitory
    currents. ECI = 0 indicates perfect cancellation, ECI = 1 indicates no
    cancellation.

    Formula: ECI = |I_rec + I_ext| / (|I_e| + |I_i|)
    where I_rec = I_e + I_i

    This function is decorated with `@use_stats` and `@use_percentiles`.
    See :func:`~btorch.analysis.statistics.use_stats` and
    :func:`~btorch.analysis.statistics.use_percentiles` for detailed usage.

    Args:
        I_e: Excitatory current [T,..., N]
        I_i: Inhibitory current [T,..., N]. Note: assumed to be
            negative (inhibitory).
        I_ext: External current [T,..., N] (optional)
        batch_axis: Axes to aggregate over (e.g., trials) in addition to the time axis.
            If None, averages over all non-neuron dimensions.
        dtype: Data type for aggregation.

    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:
        eci: ECI values per neuron (shape depends on batch_axis).
            If `stat` is provided, returns the aggregated statistic instead.
        info: Dictionary with additional statistics and optional percentile data.
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)

    # Check if all inputs are zero - return ones in that case
    if (I_e == 0).all() and (I_i == 0).all() and (I_ext is None or (I_ext == 0).all()):
        # Determine which axes are aggregated to compute output shape
        if batch_axis is not None:
            agg_axes = {0} | set(batch_axis)  # time (0) + batch axes
        else:
            agg_axes = set(range(I_e.ndim - 1))  # all except last (neurons)
        output_shape = tuple(I_e.shape[i] for i in range(I_e.ndim) if i not in agg_axes)
        if len(output_shape) == 0:
            output_shape = (1,)
        if isinstance(I_e, torch.Tensor):
            return torch.ones(output_shape, dtype=I_e.dtype, device=I_e.device)
        return np.ones(output_shape, dtype=I_e.dtype)

    # Handle I_ext by splitting into excitatory and inhibitory parts
    if I_ext is not None:
        if isinstance(I_e, torch.Tensor):
            I_ext_pos = torch.clamp(I_ext, min=0)
            I_ext_neg = torch.clamp(I_ext, max=0)
        else:
            I_ext_pos = np.clip(I_ext, 0, None)
            I_ext_neg = np.clip(I_ext, None, 0)
        I_e_eff = I_e + I_ext_pos
        I_i_eff = I_i + I_ext_neg
    else:
        I_e_eff = I_e
        I_i_eff = I_i

    I_rec = I_e_eff + I_i_eff

    # Determine axes/dims for aggregation
    if batch_axis is not None:
        agg_dims = (0,) + tuple(batch_axis)
    else:
        agg_dims = tuple(range(I_e.ndim - 1))

    if isinstance(I_e, torch.Tensor):
        numer = torch.abs(I_rec).mean(dim=agg_dims, dtype=dtype)
        denom = (torch.abs(I_e_eff) + torch.abs(I_i_eff)).mean(
            dim=agg_dims, dtype=dtype
        )
        denom = denom + torch.finfo(denom.dtype).eps
        return numer / denom
    else:
        numer = np.abs(I_rec).mean(axis=agg_dims, dtype=dtype)
        denom = (np.abs(I_e_eff) + np.abs(I_i_eff)).mean(axis=agg_dims, dtype=dtype)
        denom = denom + np.finfo(denom.dtype).eps
        return numer / denom

compute_ei_balance(I_e, I_i, *, I_ext=None, dt=1.0, max_lag_ms=30.0, batch_axis=None, dtype=None)

Compute E/I balance metrics including ECI and lag correlation.

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
I_e Tensor | ndarray

Excitatory current [T, ..., N]

required
I_i Tensor | ndarray

Inhibitory current [T, ..., N]

required
I_ext Tensor | ndarray | None

External current [T, ..., N] (optional)

None
dt float

Time step in ms

1.0
max_lag_ms float

Maximum lag for correlation analysis

30.0
batch_axis BatchAxis

Axes to aggregate over (e.g., trials). If None, averages over all non-time dimensions.

None
dtype dtype | dtype | None

Data type for ECI aggregation and lag-correlation normalization.

None

Other Parameters:

Name Type Description
stat str | dict | None

Aggregation statistic per return position. See :func:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | dict | None

Additional statistics per position. 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, ...] | dict | None

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

Returns:

Name Type Description
eci MultiStatsResult

ECI values per neuron

peak_corr MultiStatsResult

Peak correlation between E and I currents

best_lag_ms MultiStatsResult

Best lag in ms (positive = I lags E)

info MultiStatsResult

Dictionary with detailed analysis results

Source code in btorch/analysis/dynamic_tools/ei_balance.py
@use_percentiles(
    value_key={0: "eci", 1: "peak_corr", 2: "best_lag_ms"},
    default_percentiles=(10, 50, 90),
)
@use_stats(
    value_key={0: "eci", 1: "peak_corr", 2: "best_lag_ms"},
    default_stat_info={0: "mean", 1: "mean", 2: "mean"},
)
def compute_ei_balance(
    I_e: torch.Tensor | np.ndarray,
    I_i: torch.Tensor | np.ndarray,
    *,
    I_ext: torch.Tensor | np.ndarray | None = None,
    dt: float = 1.0,
    max_lag_ms: float = 30.0,
    batch_axis: BatchAxis = None,
    dtype: torch.dtype | np.dtype | None = None,
) -> MultiStatsResult:
    """Compute E/I balance metrics including ECI and lag correlation.

    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:
        I_e: Excitatory current [T, ..., N]
        I_i: Inhibitory current [T, ..., N]
        I_ext: External current [T, ..., N] (optional)
        dt: Time step in ms
        max_lag_ms: Maximum lag for correlation analysis
        batch_axis: Axes to aggregate over (e.g., trials). If None, averages
            over all non-time dimensions.
        dtype: Data type for ECI aggregation and lag-correlation normalization.

    Keyword Args:
        stat (str | dict | None): Aggregation statistic per return position.
            See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | dict | None): Additional statistics per position.
            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, ...] | dict | None): Percentile level(s)
            in [0, 100] to compute per position.
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        eci: ECI values per neuron
        peak_corr: Peak correlation between E and I currents
        best_lag_ms: Best lag in ms (positive = I lags E)
        info: Dictionary with detailed analysis results
    """
    eci, eci_info = compute_eci(
        I_e,
        I_i,
        I_ext=I_ext,
        batch_axis=batch_axis,
        dtype=dtype,
        stat=None,
    )

    peak_corr, best_lag_ms, lag_info = compute_lag_correlation(
        I_e,
        -I_i,
        dt=dt,
        max_lag_ms=max_lag_ms,
        batch_axis=batch_axis,
        dtype=dtype,
        stat=None,
    )

    info = {
        "eci_info": eci_info,
        "lag_info": lag_info,
    }

    return eci, peak_corr, best_lag_ms, info

compute_lag_correlation(x, y, *, dt=1.0, max_lag_ms=30.0, batch_axis=None, use_fft=True, dtype=None)

Compute lagged cross-correlation between two signals.

Uses FFT-based correlation for efficiency. Returns correlation values and best lag per neuron.

This function is decorated with @use_stats and @use_percentiles. See :func:~btorch.analysis.statistics.use_stats and :func:~btorch.analysis.statistics.use_percentiles for detailed usage.

Parameters:

Name Type Description Default
x Tensor | ndarray

First signal [T, ...] or [T, B, ...]

required
y Tensor | ndarray

Second signal [T, ...] or [T, B, ...]

required
dt float

Time step in ms

1.0
max_lag_ms float

Maximum lag for correlation in ms

30.0
batch_axis BatchAxis

Axes to aggregate over (e.g., trials). If None, averages over all non-time dimensions.

None
use_fft bool

If True, use FFT-based correlation (faster for long signals)

True
dtype dtype | dtype | None

Data type for correlation normalization/reduction. Use this to avoid float16 overflow in the variance/std normalization path.

None

Other Parameters:

Name Type Description
stat str | dict | None

Aggregation statistic per return position. Can be a single stat or dict mapping position to stat (e.g., {0: "mean", 1: "median"}). See :func:~btorch.analysis.statistics.use_stats.

stat_info str | list[str] | dict | None

Additional statistics to compute and store in info dict. Can be a single stat, iterable, or dict mapping position to stat(s). 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, ...] | dict | None

Percentile level(s) in [0, 100] to compute per position. Can be a single value or dict mapping position to percentile(s). See :func:~btorch.analysis.statistics.use_percentiles.

Returns:

Name Type Description
peak_corr MultiStatsResult

Correlation values at best lag per neuron. If stat is provided, returns aggregated value(s) instead.

best_lag_ms MultiStatsResult

Best lag in ms per neuron. If stat is provided, returns aggregated value(s) instead.

info MultiStatsResult

Dictionary with correlation over lags, best lags, etc.

Example

peak, lag, info = compute_lag_correlation(x, y)

Aggregate: max peak correlation, mean best lag

peak_max, lag_mean, info = compute_lag_correlation( x, y, stat={0: "max", 1: "mean"} )

Source code in btorch/analysis/dynamic_tools/ei_balance.py
@use_stats(value_key={0: "peak_corr", 1: "best_lag"})
@use_percentiles(value_key={0: "peak_corr", 1: "best_lag"})
def compute_lag_correlation(
    x: torch.Tensor | np.ndarray,
    y: torch.Tensor | np.ndarray,
    *,
    dt: float = 1.0,
    max_lag_ms: float = 30.0,
    batch_axis: BatchAxis = None,
    use_fft: bool = True,
    dtype: torch.dtype | np.dtype | None = None,
) -> MultiStatsResult:
    """Compute lagged cross-correlation between two signals.

    Uses FFT-based correlation for efficiency. Returns correlation values
    and best lag per neuron.

    This function is decorated with `@use_stats` and `@use_percentiles`.
    See :func:`~btorch.analysis.statistics.use_stats` and
    :func:`~btorch.analysis.statistics.use_percentiles` for detailed usage.

    Args:
        x: First signal [T, ...] or [T, B, ...]
        y: Second signal [T, ...] or [T, B, ...]
        dt: Time step in ms
        max_lag_ms: Maximum lag for correlation in ms
        batch_axis: Axes to aggregate over (e.g., trials). If None, averages
            over all non-time dimensions.
        use_fft: If True, use FFT-based correlation (faster for long signals)
        dtype: Data type for correlation normalization/reduction. Use this to
            avoid float16 overflow in the variance/std normalization path.

    Keyword Args:
        stat (str | dict | None): Aggregation statistic per return position.
            Can be a single stat or dict mapping position to stat
            (e.g., {0: "mean", 1: "median"}).
            See :func:`~btorch.analysis.statistics.use_stats`.
        stat_info (str | list[str] | dict | None): Additional statistics to
            compute and store in info dict. Can be a single stat, iterable,
            or dict mapping position to stat(s).
            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, ...] | dict | None): Percentile level(s)
            in [0, 100] to compute per position. Can be a single value or dict
            mapping position to percentile(s).
            See :func:`~btorch.analysis.statistics.use_percentiles`.

    Returns:
        peak_corr: Correlation values at best lag per neuron.
            If `stat` is provided, returns aggregated value(s) instead.
        best_lag_ms: Best lag in ms per neuron.
            If `stat` is provided, returns aggregated value(s) instead.
        info: Dictionary with correlation over lags, best lags, etc.

    Example:
        peak, lag, info = compute_lag_correlation(x, y)

        # Aggregate: max peak correlation, mean best lag
        peak_max, lag_mean, info = compute_lag_correlation(
            x, y, stat={0: "max", 1: "mean"}
        )
    """
    return _compute_lag_correlation(
        x,
        y,
        dt=dt,
        max_lag_ms=max_lag_ms,
        batch_axis=batch_axis,
        use_fft=use_fft,
        dtype=dtype,
    )

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.dynamic_tools.fano

Advanced Fano factor methods for spike train analysis.

This module provides methods to compensate for firing rate effects on the Fano factor, implementing:

  1. Operational Time Method: Transforms spike trains to a rate-independent reference frame by evaluating Fano factor at normalized rate (λ=1). Reference: Rajdl et al. (2020), Front. Comput. Neurosci.

  2. Mean Matching Method: Selects data points where mean spike counts are matched across conditions before computing FF. Reference: Churchland et al. (2010), Nature Neurosci.

  3. Model-Based Approaches:

  4. Modulated Poisson with multiplicative noise (Goris et al., 2014)
  5. Flexible overdispersion model (Charles et al., 2018)

All methods support both NumPy and PyTorch inputs following the btorch conventions, with GPU acceleration where applicable.

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:

_compute_mean_matching_weights_numpy(means, n_bins=10)

Compute mean-matching weights for each condition/time point.

The mean matching method ensures that the distribution of mean counts
is matched across conditions/times by computing weights that equalize

the histograms.

Args:
    means: Array of mean spike counts [n_conditions, n_neurons]
    n_bins: Number of bins for mean count histogram

Returns:
    Dictionary with weights and matching info
Source code in btorch/analysis/dynamic_tools/fano.py
def _compute_mean_matching_weights_numpy(
    means: np.ndarray,
    n_bins: int = 10,
) -> dict[str, np.ndarray]:
    """Compute mean-matching weights for each condition/time point.

        The mean matching method ensures that the distribution of mean counts
        is matched across conditions/times by computing weights that equalize
    the histograms.

        Args:
            means: Array of mean spike counts [n_conditions, n_neurons]
            n_bins: Number of bins for mean count histogram

        Returns:
            Dictionary with weights and matching info
    """
    n_conditions, n_neurons = means.shape

    mean_min, mean_max = np.nanmin(means), np.nanmax(means)
    if mean_min == mean_max:
        # All means are the same
        return {
            "weights": np.ones_like(means),
            "bin_edges": np.array([mean_min, mean_max + 1]),
            "counts_per_condition": np.full((n_conditions, 1), n_neurons),
            "min_counts_per_bin": np.full(1, n_neurons),
        }

    bin_edges = np.linspace(mean_min, mean_max, n_bins + 1)

    counts_per_condition = np.zeros((n_conditions, n_bins))
    for c in range(n_conditions):
        valid_means = means[c, ~np.isnan(means[c])]
        if len(valid_means) > 0:
            counts_per_condition[c], _ = np.histogram(valid_means, bins=bin_edges)

    # Find minimum count per bin (greatest common distribution)
    min_counts_per_bin = np.min(counts_per_condition, axis=0)

    weights = np.ones_like(means)

    for c in range(n_conditions):
        for b in range(n_bins):
            mask = (means[c] >= bin_edges[b]) & (means[c] < bin_edges[b + 1])
            if b == n_bins - 1:  # Include right edge for last bin
                mask = mask | (means[c] == bin_edges[b + 1])

            n_in_bin = np.sum(mask)
            target_n = min_counts_per_bin[b]

            if n_in_bin > 0 and target_n < n_in_bin:
                weights[c, mask] = target_n / n_in_bin
            elif n_in_bin > 0:
                weights[c, mask] = 1.0
            else:
                weights[c, mask] = 0.0

    return {
        "weights": weights,
        "bin_edges": bin_edges,
        "counts_per_condition": counts_per_condition,
        "min_counts_per_bin": min_counts_per_bin,
    }

_compute_mean_matching_weights_torch(means, n_bins=10)

Torch implementation of mean matching weights.

Source code in btorch/analysis/dynamic_tools/fano.py
def _compute_mean_matching_weights_torch(
    means: torch.Tensor,
    n_bins: int = 10,
) -> dict[str, torch.Tensor]:
    """Torch implementation of mean matching weights."""
    device = means.device
    n_conditions, n_neurons = means.shape

    mean_min, mean_max = torch.min(means), torch.max(means)
    if mean_min.item() == mean_max.item():
        return {
            "weights": torch.ones_like(means),
            "bin_edges": torch.tensor(
                [mean_min.item(), mean_max.item() + 1], device=device
            ),
            "counts_per_condition": torch.full(
                (n_conditions, 1), n_neurons, device=device
            ),
            "min_counts_per_bin": torch.full((1,), n_neurons, device=device),
        }

    bin_edges = torch.linspace(
        mean_min.item(), mean_max.item(), n_bins + 1, device=device
    )

    counts_per_condition = torch.zeros((n_conditions, n_bins), device=device)
    for c in range(n_conditions):
        for b in range(n_bins):
            mask = (means[c] >= bin_edges[b]) & (means[c] < bin_edges[b + 1])
            if b == n_bins - 1:
                mask = mask | (means[c] == bin_edges[b + 1])
            counts_per_condition[c, b] = torch.sum(mask).float()

    min_counts_per_bin = torch.min(counts_per_condition, dim=0).values

    weights = torch.ones_like(means)
    for c in range(n_conditions):
        for b in range(n_bins):
            mask = (means[c] >= bin_edges[b]) & (means[c] < bin_edges[b + 1])
            if b == n_bins - 1:
                mask = mask | (means[c] == bin_edges[b + 1])

            n_in_bin = torch.sum(mask).float()
            target_n = min_counts_per_bin[b]

            if n_in_bin > 0 and target_n < n_in_bin:
                weights[c, mask] = target_n / n_in_bin
            elif n_in_bin > 0:
                weights[c, mask] = 1.0
            else:
                weights[c, mask] = 0.0

    return {
        "weights": weights,
        "bin_edges": bin_edges,
        "counts_per_condition": counts_per_condition,
        "min_counts_per_bin": min_counts_per_bin,
    }

_compute_operational_fano_numpy(spikes, rate_hz, window_op, dt, batch_axis)

Compute Fano factor in operational time for NumPy arrays.

The operational time approach rescales time by the firing rate: w = λ * t, where λ is the firing rate in Hz.

For a renewal process: F⁽ᵒ⁾ = CV² (independent of rate).

Implementation: We normalize spike counts by rate, effectively computing statistics as if rate = 1 everywhere.

Parameters:

Name Type Description Default
spikes ndarray

Spike train [T, ...]

required
rate_hz ndarray

Estimated rate in Hz [T, ...] or scalar

required
window_op float

Window size in operational time units

required
dt float

Time step in milliseconds

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

Axes to aggregate across

required

Returns:

Name Type Description
fano_op ndarray

Operational time Fano factor

info dict

Computation info

Source code in btorch/analysis/dynamic_tools/fano.py
def _compute_operational_fano_numpy(
    spikes: np.ndarray,
    rate_hz: np.ndarray,
    window_op: float,
    dt: float,
    batch_axis: tuple[int, ...] | None,
) -> tuple[np.ndarray, dict]:
    """Compute Fano factor in operational time for NumPy arrays.

    The operational time approach rescales time by the firing rate:
    w = λ * t, where λ is the firing rate in Hz.

    For a renewal process: F⁽ᵒ⁾ = CV² (independent of rate).

    Implementation: We normalize spike counts by rate, effectively
    computing statistics as if rate = 1 everywhere.

    Args:
        spikes: Spike train [T, ...]
        rate_hz: Estimated rate in Hz [T, ...] or scalar
        window_op: Window size in operational time units
        dt: Time step in milliseconds
        batch_axis: Axes to aggregate across

    Returns:
        fano_op: Operational time Fano factor
        info: Computation info
    """
    T = spikes.shape[0]
    rest_shape = spikes.shape[1:]
    n_elements = np.prod(rest_shape) if rest_shape else 1

    flat_spikes = spikes.reshape(T, -1) if n_elements > 0 else spikes.reshape(T, 1)
    flat_rate = (
        rate_hz.reshape(T, -1)
        if isinstance(rate_hz, np.ndarray) and rate_hz.ndim > 0
        else rate_hz
    )

    n_neurons = flat_spikes.shape[1]

    def per_neuron_rate(reduce):
        # Per-neuron rate [n_neurons]: reduce over time if rate varies in time,
        # otherwise broadcast the scalar (or reduced 1-D) rate.
        if isinstance(flat_rate, np.ndarray) and flat_rate.ndim > 1:
            return reduce(flat_rate, axis=0)
        return np.full(
            n_neurons, flat_rate if np.isscalar(flat_rate) else reduce(flat_rate)
        )

    median_rate = per_neuron_rate(np.median)

    window_bins = _operational_window_bins(
        window_op, float(np.median(median_rate)), dt, T
    )

    step = max(1, window_bins // 2)
    n_windows = (T - window_bins) // step + 1

    if n_windows < 2:
        warnings.warn(
            f"Insufficient data for operational-time Fano ({n_windows} "
            "windows < 2); returning NaN",
            stacklevel=2,
        )
        return np.full(rest_shape if rest_shape else (1,), np.nan), {
            "n_windows": n_windows
        }

    counts = np.zeros((n_windows, n_neurons))
    for w in range(n_windows):
        start = w * step
        end = start + window_bins
        counts[w] = flat_spikes[start:end].sum(axis=0)

    mean_rate = per_neuron_rate(np.mean)  # [n_neurons]

    window_duration_s = window_bins * dt / 1000.0
    expected_counts = mean_rate * window_duration_s  # [n_neurons]

    normalized_counts = counts / (expected_counts[None, :] + 1e-12)

    mean_norm = np.mean(normalized_counts, axis=0)
    var_norm = np.var(normalized_counts, axis=0, ddof=1)

    fano_op = np.zeros(n_neurons)
    valid = (mean_norm > 0) & np.isfinite(var_norm)
    fano_op[valid] = var_norm[valid] / mean_norm[valid]

    if rest_shape:
        fano_op = fano_op.reshape(rest_shape)
    else:
        fano_op = fano_op[0] if n_neurons == 1 else fano_op

    if batch_axis is not None:
        fano_op = np.mean(fano_op, axis=tuple(batch_axis))

    info = {
        "method": "operational_time",
        "window_bins": window_bins,
        "n_windows": n_windows,
        "mean_rate_hz": np.mean(mean_rate),
        "window_duration_s": window_duration_s,
    }

    return fano_op, info

_compute_operational_fano_torch(spikes, rate_hz, window_op, dt, batch_axis)

Compute Fano factor in operational time for Torch tensors.

Source code in btorch/analysis/dynamic_tools/fano.py
def _compute_operational_fano_torch(
    spikes: torch.Tensor,
    rate_hz: torch.Tensor | float,
    window_op: float,
    dt: float,
    batch_axis: tuple[int, ...] | None,
) -> tuple[torch.Tensor, dict]:
    """Compute Fano factor in operational time for Torch tensors."""
    device = spikes.device
    T = spikes.shape[0]
    rest_shape = spikes.shape[1:]
    n_elements = int(np.prod(rest_shape)) if rest_shape else 1

    flat_spikes = spikes.reshape(T, -1) if n_elements > 0 else spikes.reshape(T, 1)

    if isinstance(rate_hz, torch.Tensor):
        flat_rate = rate_hz.reshape(T, -1) if rate_hz.numel() > 1 else rate_hz.item()
    else:
        flat_rate = rate_hz

    n_neurons = flat_spikes.shape[1]

    def per_neuron_rate(reduce):
        # Per-neuron rate [n_neurons]: reduce over time if rate varies in time,
        # otherwise broadcast the scalar rate.
        if isinstance(flat_rate, torch.Tensor):
            return reduce(flat_rate)
        return torch.full((n_neurons,), float(flat_rate), device=device)

    median_rate = per_neuron_rate(lambda r: torch.median(r, dim=0).values)
    window_bins = _operational_window_bins(
        window_op, torch.median(median_rate).item(), dt, T
    )

    step = max(1, window_bins // 2)
    n_windows = (T - window_bins) // step + 1

    if n_windows < 2:
        warnings.warn(
            f"Insufficient data for operational-time Fano ({n_windows} "
            "windows < 2); returning NaN",
            stacklevel=2,
        )
        return torch.full(
            rest_shape if rest_shape else (1,), float("nan"), device=device
        ), {"n_windows": n_windows}

    counts = torch.zeros((n_windows, n_neurons), device=device)
    for w in range(n_windows):
        start = w * step
        end = start + window_bins
        counts[w] = flat_spikes[start:end].sum(dim=0)

    mean_rate = per_neuron_rate(lambda r: torch.mean(r, dim=0))  # [n_neurons]

    window_duration_s = window_bins * dt / 1000.0
    expected_counts = mean_rate * window_duration_s

    normalized_counts = counts / (expected_counts.unsqueeze(0) + 1e-12)

    mean_norm = torch.mean(normalized_counts, dim=0)
    var_norm = torch.var(normalized_counts, dim=0, unbiased=True)

    fano_op = torch.zeros(n_neurons, device=device)
    valid = (mean_norm > 0) & torch.isfinite(var_norm)
    fano_op[valid] = var_norm[valid] / mean_norm[valid]

    if rest_shape:
        fano_op = fano_op.reshape(rest_shape)
    elif n_neurons == 1:
        fano_op = fano_op[0]

    if batch_axis is not None:
        fano_op = torch.mean(fano_op, dim=tuple(batch_axis))

    info = {
        "method": "operational_time",
        "window_bins": window_bins,
        "n_windows": n_windows,
        "mean_rate_hz": torch.mean(mean_rate).item(),
        "window_duration_s": window_duration_s,
    }

    return fano_op, info

_compute_weighted_fano_numpy(spike_counts, weights)

Compute weighted Fano factor.

Parameters:

Name Type Description Default
spike_counts ndarray

Spike counts [n_trials, n_neurons] or [n_conditions, n_neurons]

required
weights ndarray

Weights for each observation

required

Returns:

Type Description
ndarray

Weighted Fano factor per neuron

Source code in btorch/analysis/dynamic_tools/fano.py
def _compute_weighted_fano_numpy(
    spike_counts: np.ndarray,
    weights: np.ndarray,
) -> np.ndarray:
    """Compute weighted Fano factor.

    Args:
        spike_counts: Spike counts [n_trials, n_neurons] or [n_conditions, n_neurons]
        weights: Weights for each observation

    Returns:
        Weighted Fano factor per neuron
    """
    valid_mask = ~np.isnan(spike_counts) & ~np.isnan(weights)

    weights_normalized = np.where(
        valid_mask, weights / (np.nansum(weights, axis=0, keepdims=True) + 1e-12), 0
    )

    weighted_mean = np.nansum(spike_counts * weights_normalized, axis=0)

    V1 = np.nansum(weights, axis=0)
    V2 = np.nansum(weights**2, axis=0)

    # Avoid division by zero
    denom = V1 - V2 / (V1 + 1e-12) + 1e-12

    weighted_var = (
        np.nansum(weights * (spike_counts - weighted_mean[None, :]) ** 2, axis=0)
        / denom
    )

    fano = np.full_like(weighted_mean, np.nan)
    valid = (weighted_mean > 0) & (weighted_var >= 0)
    fano[valid] = weighted_var[valid] / weighted_mean[valid]

    return fano

_compute_weighted_fano_torch(spike_counts, weights)

Torch implementation of weighted Fano factor.

Source code in btorch/analysis/dynamic_tools/fano.py
def _compute_weighted_fano_torch(
    spike_counts: torch.Tensor,
    weights: torch.Tensor,
) -> torch.Tensor:
    """Torch implementation of weighted Fano factor."""
    valid_mask = ~torch.isnan(spike_counts) & ~torch.isnan(weights)

    weight_sums = torch.sum(weights * valid_mask.float(), dim=0, keepdim=True)
    weights_normalized = torch.where(
        valid_mask, weights / (weight_sums + 1e-12), torch.zeros_like(weights)
    )

    weighted_mean = torch.sum(spike_counts * weights_normalized, dim=0)

    V1 = torch.sum(weights * valid_mask.float(), dim=0)
    V2 = torch.sum((weights**2) * valid_mask.float(), dim=0)

    denom = V1 - V2 / (V1 + 1e-12) + 1e-12

    weighted_var = (
        torch.sum(weights * (spike_counts - weighted_mean.unsqueeze(0)) ** 2, dim=0)
        / denom
    )

    fano = torch.full_like(weighted_mean, float("nan"))
    valid = (weighted_mean > 0) & (weighted_var >= 0)
    fano[valid] = weighted_var[valid] / weighted_mean[valid]

    return fano

_estimate_rate_numpy(spikes, dt, window_ms=None)

Estimate instantaneous firing rate using sliding window.

Parameters:

Name Type Description Default
spikes ndarray

Spike train of shape [T, ...]. First dimension is time.

required
dt float

Time step in milliseconds.

required
window_ms float | None

Window size for rate estimation. If None, uses T//20 * dt.

None

Returns:

Type Description
ndarray

Estimated rate in Hz [T, ...].

Source code in btorch/analysis/dynamic_tools/fano.py
def _estimate_rate_numpy(
    spikes: np.ndarray,
    dt: float,
    window_ms: float | None = None,
) -> np.ndarray:
    """Estimate instantaneous firing rate using sliding window.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        dt: Time step in milliseconds.
        window_ms: Window size for rate estimation. If None, uses T//20 * dt.

    Returns:
        Estimated rate in Hz [T, ...].
    """
    T = spikes.shape[0]

    if window_ms is None:
        window_bins = max(10, T // 20)
    else:
        window_bins = max(1, int(window_ms / dt))

    kernel = np.ones(window_bins) / (window_bins * dt / 1000.0)

    rate = np.apply_along_axis(
        lambda x: np.convolve(x, kernel, mode="same"),
        axis=0,
        arr=spikes,
    )

    # Ensure minimum rate to avoid division by zero
    return np.maximum(rate, 1e-6)

_estimate_rate_torch(spikes, dt, window_ms=None)

Torch implementation of rate estimation.

Source code in btorch/analysis/dynamic_tools/fano.py
def _estimate_rate_torch(
    spikes: torch.Tensor,
    dt: float,
    window_ms: float | None = None,
) -> torch.Tensor:
    """Torch implementation of rate estimation."""
    T = spikes.shape[0]

    if window_ms is None:
        window_bins = max(10, T // 20)
    else:
        window_bins = max(1, int(window_ms / dt))

    # Pad with edge values to handle boundaries
    pad = window_bins // 2

    original_shape = spikes.shape
    if spikes.ndim == 1:
        spikes = spikes.unsqueeze(-1)  # [T, 1]

    # Pad using constant mode (replicate edge values)
    spike_padded = torch.nn.functional.pad(spikes, (0, 0, pad, pad), mode="constant")
    # Fill padding with edge values (replicate)
    if pad > 0:
        spike_padded[:pad] = spikes[0]
        spike_padded[-pad:] = spikes[-1]

    cumsum = torch.cumsum(spike_padded, dim=0)
    moving_sum = cumsum[window_bins:] - cumsum[:-window_bins]

    start_idx = window_bins // 2
    end_idx = start_idx + T
    moving_sum = moving_sum[start_idx:end_idx]

    if moving_sum.shape[0] < T:
        pad_right = T - moving_sum.shape[0]
        moving_sum = torch.nn.functional.pad(moving_sum, (0, 0, 0, pad_right))

    rate = moving_sum / (window_bins * dt / 1000.0)

    rate = rate.reshape(original_shape)

    return torch.clamp(rate, min=1e-6)

_fit_count_model(model, model_params, empirical_mean, stimulus_drive, is_torch)

Model mean/variance of the counts and the model-specific info entries.

Raises:

Type Description
ValueError

If model (or the flexible-model nonlinearity) is unknown.

Source code in btorch/analysis/dynamic_tools/fano.py
def _fit_count_model(
    model: str,
    model_params: dict,
    empirical_mean: np.ndarray | torch.Tensor,
    stimulus_drive: np.ndarray | torch.Tensor | None,
    is_torch: bool,
) -> tuple[np.ndarray | torch.Tensor, np.ndarray | torch.Tensor, dict]:
    """Model mean/variance of the counts and the model-specific info entries.

    Raises:
        ValueError: If ``model`` (or the flexible-model nonlinearity) is
            unknown.
    """
    if model == "modulated_poisson":
        gain_mean = model_params.get("gain_mean", 1.0)
        gain_var = model_params.get("gain_var", 0.5)
        model_mean, model_var = _modulated_poisson_moments(
            empirical_mean, gain_mean, gain_var
        )
        return (
            model_mean,
            model_var,
            {"gain_mean": gain_mean, "gain_var": gain_var},
        )

    if model == "flexible_overdispersion":
        if stimulus_drive is None:
            # The empirical mean serves as proxy for the stimulus drive.
            stimulus_drive = (
                torch.log(empirical_mean + 1)
                if is_torch
                else np.log(empirical_mean + 1)
            )
        nonlinearity = model_params.get("nonlinearity", "relu")
        noise_std = model_params.get("noise_std", 0.5)
        model_mean, model_var = _flexible_overdispersion_moments(
            stimulus_drive, noise_std, nonlinearity
        )
        return (
            model_mean,
            model_var,
            {"nonlinearity": nonlinearity, "noise_std": noise_std},
        )

    raise ValueError(f"Unknown model: {model}")

_flexible_overdispersion_moments(stimulus_drive, noise_std=0.5, nonlinearity='relu')

Compute mean and variance for flexible overdispersion model.

The flexible overdispersion model (Charles et al., 2018): λ_eff = f(g(x) + ε) where f is a nonlinearity.

Different nonlinearities produce different mean-FF relationships: - Rectified-linear: FF decreases with increasing rate - Rectified-squaring: FF ≈ constant - Exponential: FF increases with rate

Parameters:

Name Type Description Default
stimulus_drive ndarray | Tensor

Stimulus-dependent drive g(x)

required
noise_std float

Standard deviation of additive Gaussian noise ε

0.5
nonlinearity Literal['relu', 'square', 'exp', 'softplus']

Type of nonlinearity to apply

'relu'

Returns:

Name Type Description
mean ndarray | Tensor

Expected spike count

variance ndarray | Tensor

Spike count variance

Source code in btorch/analysis/dynamic_tools/fano.py
def _flexible_overdispersion_moments(
    stimulus_drive: np.ndarray | torch.Tensor,
    noise_std: float = 0.5,
    nonlinearity: Literal["relu", "square", "exp", "softplus"] = "relu",
) -> tuple[np.ndarray | torch.Tensor, np.ndarray | torch.Tensor]:
    """Compute mean and variance for flexible overdispersion model.

    The flexible overdispersion model (Charles et al., 2018):
    λ_eff = f(g(x) + ε) where f is a nonlinearity.

    Different nonlinearities produce different mean-FF relationships:
    - Rectified-linear: FF decreases with increasing rate
    - Rectified-squaring: FF ≈ constant
    - Exponential: FF increases with rate

    Args:
        stimulus_drive: Stimulus-dependent drive g(x)
        noise_std: Standard deviation of additive Gaussian noise ε
        nonlinearity: Type of nonlinearity to apply

    Returns:
        mean: Expected spike count
        variance: Spike count variance
    """
    is_torch = isinstance(stimulus_drive, torch.Tensor)

    if nonlinearity == "relu":
        # Rectified linear: f(z) = max(0, z)
        # Mean requires Gaussian integral
        if is_torch:
            # Approximation for rectified Gaussian
            phi = lambda x: 0.5 * (1 + torch.erf(x / np.sqrt(2)))
            mean = stimulus_drive * phi(stimulus_drive / noise_std)
            mean += (
                noise_std
                * torch.exp(-0.5 * (stimulus_drive / noise_std) ** 2)
                / np.sqrt(2 * np.pi)
            )
        else:
            from scipy.stats import norm

            mean = stimulus_drive * norm.cdf(stimulus_drive / noise_std)
            mean += noise_std * norm.pdf(stimulus_drive / noise_std)

    elif nonlinearity == "square":
        # Rectified squaring: f(z) = max(0, z)²
        # E[f(z)] where z ~ N(g, σ²)
        if is_torch:
            phi = lambda x: 0.5 * (1 + torch.erf(x / np.sqrt(2)))
            mean = (stimulus_drive**2 + noise_std**2) * phi(stimulus_drive / noise_std)
            mean += (
                stimulus_drive
                * noise_std
                * torch.exp(-0.5 * (stimulus_drive / noise_std) ** 2)
                / np.sqrt(2 * np.pi)
            )
        else:
            from scipy.stats import norm

            mean = (stimulus_drive**2 + noise_std**2) * norm.cdf(
                stimulus_drive / noise_std
            )
            mean += stimulus_drive * noise_std * norm.pdf(stimulus_drive / noise_std)

    elif nonlinearity == "exp":
        # Exponential: f(z) = exp(z)
        # E[exp(z)] = exp(g + σ²/2) for z ~ N(g, σ²)
        mean = (
            np.exp(stimulus_drive + 0.5 * noise_std**2)
            if not is_torch
            else torch.exp(stimulus_drive + 0.5 * noise_std**2)
        )

    elif nonlinearity == "softplus":
        # Softplus: f(z) = log(1 + exp(z))
        # Numerically stable computation
        if is_torch:
            mean = torch.nn.functional.softplus(stimulus_drive)
        else:
            mean = np.log(1 + np.exp(np.clip(stimulus_drive, -700, 700)))

    else:
        raise ValueError(f"Unknown nonlinearity: {nonlinearity}")

    # Variance approximation (quadratic for most nonlinearities)
    variance = mean + 0.5 * (mean**2)  # Simplified overdispersion

    return mean, variance

_mean_over_axes(x, batch_axis)

Average over batch_axis (no-op for None).

Source code in btorch/analysis/dynamic_tools/fano.py
def _mean_over_axes(
    x: np.ndarray | torch.Tensor, batch_axis: tuple[int, ...] | None
) -> np.ndarray | torch.Tensor:
    """Average over ``batch_axis`` (no-op for ``None``)."""
    if batch_axis is None:
        return x
    if isinstance(x, torch.Tensor):
        return torch.mean(x, dim=tuple(batch_axis))
    return np.mean(x, axis=tuple(batch_axis))

_modulated_poisson_moments(lambda_base, gain_mean=1.0, gain_var=0.5)

Compute mean and variance for modulated Poisson model.

The modulated Poisson model (Goris et al., 2014): r ~ Poisson(λ · g) where g is multiplicative gain noise.

Mean: E[r] = λ · E[g] Variance: Var[r] = E[g] · λ + Var[g] · λ²

This produces quadratic mean-variance relationship: Var[r] = E[r] + (Var[g]/E[g]²) · E[r]²

Parameters:

Name Type Description Default
lambda_base ndarray | Tensor

Base firing rate

required
gain_mean float

Mean of gain distribution (E[g])

1.0
gain_var float

Variance of gain distribution (Var[g])

0.5

Returns:

Name Type Description
mean ndarray | Tensor

Expected spike count

variance ndarray | Tensor

Spike count variance

Source code in btorch/analysis/dynamic_tools/fano.py
def _modulated_poisson_moments(
    lambda_base: np.ndarray | torch.Tensor,
    gain_mean: float = 1.0,
    gain_var: float = 0.5,
) -> tuple[np.ndarray | torch.Tensor, np.ndarray | torch.Tensor]:
    """Compute mean and variance for modulated Poisson model.

    The modulated Poisson model (Goris et al., 2014):
    r ~ Poisson(λ · g) where g is multiplicative gain noise.

    Mean: E[r] = λ · E[g]
    Variance: Var[r] = E[g] · λ + Var[g] · λ²

    This produces quadratic mean-variance relationship:
    Var[r] = E[r] + (Var[g]/E[g]²) · E[r]²

    Args:
        lambda_base: Base firing rate
        gain_mean: Mean of gain distribution (E[g])
        gain_var: Variance of gain distribution (Var[g])

    Returns:
        mean: Expected spike count
        variance: Spike count variance
    """
    mean = lambda_base * gain_mean
    # Law of total variance: Var[r] = E[Var[r|g]] + Var[E[r|g]]
    # Var[r|g] = λ·g (Poisson), E[r|g] = λ·g
    # E[Var[r|g]] = λ·E[g]
    # Var[E[r|g]] = λ²·Var[g]
    variance = lambda_base * gain_mean + (lambda_base**2) * gain_var
    return mean, variance

_operational_window_bins(window_op, median_rate, dt, T)

Window length in bins for a window of window_op operational units.

Operational time is w = lambda * t, so W operational units span about W / (lambda * dt) bins at the median rate. Counts are taken in that fixed-width window and normalized by their expected value.

Source code in btorch/analysis/dynamic_tools/fano.py
def _operational_window_bins(
    window_op: float, median_rate: float, dt: float, T: int
) -> int:
    """Window length in bins for a window of ``window_op`` operational units.

    Operational time is w = lambda * t, so W operational units span
    about W / (lambda * dt) bins at the median rate. Counts are taken in
    that fixed-width window and normalized by their expected value.
    """
    window_bins = max(5, int(window_op / median_rate / (dt / 1000.0)))
    window_bins = min(window_bins, T // 3)  # Leave room for several windows
    return max(window_bins, 2)

_resolve_window_step(T, window, overlap)

Default the window to T // 10 and return (window, step).

Raises:

Type Description
ValueError

If window <= overlap (the step would not advance).

Source code in btorch/analysis/dynamic_tools/fano.py
def _resolve_window_step(T: int, window: int | None, overlap: int) -> tuple[int, int]:
    """Default the window to ``T // 10`` and return ``(window, step)``.

    Raises:
        ValueError: If ``window <= overlap`` (the step would not advance).
    """
    if window is None:
        window = max(1, T // 10)
    step = window - overlap
    if step <= 0:
        raise ValueError(
            f"window must be greater than overlap, got window={window}, "
            f"overlap={overlap}"
        )
    return window, step

_too_few_windows_nan(spikes, n_flat, rest_shape, n_windows, label)

Failure return when fewer than two windows fit: warn, NaN result.

Source code in btorch/analysis/dynamic_tools/fano.py
def _too_few_windows_nan(
    spikes: np.ndarray | torch.Tensor,
    n_flat: int,
    rest_shape: tuple[int, ...],
    n_windows: int,
    label: str,
) -> tuple[np.ndarray | torch.Tensor, dict]:
    """Failure return when fewer than two windows fit: warn, NaN result."""
    if isinstance(spikes, torch.Tensor):
        result = torch.full((n_flat,), float("nan"), device=spikes.device)
    else:
        result = np.full((n_flat,), np.nan)
    warnings.warn(
        f"Too few windows ({n_windows} < 2) for {label} Fano; returning NaN",
        stacklevel=3,
    )
    return (result.reshape(rest_shape) if rest_shape else result), {
        "n_windows": n_windows
    }

_windowed_counts(flat, window, step, n_windows)

Spike counts per (possibly overlapping) window.

Parameters:

Name Type Description Default
flat ndarray | Tensor

Spikes of shape [T, ...].

required

Returns:

Type Description
ndarray | Tensor

Counts of shape [n_windows, ...] (float32 for torch, float64 for

ndarray | Tensor

NumPy), counted over window bins starting every step bins.

Source code in btorch/analysis/dynamic_tools/fano.py
def _windowed_counts(
    flat: np.ndarray | torch.Tensor, window: int, step: int, n_windows: int
) -> np.ndarray | torch.Tensor:
    """Spike counts per (possibly overlapping) window.

    Args:
        flat: Spikes of shape ``[T, ...]``.

    Returns:
        Counts of shape ``[n_windows, ...]`` (float32 for torch, float64 for
        NumPy), counted over ``window`` bins starting every ``step`` bins.
    """
    if isinstance(flat, torch.Tensor):
        counts = torch.zeros((n_windows, *flat.shape[1:]), device=flat.device)
        for w in range(n_windows):
            counts[w] = flat[w * step : w * step + window].sum(dim=0)
    else:
        counts = np.zeros((n_windows, *flat.shape[1:]))
        for w in range(n_windows):
            counts[w] = flat[w * step : w * step + window].sum(axis=0)
    return counts

compare_fano_methods(spikes, dt=1.0, **kwargs)

Compare different Fano factor compensation methods.

Computes Fano factor using multiple methods for comparison.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike train of shape [T, ...].

required
dt float

Time step in milliseconds.

1.0
**kwargs Any

Additional arguments passed to methods.

{}

Returns:

Type Description
dict

Dictionary mapping method name ("standard", "operational_time",

dict

"mean_matching", "modulated_poisson") to its Fano factor

dict

result. Values are always numeric. If a compensation method fails for

dict

data-dependent reasons (ValueError, RuntimeError,

dict

ArithmeticError, LinAlgError), its entry is float("nan")

dict

and a :class:UserWarning is emitted. Other exceptions (e.g.

dict

TypeError from bad arguments) are programming errors and propagate.

Source code in btorch/analysis/dynamic_tools/fano.py
def compare_fano_methods(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    **kwargs: Any,
) -> dict:
    """Compare different Fano factor compensation methods.

    Computes Fano factor using multiple methods for comparison.

    Args:
        spikes: Spike train of shape [T, ...].
        dt: Time step in milliseconds.
        **kwargs: Additional arguments passed to methods.

    Returns:
        Dictionary mapping method name (``"standard"``, ``"operational_time"``,
        ``"mean_matching"``, ``"modulated_poisson"``) to its Fano factor
        result. Values are always numeric. If a compensation method fails for
        data-dependent reasons (``ValueError``, ``RuntimeError``,
        ``ArithmeticError``, ``LinAlgError``), its entry is ``float("nan")``
        and a :class:`UserWarning` is emitted. Other exceptions (e.g.
        ``TypeError`` from bad arguments) are programming errors and propagate.
    """
    results: dict[str, Any] = {}

    from btorch.analysis.spiking import fano as standard_fano

    results["standard"], _ = standard_fano(
        spikes,
        **{k: v for k, v in kwargs.items() if k in ["window", "overlap", "batch_axis"]},
    )

    def _run(name: str, func: Callable[[], Any]) -> None:
        # Only data/numerical failures (ValueError, RuntimeError, LinAlgError,
        # FloatingPointError, ArithmeticError) are converted to NaN. Programming
        # errors such as TypeError or AttributeError propagate to the caller.
        try:
            results[name], _ = func()
        except (
            ValueError,
            RuntimeError,
            ArithmeticError,
            np.linalg.LinAlgError,
        ) as e:
            warnings.warn(
                f"Fano method {name!r} failed, returning NaN: {e}", stacklevel=3
            )
            results[name] = float("nan")

    _run(
        "operational_time",
        lambda: fano_operational_time(
            spikes,
            dt=dt,
            **{
                k: v
                for k, v in kwargs.items()
                if k not in ["window", "overlap", "batch_axis"]
            },
        ),
    )
    _run(
        "mean_matching",
        lambda: fano_mean_matching(
            spikes, **{k: v for k, v in kwargs.items() if k not in ["dt"]}
        ),
    )
    _run(
        "modulated_poisson",
        lambda: fano_model_based(
            spikes,
            model="modulated_poisson",
            **{k: v for k, v in kwargs.items() if k not in ["dt"]},
        ),
    )

    return results

fano_compensated(spikes, method='operational_time', **kwargs)

Unified interface for compensated Fano factor computation.

This function provides a unified interface to all rate-compensation methods for the Fano factor. The choice of method depends on the experimental design and data characteristics:

  • operational_time: Best for comparing variability across different firing rates. Transforms to rate-independent reference frame.
  • mean_matching: Best for condition comparisons with overlapping rate distributions. Matches rate histograms before computing FF.
  • modulated_poisson: Model-based approach assuming multiplicative gain noise. Good for explaining overdispersion.
  • flexible_overdispersion: Model-based approach with flexible nonlinearities. Good for testing different rate-FF relationships.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike train of shape [T, ...]. First dimension is time.

required
method Literal['operational_time', 'mean_matching', 'modulated_poisson', 'flexible_overdispersion']

Compensation method to use.

'operational_time'
**kwargs Any

Method-specific arguments passed to underlying functions.

{}

Returns:

Name Type Description
fano StatsResult

Compensated Fano factor values. The failure return (NaN array plus warning when fewer than 2 windows fit) is that of the selected method, see :func:fano_operational_time, :func:fano_mean_matching and :func:fano_model_based.

info StatsResult

Dictionary with method info and computed statistics.

Raises:

Type Description
ValueError

If method is not one of the supported names, plus whatever the selected method raises.

Example

ff_op, _ = fano_compensated(spikes, method="operational_time")

Mean matching (for condition comparisons)

ff_mm, _ = fano_compensated(spikes, method="mean_matching", n_bins=10)

Model-based approach

ff_mod, _ = fano_compensated( ... spikes, method="modulated_poisson", ... model_params={"gain_var": 0.5} ... )

Source code in btorch/analysis/dynamic_tools/fano.py
@use_percentiles(value_key="fano")
@use_stats(value_key="fano")
def fano_compensated(
    spikes: np.ndarray | torch.Tensor,
    method: Literal[
        "operational_time",
        "mean_matching",
        "modulated_poisson",
        "flexible_overdispersion",
    ] = "operational_time",
    **kwargs: Any,
) -> StatsResult:
    """Unified interface for compensated Fano factor computation.

    This function provides a unified interface to all rate-compensation
    methods for the Fano factor. The choice of method depends on the
    experimental design and data characteristics:

    - operational_time: Best for comparing variability across different
      firing rates. Transforms to rate-independent reference frame.
    - mean_matching: Best for condition comparisons with overlapping
      rate distributions. Matches rate histograms before computing FF.
    - modulated_poisson: Model-based approach assuming multiplicative
      gain noise. Good for explaining overdispersion.
    - flexible_overdispersion: Model-based approach with flexible
      nonlinearities. Good for testing different rate-FF relationships.

    Args:
        spikes: Spike train of shape [T, ...]. First dimension is time.
        method: Compensation method to use.
        **kwargs: Method-specific arguments passed to underlying functions.

    Returns:
        fano: Compensated Fano factor values. The failure return (NaN array
            plus warning when fewer than 2 windows fit) is that of the
            selected method, see :func:`fano_operational_time`,
            :func:`fano_mean_matching` and :func:`fano_model_based`.
        info: Dictionary with method info and computed statistics.

    Raises:
        ValueError: If ``method`` is not one of the supported names, plus
            whatever the selected method raises.

    Example:
        >>> # Operational time method (recommended for rate comparisons)
        >>> ff_op, _ = fano_compensated(spikes, method="operational_time")
        >>>
        >>> # Mean matching (for condition comparisons)
        >>> ff_mm, _ = fano_compensated(spikes, method="mean_matching", n_bins=10)
        >>>
        >>> # Model-based approach
        >>> ff_mod, _ = fano_compensated(
        ...     spikes, method="modulated_poisson",
        ...     model_params={"gain_var": 0.5}
        ... )
    """
    if method == "operational_time":
        # Filter out model_params if accidentally passed
        kwargs.pop("model_params", None)
        return fano_operational_time(spikes, **kwargs)
    elif method == "mean_matching":
        kwargs.pop("model_params", None)
        return fano_mean_matching(spikes, **kwargs)
    elif method in ("modulated_poisson", "flexible_overdispersion"):
        return fano_model_based(spikes, model=method, **kwargs)
    else:
        raise ValueError(f"Unknown method: {method}")

fano_mean_matching(spikes, window=None, overlap=0, condition_axis=1, n_bins=10, n_resamples=50, batch_axis=None)

Compute mean-matched Fano factor controlling for rate effects.

The mean matching method (Churchland et al., 2010) ensures that the distribution of mean spike counts is matched across conditions or time points before computing the Fano factor. This removes artifacts caused by rate changes.

Reference: Churchland et al. (2010) "Stimulus onset quenches neural variability: a widespread cortical phenomenon", Nature Neurosci.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike train of shape [T, n_conditions, ...] or [T, n_trials, ...]. First dimension is time.

required
window int | None

Window size in time bins (not ms) for spike counting. If None, uses T//10.

None
overlap int

Overlap between consecutive windows.

0
condition_axis int

Axis representing conditions/trials (default 1).

1
n_bins int

Number of bins for mean count histogram matching.

10
n_resamples int

Recorded in info only; the matching weights are deterministic and no resampling is performed.

50
batch_axis BatchAxis

Additional axes to aggregate across.

None

Returns:

Name Type Description
fano_mm StatsResult

Mean-matched Fano factor values. Failure return: when fewer than 2 windows fit, a NaN array of shape spikes.shape[2:] (the condition axis is removed; (1,) for [T, C] input) with a warning and info={"n_windows": n}.

info StatsResult

Dictionary with matching info and computed statistics.

Raises:

Type Description
ValueError

If window <= overlap.

Example
spikes shape: [T, n_conditions, n_neurons]

ff_mm, info = fano_mean_matching( ... spikes, condition_axis=1, n_bins=10 ... )

Source code in btorch/analysis/dynamic_tools/fano.py
@use_percentiles(value_key="fano_mm")
@use_stats(value_key="fano_mm")
def fano_mean_matching(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
    condition_axis: int = 1,
    n_bins: int = 10,
    n_resamples: int = 50,
    batch_axis: BatchAxis = None,
) -> StatsResult:
    """Compute mean-matched Fano factor controlling for rate effects.

    The mean matching method (Churchland et al., 2010) ensures that the
    distribution of mean spike counts is matched across conditions or time
    points before computing the Fano factor. This removes artifacts caused
    by rate changes.

    Reference: Churchland et al. (2010) "Stimulus onset quenches neural
    variability: a widespread cortical phenomenon", Nature Neurosci.

    Args:
        spikes: Spike train of shape [T, n_conditions, ...] or
            [T, n_trials, ...]. First dimension is time.
        window: Window size in time bins (not ms) for spike counting.
            If None, uses T//10.
        overlap: Overlap between consecutive windows.
        condition_axis: Axis representing conditions/trials (default 1).
        n_bins: Number of bins for mean count histogram matching.
        n_resamples: Recorded in ``info`` only; the matching weights are
            deterministic and no resampling is performed.
        batch_axis: Additional axes to aggregate across.

    Returns:
        fano_mm: Mean-matched Fano factor values. Failure return: when
            fewer than 2 windows fit, a NaN array of shape
            ``spikes.shape[2:]`` (the condition axis is removed;
            ``(1,)`` for [T, C] input) with a warning and
            ``info={"n_windows": n}``.
        info: Dictionary with matching info and computed statistics.

    Raises:
        ValueError: If ``window <= overlap``.

    Example:
        >>> # spikes shape: [T, n_conditions, n_neurons]
        >>> ff_mm, info = fano_mean_matching(
        ...     spikes, condition_axis=1, n_bins=10
        ... )
    """
    is_torch = isinstance(spikes, torch.Tensor)
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    T = spikes.shape[0]
    window, step = _resolve_window_step(T, window, overlap)

    # Move the condition axis to position 1.
    if condition_axis != 1:
        perm = list(range(spikes.ndim))
        perm[1], perm[condition_axis] = perm[condition_axis], perm[1]
        spikes = spikes.permute(*perm) if is_torch else spikes.transpose(*perm)

    n_conditions = spikes.shape[1]
    rest_shape = spikes.shape[2:]
    spike_flat = spikes.reshape(T, n_conditions, -1)
    n_neurons_flat = spike_flat.shape[2]

    n_windows = (T - window) // step + 1
    if n_windows < 2:
        return _too_few_windows_nan(
            spikes, n_neurons_flat, rest_shape, n_windows, "mean-matching"
        )

    counts = _windowed_counts(spike_flat, window, step, n_windows)
    means = counts.mean(dim=0) if is_torch else counts.mean(axis=0)  # [C, N]

    flat_counts = counts.reshape(-1, n_neurons_flat)
    if is_torch:
        match_info = _compute_mean_matching_weights_torch(means, n_bins)
        fano_mm = _compute_weighted_fano_torch(
            flat_counts, match_info["weights"].repeat(n_windows, 1)
        )
    else:
        match_info = _compute_mean_matching_weights_numpy(means, n_bins)
        fano_mm = _compute_weighted_fano_numpy(
            flat_counts, match_info["weights"].repeat(n_windows, axis=0)
        )

    fano_mm = _mean_over_axes(fano_mm.reshape(rest_shape), batch_axis)
    info = {
        **match_info,
        "method": "mean_matching",
        "n_bins": n_bins,
        "n_resamples": n_resamples,
    }
    return fano_mm, info

fano_model_based(spikes, window=None, overlap=0, model='modulated_poisson', model_params=None, stimulus_drive=None, batch_axis=None)

Compute model-based Fano factor with rate compensation.

Model-based approaches fit a generative model to the spike data and extract the underlying variability independent of rate effects.

Models: 1. Modulated Poisson (Goris et al., 2014): r ~ Poisson(λ · g) where g is multiplicative gain noise. Produces quadratic mean-variance relationship.

  1. Flexible Overdispersion (Charles et al., 2018): λ_eff = f(g(x) + ε) with different nonlinearities.
  2. Rectified-linear: FF decreases with rate
  3. Rectified-squaring: FF ≈ constant
  4. Exponential: FF increases with rate

References: - Goris et al. (2014) "Partitioning neuronal variability" - Charles et al. (2018) "Dethroning the Fano factor"

Parameters:

Name Type Description Default
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 T//10.

None
overlap int

Overlap between consecutive windows.

0
model Literal['modulated_poisson', 'flexible_overdispersion']

Model type to use.

'modulated_poisson'
model_params dict | None

Model-specific parameters.

None
stimulus_drive ndarray | Tensor | None

Stimulus-dependent drive (required for flexible_overdispersion).

None
batch_axis BatchAxis

Axes to average across for FF computation.

None

Returns:

Name Type Description
fano_model StatsResult

Model-based Fano factor values. Failure return: when fewer than 2 windows fit, a NaN array of shape spikes.shape[1:] with a warning and info={"n_windows": n}.

info StatsResult

Dictionary with model fit info and computed statistics.

Raises:

Type Description
ValueError

If the requested model or the nonlinearity in model_params is unknown, or if window <= overlap.

Example

ff_mod, info = fano_model_based( ... spikes, ... model="modulated_poisson", ... model_params={"gain_mean": 1.0, "gain_var": 0.5} ... )

Source code in btorch/analysis/dynamic_tools/fano.py
@use_percentiles(value_key="fano_model")
@use_stats(value_key="fano_model")
def fano_model_based(
    spikes: np.ndarray | torch.Tensor,
    window: int | None = None,
    overlap: int = 0,
    model: Literal[
        "modulated_poisson", "flexible_overdispersion"
    ] = "modulated_poisson",
    model_params: dict | None = None,
    stimulus_drive: np.ndarray | torch.Tensor | None = None,
    batch_axis: BatchAxis = None,
) -> StatsResult:
    """Compute model-based Fano factor with rate compensation.

    Model-based approaches fit a generative model to the spike data and
    extract the underlying variability independent of rate effects.

    Models:
    1. Modulated Poisson (Goris et al., 2014):
       r ~ Poisson(λ · g) where g is multiplicative gain noise.
       Produces quadratic mean-variance relationship.

    2. Flexible Overdispersion (Charles et al., 2018):
       λ_eff = f(g(x) + ε) with different nonlinearities.
       - Rectified-linear: FF decreases with rate
       - Rectified-squaring: FF ≈ constant
       - Exponential: FF increases with rate

    References:
    - Goris et al. (2014) "Partitioning neuronal variability"
    - Charles et al. (2018) "Dethroning the Fano factor"

    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 T//10.
        overlap: Overlap between consecutive windows.
        model: Model type to use.
        model_params: Model-specific parameters.
        stimulus_drive: Stimulus-dependent drive (required for flexible_overdispersion).
        batch_axis: Axes to average across for FF computation.

    Returns:
        fano_model: Model-based Fano factor values. Failure return: when fewer
            than 2 windows fit, a NaN array of shape ``spikes.shape[1:]`` with
            a warning and ``info={"n_windows": n}``.
        info: Dictionary with model fit info and computed statistics.

    Raises:
        ValueError: If the requested ``model`` or the ``nonlinearity`` in
            ``model_params`` is unknown, or if ``window <= overlap``.

    Example:
        >>> ff_mod, info = fano_model_based(
        ...     spikes,
        ...     model="modulated_poisson",
        ...     model_params={"gain_mean": 1.0, "gain_var": 0.5}
        ... )
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    is_torch = isinstance(spikes, torch.Tensor)
    T = spikes.shape[0]
    window, step = _resolve_window_step(T, window, overlap)
    rest_shape = spikes.shape[1:]
    flat_spike = spikes.reshape(T, -1)

    n_windows = (T - window) // step + 1
    if n_windows < 2:
        return _too_few_windows_nan(
            spikes, flat_spike.shape[1], rest_shape, n_windows, "model-based"
        )

    counts = _windowed_counts(flat_spike, window, step, n_windows)
    if is_torch:
        empirical_mean = counts.mean(dim=0)
        empirical_var = counts.var(dim=0, unbiased=True)
    else:
        empirical_mean = counts.mean(axis=0)
        empirical_var = counts.var(axis=0, ddof=1)

    model_mean, model_var, model_info = _fit_count_model(
        model, model_params or {}, empirical_mean, stimulus_drive, is_torch
    )
    # Model-based FF: model variance over model mean.
    fano_model = model_var / (model_mean + 1e-12)
    info = {
        "model": model,
        **model_info,
        "empirical_mean": empirical_mean,
        "empirical_var": empirical_var,
        "model_mean": model_mean,
        "model_var": model_var,
    }
    return _mean_over_axes(fano_model.reshape(rest_shape), batch_axis), info

fano_operational_time(spikes, window=None, overlap=None, rate_hz=None, dt=1.0, batch_axis=None)

Compute Fano factor in operational time (rate-independent).

The operational time Fano factor transforms the spike train such that

the firing rate equals 1 (normalized), making FF independent of the absolute firing rate. This is the recommended method for comparing variability across conditions with different rates.

For renewal processes, the operational time Fano factor equals the
squared coefficient of variation (CV²) of the ISI distribution.

Reference: Rajdl et al. (2020) "Fano Factor: A Potentially Useful
Information", Front. Comput. Neurosci.

Args:
    spikes: Spike train of shape [T, ...]. First dimension is time.
        Values are binary (0/1) or spike counts.
    window: Window size in operational time units (default: 1.0). This is a
        dimensionless expected spike count, not a number of time bins.
        This is the expected count at rate=1 (i.e., 1 spike expected).
    overlap: Unsupported. Operational-time windows are disjoint; any
        value other than ``None`` or ``0`` raises ``ValueError``.
    rate_hz: Firing rate in Hz. Can be:
        - Scalar: homogeneous rate
        - Array [T, ...]: time-varying rate
        - None: estimated from data using sliding window
    dt: Time step in milliseconds for original time axis.
    batch_axis: Axes to average across for FF computation.

Returns:
    fano_op: Operational time Fano factor values. Failure return: when
        fewer than 2 windows fit, a NaN array of shape
        ``spikes.shape[1:]`` (``(1,)`` for 1D input) with a warning
        and ``info={"n_windows": n}``.
    info: Dictionary with operational time info and computed statistics.

Raises:
    ValueError: If ``overlap`` is neither ``None`` nor ``0``.

Example:
    >>> # Compare Fano factors at different rates
    >>> spikes_low_rate = generate_poisson_spikes(rate_hz=20, ...)
    >>> spikes_high_rate = generate_poisson_spikes(rate_hz=80, ...)
    >>> ff_low, _ = fano_operational_time(spikes_low_rate)
    >>> ff_high, _ = fano_operational_time(spikes_high_rate)
    >>> # Both should be ≈ 1 regardless of rate difference
Source code in btorch/analysis/dynamic_tools/fano.py
@use_percentiles(value_key="fano_op")
@use_stats(value_key="fano_op")
def fano_operational_time(
    spikes: np.ndarray | torch.Tensor,
    window: float | None = None,
    overlap: int | None = None,
    rate_hz: np.ndarray | torch.Tensor | float | None = None,
    dt: float = 1.0,
    batch_axis: BatchAxis = None,
) -> StatsResult:
    """Compute Fano factor in operational time (rate-independent).

        The operational time Fano factor transforms the spike train such that
    the firing rate equals 1 (normalized), making FF independent of the
        absolute firing rate. This is the recommended method for comparing
        variability across conditions with different rates.

        For renewal processes, the operational time Fano factor equals the
        squared coefficient of variation (CV²) of the ISI distribution.

        Reference: Rajdl et al. (2020) "Fano Factor: A Potentially Useful
        Information", Front. Comput. Neurosci.

        Args:
            spikes: Spike train of shape [T, ...]. First dimension is time.
                Values are binary (0/1) or spike counts.
            window: Window size in operational time units (default: 1.0). This is a
                dimensionless expected spike count, not a number of time bins.
                This is the expected count at rate=1 (i.e., 1 spike expected).
            overlap: Unsupported. Operational-time windows are disjoint; any
                value other than ``None`` or ``0`` raises ``ValueError``.
            rate_hz: Firing rate in Hz. Can be:
                - Scalar: homogeneous rate
                - Array [T, ...]: time-varying rate
                - None: estimated from data using sliding window
            dt: Time step in milliseconds for original time axis.
            batch_axis: Axes to average across for FF computation.

        Returns:
            fano_op: Operational time Fano factor values. Failure return: when
                fewer than 2 windows fit, a NaN array of shape
                ``spikes.shape[1:]`` (``(1,)`` for 1D input) with a warning
                and ``info={"n_windows": n}``.
            info: Dictionary with operational time info and computed statistics.

        Raises:
            ValueError: If ``overlap`` is neither ``None`` nor ``0``.

        Example:
            >>> # Compare Fano factors at different rates
            >>> spikes_low_rate = generate_poisson_spikes(rate_hz=20, ...)
            >>> spikes_high_rate = generate_poisson_spikes(rate_hz=80, ...)
            >>> ff_low, _ = fano_operational_time(spikes_low_rate)
            >>> ff_high, _ = fano_operational_time(spikes_high_rate)
            >>> # Both should be ≈ 1 regardless of rate difference
    """
    if isinstance(batch_axis, int):
        batch_axis = (batch_axis,)
    if overlap:
        raise ValueError(
            "fano_operational_time does not support overlapping windows; "
            f"got overlap={overlap!r}."
        )
    if window is None:
        window = 1.0  # Unit operational time window

    is_torch = isinstance(spikes, torch.Tensor)

    # Estimate rate if not provided
    if rate_hz is None:
        if is_torch:
            rate_hz = _estimate_rate_torch(spikes, dt)
        else:
            rate_hz = _estimate_rate_numpy(spikes, dt)

    if is_torch:
        return _compute_operational_fano_torch(spikes, rate_hz, window, dt, batch_axis)
    else:
        return _compute_operational_fano_numpy(spikes, rate_hz, window, 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.dynamic_tools.lyapunov_dynamics

Functions:

compute_continuous_spiking_rate(spikes, dt, sigma=20.0)

Convert discrete spike trains into continuous firing rates using Gaussian smoothing.

The output follows the input type: a torch.Tensor input gives a float64 tensor on the input device, anything else a float64 NumPy array. The smoothing itself runs in SciPy on the CPU.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix of shape (time_steps, n_neurons).

required
dt float

Simulation time step in ms.

required
sigma float

Standard deviation of the Gaussian kernel in ms. Default 20 ms.

20.0

Returns:

Type Description
ndarray | Tensor

Continuous firing rate traces of shape (time_steps, n_neurons),

ndarray | Tensor

as a tensor for tensor input and as an array otherwise.

ndarray | Tensor

There is no NaN failure return; NaN/inf in the input propagate.

Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
def compute_continuous_spiking_rate(
    spikes: np.ndarray | torch.Tensor,
    dt: float,
    sigma: float = 20.0,
) -> np.ndarray | torch.Tensor:
    """Convert discrete spike trains into continuous firing rates using
    Gaussian smoothing.

    The output follows the input type: a ``torch.Tensor`` input gives a
    ``float64`` tensor on the input device, anything else a ``float64`` NumPy
    array. The smoothing itself runs in SciPy on the CPU.

    Args:
        spikes: Spike matrix of shape ``(time_steps, n_neurons)``.
        dt: Simulation time step in ms.
        sigma: Standard deviation of the Gaussian kernel in ms. Default 20 ms.

    Returns:
        Continuous firing rate traces of shape ``(time_steps, n_neurons)``,
        as a tensor for tensor input and as an array otherwise.
        There is no NaN failure return; NaN/inf in the input propagate.
    """
    # sigma is in ms, dt in ms: convert to bins
    sigma_bins = sigma / dt

    rates = gaussian_filter1d(to_numpy(spikes).astype(float), sigma=sigma_bins, axis=0)

    if isinstance(spikes, torch.Tensor):
        return torch.from_numpy(rates).to(spikes.device)
    return rates

compute_expansion_to_contraction_ratio(lyapunov_spectrum)

Compute the ratio of expansion to contraction from the Lyapunov spectrum.

Parameters:

Name Type Description Default
lyapunov_spectrum list | ndarray

A list or numpy array of Lyapunov exponents.

required

Returns:

Type Description
float

The ratio of the sum of positive exponents to the absolute sum of

float

negative exponents. np.inf when there is no negative exponent

float

(pure expansion; for an all-zero spectrum this is also inf). No

float

NaN is returned.

Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
def compute_expansion_to_contraction_ratio(
    lyapunov_spectrum: list | np.ndarray,
) -> float:
    """Compute the ratio of expansion to contraction from the Lyapunov
    spectrum.

    Args:
        lyapunov_spectrum: A list or numpy array of Lyapunov exponents.

    Returns:
        The ratio of the sum of positive exponents to the absolute sum of
        negative exponents. ``np.inf`` when there is no negative exponent
        (pure expansion; for an all-zero spectrum this is also ``inf``). No
        NaN is returned.
    """
    lyapunov_spectrum = np.array(lyapunov_spectrum)
    positive_sum = np.sum(lyapunov_spectrum[lyapunov_spectrum > 0])
    negative_sum = np.sum(np.abs(lyapunov_spectrum[lyapunov_spectrum < 0]))

    if negative_sum == 0:
        return np.inf  # Avoid division by zero; indicates pure expansion

    ratio = positive_sum / negative_sum
    return ratio

compute_ks_entropy(time_series, emb_dim=6, lag=1)

Compute the Kolmogorov-Sinai (KS) entropy of a given time series using the nolds library.

Parameters:

Name Type Description Default
time_series ndarray

A 1D numpy array representing the time series data.

required
emb_dim int

Embedding dimension. Default 6.

6
lag int

Lag between samples. Default 1.

1

Returns:

Type Description
float

The estimated KS entropy. No NaN sentinel is added here; degenerate

float

series give whatever nolds.sampen returns.

Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
def compute_ks_entropy(
    time_series: np.ndarray, emb_dim: int = 6, lag: int = 1
) -> float:
    """Compute the Kolmogorov-Sinai (KS) entropy of a given time series using
    the nolds library.

    Args:
        time_series: A 1D numpy array representing the time series data.
        emb_dim: Embedding dimension. Default 6.
        lag: Lag between samples. Default 1.

    Returns:
        The estimated KS entropy. No NaN sentinel is added here; degenerate
        series give whatever ``nolds.sampen`` returns.
    """
    nolds = require("nolds", "analysis", "Lyapunov/entropy estimation")
    ks_entropy = nolds.sampen(time_series, emb_dim=emb_dim, lag=lag)
    return ks_entropy

compute_lyapunov_exponent_spectrum(time_series, emb_dim=6, matrix_dim=4, tau=1)

Compute the full Lyapunov spectrum of a given time series using the nolds library.

Parameters:

Name Type Description Default
time_series ndarray

A 1D numpy array representing the time series data.

required
emb_dim int

Embedding dimension. Default 6.

6
matrix_dim int

Matrix dimension. Default 4.

4
tau int

Time delay. Default 1.

1

Returns:

Type Description
list

A list of estimated Lyapunov exponents. No NaN sentinel is added

list

here; degenerate series give whatever nolds.lyap_e returns.

Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
def compute_lyapunov_exponent_spectrum(
    time_series: np.ndarray,
    emb_dim: int = 6,
    matrix_dim: int = 4,
    tau: int = 1,
) -> list:
    """Compute the full Lyapunov spectrum of a given time series using the
    nolds library.

    Args:
        time_series: A 1D numpy array representing the time series data.
        emb_dim: Embedding dimension. Default 6.
        matrix_dim: Matrix dimension. Default 4.
        tau: Time delay. Default 1.

    Returns:
        A list of estimated Lyapunov exponents. No NaN sentinel is added
        here; degenerate series give whatever ``nolds.lyap_e`` returns.
    """
    nolds = require("nolds", "analysis", "Lyapunov/entropy estimation")
    lyapunov_spectrum = nolds.lyap_e(
        time_series, emb_dim=emb_dim, matrix_dim=matrix_dim, tau=tau
    )
    return lyapunov_spectrum

compute_max_lyapunov_exponent(time_series, emb_dim=6, lag=1, tau=1)

Compute the largest Lyapunov exponent of a given time series using the nolds library.

Parameters:

Name Type Description Default
time_series ndarray

A 1D numpy array representing the time series data.

required
emb_dim int

Embedding dimension. Default 6.

6
lag int

Lag between samples. Default 1.

1
tau int

Time delay. Default 1.

1

Returns:

Type Description
float

The estimated largest Lyapunov exponent. No NaN sentinel is added

float

here; degenerate series give whatever nolds.lyap_r returns.

Source code in btorch/analysis/dynamic_tools/lyapunov_dynamics.py
def compute_max_lyapunov_exponent(
    time_series: np.ndarray,
    emb_dim: int = 6,
    lag: int = 1,
    tau: int = 1,
) -> float:
    """Compute the largest Lyapunov exponent of a given time series using the
    nolds library.

    Args:
        time_series: A 1D numpy array representing the time series data.
        emb_dim: Embedding dimension. Default 6.
        lag: Lag between samples. Default 1.
        tau: Time delay. Default 1.

    Returns:
        The estimated largest Lyapunov exponent. No NaN sentinel is added
        here; degenerate series give whatever ``nolds.lyap_r`` returns.
    """
    nolds = require("nolds", "analysis", "Lyapunov/entropy estimation")
    lyapunov_exponent = nolds.lyap_r(time_series, emb_dim=emb_dim, lag=lag, tau=tau)
    return lyapunov_exponent

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

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.dynamic_tools.micro_scale

Functions:

compute_fr_distribution(spikes, dt=1.0)

Compute the mean population firing rate at each timestep and characterize its distribution.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix of shape (Time, Neurons).

required
dt float

Simulation time step in ms.

1.0

Returns:

Type Description
dict

Dictionary with keys rates, mean, skew, kurt. There

dict

is no NaN failure path; skew/kurt are NaN when the rate trace

dict

is constant (zero variance, as returned by scipy).

Source code in btorch/analysis/dynamic_tools/micro_scale.py
def compute_fr_distribution(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
) -> dict:
    """Compute the mean population firing rate at each timestep and
    characterize its distribution.

    Args:
        spikes: Spike matrix of shape ``(Time, Neurons)``.
        dt: Simulation time step in ms.

    Returns:
        Dictionary with keys ``rates``, ``mean``, ``skew``, ``kurt``. There
        is no NaN failure path; ``skew``/``kurt`` are NaN when the rate trace
        is constant (zero variance, as returned by scipy).
    """
    if isinstance(spikes, torch.Tensor):
        spikes = spikes.detach().cpu().numpy()

    window_size = 5
    kernel = np.ones(window_size) / (window_size * dt / 1000.0)  # convert to Hz
    pop_spikes = spikes.mean(axis=1)  # (T,)
    rates = np.convolve(pop_spikes, kernel, mode="same")

    return {
        "rates": rates,
        "mean": np.mean(rates),
        "skew": skew(rates),
        "kurt": kurtosis(rates),
    }

compute_spike_distance(spikes, dt=1.0, subset_size=100, seed=None)

Compute the SPIKE-distance (Kreuz et al., 2013).

Measures the degree of asynchrony between spike trains. Zero means fully synchronous.

Parameters:

Name Type Description Default
spikes ndarray | Tensor

Spike matrix of shape (Time, Neurons).

required
dt float

Simulation time step in ms.

1.0
subset_size int

Number of randomly sampled neurons for pairwise distance.

100
seed int | None

Random seed for neuron sampling.

None

Returns:

Type Description
float

Mean SPIKE-distance across all neuron pairs; float("nan") when

float

there are fewer than two neurons (no pair exists).

Source code in btorch/analysis/dynamic_tools/micro_scale.py
def compute_spike_distance(
    spikes: np.ndarray | torch.Tensor,
    dt: float = 1.0,
    subset_size: int = 100,
    seed: "int | None" = None,
) -> float:
    """Compute the SPIKE-distance (Kreuz et al., 2013).

    Measures the degree of asynchrony between spike trains. Zero means fully
    synchronous.

    Args:
        spikes: Spike matrix of shape ``(Time, Neurons)``.
        dt: Simulation time step in ms.
        subset_size: Number of randomly sampled neurons for pairwise distance.
        seed: Random seed for neuron sampling.

    Returns:
        Mean SPIKE-distance across all neuron pairs; ``float("nan")`` when
        there are fewer than two neurons (no pair exists).
    """
    if isinstance(spikes, torch.Tensor):
        spikes = spikes.detach().cpu().numpy()

    T_steps, N = spikes.shape
    times = np.arange(T_steps) * dt

    # random subsampling to keep pairwise computation tractable
    if N > subset_size:
        if seed is not None:
            np.random.seed(seed)
        indices = np.random.choice(N, subset_size, replace=False)
        selected_spikes = spikes[:, indices]
        N_subset = subset_size
    else:
        selected_spikes = spikes
        N_subset = N

    # precompute t_prev, t_next, and isi for each neuron; shape: (N_subset, T_steps)
    t_prev = np.zeros((N_subset, T_steps))
    t_next = np.zeros((N_subset, T_steps))
    isi = np.zeros((N_subset, T_steps))

    for n in range(N_subset):
        spike_indices = np.where(selected_spikes[:, n] > 0)[0]
        spike_times = spike_indices * dt

        if len(spike_times) == 0:
            # no spikes: span the full interval as a boundary fallback
            t_prev[n, :] = 0
            t_next[n, :] = times[-1]
            isi[n, :] = times[-1]
            continue

        # Use a forward scan for t_prev = max(s | s <= t)
        # and a backward scan for t_next = min(s | s >= t).
        # searchsorted alone does not handle ties correctly at spike times,
        # so we fill with explicit linear scans instead.

        curr_spike = 0.0
        spike_idx = 0
        for t_idx, t in enumerate(times):
            if spike_idx < len(spike_times) and t >= spike_times[spike_idx]:
                curr_spike = spike_times[spike_idx]
                # advance index if we've reached the next spike
                if spike_idx < len(spike_times) - 1 and t >= spike_times[spike_idx + 1]:
                    spike_idx += 1
                    curr_spike = spike_times[spike_idx]
            t_prev[n, t_idx] = curr_spike

        curr_spike = times[-1]
        spike_idx = len(spike_times) - 1
        for t_idx in range(T_steps - 1, -1, -1):
            t = times[t_idx]
            if spike_idx >= 0 and t <= spike_times[spike_idx]:
                curr_spike = spike_times[spike_idx]
                if spike_idx > 0 and t <= spike_times[spike_idx - 1]:
                    spike_idx -= 1
                    curr_spike = spike_times[spike_idx]
            t_next[n, t_idx] = curr_spike

        isi[n, :] = t_next[n, :] - t_prev[n, :]

        isi[n, isi[n, :] == 0] = dt

    # Pairwise SPIKE-distance:
    # S(t) = (|dt_p1-dt_p2|*isi2 + |dt_f1-dt_f2|*isi1) / (0.5*(isi1+isi2)^2)
    dt_p = times[None, :] - t_prev  # (N, T)
    dt_f = t_next - times[None, :]  # (N, T)

    pairwise_distances = []

    # All pairs: with N_subset=50, this is 1225 pairs — acceptable cost.
    for i in range(N_subset):
        for j in range(i + 1, N_subset):
            isi1 = isi[i]
            isi2 = isi[j]

            avg_isi_sq = 0.5 * (isi1 + isi2) ** 2
            avg_isi_sq[avg_isi_sq == 0] = 1.0  # avoid division by zero

            term1 = np.abs(dt_p[i] - dt_p[j]) * isi2
            term2 = np.abs(dt_f[i] - dt_f[j]) * isi1

            s_t = (term1 + term2) / avg_isi_sq

            dist = np.mean(s_t)  # integrate over time
            pairwise_distances.append(dist)

    if not pairwise_distances:
        # Fewer than two neurons: the pairwise distance is undefined.
        return float("nan")

    return np.mean(pairwise_distances)