File size: 5,898 Bytes
e8edb9d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | """Numba-JIT compiled kernels for scPTR."""
from __future__ import annotations
import numpy as np
import numba as nb
@nb.njit(parallel=True, cache=True)
def _smooth_kernel(
data: np.ndarray,
indices_flat: np.ndarray,
indptr: np.ndarray,
distances_flat: np.ndarray,
bandwidths: np.ndarray,
out: np.ndarray,
) -> None:
"""Gaussian kernel smoothing over kNN graph.
Parameters
----------
data : (n_obs, n_genes) float32
Gene expression matrix to smooth.
indices_flat : (nnz,) int32
CSR indices array of the kNN graph.
indptr : (n_obs+1,) int32
CSR indptr array of the kNN graph.
distances_flat : (nnz,) float32
CSR data array (distances) of the kNN graph.
bandwidths : (n_obs,) float32
Per-cell bandwidth for the Gaussian kernel.
out : (n_obs, n_genes) float32
Output array (pre-allocated).
"""
n_obs = data.shape[0]
n_genes = data.shape[1]
for i in nb.prange(n_obs):
start = indptr[i]
end = indptr[i + 1]
bw = bandwidths[i]
bw2 = bw * bw
if bw2 < 1e-12:
bw2 = 1e-12
# Compute weights
n_neighbors = end - start
weights = np.empty(n_neighbors + 1, dtype=np.float32)
neighbor_idx = np.empty(n_neighbors + 1, dtype=np.int64)
# Self-connection with weight 1
weights[0] = 1.0
neighbor_idx[0] = i
total_weight = 1.0
for k in range(n_neighbors):
j = indices_flat[start + k]
d = distances_flat[start + k]
w = np.exp(-0.5 * d * d / bw2)
weights[k + 1] = w
neighbor_idx[k + 1] = j
total_weight += w
# Weighted average
inv_total = 1.0 / total_weight
for g in range(n_genes):
val = 0.0
for k in range(n_neighbors + 1):
val += weights[k] * data[neighbor_idx[k], g]
out[i, g] = val * inv_total
@nb.njit(parallel=True, cache=True)
def _compute_adaptive_bandwidths(
distances_flat: np.ndarray,
indptr: np.ndarray,
) -> np.ndarray:
"""Compute per-cell adaptive bandwidth as median neighbor distance.
Parameters
----------
distances_flat : (nnz,) float32
indptr : (n_obs+1,) int32
Returns
-------
bandwidths : (n_obs,) float32
"""
n_obs = indptr.shape[0] - 1
bandwidths = np.empty(n_obs, dtype=np.float32)
for i in nb.prange(n_obs):
start = indptr[i]
end = indptr[i + 1]
n_neighbors = end - start
if n_neighbors == 0:
bandwidths[i] = 1.0
continue
# Copy distances for this cell and sort to get median
dists = np.empty(n_neighbors, dtype=np.float32)
for k in range(n_neighbors):
dists[k] = distances_flat[start + k]
dists.sort()
mid = n_neighbors // 2
if n_neighbors % 2 == 0:
bandwidths[i] = (dists[mid - 1] + dists[mid]) / 2.0
else:
bandwidths[i] = dists[mid]
if bandwidths[i] < 1e-6:
bandwidths[i] = 1.0
return bandwidths
@nb.njit(parallel=True, cache=True)
def _compute_gamma_kernel(
u_smooth: np.ndarray,
s_smooth: np.ndarray,
beta: np.ndarray,
clip_vals: np.ndarray,
out: np.ndarray,
) -> None:
"""Compute per-cell per-gene degradation rate gamma.
gamma[i,g] = beta[g] * u_smooth[i,g] / max(s_smooth[i,g], 1e-6)
Clipped at clip_vals[g] per gene.
Parameters
----------
u_smooth : (n_obs, n_genes) float32
s_smooth : (n_obs, n_genes) float32
beta : (n_genes,) float32
clip_vals : (n_genes,) float32
Per-gene clip values (e.g., 99th percentile).
out : (n_obs, n_genes) float32
"""
n_obs = u_smooth.shape[0]
n_genes = u_smooth.shape[1]
for i in nb.prange(n_obs):
for g in range(n_genes):
s_val = s_smooth[i, g]
if s_val < 1e-6:
s_val = 1e-6
gamma_val = beta[g] * u_smooth[i, g] / s_val
if gamma_val > clip_vals[g]:
gamma_val = clip_vals[g]
if gamma_val < 0.0:
gamma_val = 0.0
out[i, g] = gamma_val
@nb.njit(parallel=True, cache=True)
def _velocity_kernel(
gamma: np.ndarray,
indices_flat: np.ndarray,
indptr: np.ndarray,
distances_flat: np.ndarray,
bandwidths: np.ndarray,
out: np.ndarray,
) -> None:
"""Compute PT velocity as weighted mean gamma difference from neighbors.
v[i,g] = sum_j(w_ij * (gamma[j,g] - gamma[i,g]))
Parameters
----------
gamma : (n_obs, n_genes) float32
indices_flat, indptr, distances_flat : kNN graph CSR arrays
bandwidths : (n_obs,) float32
out : (n_obs, n_genes) float32
"""
n_obs = gamma.shape[0]
n_genes = gamma.shape[1]
for i in nb.prange(n_obs):
start = indptr[i]
end = indptr[i + 1]
bw = bandwidths[i]
bw2 = bw * bw
if bw2 < 1e-12:
bw2 = 1e-12
n_neighbors = end - start
if n_neighbors == 0:
for g in range(n_genes):
out[i, g] = 0.0
continue
# Compute weights
total_weight = 0.0
for k in range(n_neighbors):
d = distances_flat[start + k]
w = np.exp(-0.5 * d * d / bw2)
total_weight += w
if total_weight < 1e-12:
for g in range(n_genes):
out[i, g] = 0.0
continue
inv_total = 1.0 / total_weight
for g in range(n_genes):
val = 0.0
for k in range(n_neighbors):
j = indices_flat[start + k]
d = distances_flat[start + k]
w = np.exp(-0.5 * d * d / bw2)
val += w * (gamma[j, g] - gamma[i, g])
out[i, g] = val * inv_total
|