decal-ccc 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 K03 Senescence_Comm
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: decal-ccc
3
+ Version: 0.2.0
4
+ Summary: decal: decoy-calibrated identifiability audit for differential cell-cell communication
5
+ Author: K03 Senescence_Comm
6
+ License: MIT
7
+ Project-URL: Source, https://github.com/k03-senescence/decal
8
+ Keywords: cell-cell communication,single-cell,identifiability,FDR,decoy
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
11
+ Classifier: Intended Audience :: Science/Research
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy>=1.22
16
+ Requires-Dist: scipy>=1.8
17
+ Dynamic: license-file
18
+
19
+ # decal — 差异细胞通讯的可辨识性诊断
20
+
21
+ > **Decoy-Calibrated communication audit.**
22
+ > 在你报告"某条配体-受体通讯被改写"之前,先问一句:**这个结论能不能和表达丰度区分开?**
23
+
24
+ `decal` 给任意"两组细胞的配体-受体差异通讯"分析做三件事:
25
+
26
+ | 输出 | 含义 | 读法 |
27
+ |---|---|---|
28
+ | `delta` | 每位供体的效应中位数(全局位移) | \|δ\|>0.3 → 排序是位移在排,不是生物学在排 |
29
+ | `rho_abund_S` | 扣位移后残差与丰度的秩相关 | >0.5 → 排序≈丰度排序,别解释配对排序 |
30
+ | `decoy_auroc` | 真对 vs 分层匹配诱饵的可分性 | 0.5 = 配对身份零信息 |
31
+ | `match_balance` | 诱饵在丰度/检出上的残差 | >0.15 = 配平失败,`decoy_auroc` 不可解释 |
32
+ | `n_calls_q10` | 诱饵校准 + BH 后 q<0.10 的调用数 | 0 = 该主张无法与丰度区分 |
33
+ | `verdict` | 四值判定 | 见下 |
34
+
35
+ `verdict` 取值:`identifiable` / `marginal-dominated` / `not-identifiable` / `decoy-mismatch`
36
+
37
+ ---
38
+
39
+ ## 安装
40
+
41
+ ```bash
42
+ pip install decal-ccc # 发布后
43
+ # 或从源码
44
+ cd decal && pip install -e .
45
+ ```
46
+
47
+ 依赖只有 `numpy` 与 `scipy`,无 GPU、无其他包。
48
+
49
+ ## 用法
50
+
51
+ ### Python
52
+
53
+ ```python
54
+ from decal import audit
55
+
56
+ # H, L: (n_donor, n_gene) 的两组均值矩阵(建议已按细胞总量归一化,如 log1p(CP10K))
57
+ # genes: 基因名列表
58
+ # lr: [(配体, 受体), ...] 或 [(通路, 配体, [受体, ...]), ...]
59
+ res = audit(H, L, genes, lr)
60
+ print(res["delta"], res["rho_abund_S"], res["n_calls_q10"], res["verdict"])
61
+ ```
62
+
63
+ ### 命令行
64
+
65
+ ```bash
66
+ decal --npz means.npz --lr lr_db.json
67
+ decal --npz means.npz --lr lr_db.json --json
68
+ ```
69
+
70
+ `means.npz` 需包含 `means_H` / `means_L` / `genes`。
71
+
72
+ ---
73
+
74
+ ## 为什么诱饵必须分层匹配
75
+
76
+ 最近邻匹配会留下系统性残差。我们在真实数据上实测:
77
+
78
+ | 方法 | 真对 vs 诱饵 AUROC |
79
+ |---|---|
80
+ | TabPFN-3.5(2026 TabArena/BeyondArena 双榜前三,20 特征,配体分组 5 折) | **0.829** |
81
+ | Logistic 回归 | 0.618 |
82
+ | \|E\| 单特征 | 0.501 |
83
+ | **分层精确匹配(丰度五分位 × 检出五分位)** | **0.509** |
84
+
85
+ 那 0.32 的"领先"全部来自匹配残差(真受体比诱饵更低表达、更差检出)。
86
+ **模型越强,越会学混杂。** 所以 decal v2:
87
+
88
+ 1. 强制在同一 (丰度, 检出) 层内抽诱饵;
89
+ 2. 输出 `match_balance`;
90
+ 3. 配平失败时直接返回 `verdict="decoy-mismatch"`,**拒绝解释 AUROC**。
91
+
92
+ ---
93
+
94
+ ## 在 KPMP 上的实测输出
95
+
96
+ ```json
97
+ {
98
+ "n_pairs": 1572, "n_decoys": 4716,
99
+ "delta": 0.712, "delta_sd": 0.330, "frac_up": 0.946,
100
+ "rho_abund_S": 0.670, "decoy_auroc": 0.498,
101
+ "match_balance": {"abund": 0.113, "det": 0.015},
102
+ "n_calls_q05": 0, "n_calls_q10": 0,
103
+ "verdict": "not-identifiable"
104
+ }
105
+ ```
106
+
107
+ 94.6% 的对同向上调(δ=0.71);扣位移后残差与丰度相关 0.67;真对与诱饵 AUROC 0.50;
108
+ FDR 0.10 下零调用。对照:LIANA 2.1.1 在同一批细胞上报 8,504 条"显著"交互。
109
+
110
+ ---
111
+
112
+ ## 建议的报告方式
113
+
114
+ - δ 大时,不要解释"哪一对通讯被改写",只解释"配体/受体程序整体上调"。
115
+ - 任何配对级主张,附上 `n_calls_q10`。若为 0,说明该主张无法与丰度匹配诱饵区分。
116
+ - 需要配对级结论时,去找正交证据(空间邻接、蛋白、扰动),而不是换打分公式。
117
+ - **报告层级**:细胞类型对(可辨识)> 配体/受体程序 > LR 对(多数情况下不可辨识)。
118
+
119
+ ---
120
+
121
+ ## 引用
122
+
123
+ 如果你用 decal 做了可辨识性诊断,请引用配套论文(见 CITATION.cff)。
124
+
125
+ ## License
126
+
127
+ MIT
@@ -0,0 +1,109 @@
1
+ # decal — 差异细胞通讯的可辨识性诊断
2
+
3
+ > **Decoy-Calibrated communication audit.**
4
+ > 在你报告"某条配体-受体通讯被改写"之前,先问一句:**这个结论能不能和表达丰度区分开?**
5
+
6
+ `decal` 给任意"两组细胞的配体-受体差异通讯"分析做三件事:
7
+
8
+ | 输出 | 含义 | 读法 |
9
+ |---|---|---|
10
+ | `delta` | 每位供体的效应中位数(全局位移) | \|δ\|>0.3 → 排序是位移在排,不是生物学在排 |
11
+ | `rho_abund_S` | 扣位移后残差与丰度的秩相关 | >0.5 → 排序≈丰度排序,别解释配对排序 |
12
+ | `decoy_auroc` | 真对 vs 分层匹配诱饵的可分性 | 0.5 = 配对身份零信息 |
13
+ | `match_balance` | 诱饵在丰度/检出上的残差 | >0.15 = 配平失败,`decoy_auroc` 不可解释 |
14
+ | `n_calls_q10` | 诱饵校准 + BH 后 q<0.10 的调用数 | 0 = 该主张无法与丰度区分 |
15
+ | `verdict` | 四值判定 | 见下 |
16
+
17
+ `verdict` 取值:`identifiable` / `marginal-dominated` / `not-identifiable` / `decoy-mismatch`
18
+
19
+ ---
20
+
21
+ ## 安装
22
+
23
+ ```bash
24
+ pip install decal-ccc # 发布后
25
+ # 或从源码
26
+ cd decal && pip install -e .
27
+ ```
28
+
29
+ 依赖只有 `numpy` 与 `scipy`,无 GPU、无其他包。
30
+
31
+ ## 用法
32
+
33
+ ### Python
34
+
35
+ ```python
36
+ from decal import audit
37
+
38
+ # H, L: (n_donor, n_gene) 的两组均值矩阵(建议已按细胞总量归一化,如 log1p(CP10K))
39
+ # genes: 基因名列表
40
+ # lr: [(配体, 受体), ...] 或 [(通路, 配体, [受体, ...]), ...]
41
+ res = audit(H, L, genes, lr)
42
+ print(res["delta"], res["rho_abund_S"], res["n_calls_q10"], res["verdict"])
43
+ ```
44
+
45
+ ### 命令行
46
+
47
+ ```bash
48
+ decal --npz means.npz --lr lr_db.json
49
+ decal --npz means.npz --lr lr_db.json --json
50
+ ```
51
+
52
+ `means.npz` 需包含 `means_H` / `means_L` / `genes`。
53
+
54
+ ---
55
+
56
+ ## 为什么诱饵必须分层匹配
57
+
58
+ 最近邻匹配会留下系统性残差。我们在真实数据上实测:
59
+
60
+ | 方法 | 真对 vs 诱饵 AUROC |
61
+ |---|---|
62
+ | TabPFN-3.5(2026 TabArena/BeyondArena 双榜前三,20 特征,配体分组 5 折) | **0.829** |
63
+ | Logistic 回归 | 0.618 |
64
+ | \|E\| 单特征 | 0.501 |
65
+ | **分层精确匹配(丰度五分位 × 检出五分位)** | **0.509** |
66
+
67
+ 那 0.32 的"领先"全部来自匹配残差(真受体比诱饵更低表达、更差检出)。
68
+ **模型越强,越会学混杂。** 所以 decal v2:
69
+
70
+ 1. 强制在同一 (丰度, 检出) 层内抽诱饵;
71
+ 2. 输出 `match_balance`;
72
+ 3. 配平失败时直接返回 `verdict="decoy-mismatch"`,**拒绝解释 AUROC**。
73
+
74
+ ---
75
+
76
+ ## 在 KPMP 上的实测输出
77
+
78
+ ```json
79
+ {
80
+ "n_pairs": 1572, "n_decoys": 4716,
81
+ "delta": 0.712, "delta_sd": 0.330, "frac_up": 0.946,
82
+ "rho_abund_S": 0.670, "decoy_auroc": 0.498,
83
+ "match_balance": {"abund": 0.113, "det": 0.015},
84
+ "n_calls_q05": 0, "n_calls_q10": 0,
85
+ "verdict": "not-identifiable"
86
+ }
87
+ ```
88
+
89
+ 94.6% 的对同向上调(δ=0.71);扣位移后残差与丰度相关 0.67;真对与诱饵 AUROC 0.50;
90
+ FDR 0.10 下零调用。对照:LIANA 2.1.1 在同一批细胞上报 8,504 条"显著"交互。
91
+
92
+ ---
93
+
94
+ ## 建议的报告方式
95
+
96
+ - δ 大时,不要解释"哪一对通讯被改写",只解释"配体/受体程序整体上调"。
97
+ - 任何配对级主张,附上 `n_calls_q10`。若为 0,说明该主张无法与丰度匹配诱饵区分。
98
+ - 需要配对级结论时,去找正交证据(空间邻接、蛋白、扰动),而不是换打分公式。
99
+ - **报告层级**:细胞类型对(可辨识)> 配体/受体程序 > LR 对(多数情况下不可辨识)。
100
+
101
+ ---
102
+
103
+ ## 引用
104
+
105
+ 如果你用 decal 做了可辨识性诊断,请引用配套论文(见 CITATION.cff)。
106
+
107
+ ## License
108
+
109
+ MIT
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "decal-ccc"
7
+ version = "0.2.0"
8
+ description = "decal: decoy-calibrated identifiability audit for differential cell-cell communication"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "K03 Senescence_Comm" }]
13
+ keywords = ["cell-cell communication", "single-cell", "identifiability", "FDR", "decoy"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
17
+ "Intended Audience :: Science/Research",
18
+ ]
19
+ dependencies = ["numpy>=1.22", "scipy>=1.8"]
20
+
21
+ [project.urls]
22
+ Source = "https://github.com/k03-senescence/decal"
23
+
24
+ [project.scripts]
25
+ decal = "decal.cli:main"
26
+
27
+ [tool.setuptools.packages.find]
28
+ where = ["src"]
29
+
30
+ [tool.setuptools.package-data]
31
+ decal = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,19 @@
1
+ """decal — 差异细胞通讯的可辨识性诊断(Decoy-Calibrated communication audit)
2
+
3
+ 给任意"两组细胞的配体-受体差异通讯"分析做三件事:
4
+
5
+ 1. 位移诊断 δ:每位供体的效应中位数。|δ|>0.3 表示几乎所有 LR 对同向移动,
6
+ 此时的配对排序是位移在排,不是生物学在排。
7
+ 2. 诱饵校准:用"同一配体 + 丰度/检出匹配的非同源受体"构造零分布,
8
+ 给每条 LR 对算经验 p 值,BH 控 FDR。回答"控制表达丰度之后还有几条站得住"。
9
+ 3. 判定:identifiable / marginal-dominated / not-identifiable / decoy-mismatch。
10
+
11
+ 关键约定(v2):诱饵必须在 (丰度 × 检出) 层内精确匹配。
12
+ 最近邻匹配会留下系统性残差,柔性模型(如 TabPFN-3.5)能把它学成 0.83 的假 AUROC;
13
+ 分层精确匹配后真实可分性只有 0.51。decal 会输出 match_balance,
14
+ 配平失败时直接返回 verdict="decoy-mismatch",拒绝解释 AUROC。
15
+ """
16
+ from .core import audit, _auc as auroc, _pairs as parse_pairs
17
+
18
+ __version__ = "0.2.0"
19
+ __all__ = ["audit", "auroc", "parse_pairs", "__version__"]
@@ -0,0 +1,47 @@
1
+ """decal 命令行入口
2
+
3
+ decal --npz means.npz --lr lr_db.json
4
+ decal --npz means.npz --lr lr_db.json --n-decoy 3 --min-det 0.15
5
+ """
6
+ import argparse, json, sys
7
+ import numpy as np
8
+
9
+
10
+ def main(argv=None):
11
+ ap = argparse.ArgumentParser(
12
+ prog="decal",
13
+ description="差异细胞通讯的可辨识性诊断(位移 δ + 分层诱饵校准 + 判定)")
14
+ ap.add_argument("--npz", required=True,
15
+ help="含 means_H / means_L / genes 的 npz(H/L 为 (n_donor, n_gene) 组均值)")
16
+ ap.add_argument("--lr", required=True,
17
+ help="LR 库 json:[[通路,配体,[受体..]]...] 或 [[配体,受体]...]")
18
+ ap.add_argument("--n-decoy", type=int, default=3, help="每对的诱饵个数(默认 3)")
19
+ ap.add_argument("--min-det", type=float, default=0.15, help="最低检出率(默认 0.15)")
20
+ ap.add_argument("--no-stratify", action="store_true", help="关闭分层匹配(仅调试用)")
21
+ ap.add_argument("--json", action="store_true", help="只输出 JSON")
22
+ a = ap.parse_args(argv)
23
+
24
+ from .core import audit
25
+ z = np.load(a.npz, allow_pickle=True)
26
+ H = z["means_H"].astype(float)
27
+ L = z["means_L"].astype(float)
28
+ genes = [str(g) for g in z["genes"]]
29
+ lr = json.load(open(a.lr, encoding="utf-8"))
30
+ r = audit(H, L, genes, lr, n_decoy=a.n_decoy, min_det=a.min_det,
31
+ stratify=not a.no_stratify)
32
+ out = {k: v for k, v in r.items() if k not in ("q", "pairs", "S")}
33
+ if a.json:
34
+ print(json.dumps(out, indent=1, ensure_ascii=False))
35
+ else:
36
+ print(f"decal v2 pairs={out['n_pairs']} decoys={out['n_decoys']}")
37
+ print(f" delta {out['delta']:+.3f} (sd {out['delta_sd']:.3f})")
38
+ print(f" rho_abund_S {out['rho_abund_S']:+.3f}")
39
+ print(f" decoy_auroc {out['decoy_auroc']:.3f}")
40
+ print(f" match_balance {out['match_balance']}")
41
+ print(f" calls q<0.05 {out['n_calls_q05']} q<0.10 {out['n_calls_q10']}")
42
+ print(f" verdict {out['verdict']}")
43
+ return 0 if out["verdict"] == "identifiable" else 2
44
+
45
+
46
+ if __name__ == "__main__":
47
+ sys.exit(main())
@@ -0,0 +1,182 @@
1
+ """decal.core — 核心审计函数
2
+
3
+ decal — 差异通讯的可辨识性诊断(Decoy-Calibrated communication audit)
4
+
5
+ v2 更新(2026-11-14):诱饵必须在 (丰度 × 检出) 层内精确匹配。
6
+ v1 的最近邻匹配会在丰度/检出上留下系统性残差(实测真受体 det 0.348 / ab 0.385,
7
+ 即真对系统性低于诱饵);任何柔性模型(TabPFN-3.5)都能把这些残差学到 0.83 AUROC,
8
+ 而分层后的真实可分性只有 0.51。v2 输出 match_balance,让你一眼看出诱饵是否配平。
9
+
10
+ 用法:
11
+ from decal import audit
12
+ r = audit(H, L, genes, lr=[(lig, rec), ...])
13
+ print(r["delta"], r["n_calls_q10"], r["verdict"], r["match_balance"])
14
+
15
+ 命令行:
16
+ python decal.py --npz results/k03_step90_kpmp_full.npz --lr results/k03_lr_db_full.json
17
+
18
+ 输入
19
+ H, L : (n_donor, n_gene) 组均值矩阵(建议已按细胞总量归一化,如 log1p(CP10K))
20
+ genes: 基因名列表
21
+ lr : [(配体, 受体)] 或 [(通路, 配体, [受体...])]
22
+
23
+ 输出
24
+ delta 每位供体效应中位数(全局位移);|delta|>0.3 视为重位移
25
+ rho_abund_S 残差与丰度的秩相关(>0.5 说明排序≈丰度排序)
26
+ decoy_auroc |E| 区分真对与分层匹配诱饵的能力(0.5 = 配对身份无信息)
27
+ match_balance 诱饵在丰度/检出上的残差(>0.15 说明匹配失败,AUROC 不可信)
28
+ n_calls_q10 诱饵校准 + BH 后 q<0.10 的调用数
29
+ verdict "identifiable" / "marginal-dominated" / "not-identifiable"
30
+ """
31
+ import numpy as np
32
+ from scipy import stats
33
+
34
+ EPS = 1e-2
35
+
36
+
37
+ def _pairs(lr):
38
+ out = set()
39
+ for item in lr:
40
+ if len(item) == 3 and isinstance(item[2], (list, tuple)):
41
+ _, lig, recs = item
42
+ for r in recs:
43
+ out.add((str(lig), str(r)))
44
+ else:
45
+ out.add((str(item[0]), str(item[1])))
46
+ return sorted(out)
47
+
48
+
49
+ def _auc(y, s):
50
+ r = stats.rankdata(s)
51
+ n1 = y.sum()
52
+ n0 = len(y) - n1
53
+ return float((r[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * n0))
54
+
55
+
56
+ def audit(H, L, genes, lr, n_decoy=3, seed=0, min_det=0.15, min_abund=None,
57
+ stratify=True, receptor_only=True):
58
+ H = np.asarray(H, float)
59
+ L = np.asarray(L, float)
60
+ gi = {}
61
+ for i, g in enumerate(genes):
62
+ gi.setdefault(str(g), i)
63
+
64
+ P = [(l, r) for l, r in _pairs(lr) if l in gi and r in gi]
65
+ if len(P) < 10:
66
+ raise ValueError(f"可测 LR 对太少({len(P)}),检查基因名是否匹配")
67
+ li = np.array([gi[l] for l, _ in P])
68
+ ri = np.array([gi[r] for _, r in P])
69
+
70
+ Hl, Ll = np.log(H + EPS), np.log(L + EPS)
71
+ E_full = (Hl[:, li] - Ll[:, li]) + (Hl[:, ri] - Ll[:, ri])
72
+ delta_d = np.median(E_full, axis=1)
73
+ delta = float(np.median(delta_d))
74
+ S = (E_full - delta_d[:, None]).mean(0)
75
+ E = S + float(np.mean(delta_d))
76
+ dL = (Hl[:, li] - Ll[:, li]).mean(0)
77
+ dAll = (Hl - Ll).mean(0)
78
+
79
+ det = np.minimum((H > 0).mean(0), (L > 0).mean(0))
80
+ keep = det[li] >= min_det
81
+ keep &= det[ri] >= min_det
82
+ ab_g = 0.5 * (Hl.mean(0) + Ll.mean(0))
83
+ ab = 0.5 * (ab_g[li] + ab_g[ri])
84
+ if min_abund is not None:
85
+ keep &= ab >= min_abund
86
+
87
+ rho = float(stats.spearmanr(ab[keep], S[keep]).statistic) if keep.sum() > 10 else np.nan
88
+
89
+ # 诱饵池
90
+ allg = [g for g in genes if det[gi[g]] >= min_det]
91
+ rec_deg = {}
92
+ lig_rec = {}
93
+ for l, r in P:
94
+ lig_rec.setdefault(l, set()).add(r)
95
+ for _, l, rs in lr:
96
+ for r in rs:
97
+ rec_deg[r] = rec_deg.get(r, 0) + 1
98
+ if receptor_only:
99
+ pool = [g for g in allg if rec_deg.get(g, 0) > 0]
100
+ else:
101
+ pool = allg
102
+ pidx = np.array([gi[g] for g in pool])
103
+ ab_p, det_p = ab_g[pidx], det[pidx]
104
+
105
+ # 分层边界
106
+ qa = np.quantile(ab_p, [.2, .4, .6, .8])
107
+ qd = np.quantile(det_p, [.2, .4, .6, .8])
108
+
109
+ def stratum(a, d):
110
+ return int(np.digitize(a, qa)) * 5 + int(np.digitize(d, qd))
111
+
112
+ rng = np.random.default_rng(seed)
113
+ dec, dec_str, resid = [], [], {"abund": [], "det": []}
114
+ for j in np.where(keep)[0]:
115
+ l, r = P[j]
116
+ ban = lig_rec.get(l, set())
117
+ cand = [(g, gi[g]) for g in pool if g != l and g not in ban]
118
+ if stratify:
119
+ st = stratum(ab_g[gi[r]], det[gi[r]])
120
+ sub = [(g, i2) for g, i2 in cand if stratum(ab_g[i2], det[i2]) == st]
121
+ if len(sub) >= n_decoy:
122
+ cand = sub
123
+ if not cand:
124
+ continue
125
+ d = np.array([abs(ab_g[i2] - ab_g[gi[r]]) + 1.0 * abs(det[i2] - det[gi[r]])
126
+ for _, i2 in cand])
127
+ o = np.argsort(d)[:max(n_decoy * 4, 12)]
128
+ sel = rng.choice(o, size=min(n_decoy, len(o)), replace=False)
129
+ for s in sel:
130
+ g, i2 = cand[int(s)]
131
+ dec.append(float(dL[j] + dAll[i2])); dec_str.append(stratum(ab_g[gi[r]], det[gi[r]]))
132
+ resid["abund"].append(abs(ab_g[i2] - ab_g[gi[r]]))
133
+ resid["det"].append(abs(det[i2] - det[gi[r]]))
134
+ dec = np.asarray(dec)
135
+ balance = {k: float(np.mean(v)) if v else np.nan for k, v in resid.items()}
136
+
137
+ if len(dec) >= 50:
138
+ # 分层零分布 + 参数尾:经验 p 的分辨率被诱饵总数卡死(p_min = 1/(N+1)),
139
+ # 在 BH 之下根本不可能给出调用。这里用诱饵估计 (mu, sigma) 后做高斯尾外推。
140
+ from scipy.stats import norm as _norm
141
+ pv = np.ones(int(keep.sum()))
142
+ idx_keep = np.where(keep)[0]
143
+ dec_s = np.asarray(dec_str, dtype=int) if 'dec_str' in dir() else None
144
+ # 退化路径:不分层时用整体零分布
145
+ med = float(np.median(dec)); sdv = float(1.4826 * np.median(np.abs(dec - med))) + 1e-9
146
+ for u, j in enumerate(idx_keep):
147
+ se = float(np.std(E_full[:, j], ddof=1) / np.sqrt(E_full.shape[0]))
148
+ z = (E[j] - med) / (sdv ** 2 + se ** 2) ** 0.5
149
+ pv[u] = 2.0 * _norm.sf(abs(z))
150
+ order = np.argsort(pv)
151
+ m = len(pv)
152
+ q = np.empty(m)
153
+ prev = 1.0
154
+ for rank, i in enumerate(order[::-1]):
155
+ k = m - rank
156
+ prev = min(prev, pv[i] * m / k)
157
+ q[i] = prev
158
+ auroc = _auc(np.r_[np.ones(keep.sum()), np.zeros(len(dec))],
159
+ np.r_[E[keep], dec])
160
+ else:
161
+ q = np.ones(int(keep.sum()))
162
+ auroc = np.nan
163
+
164
+ n10 = int((q < 0.10).sum())
165
+ balanced = (balance.get("abund", 9) < 0.15) and (balance.get("det", 9) < 0.15)
166
+ if not balanced:
167
+ verdict = "decoy-mismatch" # 诱饵配平失败:AUROC 不可解释
168
+ elif auroc < 0.56 and n10 == 0:
169
+ verdict = "not-identifiable"
170
+ elif abs(delta) > 0.3 or abs(rho) > 0.5:
171
+ verdict = "marginal-dominated"
172
+ else:
173
+ verdict = "identifiable"
174
+
175
+ return {"n_pairs": int(keep.sum()), "n_decoys": int(len(dec)),
176
+ "delta": delta, "delta_sd": float(np.std(delta_d)),
177
+ "frac_up": float((E[keep] > 0).mean()),
178
+ "rho_abund_S": rho, "decoy_auroc": float(auroc),
179
+ "match_balance": balance,
180
+ "n_calls_q05": int((q < 0.05).sum()), "n_calls_q10": n10,
181
+ "verdict": verdict, "q": q,
182
+ "pairs": [P[j] for j in np.where(keep)[0]], "S": S[keep]}
File without changes
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: decal-ccc
3
+ Version: 0.2.0
4
+ Summary: decal: decoy-calibrated identifiability audit for differential cell-cell communication
5
+ Author: K03 Senescence_Comm
6
+ License: MIT
7
+ Project-URL: Source, https://github.com/k03-senescence/decal
8
+ Keywords: cell-cell communication,single-cell,identifiability,FDR,decoy
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
11
+ Classifier: Intended Audience :: Science/Research
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy>=1.22
16
+ Requires-Dist: scipy>=1.8
17
+ Dynamic: license-file
18
+
19
+ # decal — 差异细胞通讯的可辨识性诊断
20
+
21
+ > **Decoy-Calibrated communication audit.**
22
+ > 在你报告"某条配体-受体通讯被改写"之前,先问一句:**这个结论能不能和表达丰度区分开?**
23
+
24
+ `decal` 给任意"两组细胞的配体-受体差异通讯"分析做三件事:
25
+
26
+ | 输出 | 含义 | 读法 |
27
+ |---|---|---|
28
+ | `delta` | 每位供体的效应中位数(全局位移) | \|δ\|>0.3 → 排序是位移在排,不是生物学在排 |
29
+ | `rho_abund_S` | 扣位移后残差与丰度的秩相关 | >0.5 → 排序≈丰度排序,别解释配对排序 |
30
+ | `decoy_auroc` | 真对 vs 分层匹配诱饵的可分性 | 0.5 = 配对身份零信息 |
31
+ | `match_balance` | 诱饵在丰度/检出上的残差 | >0.15 = 配平失败,`decoy_auroc` 不可解释 |
32
+ | `n_calls_q10` | 诱饵校准 + BH 后 q<0.10 的调用数 | 0 = 该主张无法与丰度区分 |
33
+ | `verdict` | 四值判定 | 见下 |
34
+
35
+ `verdict` 取值:`identifiable` / `marginal-dominated` / `not-identifiable` / `decoy-mismatch`
36
+
37
+ ---
38
+
39
+ ## 安装
40
+
41
+ ```bash
42
+ pip install decal-ccc # 发布后
43
+ # 或从源码
44
+ cd decal && pip install -e .
45
+ ```
46
+
47
+ 依赖只有 `numpy` 与 `scipy`,无 GPU、无其他包。
48
+
49
+ ## 用法
50
+
51
+ ### Python
52
+
53
+ ```python
54
+ from decal import audit
55
+
56
+ # H, L: (n_donor, n_gene) 的两组均值矩阵(建议已按细胞总量归一化,如 log1p(CP10K))
57
+ # genes: 基因名列表
58
+ # lr: [(配体, 受体), ...] 或 [(通路, 配体, [受体, ...]), ...]
59
+ res = audit(H, L, genes, lr)
60
+ print(res["delta"], res["rho_abund_S"], res["n_calls_q10"], res["verdict"])
61
+ ```
62
+
63
+ ### 命令行
64
+
65
+ ```bash
66
+ decal --npz means.npz --lr lr_db.json
67
+ decal --npz means.npz --lr lr_db.json --json
68
+ ```
69
+
70
+ `means.npz` 需包含 `means_H` / `means_L` / `genes`。
71
+
72
+ ---
73
+
74
+ ## 为什么诱饵必须分层匹配
75
+
76
+ 最近邻匹配会留下系统性残差。我们在真实数据上实测:
77
+
78
+ | 方法 | 真对 vs 诱饵 AUROC |
79
+ |---|---|
80
+ | TabPFN-3.5(2026 TabArena/BeyondArena 双榜前三,20 特征,配体分组 5 折) | **0.829** |
81
+ | Logistic 回归 | 0.618 |
82
+ | \|E\| 单特征 | 0.501 |
83
+ | **分层精确匹配(丰度五分位 × 检出五分位)** | **0.509** |
84
+
85
+ 那 0.32 的"领先"全部来自匹配残差(真受体比诱饵更低表达、更差检出)。
86
+ **模型越强,越会学混杂。** 所以 decal v2:
87
+
88
+ 1. 强制在同一 (丰度, 检出) 层内抽诱饵;
89
+ 2. 输出 `match_balance`;
90
+ 3. 配平失败时直接返回 `verdict="decoy-mismatch"`,**拒绝解释 AUROC**。
91
+
92
+ ---
93
+
94
+ ## 在 KPMP 上的实测输出
95
+
96
+ ```json
97
+ {
98
+ "n_pairs": 1572, "n_decoys": 4716,
99
+ "delta": 0.712, "delta_sd": 0.330, "frac_up": 0.946,
100
+ "rho_abund_S": 0.670, "decoy_auroc": 0.498,
101
+ "match_balance": {"abund": 0.113, "det": 0.015},
102
+ "n_calls_q05": 0, "n_calls_q10": 0,
103
+ "verdict": "not-identifiable"
104
+ }
105
+ ```
106
+
107
+ 94.6% 的对同向上调(δ=0.71);扣位移后残差与丰度相关 0.67;真对与诱饵 AUROC 0.50;
108
+ FDR 0.10 下零调用。对照:LIANA 2.1.1 在同一批细胞上报 8,504 条"显著"交互。
109
+
110
+ ---
111
+
112
+ ## 建议的报告方式
113
+
114
+ - δ 大时,不要解释"哪一对通讯被改写",只解释"配体/受体程序整体上调"。
115
+ - 任何配对级主张,附上 `n_calls_q10`。若为 0,说明该主张无法与丰度匹配诱饵区分。
116
+ - 需要配对级结论时,去找正交证据(空间邻接、蛋白、扰动),而不是换打分公式。
117
+ - **报告层级**:细胞类型对(可辨识)> 配体/受体程序 > LR 对(多数情况下不可辨识)。
118
+
119
+ ---
120
+
121
+ ## 引用
122
+
123
+ 如果你用 decal 做了可辨识性诊断,请引用配套论文(见 CITATION.cff)。
124
+
125
+ ## License
126
+
127
+ MIT
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/decal/__init__.py
5
+ src/decal/cli.py
6
+ src/decal/core.py
7
+ src/decal/py.typed
8
+ src/decal_ccc.egg-info/PKG-INFO
9
+ src/decal_ccc.egg-info/SOURCES.txt
10
+ src/decal_ccc.egg-info/dependency_links.txt
11
+ src/decal_ccc.egg-info/entry_points.txt
12
+ src/decal_ccc.egg-info/requires.txt
13
+ src/decal_ccc.egg-info/top_level.txt
14
+ tests/test_core.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ decal = decal.cli:main
@@ -0,0 +1,2 @@
1
+ numpy>=1.22
2
+ scipy>=1.8
@@ -0,0 +1,54 @@
1
+ """decal 核心功能的最小测试(pytest 或直接 python tests/test_core.py)"""
2
+ import numpy as np
3
+
4
+
5
+ def _make_data(n_donor=30, n_gene=60, seed=0):
6
+ rng = np.random.default_rng(seed)
7
+ genes = [f"G{i}" for i in range(n_gene)]
8
+ mu = rng.normal(0, 2, n_gene)
9
+ H = np.exp(mu)[None, :] * np.exp(rng.normal(0, .3, (n_donor, n_gene)))
10
+ L = np.exp(mu)[None, :] * np.exp(rng.normal(0, .3, (n_donor, n_gene)))
11
+ return H, L, genes
12
+
13
+
14
+ def _lr_db(genes, n_pairs=20):
15
+ rng = np.random.default_rng(1)
16
+ out = []
17
+ for k in range(n_pairs):
18
+ l, r = rng.choice(genes, 2, replace=False)
19
+ out.append(("P%d" % k, l, [r]))
20
+ return out
21
+
22
+
23
+ def test_audit_runs():
24
+ from decal import audit
25
+ H, L, genes = _make_data()
26
+ r = audit(H, L, genes, _lr_db(genes))
27
+ assert r["n_pairs"] > 0
28
+ assert "verdict" in r
29
+ assert 0 <= r["decoy_auroc"] <= 1
30
+ assert set(r["match_balance"]) == {"abund", "det"}
31
+
32
+
33
+ def test_decoy_mismatch_flagged():
34
+ from decal import audit
35
+ H, L, genes = _make_data()
36
+ # 极端不平衡:诱饵池太小、匹配失败时必须拒绝解释 AUROC
37
+ r = audit(H, L, genes, _lr_db(genes, 15), n_decoy=3, stratify=False)
38
+ assert r["verdict"] in {"identifiable", "marginal-dominated",
39
+ "not-identifiable", "decoy-mismatch"}
40
+
41
+
42
+ def test_null_is_null():
43
+ from decal import audit
44
+ H, L, genes = _make_data(n_gene=80)
45
+ r = audit(H, L, genes, _lr_db(genes, 15))
46
+ # 无真实信号时不应给出大量调用
47
+ assert r["n_calls_q10"] <= 5
48
+
49
+
50
+ if __name__ == "__main__":
51
+ test_audit_runs(); print("ok audit_runs")
52
+ test_decoy_mismatch_flagged(); print("ok decoy_mismatch")
53
+ test_null_is_null(); print("ok null_is_null")
54
+ print("ALL TESTS PASSED")