derman-cell 0.1.0__py3-none-any.whl
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.
- derman/__init__.py +4 -0
- derman/anndata_io.py +240 -0
- derman/auditor.py +446 -0
- derman/backend.py +448 -0
- derman/cli.py +1003 -0
- derman/decoder.py +227 -0
- derman/engine.py +125 -0
- derman/preprocessing.py +217 -0
- derman/regulons.py +192 -0
- derman/router.py +463 -0
- derman/schema.py +546 -0
- derman/screener.py +288 -0
- derman/sequencer.py +599 -0
- derman/server.py +474 -0
- derman/static/index.html +827 -0
- derman/template.py +154 -0
- derman_cell-0.1.0.dist-info/METADATA +251 -0
- derman_cell-0.1.0.dist-info/RECORD +20 -0
- derman_cell-0.1.0.dist-info/WHEEL +4 -0
- derman_cell-0.1.0.dist-info/entry_points.txt +2 -0
derman/__init__.py
ADDED
derman/anndata_io.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any, Literal
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from derman.preprocessing import DEFAULT_TOP_N_GENES, pseudobulk_and_log1p
|
|
11
|
+
from derman.schema import (
|
|
12
|
+
CellProfile,
|
|
13
|
+
CompoundCandidate,
|
|
14
|
+
PerturbationItem,
|
|
15
|
+
PerturbationKind,
|
|
16
|
+
PerturbationSpec,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def inspect_h5ad_groups(
|
|
21
|
+
h5ad_path: Path,
|
|
22
|
+
cell_type_col: str = "cell_type",
|
|
23
|
+
) -> dict[str, Any]:
|
|
24
|
+
"""Summarize cell types, cell counts, and gene count in a local .h5ad dataset."""
|
|
25
|
+
try:
|
|
26
|
+
import anndata as ad
|
|
27
|
+
except ImportError as exc:
|
|
28
|
+
raise ImportError(
|
|
29
|
+
'anndata is required to read .h5ad files. Install with: uv sync --extra anndata'
|
|
30
|
+
) from exc
|
|
31
|
+
|
|
32
|
+
adata = ad.read_h5ad(str(h5ad_path), backed="r")
|
|
33
|
+
try:
|
|
34
|
+
obs_cols = list(adata.obs.columns)
|
|
35
|
+
counts: dict[str, int] = {}
|
|
36
|
+
if cell_type_col in adata.obs.columns:
|
|
37
|
+
vc = adata.obs[cell_type_col].astype(str).value_counts()
|
|
38
|
+
counts = {str(k): int(v) for k, v in vc.items()}
|
|
39
|
+
return {
|
|
40
|
+
"path": str(h5ad_path),
|
|
41
|
+
"n_obs": int(adata.n_obs),
|
|
42
|
+
"n_vars": int(adata.n_vars),
|
|
43
|
+
"obs_columns": obs_cols,
|
|
44
|
+
"cell_type_col": cell_type_col,
|
|
45
|
+
"cell_type_counts": counts,
|
|
46
|
+
}
|
|
47
|
+
finally:
|
|
48
|
+
if getattr(adata, "file", None) is not None:
|
|
49
|
+
adata.file.close()
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def load_cell_profile_from_h5ad(
|
|
53
|
+
h5ad_path: Path,
|
|
54
|
+
cell_type_value: str,
|
|
55
|
+
cell_type_col: str = "cell_type",
|
|
56
|
+
role: Literal["target", "bystander", "control"] = "target",
|
|
57
|
+
tissue: str = "h5ad_cohort",
|
|
58
|
+
layer: str | None = None,
|
|
59
|
+
gene_symbol_col: str | None = None,
|
|
60
|
+
protein_coding_genes: set[str] | None = None,
|
|
61
|
+
already_log1p: bool = False,
|
|
62
|
+
top_n: int = DEFAULT_TOP_N_GENES,
|
|
63
|
+
) -> CellProfile:
|
|
64
|
+
"""Pseudobulk all cells matching obs[cell_type_col] == cell_type_value into a CellProfile."""
|
|
65
|
+
try:
|
|
66
|
+
import anndata as ad
|
|
67
|
+
except ImportError as exc:
|
|
68
|
+
raise ImportError(
|
|
69
|
+
'anndata is required to read .h5ad files. Install with: uv sync --extra anndata'
|
|
70
|
+
) from exc
|
|
71
|
+
|
|
72
|
+
adata = ad.read_h5ad(str(h5ad_path))
|
|
73
|
+
if cell_type_col not in adata.obs.columns:
|
|
74
|
+
raise ValueError(
|
|
75
|
+
f"Column {cell_type_col!r} not found in {h5ad_path.name} obs columns: "
|
|
76
|
+
f"{list(adata.obs.columns)}"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
mask = adata.obs[cell_type_col].astype(str).to_numpy() == str(cell_type_value)
|
|
80
|
+
if not np.any(mask):
|
|
81
|
+
available = sorted(adata.obs[cell_type_col].astype(str).unique().tolist())
|
|
82
|
+
raise ValueError(
|
|
83
|
+
f"Cell type {cell_type_value!r} not found in {cell_type_col!r}. "
|
|
84
|
+
f"Available: {available[:12]}"
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
sub = adata[mask]
|
|
88
|
+
mat = sub.layers[layer] if (layer is not None and layer in sub.layers) else sub.X
|
|
89
|
+
if hasattr(mat, "toarray"):
|
|
90
|
+
dense = np.asarray(mat.toarray(), dtype=np.float64)
|
|
91
|
+
else:
|
|
92
|
+
dense = np.asarray(mat, dtype=np.float64)
|
|
93
|
+
|
|
94
|
+
if gene_symbol_col is not None and gene_symbol_col in sub.var.columns:
|
|
95
|
+
gene_names = [str(g) for g in sub.var[gene_symbol_col].tolist()]
|
|
96
|
+
else:
|
|
97
|
+
gene_names = [str(g) for g in sub.var_names.tolist()]
|
|
98
|
+
|
|
99
|
+
safe_id = f"{h5ad_path.stem}:{cell_type_value}".replace(" ", "_").lower()
|
|
100
|
+
return pseudobulk_and_log1p(
|
|
101
|
+
counts=dense,
|
|
102
|
+
gene_names=gene_names,
|
|
103
|
+
cell_id=safe_id,
|
|
104
|
+
cell_type=cell_type_value,
|
|
105
|
+
tissue=tissue,
|
|
106
|
+
role=role,
|
|
107
|
+
protein_coding_genes=protein_coding_genes,
|
|
108
|
+
top_n=top_n,
|
|
109
|
+
already_log1p=already_log1p,
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def build_demo_compound_library() -> list[CompoundCandidate]:
|
|
114
|
+
"""Curated demo panel contrasting selective CAR-T sensitizers vs. pan-toxic & inert drugs."""
|
|
115
|
+
return [
|
|
116
|
+
CompoundCandidate(
|
|
117
|
+
candidate_id="trametinib_0.5uM",
|
|
118
|
+
mechanism_class="MEK1/2 inhibitor (selective)",
|
|
119
|
+
perturbation=PerturbationSpec(
|
|
120
|
+
items=[
|
|
121
|
+
PerturbationItem(
|
|
122
|
+
kind=PerturbationKind.SMALL_MOLECULE,
|
|
123
|
+
name="Trametinib",
|
|
124
|
+
smiles="CC1=C2C(=C(N(C1=O)C)NC3=C(C=C(C=C3)I)F)C(=O)N(C(=O)N2C4=CC(=CC=C4)NC(=O)C)C5CC5",
|
|
125
|
+
concentration="0.5 uM",
|
|
126
|
+
)
|
|
127
|
+
]
|
|
128
|
+
),
|
|
129
|
+
),
|
|
130
|
+
CompoundCandidate(
|
|
131
|
+
candidate_id="selumetinib_1uM",
|
|
132
|
+
mechanism_class="MEK1/2 inhibitor (selective)",
|
|
133
|
+
perturbation=PerturbationSpec(
|
|
134
|
+
items=[
|
|
135
|
+
PerturbationItem(
|
|
136
|
+
kind=PerturbationKind.SMALL_MOLECULE,
|
|
137
|
+
name="Selumetinib",
|
|
138
|
+
smiles="CN1C=NC2=C1C=C(C(=C2F)NC3=C(C=C(C=C3)Br)Cl)C(=O)NOCCO",
|
|
139
|
+
concentration="1.0 uM",
|
|
140
|
+
)
|
|
141
|
+
]
|
|
142
|
+
),
|
|
143
|
+
),
|
|
144
|
+
CompoundCandidate(
|
|
145
|
+
candidate_id="panobinostat_0.5uM",
|
|
146
|
+
mechanism_class="Pan-HDAC inhibitor (broad toxicity)",
|
|
147
|
+
perturbation=PerturbationSpec(
|
|
148
|
+
items=[
|
|
149
|
+
PerturbationItem(
|
|
150
|
+
kind=PerturbationKind.SMALL_MOLECULE,
|
|
151
|
+
name="Panobinostat",
|
|
152
|
+
smiles="CC1=C(C2=CC=CC=C2N1)CCNCC3=CC=C(C=C3)C=CC(=O)NO",
|
|
153
|
+
concentration="0.5 uM",
|
|
154
|
+
)
|
|
155
|
+
]
|
|
156
|
+
),
|
|
157
|
+
),
|
|
158
|
+
CompoundCandidate(
|
|
159
|
+
candidate_id="vorinostat_2uM",
|
|
160
|
+
mechanism_class="Pan-HDAC inhibitor (broad toxicity)",
|
|
161
|
+
perturbation=PerturbationSpec(
|
|
162
|
+
items=[
|
|
163
|
+
PerturbationItem(
|
|
164
|
+
kind=PerturbationKind.SMALL_MOLECULE,
|
|
165
|
+
name="Vorinostat",
|
|
166
|
+
smiles="C1=CC=C(C=C1)NC(=O)CCCCCCC(=O)NO",
|
|
167
|
+
concentration="2.0 uM",
|
|
168
|
+
)
|
|
169
|
+
]
|
|
170
|
+
),
|
|
171
|
+
),
|
|
172
|
+
CompoundCandidate(
|
|
173
|
+
candidate_id="ifng_10ng",
|
|
174
|
+
mechanism_class="Cytokine (MHC-I immune priming)",
|
|
175
|
+
perturbation=PerturbationSpec(
|
|
176
|
+
items=[
|
|
177
|
+
PerturbationItem(
|
|
178
|
+
kind=PerturbationKind.CYTOKINE,
|
|
179
|
+
name="IFNG",
|
|
180
|
+
kg_sentence="IFNG encodes interferon gamma, activating JAK-STAT1 and MHC class I antigen presentation.",
|
|
181
|
+
concentration="10 ng/mL",
|
|
182
|
+
)
|
|
183
|
+
]
|
|
184
|
+
),
|
|
185
|
+
),
|
|
186
|
+
CompoundCandidate(
|
|
187
|
+
candidate_id="metformin_10uM",
|
|
188
|
+
mechanism_class="Metabolic control (off-pathway)",
|
|
189
|
+
perturbation=PerturbationSpec(
|
|
190
|
+
items=[
|
|
191
|
+
PerturbationItem(
|
|
192
|
+
kind=PerturbationKind.SMALL_MOLECULE,
|
|
193
|
+
name="Metformin",
|
|
194
|
+
smiles="CN(C)C(=N)NC(=N)N",
|
|
195
|
+
concentration="10 uM",
|
|
196
|
+
)
|
|
197
|
+
]
|
|
198
|
+
),
|
|
199
|
+
),
|
|
200
|
+
]
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def load_compound_library(path: Path) -> list[CompoundCandidate]:
|
|
204
|
+
"""Load a local CSV or JSON/JSONL compound library into CompoundCandidate objects."""
|
|
205
|
+
suffix = path.suffix.lower()
|
|
206
|
+
if suffix == ".json":
|
|
207
|
+
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
208
|
+
return [CompoundCandidate.model_validate(item) for item in raw]
|
|
209
|
+
if suffix == ".jsonl":
|
|
210
|
+
return [
|
|
211
|
+
CompoundCandidate.model_validate_json(line)
|
|
212
|
+
for line in path.read_text(encoding="utf-8").splitlines()
|
|
213
|
+
if line.strip()
|
|
214
|
+
]
|
|
215
|
+
if suffix == ".csv":
|
|
216
|
+
out: list[CompoundCandidate] = []
|
|
217
|
+
with path.open("r", encoding="utf-8", newline="") as f:
|
|
218
|
+
reader = csv.DictReader(f)
|
|
219
|
+
for idx, row in enumerate(reader):
|
|
220
|
+
name = (row.get("name") or row.get("drug") or "").strip()
|
|
221
|
+
if not name:
|
|
222
|
+
continue
|
|
223
|
+
kind_str = (row.get("kind") or "small_molecule").strip().lower()
|
|
224
|
+
item = PerturbationItem(
|
|
225
|
+
kind=PerturbationKind(kind_str),
|
|
226
|
+
name=name,
|
|
227
|
+
smiles=(row.get("smiles") or "").strip() or None,
|
|
228
|
+
concentration=(row.get("concentration") or row.get("conc") or "").strip() or None,
|
|
229
|
+
kg_sentence=(row.get("kg_sentence") or "").strip() or None,
|
|
230
|
+
)
|
|
231
|
+
cid = (row.get("candidate_id") or f"cand_{idx + 1}_{name.lower()}").strip()
|
|
232
|
+
out.append(
|
|
233
|
+
CompoundCandidate(
|
|
234
|
+
candidate_id=cid,
|
|
235
|
+
mechanism_class=(row.get("mechanism_class") or "library").strip(),
|
|
236
|
+
perturbation=PerturbationSpec(items=[item]),
|
|
237
|
+
)
|
|
238
|
+
)
|
|
239
|
+
return out
|
|
240
|
+
raise ValueError(f"Unsupported library format: {path.suffix} (expected .csv, .json, or .jsonl)")
|
derman/auditor.py
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import math
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import daftar
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
from derman.backend import CellGemmaBackend
|
|
11
|
+
from derman.decoder import ExpressionDecoder
|
|
12
|
+
from derman.engine import PerturbationEngine
|
|
13
|
+
from derman.preprocessing import compute_mean_global_profile, rank_expressed_genes
|
|
14
|
+
from derman.regulons import evaluate_regulon_consistency
|
|
15
|
+
from derman.schema import (
|
|
16
|
+
CalibrationAuditReport,
|
|
17
|
+
CellProfile,
|
|
18
|
+
DropoutSensitivityAudit,
|
|
19
|
+
MeanShiftGainAudit,
|
|
20
|
+
PerturbationItem,
|
|
21
|
+
PerturbationKind,
|
|
22
|
+
PerturbationPrediction,
|
|
23
|
+
PerturbationSpec,
|
|
24
|
+
RegulonEdge,
|
|
25
|
+
ShortcutAblationAudit,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def signed_topk_jaccard(
|
|
30
|
+
pred_a: PerturbationPrediction,
|
|
31
|
+
pred_b: PerturbationPrediction,
|
|
32
|
+
top_k: int = 25,
|
|
33
|
+
) -> float:
|
|
34
|
+
"""Signed +GENE/-GENE Jaccard similarity across top-K residual shifts."""
|
|
35
|
+
set_a = {s.raw_token for s in pred_a.residual_shifts[:top_k]}
|
|
36
|
+
set_b = {s.raw_token for s in pred_b.residual_shifts[:top_k]}
|
|
37
|
+
union = set_a | set_b
|
|
38
|
+
if not union:
|
|
39
|
+
return 1.0
|
|
40
|
+
return len(set_a & set_b) / len(union)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def lfc_cosine_similarity(
|
|
44
|
+
lfc_a: dict[str, float],
|
|
45
|
+
lfc_b: dict[str, float],
|
|
46
|
+
) -> float:
|
|
47
|
+
"""Cosine similarity between two continuous log2 fold-change dictionaries."""
|
|
48
|
+
genes = sorted(set(lfc_a.keys()) | set(lfc_b.keys()))
|
|
49
|
+
if not genes:
|
|
50
|
+
return 0.0
|
|
51
|
+
vec_a = np.array([float(lfc_a.get(g, 0.0)) for g in genes], dtype=np.float64)
|
|
52
|
+
vec_b = np.array([float(lfc_b.get(g, 0.0)) for g in genes], dtype=np.float64)
|
|
53
|
+
norm_a = float(np.linalg.norm(vec_a))
|
|
54
|
+
norm_b = float(np.linalg.norm(vec_b))
|
|
55
|
+
if norm_a < 1e-12 or norm_b < 1e-12:
|
|
56
|
+
return 0.0
|
|
57
|
+
return float(np.clip(np.dot(vec_a, vec_b) / (norm_a * norm_b), -1.0, 1.0))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _combined_similarity(
|
|
61
|
+
pred_a: PerturbationPrediction,
|
|
62
|
+
pred_b: PerturbationPrediction,
|
|
63
|
+
top_k: int = 25,
|
|
64
|
+
) -> tuple[float, float, float]:
|
|
65
|
+
jac = signed_topk_jaccard(pred_a, pred_b, top_k=top_k)
|
|
66
|
+
cos = lfc_cosine_similarity(pred_a.lfc_vs_baseline, pred_b.lfc_vs_baseline)
|
|
67
|
+
combined = 0.5 * jac + 0.5 * max(0.0, cos)
|
|
68
|
+
return jac, cos, combined
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _apply_gene_dropout(
|
|
72
|
+
cell: CellProfile,
|
|
73
|
+
dropout_rate: float,
|
|
74
|
+
seed: int,
|
|
75
|
+
protect_top_housekeeping: int = 4,
|
|
76
|
+
) -> CellProfile:
|
|
77
|
+
"""Simulate 10x single-cell technical dropout on non-housekeeping expressed genes."""
|
|
78
|
+
rng = np.random.default_rng(seed)
|
|
79
|
+
ranked = rank_expressed_genes(cell.expression)
|
|
80
|
+
protected = set(ranked[:protect_top_housekeeping])
|
|
81
|
+
candidates = [g for g in ranked if g not in protected]
|
|
82
|
+
|
|
83
|
+
n_drop = min(max(1, round(len(candidates) * dropout_rate)), max(0, len(candidates) - 1))
|
|
84
|
+
dropped = set(rng.choice(candidates, size=n_drop, replace=False).tolist()) if n_drop > 0 else set()
|
|
85
|
+
|
|
86
|
+
new_expr = {g: (0.0 if g in dropped else v) for g, v in cell.expression.items()}
|
|
87
|
+
return cell.model_copy(
|
|
88
|
+
update={
|
|
89
|
+
"cell_id": f"{cell.cell_id}-drop{seed}",
|
|
90
|
+
"expression": new_expr,
|
|
91
|
+
"top_genes": rank_expressed_genes(new_expr),
|
|
92
|
+
}
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _apply_rank_jitter(
|
|
97
|
+
cell: CellProfile,
|
|
98
|
+
sigma: float,
|
|
99
|
+
seed: int,
|
|
100
|
+
) -> CellProfile:
|
|
101
|
+
"""Add tiny log1p noise to perturb near-tied gene ranks in the Source cell sentence."""
|
|
102
|
+
rng = np.random.default_rng(seed)
|
|
103
|
+
new_expr: dict[str, float] = {}
|
|
104
|
+
for g, v in cell.expression.items():
|
|
105
|
+
if v <= 0.0:
|
|
106
|
+
new_expr[g] = 0.0
|
|
107
|
+
else:
|
|
108
|
+
perturbed = max(0.01, float(v) + float(rng.normal(0.0, sigma)))
|
|
109
|
+
new_expr[g] = round(perturbed, 6)
|
|
110
|
+
return cell.model_copy(
|
|
111
|
+
update={
|
|
112
|
+
"cell_id": f"{cell.cell_id}-jitter{seed}",
|
|
113
|
+
"expression": new_expr,
|
|
114
|
+
"top_genes": rank_expressed_genes(new_expr),
|
|
115
|
+
}
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class CalibrationAuditor:
|
|
120
|
+
"""4-axis falsification & calibration auditor for virtual-cell perturbations."""
|
|
121
|
+
|
|
122
|
+
def __init__(
|
|
123
|
+
self,
|
|
124
|
+
workspace_dir: Path,
|
|
125
|
+
backend: CellGemmaBackend,
|
|
126
|
+
decoder: ExpressionDecoder,
|
|
127
|
+
regulons: list[RegulonEdge] | None = None,
|
|
128
|
+
) -> None:
|
|
129
|
+
self.workspace_dir = workspace_dir
|
|
130
|
+
self.backend = backend
|
|
131
|
+
self.decoder = decoder
|
|
132
|
+
self.regulons = regulons
|
|
133
|
+
self._engine = PerturbationEngine(
|
|
134
|
+
workspace_dir=workspace_dir,
|
|
135
|
+
backend=backend,
|
|
136
|
+
decoder=decoder,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def audit(
|
|
140
|
+
self,
|
|
141
|
+
cell: CellProfile,
|
|
142
|
+
perturbation: PerturbationSpec,
|
|
143
|
+
temperature: float = 0.7,
|
|
144
|
+
max_new_tokens: int = 384,
|
|
145
|
+
seed: int = 0,
|
|
146
|
+
dropout_rate: float = 0.15,
|
|
147
|
+
n_dropout_probes: int = 2,
|
|
148
|
+
jitter_sigma: float = 0.05,
|
|
149
|
+
top_k: int = 25,
|
|
150
|
+
save: bool = True,
|
|
151
|
+
) -> CalibrationAuditReport:
|
|
152
|
+
digest = hashlib.sha256(
|
|
153
|
+
f"{self.backend.model_id}|{self.decoder.spec.decoder_id}|"
|
|
154
|
+
f"{cell.cell_id}|{perturbation.label}|{temperature}|{seed}|"
|
|
155
|
+
f"{dropout_rate}|{n_dropout_probes}|{jitter_sigma}".encode()
|
|
156
|
+
).hexdigest()[:10]
|
|
157
|
+
audit_id = f"audit-{digest}"
|
|
158
|
+
|
|
159
|
+
params = {
|
|
160
|
+
"audit_id": audit_id,
|
|
161
|
+
"backend_model": self.backend.model_id,
|
|
162
|
+
"decoder_id": self.decoder.spec.decoder_id,
|
|
163
|
+
"cell_id": cell.cell_id,
|
|
164
|
+
"perturbation": perturbation.label,
|
|
165
|
+
"temperature": temperature,
|
|
166
|
+
"max_new_tokens": max_new_tokens,
|
|
167
|
+
"seed": seed,
|
|
168
|
+
"dropout_rate": dropout_rate,
|
|
169
|
+
"n_dropout_probes": n_dropout_probes,
|
|
170
|
+
"jitter_sigma": jitter_sigma,
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
with daftar.track("derman.audit.calibration", params=params, seed=seed) as run:
|
|
174
|
+
# Baseline prediction
|
|
175
|
+
base_pred = self._engine.predict(
|
|
176
|
+
cell=cell,
|
|
177
|
+
perturbation=perturbation,
|
|
178
|
+
temperature=temperature,
|
|
179
|
+
max_new_tokens=max_new_tokens,
|
|
180
|
+
seed=seed,
|
|
181
|
+
save=save,
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
# Axis 1: Mean-shift gain & DMSO vehicle contrast
|
|
185
|
+
mean_global = compute_mean_global_profile(
|
|
186
|
+
cell.expression, self.decoder.mean_delta_global
|
|
187
|
+
)
|
|
188
|
+
mean_shift_l2 = math.sqrt(
|
|
189
|
+
sum(
|
|
190
|
+
(mean_global.get(g, 0.0) - cell.expression.get(g, 0.0)) ** 2
|
|
191
|
+
for g in set(cell.expression) | set(mean_global)
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
res_l2 = base_pred.residual_gain_l2
|
|
195
|
+
if res_l2 + mean_shift_l2 > 1e-9:
|
|
196
|
+
non_trivial_frac = res_l2 / (res_l2 + mean_shift_l2)
|
|
197
|
+
else:
|
|
198
|
+
non_trivial_frac = 0.0
|
|
199
|
+
|
|
200
|
+
vehicle_spec = PerturbationSpec(
|
|
201
|
+
items=[
|
|
202
|
+
PerturbationItem(
|
|
203
|
+
kind=PerturbationKind.SMALL_MOLECULE,
|
|
204
|
+
name="DMSO",
|
|
205
|
+
smiles="CS(=O)C",
|
|
206
|
+
concentration="0.1%",
|
|
207
|
+
)
|
|
208
|
+
]
|
|
209
|
+
)
|
|
210
|
+
vehicle_pred = self._engine.predict(
|
|
211
|
+
cell=cell,
|
|
212
|
+
perturbation=vehicle_spec,
|
|
213
|
+
temperature=temperature,
|
|
214
|
+
max_new_tokens=max_new_tokens,
|
|
215
|
+
seed=seed,
|
|
216
|
+
save=False,
|
|
217
|
+
)
|
|
218
|
+
veh_jac = signed_topk_jaccard(base_pred, vehicle_pred, top_k=top_k)
|
|
219
|
+
veh_contrast = 1.0 - veh_jac
|
|
220
|
+
# Scale residual_l2 smoothly with tanh so empty predictions score 0
|
|
221
|
+
mag_factor = math.tanh(res_l2 / 1.5)
|
|
222
|
+
axis1_score = round(float(mag_factor * (0.45 * non_trivial_frac + 0.55 * veh_contrast)), 4)
|
|
223
|
+
|
|
224
|
+
axis1 = MeanShiftGainAudit(
|
|
225
|
+
baseline_residual_l2=round(res_l2, 4),
|
|
226
|
+
mean_shift_l2=round(mean_shift_l2, 4),
|
|
227
|
+
non_trivial_residual_fraction=round(non_trivial_frac, 4),
|
|
228
|
+
vehicle_overlap_jaccard=round(veh_jac, 4),
|
|
229
|
+
vehicle_contrast_score=round(veh_contrast, 4),
|
|
230
|
+
score=axis1_score,
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
# Axis 2: SMILES-vs-Name shortcut ablation (for small molecules with SMILES)
|
|
234
|
+
has_smiles = any(
|
|
235
|
+
it.kind == PerturbationKind.SMALL_MOLECULE and bool(it.smiles)
|
|
236
|
+
for it in perturbation.items
|
|
237
|
+
)
|
|
238
|
+
if has_smiles:
|
|
239
|
+
smiles_only_spec = PerturbationSpec(
|
|
240
|
+
items=[
|
|
241
|
+
it.model_copy(update={"name": f"Compound_{idx + 1}"})
|
|
242
|
+
if it.kind == PerturbationKind.SMALL_MOLECULE and it.smiles
|
|
243
|
+
else it
|
|
244
|
+
for idx, it in enumerate(perturbation.items)
|
|
245
|
+
],
|
|
246
|
+
condition_note=perturbation.condition_note,
|
|
247
|
+
)
|
|
248
|
+
name_only_spec = PerturbationSpec(
|
|
249
|
+
items=[
|
|
250
|
+
it.model_copy(update={"smiles": None})
|
|
251
|
+
if it.kind == PerturbationKind.SMALL_MOLECULE
|
|
252
|
+
else it
|
|
253
|
+
for it in perturbation.items
|
|
254
|
+
],
|
|
255
|
+
condition_note=perturbation.condition_note,
|
|
256
|
+
)
|
|
257
|
+
pred_smiles_only = self._engine.predict(
|
|
258
|
+
cell=cell,
|
|
259
|
+
perturbation=smiles_only_spec,
|
|
260
|
+
temperature=temperature,
|
|
261
|
+
max_new_tokens=max_new_tokens,
|
|
262
|
+
seed=seed,
|
|
263
|
+
save=False,
|
|
264
|
+
)
|
|
265
|
+
pred_name_only = self._engine.predict(
|
|
266
|
+
cell=cell,
|
|
267
|
+
perturbation=name_only_spec,
|
|
268
|
+
temperature=temperature,
|
|
269
|
+
max_new_tokens=max_new_tokens,
|
|
270
|
+
seed=seed,
|
|
271
|
+
save=False,
|
|
272
|
+
)
|
|
273
|
+
|
|
274
|
+
s_jac, s_cos, s_ret = _combined_similarity(base_pred, pred_smiles_only, top_k=top_k)
|
|
275
|
+
n_jac, n_cos, n_ret = _combined_similarity(base_pred, pred_name_only, top_k=top_k)
|
|
276
|
+
risk_idx = max(0.0, n_ret - s_ret)
|
|
277
|
+
|
|
278
|
+
if risk_idx >= 0.45 or s_ret < 0.25:
|
|
279
|
+
risk_level = "HIGH"
|
|
280
|
+
elif risk_idx >= 0.20 or s_ret < 0.50:
|
|
281
|
+
risk_level = "MODERATE"
|
|
282
|
+
else:
|
|
283
|
+
risk_level = "LOW"
|
|
284
|
+
|
|
285
|
+
# Reward high SMILES retention and penalize pure name-memorization gap
|
|
286
|
+
axis2_score = round(float(np.clip(s_ret * (1.0 - 0.5 * risk_idx), 0.0, 1.0)), 4)
|
|
287
|
+
axis2 = ShortcutAblationAudit(
|
|
288
|
+
applicable=True,
|
|
289
|
+
smiles_only_jaccard=round(s_jac, 4),
|
|
290
|
+
smiles_only_cosine=round(s_cos, 4),
|
|
291
|
+
smiles_only_retention=round(s_ret, 4),
|
|
292
|
+
name_only_jaccard=round(n_jac, 4),
|
|
293
|
+
name_only_cosine=round(n_cos, 4),
|
|
294
|
+
name_only_retention=round(n_ret, 4),
|
|
295
|
+
shortcut_risk_index=round(risk_idx, 4),
|
|
296
|
+
risk_level=risk_level, # type: ignore[arg-type]
|
|
297
|
+
score=axis2_score,
|
|
298
|
+
)
|
|
299
|
+
else:
|
|
300
|
+
axis2 = ShortcutAblationAudit(
|
|
301
|
+
applicable=False,
|
|
302
|
+
shortcut_risk_index=0.0,
|
|
303
|
+
risk_level="N/A",
|
|
304
|
+
score=0.5,
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
# Axis 3: Single-cell dropout & near-tie rank jitter sensitivity
|
|
308
|
+
drop_jacs: list[float] = []
|
|
309
|
+
drop_coss: list[float] = []
|
|
310
|
+
drop_stabs: list[float] = []
|
|
311
|
+
for p_idx in range(max(1, n_dropout_probes)):
|
|
312
|
+
dropped_cell = _apply_gene_dropout(
|
|
313
|
+
cell=cell,
|
|
314
|
+
dropout_rate=dropout_rate,
|
|
315
|
+
seed=seed + 101 + p_idx,
|
|
316
|
+
)
|
|
317
|
+
pred_drop = self._engine.predict(
|
|
318
|
+
cell=dropped_cell,
|
|
319
|
+
perturbation=perturbation,
|
|
320
|
+
temperature=temperature,
|
|
321
|
+
max_new_tokens=max_new_tokens,
|
|
322
|
+
seed=seed,
|
|
323
|
+
save=False,
|
|
324
|
+
)
|
|
325
|
+
dj, dc, ds = _combined_similarity(base_pred, pred_drop, top_k=top_k)
|
|
326
|
+
drop_jacs.append(dj)
|
|
327
|
+
drop_coss.append(dc)
|
|
328
|
+
drop_stabs.append(ds)
|
|
329
|
+
|
|
330
|
+
jitter_cell = _apply_rank_jitter(cell=cell, sigma=jitter_sigma, seed=seed + 503)
|
|
331
|
+
pred_jitter = self._engine.predict(
|
|
332
|
+
cell=jitter_cell,
|
|
333
|
+
perturbation=perturbation,
|
|
334
|
+
temperature=temperature,
|
|
335
|
+
max_new_tokens=max_new_tokens,
|
|
336
|
+
seed=seed,
|
|
337
|
+
save=False,
|
|
338
|
+
)
|
|
339
|
+
jj, jc, js = _combined_similarity(base_pred, pred_jitter, top_k=top_k)
|
|
340
|
+
|
|
341
|
+
mean_drop_stab = float(np.mean(drop_stabs))
|
|
342
|
+
axis3_score = round(float(0.6 * mean_drop_stab + 0.4 * js), 4)
|
|
343
|
+
axis3 = DropoutSensitivityAudit(
|
|
344
|
+
dropout_rate=dropout_rate,
|
|
345
|
+
n_dropout_probes=max(1, n_dropout_probes),
|
|
346
|
+
jitter_sigma=jitter_sigma,
|
|
347
|
+
dropout_jaccard=round(float(np.mean(drop_jacs)), 4),
|
|
348
|
+
dropout_cosine=round(float(np.mean(drop_coss)), 4),
|
|
349
|
+
dropout_stability=round(mean_drop_stab, 4),
|
|
350
|
+
rank_jitter_jaccard=round(jj, 4),
|
|
351
|
+
rank_jitter_cosine=round(jc, 4),
|
|
352
|
+
rank_jitter_stability=round(js, 4),
|
|
353
|
+
score=axis3_score,
|
|
354
|
+
)
|
|
355
|
+
|
|
356
|
+
# Axis 4: TF-regulon directional consistency
|
|
357
|
+
axis4 = evaluate_regulon_consistency(
|
|
358
|
+
lfc_map=base_pred.lfc_vs_baseline,
|
|
359
|
+
regulons=self.regulons,
|
|
360
|
+
)
|
|
361
|
+
|
|
362
|
+
# Composite score & explicit falsification warnings
|
|
363
|
+
if axis2.applicable:
|
|
364
|
+
composite = (
|
|
365
|
+
0.25 * axis1.score
|
|
366
|
+
+ 0.25 * axis2.score
|
|
367
|
+
+ 0.25 * axis3.score
|
|
368
|
+
+ 0.25 * axis4.score
|
|
369
|
+
)
|
|
370
|
+
else:
|
|
371
|
+
composite = (axis1.score + axis3.score + axis4.score) / 3.0
|
|
372
|
+
composite = round(float(np.clip(composite, 0.0, 1.0)), 4)
|
|
373
|
+
|
|
374
|
+
warnings: list[str] = []
|
|
375
|
+
if axis1.vehicle_overlap_jaccard > 0.35:
|
|
376
|
+
warnings.append(
|
|
377
|
+
f"High DMSO vehicle overlap ({axis1.vehicle_overlap_jaccard * 100:.1f}%): "
|
|
378
|
+
"prediction may reflect nonspecific housekeeping drift."
|
|
379
|
+
)
|
|
380
|
+
if axis1.baseline_residual_l2 < 0.5:
|
|
381
|
+
warnings.append(
|
|
382
|
+
f"Weak residual perturbation magnitude (L2={axis1.baseline_residual_l2:.3f})."
|
|
383
|
+
)
|
|
384
|
+
if axis2.applicable and axis2.risk_level == "HIGH":
|
|
385
|
+
warnings.append(
|
|
386
|
+
f"HIGH name-memorization shortcut risk: SMILES-only retention dropped to "
|
|
387
|
+
f"{(axis2.smiles_only_retention or 0.0) * 100:.1f}% vs. "
|
|
388
|
+
f"Name-only {(axis2.name_only_retention or 0.0) * 100:.1f}%."
|
|
389
|
+
)
|
|
390
|
+
elif axis2.applicable and axis2.risk_level == "MODERATE":
|
|
391
|
+
warnings.append(
|
|
392
|
+
f"Moderate shortcut sensitivity: SMILES-only retention="
|
|
393
|
+
f"{(axis2.smiles_only_retention or 0.0) * 100:.1f}%."
|
|
394
|
+
)
|
|
395
|
+
if axis3.dropout_stability < 0.55:
|
|
396
|
+
warnings.append(
|
|
397
|
+
f"Fragile under {int(dropout_rate * 100)}% single-cell gene dropout "
|
|
398
|
+
f"(stability={axis3.dropout_stability * 100:.1f}%)."
|
|
399
|
+
)
|
|
400
|
+
if axis3.rank_jitter_stability < 0.65:
|
|
401
|
+
warnings.append(
|
|
402
|
+
f"Sensitive to near-tie expression rank swaps "
|
|
403
|
+
f"(jitter stability={axis3.rank_jitter_stability * 100:.1f}%)."
|
|
404
|
+
)
|
|
405
|
+
if axis4.edge_concordance is not None and axis4.edge_concordance < 0.65:
|
|
406
|
+
warnings.append(
|
|
407
|
+
f"TF-regulon directional contradiction: only "
|
|
408
|
+
f"{axis4.n_concordant_edges}/{axis4.n_evaluated_edges} active edges concordant."
|
|
409
|
+
)
|
|
410
|
+
|
|
411
|
+
if composite >= 0.75 and not any("HIGH" in w or "contradiction" in w for w in warnings):
|
|
412
|
+
verdict = "HIGH_CONFIDENCE"
|
|
413
|
+
elif composite >= 0.50:
|
|
414
|
+
verdict = "MODERATE_VERIFY"
|
|
415
|
+
else:
|
|
416
|
+
verdict = "LOW_CONFIDENCE_FLAGGED"
|
|
417
|
+
|
|
418
|
+
run.log_result("composite_calibration_score", composite)
|
|
419
|
+
run.log_result("verdict", verdict)
|
|
420
|
+
run.log_result("shortcut_risk_level", axis2.risk_level)
|
|
421
|
+
run.log_result("dropout_stability", axis3.dropout_stability)
|
|
422
|
+
run.log_result("regulon_score", axis4.score)
|
|
423
|
+
run_id = getattr(run, "run_id", None) or getattr(run, "id", None)
|
|
424
|
+
|
|
425
|
+
report = CalibrationAuditReport(
|
|
426
|
+
audit_id=audit_id,
|
|
427
|
+
backend_model=self.backend.model_id,
|
|
428
|
+
decoder_spec=self.decoder.spec,
|
|
429
|
+
cell_id=cell.cell_id,
|
|
430
|
+
cell_type=cell.cell_type,
|
|
431
|
+
perturbation=perturbation,
|
|
432
|
+
baseline_prediction_id=base_pred.prediction_id,
|
|
433
|
+
temperature=temperature,
|
|
434
|
+
seed=seed,
|
|
435
|
+
mean_shift_gain=axis1,
|
|
436
|
+
shortcut_ablation=axis2,
|
|
437
|
+
dropout_sensitivity=axis3,
|
|
438
|
+
regulon_consistency=axis4,
|
|
439
|
+
composite_calibration_score=composite,
|
|
440
|
+
verdict=verdict, # type: ignore[arg-type]
|
|
441
|
+
warnings=warnings,
|
|
442
|
+
daftar_run_id=str(run_id) if run_id else None,
|
|
443
|
+
)
|
|
444
|
+
if save:
|
|
445
|
+
report.save(self.workspace_dir)
|
|
446
|
+
return report
|