draft-grn 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.
Files changed (100) hide show
  1. draft_grn-0.1.0.dist-info/METADATA +127 -0
  2. draft_grn-0.1.0.dist-info/RECORD +100 -0
  3. draft_grn-0.1.0.dist-info/WHEEL +5 -0
  4. draft_grn-0.1.0.dist-info/entry_points.txt +4 -0
  5. draft_grn-0.1.0.dist-info/licenses/LICENSE +21 -0
  6. draft_grn-0.1.0.dist-info/top_level.txt +2 -0
  7. draft_paired/R/check_simulator.R +140 -0
  8. draft_paired/R/positive_kinetics.R +44 -0
  9. draft_paired/R/prior_trial_context.R +24 -0
  10. draft_paired/R/simulate_prior.R +197 -0
  11. draft_paired/__init__.py +3 -0
  12. draft_paired/analysis/__init__.py +43 -0
  13. draft_paired/analysis/ccc.py +1567 -0
  14. draft_paired/analysis/ccc_alignment.py +235 -0
  15. draft_paired/analysis/ccc_config.py +95 -0
  16. draft_paired/analysis/ccc_networks.py +209 -0
  17. draft_paired/analysis/ccc_timing.py +1030 -0
  18. draft_paired/analysis/consensus.py +384 -0
  19. draft_paired/analysis/continuous_activity.py +443 -0
  20. draft_paired/analysis/edge_cluster.py +546 -0
  21. draft_paired/analysis/gene_keys.py +122 -0
  22. draft_paired/analysis/network.py +1353 -0
  23. draft_paired/analysis/repro.py +513 -0
  24. draft_paired/analysis/single_tf.py +897 -0
  25. draft_paired/analysis/topic.py +662 -0
  26. draft_paired/ccc_inputs.py +129 -0
  27. draft_paired/ccc_workflow.py +20 -0
  28. draft_paired/checkpoint.py +35 -0
  29. draft_paired/cli.py +338 -0
  30. draft_paired/cli_options.py +202 -0
  31. draft_paired/config_init.py +136 -0
  32. draft_paired/config_profiles.py +38 -0
  33. draft_paired/directory_inputs.py +249 -0
  34. draft_paired/examples/simulation_9plus3/inputs_101.npz +0 -0
  35. draft_paired/examples/simulation_9plus3/inputs_102.npz +0 -0
  36. draft_paired/examples/simulation_9plus3/inputs_103.npz +0 -0
  37. draft_paired/examples/simulation_9plus3/manifest.json +120 -0
  38. draft_paired/examples/simulation_9plus3/prior.tsv +1801 -0
  39. draft_paired/examples/simulation_9plus3/prior_provenance.json +6 -0
  40. draft_paired/examples/simulation_9plus3/truth_101.npz +0 -0
  41. draft_paired/examples/simulation_9plus3/truth_102.npz +0 -0
  42. draft_paired/examples/simulation_9plus3/truth_103.npz +0 -0
  43. draft_paired/graph_builder.py +293 -0
  44. draft_paired/graph_input.py +143 -0
  45. draft_paired/infer.py +286 -0
  46. draft_paired/input_schema.py +143 -0
  47. draft_paired/io.py +101 -0
  48. draft_paired/lineage.py +152 -0
  49. draft_paired/models/__init__.py +23 -0
  50. draft_paired/models/gnn.py +267 -0
  51. draft_paired/pipeline.py +85 -0
  52. draft_paired/preprocess.py +336 -0
  53. draft_paired/prior_preparation.py +765 -0
  54. draft_paired/prior_resources.py +215 -0
  55. draft_paired/reproduce.py +394 -0
  56. draft_paired/simulation.py +563 -0
  57. draft_paired/simulation_generate.py +646 -0
  58. draft_paired/simulation_training.py +196 -0
  59. draft_paired/templates/draft_ccc_template.yaml +39 -0
  60. draft_paired/templates/draft_example_fly_ccc.yaml +77 -0
  61. draft_paired/templates/draft_example_fly_germ.yaml +125 -0
  62. draft_paired/templates/draft_example_fly_soma.yaml +125 -0
  63. draft_paired/templates/draft_example_mouse_development.yaml +129 -0
  64. draft_paired/templates/draft_example_mouse_motifs.yaml +141 -0
  65. draft_paired/templates/draft_lineage_template.yaml +122 -0
  66. draft_paired/templates/draft_simulation_prior_template.yaml +44 -0
  67. draft_paired/templates/draft_simulation_template.yaml +29 -0
  68. draft_paired/templates/method_profiles.yaml +29 -0
  69. draft_paired/train.py +1027 -0
  70. draft_paired/tutorial_data.py +240 -0
  71. draft_paired/utils.py +141 -0
  72. draft_paired/workflow.py +167 -0
  73. draft_paired/workflow_cli.py +282 -0
  74. draft_unpaired/__init__.py +3 -0
  75. draft_unpaired/analysis/__init__.py +3 -0
  76. draft_unpaired/analysis/continuous_activity.py +8 -0
  77. draft_unpaired/analysis/edge_cluster.py +71 -0
  78. draft_unpaired/analysis/network.py +743 -0
  79. draft_unpaired/analysis/repro.py +23 -0
  80. draft_unpaired/analysis/single_tf.py +431 -0
  81. draft_unpaired/analysis/topic.py +77 -0
  82. draft_unpaired/checkpoint.py +13 -0
  83. draft_unpaired/cli.py +200 -0
  84. draft_unpaired/config_init.py +81 -0
  85. draft_unpaired/graph_builder.py +220 -0
  86. draft_unpaired/infer.py +128 -0
  87. draft_unpaired/io.py +101 -0
  88. draft_unpaired/lineage.py +5 -0
  89. draft_unpaired/models/__init__.py +5 -0
  90. draft_unpaired/models/gnn.py +187 -0
  91. draft_unpaired/pipeline.py +88 -0
  92. draft_unpaired/preprocess.py +319 -0
  93. draft_unpaired/prior.py +301 -0
  94. draft_unpaired/reproduce.py +152 -0
  95. draft_unpaired/scmtni_prior.py +482 -0
  96. draft_unpaired/templates/draft_motif_template.yaml +136 -0
  97. draft_unpaired/templates/draft_staged_prior_template.yaml +123 -0
  98. draft_unpaired/templates/draft_unpaired_template.yaml +128 -0
  99. draft_unpaired/train.py +568 -0
  100. draft_unpaired/utils.py +19 -0
@@ -0,0 +1,1030 @@
1
+ """Receptor-centrality communication on a shared, receiver-stage time axis."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from ..checkpoint import save_checkpoint_metadata
13
+ from ..input_schema import read_cell_annotation, read_gene_table, read_table
14
+ from ..utils import ensure_directory, load_yaml_config, resolve_config_path
15
+ from .ccc_alignment import network_alignment
16
+ from .gene_keys import GeneKeys, as_request, clean_symbol, resolve_symbols
17
+
18
+ DIRECTIONS = {
19
+ "hub_to_germline": ("hub", "germ"),
20
+ "hub_to_soma": ("hub", "soma"),
21
+ "soma_to_germline": ("soma", "germ"),
22
+ "germline_to_soma": ("germ", "soma"),
23
+ }
24
+
25
+
26
+ def receptor_percentiles(
27
+ tf: np.ndarray,
28
+ tg: np.ndarray,
29
+ active_tf: np.ndarray,
30
+ active_tg: np.ndarray,
31
+ block_size: int = 4096,
32
+ *,
33
+ absolute_cosine: bool = False,
34
+ ) -> np.ndarray:
35
+ """Mean right-inclusive percentile over active TFs, for every TG.
36
+
37
+ The reference distribution contains all active TF x active TG pairs;
38
+ expression gating of the receptor is applied later and independently.
39
+ """
40
+ tf, tg = np.asarray(tf, float), np.asarray(tg, float)
41
+ if (
42
+ tf.ndim != 2
43
+ or tg.ndim != 2
44
+ or tf.shape[1] != tg.shape[1]
45
+ or not np.isfinite(tf).all()
46
+ or not np.isfinite(tg).all()
47
+ ):
48
+ raise ValueError("Receiver embeddings must be finite matrices of equal width.")
49
+ it, ig = np.flatnonzero(active_tf), np.flatnonzero(active_tg)
50
+ if not len(it) or not len(ig):
51
+ raise ValueError(
52
+ "Receiver percentile reference needs active TFs and TGs at every stage."
53
+ )
54
+ tf = tf[it] / np.maximum(np.linalg.norm(tf[it], axis=1, keepdims=True), 1e-12)
55
+ tg = tg / np.maximum(np.linalg.norm(tg, axis=1, keepdims=True), 1e-12)
56
+ reference_scores = tf @ tg[ig].T
57
+ if absolute_cosine:
58
+ reference_scores = np.abs(reference_scores)
59
+ reference = np.sort(reference_scores.ravel())
60
+ result = np.empty(len(tg))
61
+ for start in range(0, len(tg), block_size):
62
+ scores = tf @ tg[start : start + block_size].T
63
+ if absolute_cosine:
64
+ scores = np.abs(scores)
65
+ result[start : start + block_size] = (
66
+ np.searchsorted(reference, scores, side="right") / reference.size
67
+ ).mean(axis=0)
68
+ return result
69
+
70
+
71
+ def timing_call(
72
+ curve: np.ndarray, labels: list[str], early_count: int, min_range: float = 0.1
73
+ ) -> dict[str, Any]:
74
+ curve = np.asarray(curve, float)
75
+ if len(curve) != len(labels) or not 0 < early_count < len(curve):
76
+ raise ValueError(
77
+ "early_stage_count must split the receiver stages into nonempty early and late windows."
78
+ )
79
+ if not np.isfinite(curve).all() or np.any(curve < 0):
80
+ raise ValueError("Communication scores must be finite and nonnegative.")
81
+ if curve.max() == 0:
82
+ return {
83
+ "status": "unscored",
84
+ "peak_index": None,
85
+ "peak_stage": None,
86
+ "dynamic_range": 0.0,
87
+ "earliness_score": 0.0,
88
+ }
89
+ peak, maximum = int(np.argmax(curve)), float(curve.max())
90
+ dynamic = float((maximum - curve.min()) / maximum)
91
+ return {
92
+ "status": "untimed"
93
+ if dynamic < min_range
94
+ else ("early" if peak < early_count else "late"),
95
+ "peak_index": peak,
96
+ "peak_stage": labels[peak],
97
+ "dynamic_range": dynamic,
98
+ "earliness_score": float(
99
+ (curve[:early_count].max() - curve[early_count:].max()) / maximum
100
+ ),
101
+ }
102
+
103
+
104
+ def stage_nodes(
105
+ groups: list[str], parallel: list[str] | None = None
106
+ ) -> list[list[str]]:
107
+ if len(set(groups)) != len(groups) or len(groups) < 2:
108
+ raise ValueError(
109
+ "Each lineage requires at least two distinct stage groups in developmental order."
110
+ )
111
+ if not parallel:
112
+ return [[g] for g in groups]
113
+ if (
114
+ len(set(parallel)) != len(parallel)
115
+ or len(parallel) < 2
116
+ or set(parallel) != set(groups[-len(parallel) :])
117
+ ):
118
+ raise ValueError(
119
+ "parallel_groups must name the distinct terminal groups at the end of stage_groups."
120
+ )
121
+ return [[g] for g in groups[: -len(parallel)]] + [list(parallel)]
122
+
123
+
124
+ def aligned_positions(
125
+ table: pd.DataFrame, soma_groups: list[str], nodes: list[list[str]], germ_count: int
126
+ ) -> tuple[np.ndarray, np.ndarray]:
127
+ """Map sender positions to the receiver stages in both alignment directions."""
128
+ if germ_count < 2 or len(nodes) < 2:
129
+ raise ValueError("Alignment requires at least two receiver stages per lineage.")
130
+ old_s = 1 + table.soma_tau.to_numpy(float) * (len(soma_groups) - 1)
131
+ germ = 1 + table.germ_tau.to_numpy(float) * (germ_count - 1)
132
+ if len(nodes[-1]) > 1:
133
+ # Parallel terminal groups share an endpoint, reached linearly
134
+ # from their preceding stage.
135
+ last_single = len(nodes) - 1
136
+ anchor = float(np.interp(last_single, old_s, germ))
137
+ soma = np.interp(
138
+ old_s, [1, last_single, len(soma_groups)], [1, last_single, len(nodes)]
139
+ )
140
+ terminal = soma >= last_single
141
+ germ[terminal] = anchor + (soma[terminal] - last_single) * (germ_count - anchor)
142
+ else:
143
+ soma = old_s
144
+ # An inverse of a plateau uses the mean source position, with fixed ends.
145
+ inverse = (
146
+ pd.DataFrame({"germ": germ, "soma": soma})
147
+ .groupby("germ", sort=True)
148
+ .soma.mean()
149
+ )
150
+ inverse.iloc[0], inverse.iloc[-1] = 1.0, float(len(nodes))
151
+ soma_at_germ = np.interp(
152
+ np.arange(1, germ_count + 1), inverse.index, inverse.values
153
+ )
154
+ germ_at_soma = np.interp(np.arange(1, len(nodes) + 1), soma, germ)
155
+ return soma_at_germ, germ_at_soma
156
+
157
+
158
+ def _collapse(frame: pd.DataFrame, nodes: list[list[str]]) -> pd.DataFrame:
159
+ return pd.DataFrame(
160
+ {i: frame[groups].mean(axis=1) for i, groups in enumerate(nodes)},
161
+ index=frame.index,
162
+ )
163
+
164
+
165
+ def _unpaired_reference_names(
166
+ inference: dict[str, Any], paths: Any
167
+ ) -> dict[str, list[str]]:
168
+ """Resolve gene symbols in graph row order from the saved maps and gene tables."""
169
+ maps = inference.get("maps") or {}
170
+ refs = {}
171
+ for role in ("tf", "tg"):
172
+ count = inference[f"out_{role}"].shape[0]
173
+ ids = maps.get(f"{role}_ids", maps.get(role, []))
174
+ if len(ids) != count:
175
+ raise ValueError(
176
+ f"Unpaired graph maps must identify every {role.upper()} row."
177
+ )
178
+ ids = [str(value) for value in ids]
179
+ names = maps.get(f"{role}_names")
180
+ if names is None:
181
+ table = read_gene_table(getattr(paths, f"{role}_list"))
182
+ symbols = dict(zip(table.gene_id, table.gene_name))
183
+ names = [symbols.get(value, value) for value in ids]
184
+ if len(names) != count:
185
+ raise ValueError(
186
+ f"Unpaired {role.upper()} symbols must match graph row order."
187
+ )
188
+ refs[f"{role}_ids"] = ids
189
+ refs[f"{role}_names"] = [str(value) for value in names]
190
+ return refs
191
+
192
+
193
+ def _receiver_scores(
194
+ config: dict[str, Any],
195
+ name: str,
196
+ spec: dict[str, Any],
197
+ output_dir: Path,
198
+ keys: GeneKeys | None = None,
199
+ ) -> tuple[pd.DataFrame, list[str], dict[str, Any]]:
200
+ """Receptor scores indexed by gene keys (lowercase unless case separates genes).
201
+
202
+ Without keys, the case rule comes from this lineage's own gene names.
203
+ """
204
+ frame, groups, meta, vocabulary = _raw_receiver_scores(config, name, spec)
205
+ return _keyed_receiver_scores(
206
+ frame, groups, meta, keys or GeneKeys(vocabulary), name, output_dir
207
+ )
208
+
209
+
210
+ def _keyed_receiver_scores(
211
+ frame: pd.DataFrame,
212
+ groups: list[str],
213
+ meta: dict[str, Any],
214
+ keys: GeneKeys,
215
+ name: str,
216
+ output_dir: Path,
217
+ ) -> tuple[pd.DataFrame, list[str], dict[str, Any]]:
218
+ frame = frame.copy()
219
+ frame.index = keys.keys(frame.index)
220
+ if meta["source"] == "checkpoint":
221
+ source = output_dir / f"{name}_receptor_centrality.tsv"
222
+ frame.to_csv(source, sep="\t", index_label="gene_name")
223
+ meta["path"] = str(source)
224
+ values = frame.to_numpy(float)
225
+ if (
226
+ frame.index.has_duplicates
227
+ or frame.index.isna().any()
228
+ or not np.isfinite(values).all()
229
+ or np.any(values < 0)
230
+ or np.any(values > 1)
231
+ ):
232
+ raise ValueError(
233
+ "Full receptor scores require unique gene symbols and finite percentiles in [0, 1]."
234
+ )
235
+ return frame, groups, meta
236
+
237
+
238
+ def _raw_receiver_scores(
239
+ config: dict[str, Any], name: str, spec: dict[str, Any]
240
+ ) -> tuple[pd.DataFrame, list[str], dict[str, Any], list[str]]:
241
+ """Receptor scores indexed by gene symbols as spelled in their source."""
242
+ groups = [str(g) for g in spec.get("stage_groups", [])]
243
+ input_mode = spec.get("input_mode", "paired")
244
+ if spec.get("receptor_scores"):
245
+ source = resolve_config_path(config, spec["receptor_scores"])
246
+ frame = pd.read_csv(source, sep="\t", index_col=0)
247
+ frame = frame.loc[frame.index.notna()].copy()
248
+ frame.index = frame.index.astype(str).map(clean_symbol)
249
+ vocabulary = list(frame.index)
250
+ if not groups:
251
+ groups = [str(c) for c in frame.columns]
252
+ frame.columns = frame.columns.astype(str)
253
+ columns = [str(c) for c in spec.get("stage_columns", groups)]
254
+ if len(columns) != len(groups):
255
+ raise ValueError(
256
+ "stage_columns must match stage_groups in length and model order."
257
+ )
258
+ frame = frame.loc[:, columns].apply(pd.to_numeric, errors="raise")
259
+ frame.columns = groups
260
+ meta = {
261
+ "source": "precomputed",
262
+ "path": str(source),
263
+ "sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
264
+ "provenance": spec.get("score_provenance", {}),
265
+ }
266
+ else:
267
+ if not spec.get("config"):
268
+ raise ValueError(
269
+ f"ccc.{name} requires config or receptor_scores (full integer-stage percentiles)."
270
+ )
271
+ from .network import (
272
+ _dense_tf_whitelist,
273
+ _load_tf_filter,
274
+ _load_tg_meta,
275
+ _network_settings,
276
+ _pick_reference_names,
277
+ _select_valid_cols,
278
+ )
279
+
280
+ config_path = resolve_config_path(config, spec["config"])
281
+ lineage_cfg = load_yaml_config(config_path)
282
+ model_mode = lineage_cfg.get("input_mode")
283
+ input_mode = (
284
+ spec.get("input_mode")
285
+ or model_mode
286
+ or (
287
+ "unpaired"
288
+ if lineage_cfg.get("data", {}).get("tf_tg_prior")
289
+ else "paired"
290
+ )
291
+ )
292
+ if input_mode not in {"paired", "unpaired"}:
293
+ raise ValueError("CCC input_mode must be paired or unpaired.")
294
+ if model_mode is not None and model_mode != input_mode:
295
+ raise ValueError(
296
+ f"ccc.{name}.input_mode must match the training config ({model_mode})."
297
+ )
298
+ if input_mode == "paired":
299
+ from ..infer import run_inference
300
+ from ..io import InputPaths
301
+ else:
302
+ from draft_unpaired.infer import run_inference
303
+ from draft_unpaired.io import InputPaths
304
+ lineage_cfg.setdefault(
305
+ "base_dir", str(Path(config.get("base_dir", ".")).resolve())
306
+ )
307
+ inference = run_inference(lineage_cfg)
308
+ graphs = (
309
+ inference.get("graphs")
310
+ or inference.get("graphs_lineage")
311
+ or inference.get("graphs_somatic")
312
+ or inference.get("graphs_germline")
313
+ )
314
+ tf = inference["out_tf"].detach().cpu().numpy()
315
+ tg = inference["out_tg"].detach().cpu().numpy()
316
+ paths = InputPaths.from_config(lineage_cfg)
317
+ filter_path = (
318
+ resolve_config_path(
319
+ lineage_cfg, _network_settings(lineage_cfg)["tf_filter_file"]
320
+ )
321
+ if input_mode == "paired"
322
+ else paths.tf_filter_file or paths.tf_list
323
+ )
324
+ if not filter_path.exists():
325
+ filter_path = paths.tf_list
326
+ tf_filter = _load_tf_filter(filter_path)
327
+ if input_mode == "paired":
328
+ refs = _pick_reference_names(
329
+ inference.get("maps"),
330
+ paths,
331
+ len(tf),
332
+ len(tg),
333
+ int(inference["out_re"].size(0)),
334
+ tf_filter,
335
+ _load_tg_meta(paths.tg_list),
336
+ )
337
+ else:
338
+ refs = _unpaired_reference_names(inference, paths)
339
+ whitelist = _dense_tf_whitelist(
340
+ refs["tf_ids"], refs["tf_names"], tf_filter
341
+ ).numpy()
342
+ if not groups:
343
+ groups = [
344
+ str(g)
345
+ for g in (
346
+ inference.get("time_names")
347
+ or inference.get("somatic_names")
348
+ or inference.get("germline_types")
349
+ or []
350
+ )
351
+ ]
352
+ if spec.get("stage_prefix"):
353
+ groups = [str(spec["stage_prefix"]) + group for group in groups]
354
+ if len(groups) != tf.shape[1] or len(graphs) != tf.shape[1]:
355
+ raise ValueError(
356
+ f"ccc.{name}.stage_groups must match the model's {tf.shape[1]} integer stages."
357
+ )
358
+ fraction = float(
359
+ spec.get(
360
+ "active_fraction",
361
+ lineage_cfg.get("network", {})
362
+ .get("dense", {})
363
+ .get("active_thr", 0.05 if input_mode == "paired" else 0.30),
364
+ )
365
+ )
366
+ if not 0 < fraction <= 1:
367
+ raise ValueError("Receiver active_fraction must be in (0, 1].")
368
+ vocabulary = [clean_symbol(g) for g in refs["tf_names"] + refs["tg_names"]]
369
+ if input_mode == "unpaired":
370
+ local = GeneKeys(vocabulary)
371
+ tf_keys, tg_keys = local.keys(refs["tf_names"]), local.keys(refs["tg_names"])
372
+ genes = local.request(dict.fromkeys(tf_keys + tg_keys))
373
+ _, detection = load_group_expression(config, groups, genes)
374
+ tf_detection = detection.reindex(tf_keys)
375
+ tg_detection = detection.reindex(tg_keys)
376
+ columns = []
377
+ for t, graph in enumerate(graphs):
378
+ if input_mode == "paired":
379
+ vx, _, gx = _select_valid_cols(
380
+ graph["TF"].x, graph["RE"].x, graph["TG"].x
381
+ )
382
+ active_tf = (
383
+ (vx != 0).float().mean(dim=1).detach().cpu().numpy() >= fraction
384
+ ) & whitelist
385
+ active_tg = (gx != 0).float().mean(
386
+ dim=1
387
+ ).detach().cpu().numpy() >= fraction
388
+ else:
389
+ active_tf = (tf_detection.iloc[:, t].to_numpy() >= fraction) & whitelist
390
+ active_tg = tg_detection.iloc[:, t].to_numpy() >= fraction
391
+ columns.append(
392
+ receptor_percentiles(
393
+ tf[:, t],
394
+ tg[:, t],
395
+ active_tf,
396
+ active_tg,
397
+ absolute_cosine=input_mode == "unpaired",
398
+ )
399
+ )
400
+ frame = pd.DataFrame(
401
+ np.asarray(columns).T,
402
+ index=[clean_symbol(g) for g in refs["tg_names"]],
403
+ columns=groups,
404
+ )
405
+ meta = {
406
+ "source": "checkpoint",
407
+ "config_path": str(config_path),
408
+ "checkpoint_path": inference.get("checkpoint_path"),
409
+ "active_fraction": fraction,
410
+ "tf_filter_path": str(filter_path),
411
+ "stage_groups": groups,
412
+ "definition": (
413
+ "right-inclusive percentile among active TF x TG absolute cosine scores; mean over active TFs"
414
+ if input_mode == "unpaired"
415
+ else "right-inclusive percentile among active TF x TG cosine scores; mean over active TFs"
416
+ ),
417
+ }
418
+ if input_mode == "unpaired":
419
+ meta["activity_inputs"] = {
420
+ "rna_h5ad": config.get("data", {}).get("rna_h5ad"),
421
+ "stage_groups": groups,
422
+ "cell_counts": detection.attrs.get("cell_counts", {}),
423
+ "missing_genes": detection.attrs.get("missing_genes", []),
424
+ }
425
+ meta["input_mode"] = input_mode
426
+ return frame, groups, meta, vocabulary
427
+
428
+
429
+ def load_group_expression(
430
+ config: dict[str, Any],
431
+ groups: list[str],
432
+ genes: list[str],
433
+ *,
434
+ allow_layer_fallback: bool = False,
435
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
436
+ import anndata as ad
437
+ from scipy import sparse
438
+
439
+ # RNA symbols match the gene keys without regard to case unless case
440
+ # separates genes; a list of plain keys uses its own case rule.
441
+ genes = as_request(genes)
442
+ data = config.get("data", {})
443
+ if data.get("lineages"):
444
+ means, fractions, counts, missing, covered = [], [], {}, set(), set()
445
+ for name, source in data["lineages"].items():
446
+ prefix = str(source.get("stage_prefix", f"{name}::"))
447
+ selected = [group for group in groups if group.startswith(prefix)]
448
+ if not selected:
449
+ continue
450
+ if covered.intersection(selected):
451
+ raise ValueError("CCC lineage group prefixes must be distinct.")
452
+ native_config = load_yaml_config(
453
+ resolve_config_path(config, source["config"])
454
+ )
455
+ native_config.setdefault("base_dir", config.get("base_dir", "."))
456
+ native_data = native_config.setdefault("data", {})
457
+ native_data.setdefault(
458
+ "cell_id_normalization",
459
+ "exact"
460
+ if int(native_config.get("config_version", 1)) >= 2
461
+ else "sample_suffix",
462
+ )
463
+ mode = native_config.get("input_mode") or (
464
+ "unpaired" if native_data.get("tf_tg_prior") else "paired"
465
+ )
466
+ if mode == "unpaired":
467
+ native_data.pop("atac_h5ad", None)
468
+ for field in ("rna_layer", "gene_symbol_column", "cell_id_normalization"):
469
+ if field in data:
470
+ native_data[field] = data[field]
471
+ native_groups = [group[len(prefix) :] for group in selected]
472
+ mean, frac = load_group_expression(
473
+ native_config, native_groups, genes, allow_layer_fallback=True
474
+ )
475
+ mapping = dict(zip(native_groups, selected))
476
+ counts.update(
477
+ {
478
+ mapping[group]: count
479
+ for group, count in mean.attrs.get("cell_counts", {}).items()
480
+ }
481
+ )
482
+ missing.update(mean.attrs.get("missing_genes", []))
483
+ mean.attrs, frac.attrs = {}, {}
484
+ means.append(mean.rename(columns=mapping))
485
+ fractions.append(frac.rename(columns=mapping))
486
+ covered.update(selected)
487
+ if covered != set(groups):
488
+ raise ValueError(
489
+ f"CCC RNA sources do not cover groups: {sorted(set(groups) - covered)}"
490
+ )
491
+ mean = pd.concat(means, axis=1).reindex(columns=groups)
492
+ mean.attrs = {"cell_counts": counts, "missing_genes": sorted(missing)}
493
+ return mean, pd.concat(fractions, axis=1).reindex(columns=groups)
494
+ if not data.get("rna_h5ad"):
495
+ raise ValueError(
496
+ "Receptor-centrality CCC requires data.rna_h5ad with normalized RNA expression."
497
+ )
498
+ rna = ad.read_h5ad(resolve_config_path(config, data["rna_h5ad"]))
499
+ normalization = data.get("cell_id_normalization", "sample_suffix")
500
+ if normalization == "sample_suffix":
501
+ from ..preprocess import norm_id
502
+
503
+ normalize = norm_id
504
+ elif normalization == "exact":
505
+ normalize = str
506
+ else:
507
+ raise ValueError("data.cell_id_normalization must be sample_suffix or exact.")
508
+ rna_ids = pd.Index([normalize(c) for c in rna.obs_names])
509
+ if not rna_ids.is_unique:
510
+ raise ValueError("RNA cell IDs collide after the configured normalization.")
511
+ group_col = str(data.get("group_column", "cell_type"))
512
+ if data.get("annotation"):
513
+ annotation_path = resolve_config_path(config, data["annotation"])
514
+ annotation = (
515
+ read_cell_annotation(annotation_path)
516
+ if "cell_id_column" not in data and "group_column" not in data
517
+ else read_table(annotation_path)
518
+ )
519
+ cell_col = str(data.get("cell_id_column", "cell_id"))
520
+ if cell_col not in annotation or group_col not in annotation:
521
+ raise ValueError(f"CCC annotation requires {cell_col} and {group_col}.")
522
+ annotation[cell_col] = annotation[cell_col].map(normalize)
523
+ if annotation[cell_col].duplicated().any():
524
+ raise ValueError("CCC requires unique RNA and annotation cell IDs.")
525
+ membership = annotation.set_index(cell_col)[group_col].reindex(rna_ids)
526
+ else:
527
+ if group_col not in rna.obs:
528
+ raise ValueError(
529
+ f"RNA obs requires {group_col}, or provide data.annotation."
530
+ )
531
+ membership = rna.obs[group_col]
532
+ if data.get("atac_h5ad"):
533
+ atac = ad.read_h5ad(resolve_config_path(config, data["atac_h5ad"]), backed="r")
534
+ try:
535
+ atac_ids = pd.Index([normalize(c) for c in atac.obs_names])
536
+ if not atac_ids.is_unique:
537
+ raise ValueError(
538
+ "ATAC cell IDs collide after the configured normalization."
539
+ )
540
+ membership = membership.where(rna_ids.isin(atac_ids))
541
+ finally:
542
+ atac.file.close()
543
+ layer = data.get("rna_layer", "lognorm")
544
+ if layer is not None and layer not in rna.layers:
545
+ if allow_layer_fallback:
546
+ layer = None
547
+ else:
548
+ raise ValueError(
549
+ f"RNA layer {layer!r} is missing. Use --set data.rna_layer=null when X is normalized."
550
+ )
551
+ symbols = pd.Series(rna.var_names.astype(str), index=rna.var_names)
552
+ symbol_column = data.get("gene_symbol_column")
553
+ if symbol_column:
554
+ if symbol_column not in rna.var:
555
+ raise ValueError(f"RNA var has no gene symbol column {symbol_column!r}.")
556
+ symbols = rna.var[symbol_column].astype(str)
557
+ else:
558
+ lookup = {}
559
+ for key in ("tg_list", "tf_list"):
560
+ if not data.get(key):
561
+ continue
562
+ annot = read_gene_table(resolve_config_path(config, data[key]))
563
+ id_col = next(
564
+ (c for c in ("FBgn_ID", "FBgn", "gene_id", "id") if c in annot), None
565
+ )
566
+ if id_col and "gene_name" in annot:
567
+ current = (
568
+ annot.dropna(subset=[id_col, "gene_name"])
569
+ .set_index(id_col)
570
+ .gene_name.to_dict()
571
+ )
572
+ for gene_id, name in current.items():
573
+ if gene_id in lookup and lookup[gene_id].lower() != name.lower():
574
+ raise ValueError(
575
+ f"Conflicting gene symbols for RNA ID {gene_id!r} in TF/TG annotations."
576
+ )
577
+ lookup[gene_id] = name
578
+ symbols = symbols.map(lambda key: lookup.get(key, key))
579
+ symbols = resolve_symbols(symbols, genes)
580
+ keep = symbols.isin(set(genes)).to_numpy()
581
+ matrix = (rna.X if layer is None else rna.layers[layer])[:, keep]
582
+ mean, frac = {}, {}
583
+ for group in dict.fromkeys(groups):
584
+ cells = np.flatnonzero((membership == group).to_numpy())
585
+ if not len(cells):
586
+ raise ValueError(
587
+ f"No RNA cells match CCC stage group {group!r}; check stage_groups and annotation IDs."
588
+ )
589
+ values = matrix[cells]
590
+ observed = values.data if sparse.issparse(values) else np.asarray(values)
591
+ if not np.isfinite(observed).all() or np.any(observed < 0):
592
+ raise ValueError(
593
+ "CCC expression must be finite, nonnegative normalized counts."
594
+ )
595
+ mean[group] = np.asarray(values.mean(axis=0)).ravel()
596
+ frac[group] = np.asarray((values > 0).mean(axis=0)).ravel()
597
+ names = symbols.iloc[np.flatnonzero(keep)].tolist()
598
+ if len(names) != len(set(names)):
599
+ raise ValueError(
600
+ "RNA gene symbols are not unique; resolve duplicate symbols before CCC."
601
+ )
602
+ order = list(genes)
603
+ mean_frame = pd.DataFrame(mean, index=names).reindex(order, fill_value=0.0)
604
+ mean_frame.attrs["missing_genes"] = sorted(set(order) - set(names))
605
+ mean_frame.attrs["cell_counts"] = {g: int((membership == g).sum()) for g in mean}
606
+ return mean_frame, pd.DataFrame(frac, index=names).reindex(order, fill_value=0.0)
607
+
608
+
609
+ def _pair_scores(
610
+ lr: pd.DataFrame,
611
+ mean: pd.DataFrame,
612
+ frac: pd.DataFrame,
613
+ scores: dict[str, pd.DataFrame],
614
+ nodes: dict[str, list[list[str]]],
615
+ labels: dict[str, list[str]],
616
+ positions: dict[str, np.ndarray],
617
+ section: dict[str, Any],
618
+ native: dict | None = None,
619
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
620
+ pairs, curves = [], []
621
+ ligand_gate = float(section.get("ligand_min_frac", 0.05))
622
+ receptor_gate = float(section.get("receptor_gate", 0.05))
623
+ min_range = float(section.get("dynamic_range_min", 0.1))
624
+ if not (0 <= ligand_gate <= 1 and 0 <= receptor_gate <= 1 and 0 <= min_range <= 1):
625
+ raise ValueError("Expression gates and dynamic_range_min must lie in [0, 1].")
626
+ expr = {key: _collapse(mean, groups) for key, groups in nodes.items()}
627
+ detect = {key: _collapse(frac, groups) for key, groups in nodes.items()}
628
+ centrality = {key: _collapse(frame, nodes[key]) for key, frame in scores.items()}
629
+ directions = section.get("_direction_specs", DIRECTIONS)
630
+ requested = section.get("directions", list(directions))
631
+ for direction in requested:
632
+ if direction not in directions:
633
+ raise ValueError(f"Unknown CCC direction {direction!r}.")
634
+ sender, receiver = directions[direction]
635
+ if sender not in nodes:
636
+ raise ValueError(f"{direction} requires ccc.hub_group.")
637
+ n = len(nodes[receiver])
638
+ receiver_spec = section.get(receiver, {})
639
+ early_count = int(
640
+ receiver_spec.get("early_stage_count", 6 if receiver == "germ" else 4)
641
+ )
642
+ for ligand, receptor in lr[["ligand", "receptor"]].itertuples(
643
+ index=False, name=None
644
+ ):
645
+ if (
646
+ detect[sender].loc[ligand].max() < ligand_gate
647
+ or detect[receiver].loc[receptor].max() < receptor_gate
648
+ or receptor not in centrality[receiver].index
649
+ ):
650
+ continue
651
+ ligand_values = expr[sender].loc[ligand].to_numpy(float)
652
+ ligand_curve = (
653
+ np.full(n, ligand_values[0])
654
+ if sender == "hub"
655
+ else np.interp(
656
+ positions[direction],
657
+ np.arange(1, len(ligand_values) + 1),
658
+ ligand_values,
659
+ )
660
+ )
661
+ gate = detect[receiver].loc[receptor].to_numpy(float) >= receptor_gate
662
+ profiles = {
663
+ "DRAFT": ligand_curve
664
+ * centrality[receiver].loc[receptor].to_numpy(float),
665
+ "LR_expression": ligand_curve
666
+ * expr[receiver].loc[receptor].to_numpy(float),
667
+ }
668
+ for method, tables in (native or {}).items():
669
+ frame = tables.get((ligand, receptor))
670
+ if frame is None:
671
+ profiles[method] = np.zeros(n)
672
+ continue
673
+ matrix = np.array(
674
+ [
675
+ [
676
+ frame.loc[snode, rnode].to_numpy(float).mean()
677
+ for rnode in nodes[receiver]
678
+ ]
679
+ for snode in nodes[sender]
680
+ ]
681
+ )
682
+ profiles[method] = (
683
+ matrix[0]
684
+ if sender == "hub"
685
+ else np.array(
686
+ [
687
+ np.interp(
688
+ positions[direction][i],
689
+ np.arange(1, len(matrix) + 1),
690
+ matrix[:, i],
691
+ )
692
+ for i in range(n)
693
+ ]
694
+ )
695
+ )
696
+ for method, profile in profiles.items():
697
+ curve = profile * gate
698
+ identity = {
699
+ "direction": direction,
700
+ "method": method,
701
+ "ligand": ligand,
702
+ "receptor": receptor,
703
+ }
704
+ pairs.append(
705
+ {
706
+ **identity,
707
+ **timing_call(curve, labels[receiver], early_count, min_range),
708
+ }
709
+ )
710
+ curves.extend(
711
+ {
712
+ **identity,
713
+ "stage_index": i,
714
+ "stage": labels[receiver][i],
715
+ "score": float(value),
716
+ "receptor_detected": bool(gate[i]),
717
+ }
718
+ for i, value in enumerate(curve)
719
+ )
720
+ return pd.DataFrame(pairs), pd.DataFrame(curves)
721
+
722
+
723
+ def _native_baselines(
724
+ config: dict[str, Any], groups: list[str], keys: GeneKeys | None = None
725
+ ) -> tuple[dict, dict]:
726
+ keys = keys or GeneKeys()
727
+ native, provenance = {}, {}
728
+ for method, spec in config.get("ccc", {}).get("baselines", {}).items():
729
+ if method in {"DRAFT", "LR_expression"}:
730
+ raise ValueError(
731
+ "External baseline names must differ from DRAFT and LR_expression."
732
+ )
733
+ path = resolve_config_path(config, spec["edges"])
734
+ data = pd.read_csv(path, sep="\t")
735
+ for column in (spec["sender"], spec["receiver"]):
736
+ data[column] = data[column].astype(str)
737
+ if not set(data[column]) & set(groups):
738
+ raise ValueError(
739
+ f"{method} {column} groups do not overlap the RNA stage groups."
740
+ )
741
+ if "key" in spec:
742
+ pair = (
743
+ data[spec["key"]]
744
+ .astype(str)
745
+ .str.split(spec.get("key_separator", "_"), n=1, expand=True)
746
+ )
747
+ if pair.shape[1] != 2:
748
+ raise ValueError(
749
+ f"Cannot split {method} LR keys; provide ligand/receptor column mappings instead."
750
+ )
751
+ data["__ligand"], data["__receptor"] = pair[0], pair[1]
752
+ else:
753
+ data["__ligand"] = data[spec.get("ligand", "ligand")].astype(str)
754
+ data["__receptor"] = data[spec.get("receptor", "receptor")].astype(str)
755
+ data[spec["score"]] = pd.to_numeric(data[spec["score"]], errors="raise")
756
+ data["__ligand"] = keys.series(data["__ligand"])
757
+ data["__receptor"] = keys.series(data["__receptor"])
758
+ values = data[spec["score"]].to_numpy(float)
759
+ if not np.isfinite(values).all() or np.any(values < 0):
760
+ raise ValueError(f"{method} scores must be finite and nonnegative.")
761
+ native[method] = {
762
+ (ligand, receptor): part.pivot_table(
763
+ index=spec["sender"],
764
+ columns=spec["receiver"],
765
+ values=spec["score"],
766
+ aggfunc="max",
767
+ )
768
+ .reindex(index=groups, columns=groups)
769
+ .fillna(0.0)
770
+ for (ligand, receptor), part in data.groupby(["__ligand", "__receptor"])
771
+ }
772
+ provenance[method] = {
773
+ "path": str(path),
774
+ "sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
775
+ }
776
+ return native, provenance
777
+
778
+
779
+ def literature_benchmark(
780
+ pairs: pd.DataFrame,
781
+ literature: pd.DataFrame,
782
+ seed: int = 2025,
783
+ draws: int = 1000,
784
+ keys: GeneKeys | None = None,
785
+ ) -> pd.DataFrame:
786
+ """Balanced non-literature draws shared by every method of a direction."""
787
+ from sklearn.metrics import roc_auc_score
788
+
789
+ if draws < 1:
790
+ raise ValueError("benchmark_draws must be positive.")
791
+ keys = keys or GeneKeys(pairs.ligand, pairs.receptor)
792
+ literature = literature.copy()
793
+ for col in ("ligand", "receptor"):
794
+ literature[col] = keys.series(literature[col].astype(str))
795
+ keys = set(
796
+ literature[["direction", "ligand", "receptor"]].itertuples(
797
+ index=False, name=None
798
+ )
799
+ )
800
+ rng, results = np.random.default_rng(seed), []
801
+ for direction, data in pairs.groupby("direction", sort=False):
802
+ reference = data[data.method == "DRAFT"].set_index(["ligand", "receptor"])
803
+ positive = np.array([(direction, a, b) in keys for a, b in reference.index])
804
+ ip, ine = np.flatnonzero(positive), np.flatnonzero(~positive)
805
+ enough = len(ip) > 1 and len(ine) >= len(ip)
806
+ samples = (
807
+ [rng.choice(ine, len(ip), replace=False) for _ in range(draws)]
808
+ if enough
809
+ else []
810
+ )
811
+ for method, part in data.groupby("method", sort=False):
812
+ part = part.set_index(["ligand", "receptor"]).reindex(reference.index)
813
+ scores = part.earliness_score.to_numpy(float)
814
+ auc = (
815
+ np.mean(
816
+ [
817
+ roc_auc_score(
818
+ np.r_[np.ones(len(ip)), np.zeros(len(ip))],
819
+ scores[np.r_[ip, sample]],
820
+ )
821
+ for sample in samples
822
+ ]
823
+ )
824
+ if enough
825
+ else np.nan
826
+ )
827
+ results.append(
828
+ {
829
+ "direction": direction,
830
+ "method": method,
831
+ "literature_count": len(ip),
832
+ "other_count": len(ine),
833
+ "literature_early": int(
834
+ (part.status.to_numpy()[ip] == "early").sum()
835
+ ),
836
+ "balanced_auroc": float(auc),
837
+ "draws": draws if enough else 0,
838
+ "status": "evaluated" if enough else "insufficient_reference_pairs",
839
+ }
840
+ )
841
+ return pd.DataFrame(results)
842
+
843
+
844
+ def run_receptor_ccc(config: dict[str, Any]) -> dict[str, Any]:
845
+ from .ccc import _ccc_settings, _set_seed
846
+ from .ccc_config import normalize_ccc_config
847
+
848
+ config = normalize_ccc_config(config)
849
+ settings, section = _ccc_settings(config), config.get("ccc", {})
850
+ aliases = section.get("_lineage_aliases", {})
851
+ directions = section.get("_direction_specs", DIRECTIONS)
852
+ output = ensure_directory(resolve_config_path(config, settings["output_dir"]))
853
+ _set_seed(settings["seed"])
854
+ scores, groups, metadata = {}, {}, {}
855
+ raw = {
856
+ name: _raw_receiver_scores(config, aliases.get(name, name), section.get(name, {}))
857
+ for name in ("soma", "germ")
858
+ }
859
+ # One case rule for both lineages: genes that differ only by case in
860
+ # either gene table (such as Drosophila Tor and tor) stay separate.
861
+ keys = GeneKeys(*(item[3] for item in raw.values()))
862
+ for name, (frame, stage_groups, meta, _) in raw.items():
863
+ scores[name], groups[name], metadata[name] = _keyed_receiver_scores(
864
+ frame, stage_groups, meta, keys, aliases.get(name, name), output
865
+ )
866
+ nodes = {
867
+ key: stage_nodes(value, section.get(key, {}).get("parallel_groups"))
868
+ for key, value in groups.items()
869
+ }
870
+ labels = {
871
+ key: section.get(key, {}).get("stage_labels")
872
+ or [
873
+ "/".join(
874
+ group.removeprefix(str(section.get(key, {}).get("stage_prefix", "")))
875
+ for group in node
876
+ )
877
+ for node in value
878
+ ]
879
+ for key, value in nodes.items()
880
+ }
881
+ if any(len(labels[key]) != len(nodes[key]) for key in nodes):
882
+ raise ValueError(
883
+ "stage_labels must have one label per receiver time point after merging parallel groups."
884
+ )
885
+ if section.get("hub_group"):
886
+ nodes["hub"] = [[str(section["hub_group"])]]
887
+ lr = pd.read_csv(resolve_config_path(config, settings["ccc_csv"]))
888
+ lr = lr.rename(
889
+ columns={"source_genesymbol": "ligand", "target_genesymbol": "receptor"}
890
+ )
891
+ if not {"ligand", "receptor"}.issubset(lr.columns):
892
+ raise ValueError(
893
+ "LR resource requires ligand/receptor or source_genesymbol/target_genesymbol columns."
894
+ )
895
+ lr = lr[["ligand", "receptor"]].dropna().astype(str)
896
+ symbols = pd.unique(lr.to_numpy().ravel())
897
+ ambiguous = sorted(s for s in symbols if keys(s) is None)
898
+ lr = lr.apply(keys.series).dropna().drop_duplicates()
899
+ common_genes = set(scores["soma"].index) & set(scores["germ"].index)
900
+ lr = lr[lr.ligand.isin(common_genes) & lr.receptor.isin(common_genes)]
901
+ if lr.empty:
902
+ raise ValueError("No ligand-receptor pairs overlap both lineage gene sets.")
903
+ genes = keys.request(sorted(set(lr.ligand) | set(lr.receptor)))
904
+ all_groups = [g for value in nodes.values() for node in value for g in node]
905
+ mean, frac = load_group_expression(config, all_groups, genes)
906
+ alignment, alignment_report = network_alignment(config, output)
907
+ soma_at_germ, germ_at_soma = aligned_positions(
908
+ alignment, groups["soma"], nodes["soma"], len(nodes["germ"])
909
+ )
910
+ positions = {
911
+ name: soma_at_germ if (sender, receiver) == ("soma", "germ") else germ_at_soma
912
+ for name, (sender, receiver) in directions.items()
913
+ if sender != "hub"
914
+ }
915
+ native, baseline_provenance = _native_baselines(
916
+ config, list(dict.fromkeys(all_groups)), keys
917
+ )
918
+ pairs, curves = _pair_scores(
919
+ lr, mean, frac, scores, nodes, labels, positions, section, native
920
+ )
921
+ if pairs.empty:
922
+ raise ValueError(
923
+ "No LR candidates pass the expression gates in the requested directions."
924
+ )
925
+ pairs_path, curves_path = output / "ccc_pairs.tsv", output / "ccc_curves.tsv"
926
+ pairs.to_csv(pairs_path, sep="\t", index=False)
927
+ curves.to_csv(curves_path, sep="\t", index=False)
928
+ benchmark_path = None
929
+ if section.get("literature_pairs"):
930
+ literature = pd.read_csv(
931
+ resolve_config_path(config, section["literature_pairs"]), sep="\t"
932
+ )
933
+ benchmark = literature_benchmark(
934
+ pairs,
935
+ literature,
936
+ settings["seed"],
937
+ int(section.get("benchmark_draws", 1000)),
938
+ keys,
939
+ )
940
+ benchmark_path = output / "ccc_benchmark.tsv"
941
+ benchmark.to_csv(benchmark_path, sep="\t", index=False)
942
+ mean.to_csv(output / "group_mean_expression.tsv", sep="\t", index_label="gene_name")
943
+ frac.to_csv(
944
+ output / "group_detection_fraction.tsv", sep="\t", index_label="gene_name"
945
+ )
946
+ pd.DataFrame(
947
+ {
948
+ f"{aliases.get('soma', 'soma')}_stage": labels["soma"],
949
+ f"{aliases.get('germ', 'germ')}_position": germ_at_soma,
950
+ }
951
+ ).to_csv(output / "ccc_stage_alignment.tsv", sep="\t", index=False)
952
+ figures = []
953
+ if section.get("save_fig", True):
954
+ import matplotlib.pyplot as plt
955
+
956
+ for direction, group in curves[curves.method == "DRAFT"].groupby(
957
+ "direction", sort=False
958
+ ):
959
+ matrix = group.pivot(
960
+ index=["ligand", "receptor"], columns="stage_index", values="score"
961
+ )
962
+ values = matrix.to_numpy(float)
963
+ values = values / np.maximum(values.max(axis=1, keepdims=True), 1e-12)
964
+ fig, ax = plt.subplots(figsize=(10, max(3, min(18, len(matrix) * 0.2))))
965
+ ax.imshow(
966
+ values,
967
+ aspect="auto",
968
+ interpolation="nearest",
969
+ cmap="viridis",
970
+ vmin=0,
971
+ vmax=1,
972
+ )
973
+ receiver = directions[direction][1]
974
+ ax.set_xticks(
975
+ np.arange(len(labels[receiver])),
976
+ labels[receiver],
977
+ rotation=45,
978
+ ha="right",
979
+ )
980
+ ax.set_yticks(
981
+ np.arange(len(matrix)),
982
+ [f"{a}–{b}" for a, b in matrix.index],
983
+ fontsize=7,
984
+ )
985
+ ax.set_title(f"{direction}: DRAFT score / pair maximum")
986
+ path = output / f"{direction}_heatmap.png"
987
+ fig.savefig(path, dpi=200, bbox_inches="tight")
988
+ plt.close(fig)
989
+ figures.append(str(path))
990
+ report = {
991
+ "analysis": "ccc",
992
+ "score_mode": "receptor_centrality",
993
+ "output_dir": str(output),
994
+ "chosen_alignment": "DTW",
995
+ "alignment": alignment_report,
996
+ "receiver_scores": {
997
+ aliases.get(key, key): value for key, value in metadata.items()
998
+ },
999
+ "expression_inputs": {
1000
+ "lineages": config.get("data", {}).get("lineages"),
1001
+ "rna_h5ad": config.get("data", {}).get("rna_h5ad"),
1002
+ "atac_h5ad": config.get("data", {}).get("atac_h5ad"),
1003
+ "cell_id_normalization": config.get("data", {}).get(
1004
+ "cell_id_normalization", "sample_suffix"
1005
+ ),
1006
+ "cell_counts": mean.attrs.get("cell_counts", {}),
1007
+ "missing_genes": mean.attrs.get("missing_genes", []),
1008
+ },
1009
+ # LR symbols skipped because they match genes that differ only by case.
1010
+ "lr_symbols_ambiguous_by_case": ambiguous,
1011
+ "method_profile": config.get("method_profile"),
1012
+ "ligand_min_frac": float(section.get("ligand_min_frac", 0.05)),
1013
+ "receptor_gate": float(section.get("receptor_gate", 0.05)),
1014
+ "dynamic_range_min": float(section.get("dynamic_range_min", 0.1)),
1015
+ "stage_nodes": {aliases.get(key, key): value for key, value in nodes.items()},
1016
+ "seed": settings["seed"],
1017
+ "pairs_path": str(pairs_path),
1018
+ "curves_path": str(curves_path),
1019
+ "figures": figures,
1020
+ "baselines": baseline_provenance,
1021
+ "benchmark_path": str(benchmark_path) if benchmark_path else None,
1022
+ "candidates_per_direction": pairs[pairs.method == "DRAFT"]
1023
+ .groupby("direction")
1024
+ .size()
1025
+ .to_dict(),
1026
+ }
1027
+ if aliases:
1028
+ report["lineage_order"] = list(aliases.values())
1029
+ save_checkpoint_metadata(output / "ccc_report.json", report)
1030
+ return report