| import torch |
| import logging |
|
|
| logger = logging.getLogger(__name__) |
|
|
| def scgpt_binning_torch(x: torch.Tensor, n_bins: int = 51) -> torch.Tensor: |
| """ |
| 针对 Cell * Gene 矩阵的纯 PyTorch 向量化分箱 (scGPT-style) |
| |
| Args: |
| x (torch.Tensor): 细胞 x 基因矩阵,形状为 (N, G),必须是非负数。 |
| n_bins (int): 分箱总数。Bin 0 被硬性保留给表达量为 0 的基因。 |
| |
| Returns: |
| torch.Tensor: 分箱后的整数矩阵,形状为 (N, G),值域为 [0, n_bins - 1]。 |
| """ |
| if n_bins <= 1: |
| raise ValueError(f"n_bins 必须大于 1,当前为 {n_bins}") |
| if x.min() < 0: |
| raise ValueError(f"期望非负表达矩阵,但检测到最小值为 {x.min().item()}") |
|
|
| N, G = x.shape |
| binned_x = torch.zeros_like(x, dtype=torch.long) |
|
|
| |
| |
| non_zero_mask = x > 0 |
|
|
| |
| row_max = x.max(dim=1).values |
| if (row_max == 0).any(): |
| logger.warning("输入数据中包含全 0 表达的细胞,它们的分箱结果将全部为 0。") |
|
|
| |
| |
| |
| x_nan = x.clone().to(torch.float32) |
| x_nan[~non_zero_mask] = float('nan') |
|
|
| |
| |
| q = torch.linspace(0, 1, steps=n_bins - 1, dtype=torch.float32, device=x.device) |
|
|
| |
| |
| bins = torch.nanquantile(x_nan, q, dim=1).T |
| |
| |
| bins = torch.nan_to_num(bins, nan=0.0) |
|
|
| |
| |
| |
| digits = torch.searchsorted(bins, x.contiguous(), right=True) |
|
|
| |
| digits = torch.clamp(digits, min=1, max=n_bins - 1) |
|
|
| |
| |
| |
| binned_x[non_zero_mask] = digits[non_zero_mask] |
|
|
| return binned_x |