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,1567 @@
1
+ """Network alignment and cell-cell communication analyses."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import glob
6
+ import os
7
+ import random
8
+ import re
9
+ from collections import defaultdict
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import matplotlib.gridspec as gridspec
14
+ import matplotlib.pyplot as plt
15
+ import numpy as np
16
+ import pandas as pd
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from scipy.stats import entropy
20
+ from sklearn.cluster import KMeans
21
+
22
+ from ..checkpoint import save_checkpoint_metadata
23
+ from ..input_schema import map_gene_names, read_gene_table
24
+ from ..io import strip_copy_suffix
25
+ from ..utils import ensure_directory, load_yaml_config
26
+ from .gene_keys import GeneKeys, clean_symbol
27
+
28
+ try:
29
+ import scipy.sparse as sp
30
+ import scipy.sparse.linalg as spla
31
+
32
+ HAS_SCIPY = True
33
+ except Exception:
34
+ HAS_SCIPY = False
35
+
36
+
37
+ EDGE_GLOBS = ("TF_TG_dense_t*.tsv",)
38
+
39
+
40
+ def _section(config: dict[str, Any], key: str) -> dict[str, Any]:
41
+ value = config.get(key, {})
42
+ return value if isinstance(value, dict) else {}
43
+
44
+
45
+ def _resolve_path(base_dir: Path, value: str | Path) -> Path:
46
+ path = Path(value).expanduser()
47
+ if not path.is_absolute():
48
+ path = base_dir / path
49
+ return path.resolve()
50
+
51
+
52
+ def _resolve_tf_filter_path(
53
+ base_dir: Path,
54
+ configured_value: str | Path,
55
+ fallback_tf_path: Path,
56
+ ) -> tuple[Path, bool]:
57
+ target = _resolve_path(base_dir, configured_value)
58
+ if target.exists():
59
+ return target, False
60
+ return fallback_tf_path.resolve(), True
61
+
62
+
63
+ def _ccc_settings(config: dict[str, Any]) -> dict[str, Any]:
64
+ section = _section(config, "ccc")
65
+ data_cfg = _section(config, "data")
66
+ return {
67
+ "seed": int(section.get("seed", 4122)),
68
+ "output_dir": str(section.get("output_dir", "result/ccc")),
69
+ "network_dir_soma": str(section.get("network_dir_soma", "result/soma/network_dense")),
70
+ "network_dir_germ": str(section.get("network_dir_germ", "result/germ/network_dense")),
71
+ "tg_annot_soma": str(section.get("tg_annot_soma", data_cfg.get("tg_list", "TG.tsv"))),
72
+ "tg_annot_germ": str(section.get("tg_annot_germ", data_cfg.get("tg_list", "TG.tsv"))),
73
+ "tf_annot_soma": str(section.get("tf_annot_soma", data_cfg.get("tf_list", "TF.tsv"))),
74
+ "tf_annot_germ": str(section.get("tf_annot_germ", data_cfg.get("tf_list", "TF.tsv"))),
75
+ "ccc_csv": str(section.get("ccc_csv", "ccc.csv")),
76
+ "tf_filter_path": str(section.get("tf_filter_path", "TF_filtered.tsv")),
77
+ "sigma_time": float(section.get("sigma_time", 0.7)),
78
+ "finger_r": int(section.get("finger_r", 20)),
79
+ "norm_eps": float(section.get("norm_eps", 1e-8)),
80
+ "use_log1p": bool(section.get("use_log1p", False)),
81
+ "use_clip": bool(section.get("use_clip", False)),
82
+ "clip_q": float(section.get("clip_q", 0.99)),
83
+ "warp_fp_w": float(section.get("warp_fp_w", 1.0)),
84
+ "warp_ent_w": float(section.get("warp_ent_w", 100.0)),
85
+ "warp_lam_d2": float(section.get("warp_lam_d2", 100.0)),
86
+ "warp_steps": int(section.get("warp_steps", 2000)),
87
+ "warp_lr": float(section.get("warp_lr", 1e-3)),
88
+ "dtw_fp_w": float(section.get("dtw_fp_w", 1.0)),
89
+ "dtw_ent_w": float(section.get("dtw_ent_w", 0.0)),
90
+ "dtw_band": section.get("dtw_band", 6),
91
+ "dtw_lam_d2": float(section.get("dtw_lam_d2", 1.0)),
92
+ "dtw_n_iter": int(section.get("dtw_n_iter", 50)),
93
+ "alignment_method": str(section.get("alignment_method", "dtw")),
94
+ "min_common_times": int(section.get("min_common_times", 6)),
95
+ "alignment_n_boot": int(section.get("alignment_n_boot", 200)),
96
+ "tie_tol": float(section.get("tie_tol", 1e-6)),
97
+ "prefer_on_tie": str(section.get("prefer_on_tie", "DTW")),
98
+ "corr_thresh": float(section.get("corr_thresh", 0.2)),
99
+ "top_k_prog": int(section.get("top_k_prog", 200)),
100
+ "kmeans_clusters": int(section.get("kmeans_clusters", 3)),
101
+ "kmeans_random_state": int(section.get("kmeans_random_state", 42)),
102
+ "kmeans_n_init": int(section.get("kmeans_n_init", 10)),
103
+ "gap_frac": float(section.get("gap_frac", 0.03)),
104
+ "heatmap_figure": str(section.get("heatmap_figure", "LR_short_axis.png")),
105
+ "peak_table_tsv": str(section.get("peak_table_tsv", "LR_peak_stage_table.tsv")),
106
+ "peak_table_csv": str(section.get("peak_table_csv", "LR_peak_stage_table.csv")),
107
+ "stage_table": str(section.get("stage_table", "stage_boundaries.tsv")),
108
+ "warp_cont_tsv": str(section.get("warp_cont_tsv", "time_warp_continuous_soma_to_germ.tsv")),
109
+ "warp_dtw_tsv": str(section.get("warp_dtw_tsv", "time_warp_dtw_soma_to_germ.tsv")),
110
+ "alignment_bar_figure": str(section.get("alignment_bar_figure", "alignment_method_comparison.png")),
111
+ "alignment_bar_tsv": str(section.get("alignment_bar_tsv", "alignment_method_comparison.tsv")),
112
+ "heatmap_width": float(section.get("heatmap_width", 16.0)),
113
+ "heatmap_height": float(section.get("heatmap_height", 3.5)),
114
+ "group_meta": {
115
+ 0: {"name": "GSC/Gb", "color": "#E64B35"},
116
+ 1: {"name": "Sp-2,4,8,16", "color": "#4DBBD5"},
117
+ 2: {"name": "Spermatocytes", "color": "#00A087"},
118
+ },
119
+ }
120
+
121
+
122
+ def _set_seed(seed: int) -> None:
123
+ os.environ["PYTHONHASHSEED"] = str(seed)
124
+ os.environ["OMP_NUM_THREADS"] = "1"
125
+ os.environ["MKL_NUM_THREADS"] = "1"
126
+ os.environ["OPENBLAS_NUM_THREADS"] = "1"
127
+ os.environ["VECLIB_MAXIMUM_THREADS"] = "1"
128
+ os.environ["NUMEXPR_NUM_THREADS"] = "1"
129
+ random.seed(seed)
130
+ np.random.seed(seed)
131
+ torch.manual_seed(seed)
132
+ if torch.cuda.is_available():
133
+ torch.cuda.manual_seed_all(seed)
134
+ try:
135
+ torch.use_deterministic_algorithms(True, warn_only=True)
136
+ torch.backends.cudnn.deterministic = True
137
+ torch.backends.cudnn.benchmark = False
138
+ torch.backends.cuda.matmul.allow_tf32 = False
139
+ torch.backends.cudnn.allow_tf32 = False
140
+ except Exception:
141
+ pass
142
+
143
+
144
+ def _clean_cols(frame: pd.DataFrame) -> pd.DataFrame:
145
+ output = frame.copy()
146
+ output.columns = (
147
+ output.columns.astype(str)
148
+ .str.replace("\ufeff", "", regex=False)
149
+ .str.strip()
150
+ .str.lower()
151
+ )
152
+ return output
153
+
154
+
155
+ def _clean_gene_names(series: pd.Series) -> pd.Series:
156
+ return (
157
+ series.astype(str)
158
+ .str.replace("\ufeff", "", regex=False)
159
+ .str.strip()
160
+ .str.lower()
161
+ .str.replace(r"^(tf:|tg:)", "", regex=True)
162
+ )
163
+
164
+
165
+ def parse_time_from_filename(path: str | Path) -> float:
166
+ stem = Path(path).stem
167
+ match = re.match(r"^TF_TG_dense_t([-+]?[0-9]*\.?[0-9]+)$", stem)
168
+ if match:
169
+ return float(match.group(1))
170
+ label = stem.split("_")[-1]
171
+ match = re.match(r"([-+]?[0-9]*\.?[0-9]+)", label)
172
+ if not match:
173
+ raise ValueError(f"Cannot parse time from filename: {path}")
174
+ return float(match.group(1))
175
+
176
+
177
+ def list_edge_files(network_dir: str | Path) -> list[Path]:
178
+ directory = Path(network_dir)
179
+ for pattern in EDGE_GLOBS:
180
+ files = [Path(path).resolve() for path in glob.glob(str(directory / pattern))]
181
+ if files:
182
+ return sorted(files, key=parse_time_from_filename)
183
+ raise ValueError(f"No recognizable TF-TG files were found under {directory}.")
184
+
185
+
186
+ def gaussian_smooth_over_time(df: pd.DataFrame, times: np.ndarray, sigma: float) -> pd.DataFrame:
187
+ values = df.to_numpy(dtype=float)
188
+ times = np.asarray(times, dtype=float)
189
+ count = len(times)
190
+ diff = times.reshape(count, 1) - times.reshape(1, count)
191
+ kernel = np.exp(-0.5 * (diff / sigma) ** 2)
192
+ kernel = kernel / kernel.sum(axis=1, keepdims=True)
193
+ smoothed = values @ kernel.T
194
+ return pd.DataFrame(smoothed, index=df.index, columns=df.columns)
195
+
196
+
197
+ def collapse_duplicate_timecols(df: pd.DataFrame, ndigits: int = 6) -> tuple[pd.DataFrame, np.ndarray]:
198
+ output = df.copy()
199
+ output.columns = np.round(np.asarray(output.columns, dtype=float), ndigits)
200
+ output = output.T.groupby(level=0).mean().T
201
+ output = output.loc[:, sorted(output.columns)]
202
+ return output, output.columns.to_numpy(dtype=float)
203
+
204
+
205
+ def load_activity_from_grn(network_dir: str | Path, tg_annot_path: str | Path, prob_col: str = "prob") -> tuple[pd.DataFrame, np.ndarray]:
206
+ tg = read_gene_table(tg_annot_path)
207
+ tg = _clean_cols(tg)
208
+ if "gene_name" not in tg.columns:
209
+ raise ValueError(f"{tg_annot_path} must contain gene_name.")
210
+ if "tg_idx" not in tg.columns:
211
+ tg["tg_idx"] = np.arange(1, len(tg) + 1)
212
+ tg["gene_name"] = _clean_gene_names(tg["gene_name"])
213
+ tg = tg.drop_duplicates(subset=["tg_idx"]).copy()
214
+ tg_idx_to_name = tg.set_index("tg_idx")["gene_name"]
215
+ tg_gene_order = tg["gene_name"].tolist()
216
+
217
+ series_list: list[pd.Series] = []
218
+ times: list[float] = []
219
+ for path in list_edge_files(network_dir):
220
+ frame = pd.read_csv(path, sep="\t")
221
+ frame = _clean_cols(frame)
222
+ if prob_col not in frame.columns:
223
+ raise ValueError(f"{path} is missing {prob_col}. Columns: {list(frame.columns)}")
224
+ if "tg" in frame.columns:
225
+ frame["tg"] = _clean_gene_names(frame["tg"])
226
+ grouped = frame.groupby("tg")[prob_col].sum()
227
+ grouped = grouped.reindex(tg_gene_order, fill_value=0.0)
228
+ grouped.index = tg_gene_order
229
+ elif "tg_idx" in frame.columns:
230
+ frame["tg_idx"] = pd.to_numeric(frame["tg_idx"], errors="coerce").astype("Int64")
231
+ grouped = frame.groupby("tg_idx")[prob_col].sum()
232
+ grouped = grouped.reindex(tg_idx_to_name.index, fill_value=0.0)
233
+ grouped.index = tg_idx_to_name.values
234
+ else:
235
+ raise ValueError(f"{path} must contain tg or tg_idx.")
236
+ series_list.append(grouped)
237
+ times.append(parse_time_from_filename(path))
238
+
239
+ ordered = sorted(zip(times, series_list), key=lambda item: item[0])
240
+ sorted_times = [item[0] for item in ordered]
241
+ matrix = pd.concat([item[1] for item in ordered], axis=1)
242
+ matrix.columns = sorted_times
243
+ matrix.index = _clean_gene_names(pd.Series(matrix.index, index=matrix.index)).values
244
+ matrix = matrix.groupby(matrix.index).sum().sort_index()
245
+ return matrix, np.asarray(sorted_times, dtype=float)
246
+
247
+
248
+ def load_lr_candidates(ccc_csv: str | Path, act_s: pd.DataFrame, act_g: pd.DataFrame) -> pd.DataFrame:
249
+ frame = pd.read_csv(ccc_csv)
250
+ frame["ligand"] = frame["source_genesymbol"].astype(str).str.lower()
251
+ frame["receptor"] = frame["target_genesymbol"].astype(str).str.lower()
252
+ frame = frame[["ligand", "receptor"]].dropna().drop_duplicates()
253
+ frame = frame[frame["ligand"].isin(act_s.index) & frame["receptor"].isin(act_g.index)]
254
+ return frame.reset_index(drop=True)
255
+
256
+
257
+ def _gene_names(series: pd.Series, keep_case: bool) -> pd.Series:
258
+ if keep_case:
259
+ return series.astype(str).map(clean_symbol)
260
+ return _clean_gene_names(series)
261
+
262
+
263
+ def _map_edge_genes(values: pd.Series, genes: pd.DataFrame) -> pd.Series:
264
+ """Map edge genes to IDs by exact spelling, then ignoring case when unique."""
265
+ mapped = map_gene_names(values, genes)
266
+ missing = ~mapped.isin(set(genes.gene_id))
267
+ if missing.any():
268
+ lookup: dict[str, set[str]] = defaultdict(set)
269
+ for column in ("gene_id", "gene_name"):
270
+ for value, gene_id in zip(genes[column], genes.gene_id):
271
+ lookup[str(value).lower()].add(gene_id)
272
+ unique = {key: next(iter(ids)) for key, ids in lookup.items() if len(ids) == 1}
273
+ lowered = values.astype(str).map(strip_copy_suffix).str.lower()
274
+ mapped = mapped.where(~missing, lowered.map(unique))
275
+ return mapped
276
+
277
+
278
+ def _read_annot(path: str | Path, idx_col: str, keep_case: bool = False) -> pd.DataFrame:
279
+ frame = _clean_cols(read_gene_table(path))
280
+ if idx_col not in frame.columns:
281
+ frame[idx_col] = np.arange(1, len(frame) + 1)
282
+ frame[idx_col] = pd.to_numeric(frame[idx_col], errors="coerce").astype(int)
283
+ frame = frame.loc[frame["gene_name"].notna()].copy()
284
+ frame["gene_name"] = _gene_names(frame["gene_name"], keep_case)
285
+ frame["gene_id"] = _gene_names(frame["gene_id"], keep_case)
286
+ return (
287
+ frame[[idx_col, "gene_id", "gene_name"]]
288
+ .drop_duplicates(subset=[idx_col])
289
+ .set_index(idx_col)
290
+ .sort_index()
291
+ )
292
+
293
+
294
+ def _read_edge_file(path: str | Path, prob_col: str = "prob", keep_case: bool = False) -> pd.DataFrame:
295
+ frame = pd.read_csv(path, sep="\t")
296
+ frame = _clean_cols(frame)
297
+ if prob_col not in frame.columns:
298
+ for candidate in ["score", "weight", "probability", "p"]:
299
+ if candidate in frame.columns:
300
+ frame = frame.rename(columns={candidate: prob_col})
301
+ break
302
+ if prob_col not in frame.columns:
303
+ raise ValueError(f"{path} is missing {prob_col}.")
304
+ if {"tf", "tg"}.issubset(frame.columns):
305
+ output = frame[["tf", "tg", prob_col]].copy()
306
+ output["tf"] = _gene_names(output["tf"], keep_case)
307
+ output["tg"] = _gene_names(output["tg"], keep_case)
308
+ output[prob_col] = pd.to_numeric(output[prob_col], errors="coerce").astype(float)
309
+ return output
310
+ if {"tf_idx", "tg_idx"}.issubset(frame.columns):
311
+ output = frame[["tf_idx", "tg_idx", prob_col]].copy()
312
+ output["tf_idx"] = pd.to_numeric(output["tf_idx"], errors="coerce").astype(int)
313
+ output["tg_idx"] = pd.to_numeric(output["tg_idx"], errors="coerce").astype(int)
314
+ output[prob_col] = pd.to_numeric(output[prob_col], errors="coerce").astype(float)
315
+ return output
316
+ raise ValueError(f"{path} must contain TF/TG or tf_idx/tg_idx.")
317
+
318
+
319
+ def _load_network_series(
320
+ network_dir: str | Path,
321
+ tf_annot_path: str | Path,
322
+ tg_annot_path: str | Path,
323
+ prob_col: str = "prob",
324
+ keep_case: bool = False,
325
+ ) -> tuple[np.ndarray, list[Any], list[str], list[str]]:
326
+ """Load a network series with TF and TG names in annotation row order.
327
+
328
+ Names match edges by exact spelling first, so genes that differ only by case
329
+ stay separate. Returned names keep their case with keep_case; otherwise
330
+ they are lowercase except where case separates genes.
331
+ """
332
+ tf = _read_annot(tf_annot_path, "tf_idx", keep_case=True)
333
+ tg = _read_annot(tg_annot_path, "tg_idx", keep_case=True)
334
+ tf_id_to_row = {name: idx for idx, name in enumerate(tf["gene_id"].tolist())}
335
+ tg_id_to_col = {name: idx for idx, name in enumerate(tg["gene_id"].tolist())}
336
+ tf_idx_to_row = {idx: pos for pos, idx in enumerate(tf.index.tolist())}
337
+ tg_idx_to_col = {idx: pos for pos, idx in enumerate(tg.index.tolist())}
338
+
339
+ mats: list[Any] = []
340
+ times: list[float] = []
341
+ for path in list_edge_files(network_dir):
342
+ time_value = parse_time_from_filename(path)
343
+ edges = _read_edge_file(path, prob_col=prob_col, keep_case=True)
344
+ original_count = len(edges)
345
+ if {"tf", "tg"}.issubset(edges.columns):
346
+ edges["tf"] = _map_edge_genes(edges["tf"], tf)
347
+ edges["tg"] = _map_edge_genes(edges["tg"], tg)
348
+ edges = edges[edges["tf"].isin(tf_id_to_row) & edges["tg"].isin(tg_id_to_col)].copy()
349
+ if original_count and edges.empty:
350
+ raise ValueError(f"{path}: no edge names overlap the TF/TG annotations.")
351
+ edges = edges.groupby(["tf", "tg"], as_index=False)[prob_col].sum()
352
+ rows = edges["tf"].map(tf_id_to_row).to_numpy(dtype=int)
353
+ cols = edges["tg"].map(tg_id_to_col).to_numpy(dtype=int)
354
+ vals = edges[prob_col].to_numpy(dtype=np.float32)
355
+ else:
356
+ edges = edges[edges["tf_idx"].isin(tf_idx_to_row) & edges["tg_idx"].isin(tg_idx_to_col)].copy()
357
+ if original_count and edges.empty:
358
+ raise ValueError(f"{path}: no edge indices overlap the TF/TG annotations.")
359
+ edges = edges.groupby(["tf_idx", "tg_idx"], as_index=False)[prob_col].sum()
360
+ rows = edges["tf_idx"].map(tf_idx_to_row).to_numpy(dtype=int)
361
+ cols = edges["tg_idx"].map(tg_idx_to_col).to_numpy(dtype=int)
362
+ vals = edges[prob_col].to_numpy(dtype=np.float32)
363
+ shape = (len(tf), len(tg))
364
+ if not np.isfinite(vals).all() or np.any(vals < 0):
365
+ raise ValueError(f"{path}: weighted adjacency requires finite nonnegative edge weights.")
366
+ if HAS_SCIPY:
367
+ matrix = sp.coo_matrix((vals, (rows, cols)), shape=shape).tocsr()
368
+ matrix.sum_duplicates()
369
+ matrix.eliminate_zeros()
370
+ else:
371
+ matrix = np.zeros(shape, dtype=np.float32)
372
+ np.add.at(matrix, (rows, cols), vals)
373
+ mats.append(matrix)
374
+ times.append(time_value)
375
+
376
+ if len(times) < 2:
377
+ raise ValueError(f"Too few timepoints were loaded from {network_dir}.")
378
+ order = np.argsort(times)
379
+ sorted_times = np.asarray(times, dtype=float)[order]
380
+ sorted_mats = [mats[idx] for idx in order]
381
+ tf_names, tg_names = tf["gene_name"].tolist(), tg["gene_name"].tolist()
382
+ if not keep_case:
383
+ keys = GeneKeys(tf_names, tg_names)
384
+ tf_names, tg_names = keys.keys(tf_names), keys.keys(tg_names)
385
+ return sorted_times, sorted_mats, tf_names, tg_names
386
+
387
+
388
+ def _restrict_to_common(mats: list[Any], tf_names: list[str], tg_names: list[str], tf_common: list[str], tg_common: list[str]) -> list[Any]:
389
+ tf_idx = {name: idx for idx, name in enumerate(tf_names)}
390
+ tg_idx = {name: idx for idx, name in enumerate(tg_names)}
391
+ row_idx = np.asarray([tf_idx[name] for name in tf_common], dtype=int)
392
+ col_idx = np.asarray([tg_idx[name] for name in tg_common], dtype=int)
393
+ output: list[Any] = []
394
+ for matrix in mats:
395
+ if HAS_SCIPY:
396
+ output.append(matrix[row_idx, :][:, col_idx].tocsr())
397
+ else:
398
+ output.append(matrix[np.ix_(row_idx, col_idx)])
399
+ return output
400
+
401
+
402
+ def _apply_log_clip(matrix: Any, settings: dict[str, Any]) -> Any:
403
+ if settings["use_log1p"]:
404
+ if HAS_SCIPY:
405
+ output = matrix.copy()
406
+ output.data = np.log1p(output.data)
407
+ matrix = output
408
+ else:
409
+ matrix = np.log1p(matrix)
410
+ if settings["use_clip"]:
411
+ if HAS_SCIPY:
412
+ q_value = np.quantile(matrix.data, settings["clip_q"]) if matrix.nnz > 0 else 0.0
413
+ output = matrix.copy()
414
+ output.data = np.minimum(output.data, q_value)
415
+ matrix = output
416
+ else:
417
+ q_value = np.quantile(matrix, settings["clip_q"])
418
+ matrix = np.minimum(matrix, q_value)
419
+ return matrix
420
+
421
+
422
+ def _normalize_bipartite(matrix: Any, settings: dict[str, Any]) -> Any:
423
+ matrix = _apply_log_clip(matrix, settings)
424
+ eps = settings["norm_eps"]
425
+ if HAS_SCIPY:
426
+ tf_deg = np.asarray(matrix.sum(axis=1)).ravel() + eps
427
+ tg_deg = np.asarray(matrix.sum(axis=0)).ravel() + eps
428
+ d_tf = sp.diags(1.0 / np.sqrt(tf_deg))
429
+ d_tg = sp.diags(1.0 / np.sqrt(tg_deg))
430
+ output = (d_tf @ matrix @ d_tg).tocsr()
431
+ output.eliminate_zeros()
432
+ return output
433
+ tf_deg = matrix.sum(axis=1) + eps
434
+ tg_deg = matrix.sum(axis=0) + eps
435
+ return (matrix / np.sqrt(tf_deg[:, None])) / np.sqrt(tg_deg[None, :])
436
+
437
+
438
+ def _top_r_svals(matrix: Any, r: int) -> np.ndarray:
439
+ if r < 1:
440
+ raise ValueError("finger_r must be positive.")
441
+ if r >= min(matrix.shape):
442
+ dense = matrix.toarray() if HAS_SCIPY else matrix
443
+ values = np.linalg.svd(dense, compute_uv=False)[:r].astype(np.float32)
444
+ return np.pad(values, (0, max(0, r - len(values))))
445
+ if HAS_SCIPY:
446
+ k = min(r, min(matrix.shape) - 1)
447
+ if k <= 0:
448
+ return np.zeros(r, dtype=np.float32)
449
+ # Double precision and a fixed start vector give the same values on every call.
450
+ matrix = matrix.astype(np.float64)
451
+ v0 = np.random.default_rng(0).standard_normal(min(matrix.shape))
452
+ try:
453
+ values = spla.svds(
454
+ matrix, k=k, which="LM", return_singular_vectors=False, v0=v0
455
+ )
456
+ values = np.sort(values)[::-1].astype(np.float32)
457
+ except Exception:
458
+ dense = matrix.toarray()
459
+ values = np.linalg.svd(dense, compute_uv=False)[:k].astype(np.float32)
460
+ else:
461
+ values = np.linalg.svd(matrix, compute_uv=False)[: min(r, min(matrix.shape))].astype(np.float32)
462
+ if len(values) < r:
463
+ values = np.pad(values, (0, r - len(values))).astype(np.float32)
464
+ return values[:r]
465
+
466
+
467
+ def _tf_centrality(matrix: Any) -> np.ndarray:
468
+ if HAS_SCIPY:
469
+ return np.asarray(matrix.sum(axis=1)).ravel().astype(np.float32)
470
+ return matrix.sum(axis=1).astype(np.float32)
471
+
472
+
473
+ def _zscore_cols(
474
+ values: np.ndarray, eps: float = 1e-12, rtol: float = 1e-6
475
+ ) -> np.ndarray:
476
+ """Standardize columns; columns that are constant up to rounding become zero.
477
+
478
+ The leading singular value of a degree-normalized network is 1 at every
479
+ stage. Its float32 rounding differences are not standardized into a feature.
480
+ """
481
+ mean = values.mean(axis=0, keepdims=True)
482
+ std = values.std(axis=0, keepdims=True)
483
+ constant = std <= np.maximum(eps, rtol * np.abs(mean))
484
+ return np.where(constant, 0.0, (values - mean) / np.where(constant, 1.0, std))
485
+
486
+
487
+ def _zscore_rows(values: np.ndarray, eps: float = 1e-12) -> np.ndarray:
488
+ mean = values.mean(axis=1, keepdims=True)
489
+ std = values.std(axis=1, keepdims=True)
490
+ std[std < eps] = 1.0
491
+ return (values - mean) / std
492
+
493
+
494
+ def _normalize_time_to_01(values: np.ndarray) -> np.ndarray:
495
+ values = np.asarray(values, dtype=float)
496
+ return (values - values.min()) / (values.max() - values.min() + 1e-12)
497
+
498
+
499
+ def _get_unique_df(df: pd.DataFrame) -> pd.DataFrame:
500
+ output = df.copy()
501
+ output.columns = [float(column) for column in output.columns]
502
+ output = output.T.groupby(level=0).mean().T
503
+ output = output.loc[:, sorted(output.columns)]
504
+ return output
505
+
506
+
507
+ def _calculate_shannon_entropy(values: np.ndarray) -> float:
508
+ values = np.asarray(values, dtype=float).reshape(-1)
509
+ if values.size == 0:
510
+ return 0.0
511
+ if np.min(values) < 0:
512
+ values = values - np.min(values)
513
+ total = values.sum()
514
+ if total <= 0:
515
+ return 0.0
516
+ probs = values / total
517
+ return float(entropy(probs))
518
+
519
+
520
+ def _entropy_curve(df: pd.DataFrame) -> tuple[np.ndarray, np.ndarray]:
521
+ cols = np.asarray([float(column) for column in df.columns], dtype=float)
522
+ values = np.asarray([_calculate_shannon_entropy(df[column].values) for column in cols], dtype=float)
523
+ return cols, values
524
+
525
+
526
+ def _norm01(values: np.ndarray) -> np.ndarray:
527
+ values = np.asarray(values, dtype=float)
528
+ v_min = np.min(values)
529
+ v_max = np.max(values)
530
+ if v_max - v_min < 1e-12:
531
+ return np.zeros_like(values, dtype=float)
532
+ return (values - v_min) / (v_max - v_min)
533
+
534
+
535
+ def _zscore_np(values: np.ndarray) -> np.ndarray:
536
+ values = np.asarray(values, dtype=float)
537
+ return (values - values.mean()) / (values.std() + 1e-12)
538
+
539
+
540
+ def _load_filtered_tfs(path: str | Path) -> list[str] | None:
541
+ if not Path(path).exists():
542
+ return None
543
+ frame = pd.read_csv(path, sep="\t").fillna("")
544
+ frame.columns = frame.columns.astype(str).str.strip().str.lower()
545
+ if "gene_name" not in frame.columns:
546
+ if frame.shape[1] == 1:
547
+ col = str(frame.columns[0]).strip().lower()
548
+ if frame.empty and col:
549
+ frame = pd.DataFrame({"gene_name": [col]})
550
+ else:
551
+ frame = frame.rename(columns={frame.columns[0]: "gene_name"})
552
+ else:
553
+ return None
554
+ frame["gene_name"] = frame["gene_name"].astype(str).map(clean_symbol)
555
+ if "is_tf" in frame.columns:
556
+ keep = frame["is_tf"].astype(str).str.strip().str.lower().isin(["true", "1", "t", "yes"])
557
+ frame = frame.loc[keep].copy()
558
+ return sorted(set(frame["gene_name"]))
559
+
560
+
561
+ def prepare_entropy_on_net_grid(
562
+ c_s_z: pd.DataFrame,
563
+ c_g_z: pd.DataFrame,
564
+ tau_s_net: np.ndarray,
565
+ tau_g_net: np.ndarray,
566
+ tf_filter_path: str | Path,
567
+ ) -> tuple[np.ndarray, np.ndarray]:
568
+ soma_df = _get_unique_df(c_s_z)
569
+ germ_df = _get_unique_df(c_g_z)
570
+ # TFs match without regard to case unless case separates them (H and h).
571
+ keys = GeneKeys(soma_df.index, germ_df.index)
572
+ soma_df.index = keys.keys(soma_df.index)
573
+ germ_df.index = keys.keys(germ_df.index)
574
+ common_tfs = sorted(set(soma_df.index) & set(germ_df.index))
575
+ if not common_tfs:
576
+ raise ValueError("C_s_z and C_g_z do not share any TFs.")
577
+ soma_df = soma_df.loc[common_tfs]
578
+ germ_df = germ_df.loc[common_tfs]
579
+ filtered_tfs = _load_filtered_tfs(tf_filter_path)
580
+ if filtered_tfs is not None:
581
+ keep = sorted(set(keys.keys(filtered_tfs)) & set(common_tfs))
582
+ if keep:
583
+ soma_df = soma_df.loc[keep]
584
+ germ_df = germ_df.loc[keep]
585
+ t_s_raw, ent_s = _entropy_curve(soma_df)
586
+ t_g_raw, ent_g = _entropy_curve(germ_df)
587
+ t_s_norm = _norm01(t_s_raw)
588
+ t_g_norm = _norm01(t_g_raw)
589
+ tau_s_net = np.asarray(tau_s_net, dtype=float)
590
+ tau_g_net = np.asarray(tau_g_net, dtype=float)
591
+ ent_s_on_s_net = np.interp(tau_s_net, t_s_norm, ent_s)
592
+ ent_g_on_g_net = np.interp(tau_g_net, t_g_norm, ent_g)
593
+ return _zscore_np(ent_s_on_s_net), _zscore_np(ent_g_on_g_net)
594
+
595
+
596
+ def interp_df_over_time(df: pd.DataFrame, times: np.ndarray, query_times: np.ndarray) -> pd.DataFrame:
597
+ times = np.asarray(times, dtype=float)
598
+ query_times = np.asarray(query_times, dtype=float)
599
+ order = np.argsort(times)
600
+ times = times[order]
601
+ values = df.values[:, order]
602
+ query_clip = np.clip(query_times, times[0], times[-1])
603
+ idx = np.searchsorted(times, query_clip, side="left")
604
+ idx = np.clip(idx, 1, len(times) - 1)
605
+ t0, t1 = times[idx - 1], times[idx]
606
+ y0, y1 = values[:, idx - 1], values[:, idx]
607
+ weight = (query_clip - t0) / (t1 - t0 + 1e-12)
608
+ out = y0 + (y1 - y0) * weight.reshape(1, -1)
609
+ return pd.DataFrame(out, index=df.index, columns=query_times)
610
+
611
+
612
+ def interp_df_time(df: pd.DataFrame, times: np.ndarray, query_times: np.ndarray) -> pd.DataFrame:
613
+ return interp_df_over_time(df, times, query_times)
614
+
615
+
616
+ def learn_monotone_warp_continuous(
617
+ tau_s: np.ndarray,
618
+ fs: np.ndarray,
619
+ tau_g: np.ndarray,
620
+ fg: np.ndarray,
621
+ ent_s: np.ndarray | None = None,
622
+ ent_g: np.ndarray | None = None,
623
+ fp_w: float = 1.0,
624
+ ent_w: float = 0.0,
625
+ lam_d2: float = 1e-2,
626
+ steps: int = 2000,
627
+ lr: float = 1e-3,
628
+ ) -> np.ndarray:
629
+ device = "cuda" if torch.cuda.is_available() else "cpu"
630
+ tau_g_t = torch.tensor(tau_g, dtype=torch.float32, device=device)
631
+ fs_t = torch.tensor(fs, dtype=torch.float32, device=device)
632
+ fg_t = torch.tensor(fg, dtype=torch.float32, device=device)
633
+ ent_s_t = None if ent_s is None else torch.tensor(ent_s, dtype=torch.float32, device=device)
634
+ ent_g_t = None if ent_g is None else torch.tensor(ent_g, dtype=torch.float32, device=device)
635
+
636
+ def zscore_torch(values: torch.Tensor) -> torch.Tensor:
637
+ return (values - values.mean()) / (values.std(unbiased=False) + 1e-12)
638
+
639
+ def pearson_corr_torch(left: torch.Tensor, right: torch.Tensor) -> torch.Tensor:
640
+ left = left - left.mean()
641
+ right = right - right.mean()
642
+ num = (left * right).mean()
643
+ den = left.std(unbiased=False) * right.std(unbiased=False) + 1e-12
644
+ return num / den
645
+
646
+ def interp_g(query: torch.Tensor) -> torch.Tensor:
647
+ idx = torch.searchsorted(tau_g_t, query).clamp(1, len(tau_g_t) - 1)
648
+ u0, u1 = tau_g_t[idx - 1], tau_g_t[idx]
649
+ y0, y1 = fg_t[idx - 1], fg_t[idx]
650
+ weight = (query - u0) / (u1 - u0 + 1e-12)
651
+ return y0 + (y1 - y0) * weight.unsqueeze(-1)
652
+
653
+ def interp_ent_g(query: torch.Tensor) -> torch.Tensor:
654
+ idx = torch.searchsorted(tau_g_t, query).clamp(1, len(tau_g_t) - 1)
655
+ u0, u1 = tau_g_t[idx - 1], tau_g_t[idx]
656
+ y0, y1 = ent_g_t[idx - 1], ent_g_t[idx]
657
+ weight = (query - u0) / (u1 - u0 + 1e-12)
658
+ return y0 + (y1 - y0) * weight
659
+
660
+ count = len(tau_s)
661
+ alpha = torch.nn.Parameter(torch.zeros(count - 1, device=device))
662
+ optimizer = torch.optim.Adam([alpha], lr=lr)
663
+ eps = 1e-6
664
+ for _ in range(steps):
665
+ delta = F.softplus(alpha) + eps
666
+ warp = torch.cat([torch.zeros(1, device=device), torch.cumsum(delta, dim=0)], dim=0)
667
+ warp = warp / (warp[-1] + 1e-12)
668
+ g_at_w = interp_g(warp)
669
+ fit_fp = ((fs_t - g_at_w) ** 2).sum(dim=1).mean()
670
+ if ent_s_t is not None and ent_g_t is not None:
671
+ ent_g_at_w = interp_ent_g(warp)
672
+ ent_loss = 1.0 - pearson_corr_torch(zscore_torch(ent_s_t), zscore_torch(ent_g_at_w))
673
+ else:
674
+ ent_loss = torch.tensor(0.0, dtype=torch.float32, device=device)
675
+ if count >= 3:
676
+ smooth_d2 = ((warp[2:] - 2 * warp[1:-1] + warp[:-2]) ** 2).mean()
677
+ else:
678
+ smooth_d2 = torch.tensor(0.0, dtype=torch.float32, device=device)
679
+ loss = fp_w * fit_fp + ent_w * ent_loss + lam_d2 * smooth_d2
680
+ optimizer.zero_grad()
681
+ loss.backward()
682
+ optimizer.step()
683
+ return warp.detach().cpu().numpy()
684
+
685
+
686
+ def isotonic_increasing(values: np.ndarray) -> np.ndarray:
687
+ values = np.asarray(values, dtype=float).reshape(-1)
688
+ n0 = len(values)
689
+ levels = values.copy()
690
+ weights = np.ones(n0, dtype=float)
691
+ idx = 0
692
+ while idx < len(levels) - 1:
693
+ if levels[idx] > levels[idx + 1]:
694
+ new_level = (levels[idx] * weights[idx] + levels[idx + 1] * weights[idx + 1]) / (weights[idx] + weights[idx + 1])
695
+ levels[idx] = new_level
696
+ weights[idx] = weights[idx] + weights[idx + 1]
697
+ levels = np.delete(levels, idx + 1)
698
+ weights = np.delete(weights, idx + 1)
699
+ if idx > 0:
700
+ idx -= 1
701
+ else:
702
+ idx += 1
703
+ output = np.empty(n0, dtype=float)
704
+ start = 0
705
+ for level, weight in zip(levels, weights):
706
+ width = int(round(weight))
707
+ output[start : start + width] = level
708
+ start += width
709
+ return output
710
+
711
+
712
+ def smooth_warp_d2_monotone(
713
+ warp0: np.ndarray,
714
+ lam: float = 10.0,
715
+ n_iter: int = 3,
716
+ clip01: bool = True,
717
+ enforce_endpoints: bool = True,
718
+ ) -> np.ndarray:
719
+ warp0 = np.asarray(warp0, dtype=float).reshape(-1)
720
+ n = len(warp0)
721
+ if n < 3 or lam <= 0:
722
+ output = warp0.copy()
723
+ if clip01:
724
+ output = np.clip(output, 0.0, 1.0)
725
+ return isotonic_increasing(output)
726
+
727
+ d2 = np.zeros((n - 2, n), dtype=float)
728
+ for idx in range(n - 2):
729
+ d2[idx, idx] = 1.0
730
+ d2[idx, idx + 1] = -2.0
731
+ d2[idx, idx + 2] = 1.0
732
+ lap = d2.T @ d2
733
+
734
+ output = warp0.copy()
735
+ for _ in range(n_iter):
736
+ a_mat = np.eye(n) + lam * lap
737
+ b_vec = warp0.copy()
738
+ if enforce_endpoints:
739
+ a_mat[0, :] = 0.0
740
+ a_mat[0, 0] = 1.0
741
+ b_vec[0] = warp0[0]
742
+ a_mat[-1, :] = 0.0
743
+ a_mat[-1, -1] = 1.0
744
+ b_vec[-1] = warp0[-1]
745
+ output = np.linalg.solve(a_mat, b_vec)
746
+ if clip01:
747
+ output = np.clip(output, 0.0, 1.0)
748
+ output = isotonic_increasing(output)
749
+ if enforce_endpoints:
750
+ output[0] = warp0[0]
751
+ output[-1] = warp0[-1]
752
+ output = isotonic_increasing(output)
753
+ if output[-1] > 1e-12:
754
+ output = output / output[-1]
755
+ return output
756
+
757
+
758
+ def dtw_path(cost: np.ndarray, band: int | None = None) -> list[tuple[int, int]]:
759
+ cost = np.asarray(cost, dtype=float)
760
+ if cost.ndim != 2 or not cost.size or not np.isfinite(cost).all():
761
+ raise ValueError("DTW requires a nonempty finite cost matrix.")
762
+ if band is not None and band < 0:
763
+ raise ValueError("DTW band must be nonnegative or null.")
764
+ t_s, t_g = cost.shape
765
+ inf = np.inf
766
+ dp = np.full((t_s + 1, t_g + 1), inf, dtype=np.float64)
767
+ bt = np.zeros((t_s + 1, t_g + 1, 2), dtype=np.int32)
768
+ dp[0, 0] = 0.0
769
+ for i in range(1, t_s + 1):
770
+ j_start, j_end = 1, t_g
771
+ if band is not None:
772
+ j_center = int(round(i * t_g / t_s))
773
+ j_start = max(1, j_center - band)
774
+ j_end = min(t_g, j_center + band)
775
+ for j in range(j_start, j_end + 1):
776
+ current = cost[i - 1, j - 1]
777
+ prevs = [dp[i - 1, j], dp[i, j - 1], dp[i - 1, j - 1]]
778
+ choice = int(np.argmin(prevs))
779
+ if choice == 0:
780
+ dp[i, j] = prevs[0] + current
781
+ bt[i, j] = (i - 1, j)
782
+ elif choice == 1:
783
+ dp[i, j] = prevs[1] + current
784
+ bt[i, j] = (i, j - 1)
785
+ else:
786
+ dp[i, j] = prevs[2] + current
787
+ bt[i, j] = (i - 1, j - 1)
788
+ if not np.isfinite(dp[t_s, t_g]):
789
+ raise ValueError("No DTW path connects both endpoints within the requested band.")
790
+ i, j = t_s, t_g
791
+ path: list[tuple[int, int]] = []
792
+ while i > 0 or j > 0:
793
+ path.append((i - 1, j - 1))
794
+ i2, j2 = bt[i, j]
795
+ i, j = int(i2), int(j2)
796
+ if i == 0 and j == 0:
797
+ break
798
+ path.reverse()
799
+ return path
800
+
801
+
802
+ def _canon_timecols(df: pd.DataFrame, ndigits: int = 6) -> pd.DataFrame:
803
+ output = df.copy()
804
+ output.columns = np.round(np.asarray(output.columns, dtype=float), ndigits)
805
+ output = output.T.groupby(level=0).mean().T
806
+ cols = np.asarray(sorted(output.columns), dtype=float)
807
+ return output.loc[:, cols]
808
+
809
+
810
+ def _shannon_entropy(values: np.ndarray, eps: float = 1e-12) -> float:
811
+ values = np.asarray(values, float).reshape(-1)
812
+ if values.size == 0:
813
+ return 0.0
814
+ if np.min(values) < 0:
815
+ values = values - np.min(values)
816
+ total = float(np.sum(values))
817
+ if total <= 0:
818
+ return 0.0
819
+ probs = values / (total + eps)
820
+ probs = probs[probs > 0]
821
+ return float(-(probs * np.log(probs + eps)).sum())
822
+
823
+
824
+ def _pearson_corr(left: np.ndarray, right: np.ndarray, eps: float = 1e-12) -> float:
825
+ left = np.asarray(left, float).reshape(-1)
826
+ right = np.asarray(right, float).reshape(-1)
827
+ if left.size < 2 or right.size < 2:
828
+ return 0.0
829
+ left = left - left.mean()
830
+ right = right - right.mean()
831
+ den = (np.linalg.norm(left) * np.linalg.norm(right)) + eps
832
+ return float(left.dot(right) / den)
833
+
834
+
835
+ def entropy_corr_score(
836
+ soma_df: pd.DataFrame,
837
+ other_df: pd.DataFrame,
838
+ min_common_times: int = 6,
839
+ n_boot: int = 200,
840
+ seed: int = 0,
841
+ ) -> tuple[float, int]:
842
+ common_times = sorted(set(soma_df.columns) & set(other_df.columns))
843
+ count = len(common_times)
844
+ if count < min_common_times:
845
+ return float("nan"), count
846
+ s_curve = np.asarray([_shannon_entropy(soma_df[t].values) for t in common_times], dtype=float)
847
+ o_curve = np.asarray([_shannon_entropy(other_df[t].values) for t in common_times], dtype=float)
848
+ if n_boot <= 1:
849
+ return _pearson_corr(s_curve, o_curve), count
850
+ rng = np.random.default_rng(seed)
851
+ idx = np.arange(count)
852
+ boots = np.empty(n_boot, float)
853
+ for boot_idx in range(n_boot):
854
+ sample = rng.choice(idx, size=count, replace=True)
855
+ boots[boot_idx] = _pearson_corr(s_curve[sample], o_curve[sample])
856
+ return float(np.nanmean(boots)), count
857
+
858
+
859
+ def pick_alignment_method(
860
+ c_s_z: pd.DataFrame,
861
+ c_g_cont_on_s: pd.DataFrame,
862
+ c_g_dtw_on_s: pd.DataFrame,
863
+ min_common_times: int = 6,
864
+ n_boot: int = 200,
865
+ seed_cont: int = 1,
866
+ seed_dtw: int = 2,
867
+ tie_tol: float = 1e-6,
868
+ prefer_on_tie: str = "DTW",
869
+ ) -> tuple[str, dict[str, Any]]:
870
+ soma_df = _canon_timecols(c_s_z)
871
+ cont_df = _canon_timecols(c_g_cont_on_s)
872
+ dtw_df = _canon_timecols(c_g_dtw_on_s)
873
+ ent_cont, n_cont = entropy_corr_score(soma_df, cont_df, min_common_times=min_common_times, n_boot=n_boot, seed=seed_cont)
874
+ ent_dtw, n_dtw = entropy_corr_score(soma_df, dtw_df, min_common_times=min_common_times, n_boot=n_boot, seed=seed_dtw)
875
+ if not (np.isfinite(ent_cont) and np.isfinite(ent_dtw)):
876
+ raise ValueError(f"Invalid entropy corr values: cont={ent_cont}, dtw={ent_dtw}")
877
+ gap = ent_cont - ent_dtw
878
+ if abs(gap) <= tie_tol:
879
+ chosen = prefer_on_tie
880
+ else:
881
+ chosen = "Warping" if ent_cont > ent_dtw else "DTW"
882
+ metrics = {
883
+ "entropy_corr_cont": float(ent_cont),
884
+ "entropy_corr_dtw": float(ent_dtw),
885
+ "n_common_times_cont": int(n_cont),
886
+ "n_common_times_dtw": int(n_dtw),
887
+ "gap_cont_minus_dtw": float(gap),
888
+ "chosen_method": str(chosen),
889
+ "prefer_on_tie": str(prefer_on_tie),
890
+ "tie_tol": float(tie_tol),
891
+ }
892
+ return chosen, metrics
893
+
894
+
895
+ def _build_alignment_comparison_outputs(
896
+ output_dir: Path,
897
+ settings: dict[str, Any],
898
+ chosen_method: str,
899
+ metrics: dict[str, Any],
900
+ ) -> dict[str, Any]:
901
+ rows = [
902
+ {
903
+ "method": "Linear",
904
+ "entropy_corr": float(metrics["entropy_corr_linear"]),
905
+ "n_common_times": int(metrics["n_common_times_linear"]),
906
+ "used_for_choice": False,
907
+ "chosen": False,
908
+ },
909
+ {
910
+ "method": "Warping",
911
+ "entropy_corr": float(metrics["entropy_corr_cont"]),
912
+ "n_common_times": int(metrics["n_common_times_cont"]),
913
+ "used_for_choice": True,
914
+ "chosen": str(chosen_method) == "Warping",
915
+ },
916
+ {
917
+ "method": "DTW",
918
+ "entropy_corr": float(metrics["entropy_corr_dtw"]),
919
+ "n_common_times": int(metrics["n_common_times_dtw"]),
920
+ "used_for_choice": True,
921
+ "chosen": str(chosen_method) == "DTW",
922
+ },
923
+ ]
924
+ table = pd.DataFrame(rows)
925
+ table_path = output_dir / settings["alignment_bar_tsv"]
926
+ table.to_csv(table_path, sep="\t", index=False)
927
+
928
+ colors = ["#BDBDBD", "#4DBBD5", "#E64B35"]
929
+ fig, ax = plt.subplots(figsize=(6.5, 4.5))
930
+ bars = ax.bar(table["method"], table["entropy_corr"], color=colors, edgecolor="black", linewidth=0.8)
931
+ ax.axhline(0.0, color="black", linewidth=0.8)
932
+ ax.set_ylabel("Entropy Correlation", fontsize=12)
933
+ ax.set_title("Alignment Method Comparison", fontsize=14)
934
+ ax.spines["top"].set_visible(False)
935
+ ax.spines["right"].set_visible(False)
936
+
937
+ values = table["entropy_corr"].to_numpy(dtype=float)
938
+ span = max(np.nanmax(np.abs(values)), 1e-6)
939
+ offset = max(span * 0.04, 0.01)
940
+ for bar, row in zip(bars, rows):
941
+ value = float(row["entropy_corr"])
942
+ y_pos = value + offset if value >= 0 else value - offset
943
+ va = "bottom" if value >= 0 else "top"
944
+ label = f"{value:.3f}"
945
+ if row["chosen"]:
946
+ label = f"{label}\nchosen"
947
+ ax.text(
948
+ bar.get_x() + bar.get_width() / 2.0,
949
+ y_pos,
950
+ label,
951
+ ha="center",
952
+ va=va,
953
+ fontsize=10,
954
+ fontweight="bold" if row["chosen"] else "normal",
955
+ )
956
+
957
+ fig.tight_layout()
958
+ figure_path = output_dir / settings["alignment_bar_figure"]
959
+ fig.savefig(figure_path, dpi=300, bbox_inches="tight")
960
+ plt.close(fig)
961
+
962
+ return {
963
+ "figure_path": str(figure_path),
964
+ "table_path": str(table_path),
965
+ "methods": rows,
966
+ }
967
+
968
+
969
+ def compute_receptor_programs(act_g: pd.DataFrame, receptors: list[str], corr_thresh: float = 0.6, top_k: int | None = 200) -> dict[str, list[str]]:
970
+ genes = list(act_g.index)
971
+ gene_to_idx = {gene: idx for idx, gene in enumerate(genes)}
972
+ values = act_g.values
973
+ z_values = values - values.mean(axis=1, keepdims=True)
974
+ std = z_values.std(axis=1, keepdims=True)
975
+ std[std == 0] = 1.0
976
+ z_values = z_values / std
977
+ programs: dict[str, list[str]] = {}
978
+ for receptor in receptors:
979
+ if receptor not in gene_to_idx:
980
+ continue
981
+ idx_r = gene_to_idx[receptor]
982
+ r_vec = z_values[idx_r]
983
+ corr = (z_values * r_vec).mean(axis=1)
984
+ corr[idx_r] = 0.0
985
+ if top_k is not None:
986
+ idx = np.argsort(-np.abs(corr))[:top_k]
987
+ if corr_thresh is not None:
988
+ idx = idx[np.abs(corr[idx]) >= corr_thresh]
989
+ elif corr_thresh is not None:
990
+ idx = np.where(np.abs(corr) >= corr_thresh)[0]
991
+ else:
992
+ idx = np.arange(len(genes))
993
+ prog_genes = [genes[item] for item in idx]
994
+ if prog_genes:
995
+ programs[receptor] = prog_genes
996
+ return programs
997
+
998
+
999
+ def compute_program_curves(programs: dict[str, list[str]], act_g: pd.DataFrame) -> pd.DataFrame:
1000
+ payload: dict[str, np.ndarray] = {}
1001
+ for receptor, genes in programs.items():
1002
+ genes_ok = [gene for gene in genes if gene in act_g.index]
1003
+ if not genes_ok:
1004
+ continue
1005
+ payload[receptor] = act_g.loc[genes_ok].mean(axis=0).values
1006
+ return pd.DataFrame.from_dict(payload, orient="index", columns=act_g.columns)
1007
+
1008
+
1009
+ def compute_prog_comm_curves(
1010
+ lr_df: pd.DataFrame,
1011
+ act_s: pd.DataFrame,
1012
+ prog_df: pd.DataFrame,
1013
+ ) -> tuple[dict[tuple[str, str], np.ndarray], pd.DataFrame, np.ndarray]:
1014
+ times = np.asarray(act_s.columns, dtype=float)
1015
+ prog_reindexed = prog_df.reindex(columns=act_s.columns)
1016
+ if prog_reindexed.isna().any().any():
1017
+ missing = act_s.columns[prog_reindexed.isna().all(axis=0)]
1018
+ raise ValueError(f"prog_df is missing aligned columns: {missing[:10].tolist()}")
1019
+ curves: dict[tuple[str, str], np.ndarray] = {}
1020
+ records: list[dict[str, Any]] = []
1021
+ for _, row in lr_df.iterrows():
1022
+ ligand = row["ligand"]
1023
+ receptor = row["receptor"]
1024
+ if ligand not in act_s.index or receptor not in prog_reindexed.index:
1025
+ continue
1026
+ ligand_curve = act_s.loc[ligand].values.astype(float)
1027
+ program_curve = prog_reindexed.loc[receptor].values.astype(float)
1028
+ comm = ligand_curve * program_curve
1029
+ curves[(ligand, receptor)] = comm
1030
+ records.append({"ligand": ligand, "receptor": receptor, "score_prog": float(comm.sum())})
1031
+ scores_df = pd.DataFrame(records).sort_values("score_prog", ascending=False).reset_index(drop=True)
1032
+ return curves, scores_df, times
1033
+
1034
+
1035
+ def build_receptor_tfs_from_grn(
1036
+ network_dir_germ: str | Path,
1037
+ tf_annot_path: str | Path,
1038
+ tg_annot_path: str | Path,
1039
+ programs: dict[str, list[str]],
1040
+ ) -> dict[str, str]:
1041
+ tf = _read_annot(tf_annot_path, "tf_idx")
1042
+ tg = _read_annot(tg_annot_path, "tg_idx")
1043
+ tf_map = dict(zip(tf.index, tf["gene_name"]))
1044
+ tg_map = dict(zip(tg.index, tg["gene_name"]))
1045
+ tg_to_tfs: dict[str, set[str]] = defaultdict(set)
1046
+ for path in list_edge_files(network_dir_germ):
1047
+ frame = _read_edge_file(path, prob_col="prob")
1048
+ if {"tf", "tg"}.issubset(frame.columns):
1049
+ tf_names = frame["tf"]
1050
+ tg_names = frame["tg"]
1051
+ else:
1052
+ tf_names = frame["tf_idx"].map(tf_map)
1053
+ tg_names = frame["tg_idx"].map(tg_map)
1054
+ mask = tf_names.notna() & tg_names.notna()
1055
+ for tf_name, tg_name in zip(tf_names[mask].values, tg_names[mask].values):
1056
+ tg_to_tfs[str(tg_name)].add(str(tf_name))
1057
+ receptor_to_tfs: dict[str, str] = {}
1058
+ for receptor, genes in programs.items():
1059
+ tf_set: set[str] = set()
1060
+ for gene in genes:
1061
+ tf_set |= tg_to_tfs.get(gene, set())
1062
+ receptor_to_tfs[receptor] = ";".join(sorted(tf_set)) if tf_set else ""
1063
+ return receptor_to_tfs
1064
+
1065
+
1066
+ def _compute_stage_segments(act_s: pd.DataFrame, act_g: pd.DataFrame) -> tuple[dict[str, np.ndarray], pd.DataFrame]:
1067
+ common_times = act_s.columns.to_numpy(dtype=float)
1068
+ t_min = float(common_times[0])
1069
+ t_max = float(common_times[-1])
1070
+ t_norm = (common_times - t_min) / (t_max - t_min + 1e-12)
1071
+ x_s = act_s.values
1072
+ x_g = act_g.values
1073
+ diff_s = np.diff(x_s, axis=1)
1074
+ diff_g = np.diff(x_g, axis=1)
1075
+ delta = (diff_s ** 2).sum(axis=0) + (diff_g ** 2).sum(axis=0)
1076
+ t_count = act_s.shape[1]
1077
+ if t_count < 3 or delta.size < 2:
1078
+ k1 = t_count // 3
1079
+ k2 = 2 * t_count // 3
1080
+ else:
1081
+ split_indices = np.argsort(-delta)[:2]
1082
+ split_indices = np.sort(split_indices)
1083
+ k1, k2 = int(split_indices[0]), int(split_indices[1])
1084
+ k1 = max(0, min(k1, t_count - 3))
1085
+ k2 = max(k1 + 1, min(k2, t_count - 2))
1086
+ segments = {
1087
+ "early": np.arange(0, k1 + 1),
1088
+ "mid": np.arange(k1 + 1, k2 + 1),
1089
+ "late": np.arange(k2 + 1, t_count),
1090
+ }
1091
+ records: list[dict[str, Any]] = []
1092
+ for name, idxs in segments.items():
1093
+ if len(idxs) == 0:
1094
+ continue
1095
+ i0 = int(idxs[0])
1096
+ i1 = int(idxs[-1])
1097
+ records.append(
1098
+ {
1099
+ "stage": name,
1100
+ "idx_start": i0,
1101
+ "idx_end": i1,
1102
+ "t_raw_start": float(common_times[i0]),
1103
+ "t_raw_end": float(common_times[i1]),
1104
+ "t_norm_start": float(t_norm[i0]),
1105
+ "t_norm_end": float(t_norm[i1]),
1106
+ }
1107
+ )
1108
+ return segments, pd.DataFrame(records)
1109
+
1110
+
1111
+ def _build_heatmap_outputs(
1112
+ curves_all: dict[tuple[str, str], np.ndarray],
1113
+ scores_all: pd.DataFrame,
1114
+ times_all: np.ndarray,
1115
+ output_dir: Path,
1116
+ settings: dict[str, Any],
1117
+ ) -> dict[str, Any]:
1118
+ if not curves_all:
1119
+ raise ValueError("curves_all is empty.")
1120
+ pairs_list = list(curves_all.keys())
1121
+ raw_mat = np.vstack([curves_all[pair] for pair in pairs_list])
1122
+ row_max = raw_mat.max(axis=1, keepdims=True)
1123
+ row_max[row_max == 0] = 1.0
1124
+ data_norm = raw_mat / row_max
1125
+ keep_idx = raw_mat.max(axis=1) > 0
1126
+ data_norm = data_norm[keep_idx]
1127
+ raw_mat = raw_mat[keep_idx]
1128
+ pairs_list = [pairs_list[idx] for idx in range(len(pairs_list)) if keep_idx[idx]]
1129
+ n_pairs = len(pairs_list)
1130
+ if n_pairs < settings["kmeans_clusters"]:
1131
+ raise ValueError(
1132
+ f"Valid LR pair count ({n_pairs}) is smaller than kmeans_clusters ({settings['kmeans_clusters']})."
1133
+ )
1134
+
1135
+ peak_indices = np.argmax(data_norm, axis=1)
1136
+ peak_times = np.asarray(times_all, dtype=float)[peak_indices]
1137
+ kmeans = KMeans(
1138
+ n_clusters=settings["kmeans_clusters"],
1139
+ random_state=settings["kmeans_random_state"],
1140
+ n_init=settings["kmeans_n_init"],
1141
+ ).fit(peak_times.reshape(-1, 1))
1142
+ centers = kmeans.cluster_centers_.flatten()
1143
+ labels = kmeans.labels_
1144
+ sorted_center_idx = np.argsort(centers)
1145
+ map_label = {old: new for new, old in enumerate(sorted_center_idx)}
1146
+ new_labels = np.asarray([map_label[int(label)] for label in labels], dtype=int)
1147
+
1148
+ grouped_indices: list[np.ndarray] = []
1149
+ for group_id in range(settings["kmeans_clusters"]):
1150
+ current = np.where(new_labels == group_id)[0]
1151
+ ordered = current[np.argsort(peak_times[current])]
1152
+ grouped_indices.append(ordered)
1153
+
1154
+ gap_width = int(n_pairs * settings["gap_frac"])
1155
+ if gap_width < 1:
1156
+ gap_width = 1
1157
+ nan_gap = np.full((data_norm.shape[1], gap_width), np.nan)
1158
+
1159
+ matrix_parts: list[np.ndarray] = []
1160
+ final_labels_list: list[str] = []
1161
+ group_label_positions: list[float] = []
1162
+ current_col = 0
1163
+ for group_id in range(settings["kmeans_clusters"]):
1164
+ indices = grouped_indices[group_id]
1165
+ sub_matrix = data_norm[indices].T
1166
+ matrix_parts.append(sub_matrix)
1167
+ final_labels_list.extend([f"{pairs_list[idx][0]}->{pairs_list[idx][1]}" for idx in indices])
1168
+ group_width = len(indices)
1169
+ group_label_positions.append(current_col + group_width / 2.0)
1170
+ current_col += group_width
1171
+ if group_id < settings["kmeans_clusters"] - 1:
1172
+ matrix_parts.append(nan_gap)
1173
+ final_labels_list.extend([""] * gap_width)
1174
+ current_col += gap_width
1175
+ plotting_matrix = np.hstack(matrix_parts)
1176
+
1177
+ fig = plt.figure(figsize=(settings["heatmap_width"], settings["heatmap_height"]))
1178
+ gs = gridspec.GridSpec(1, 3, width_ratios=[0.02, 0.96, 0.02], wspace=0.05)
1179
+ ax_hm = fig.add_subplot(gs[1])
1180
+ cmap = plt.get_cmap("magma_r").copy()
1181
+ cmap.set_bad(color="white")
1182
+ image = ax_hm.imshow(
1183
+ plotting_matrix,
1184
+ aspect="auto",
1185
+ interpolation="nearest",
1186
+ cmap=cmap,
1187
+ origin="lower",
1188
+ extent=[0, len(final_labels_list), 0, 1],
1189
+ )
1190
+
1191
+ total = len(final_labels_list)
1192
+ step = max(1, total // 60)
1193
+ tick_locs = np.arange(0, total, step) + 0.5
1194
+ tick_txts = [final_labels_list[idx] for idx in range(0, total, step)]
1195
+ ax_hm.set_xticks(tick_locs)
1196
+ ax_hm.set_xticklabels(tick_txts, rotation=90, fontsize=8)
1197
+ for group_id, x_pos in enumerate(group_label_positions):
1198
+ meta = settings["group_meta"][group_id]
1199
+ ax_hm.text(
1200
+ x_pos,
1201
+ 1.05,
1202
+ meta["name"],
1203
+ transform=ax_hm.get_xaxis_transform(),
1204
+ ha="center",
1205
+ va="bottom",
1206
+ fontweight="bold",
1207
+ fontsize=14,
1208
+ color=meta["color"],
1209
+ )
1210
+ ax_hm.set_ylabel("Normalized Time", fontsize=18)
1211
+ ax_hm.set_yticks([0, 1])
1212
+ ax_hm.spines["top"].set_visible(False)
1213
+ ax_hm.spines["right"].set_visible(False)
1214
+ ax_cb = fig.add_subplot(gs[2])
1215
+ plt.colorbar(image, cax=ax_cb, label="Score")
1216
+ fig_path = output_dir / settings["heatmap_figure"]
1217
+ fig.savefig(fig_path, dpi=300, bbox_inches="tight")
1218
+ plt.close(fig)
1219
+
1220
+ score_map = {
1221
+ (str(row["ligand"]), str(row["receptor"])): float(row["score_prog"])
1222
+ for _, row in scores_all.iterrows()
1223
+ }
1224
+ summary_df = pd.DataFrame(
1225
+ {
1226
+ "ligand": [pair[0] for pair in pairs_list],
1227
+ "receptor": [pair[1] for pair in pairs_list],
1228
+ "pair": [f"{pair[0]}->{pair[1]}" for pair in pairs_list],
1229
+ "peak_time": peak_times,
1230
+ "peak_stage": [settings["group_meta"][int(group_id)]["name"] for group_id in new_labels],
1231
+ "peak_score_raw": raw_mat[np.arange(raw_mat.shape[0]), peak_indices],
1232
+ "total_score_raw": [score_map.get(pair, np.nan) for pair in pairs_list],
1233
+ }
1234
+ ).sort_values(["peak_stage", "peak_time", "peak_score_raw"], ascending=[True, True, False])
1235
+
1236
+ peak_tsv = output_dir / settings["peak_table_tsv"]
1237
+ peak_csv = output_dir / settings["peak_table_csv"]
1238
+ summary_df.to_csv(peak_tsv, sep="\t", index=False)
1239
+ summary_df.to_csv(peak_csv, index=False)
1240
+
1241
+ return {
1242
+ "figure_path": str(fig_path),
1243
+ "peak_table_tsv": str(peak_tsv),
1244
+ "peak_table_csv": str(peak_csv),
1245
+ "valid_pair_count": int(n_pairs),
1246
+ "heatmap_shape": [int(plotting_matrix.shape[0]), int(plotting_matrix.shape[1])],
1247
+ "group_centers": [float(value) for value in centers.tolist()],
1248
+ }
1249
+
1250
+
1251
+ def _run_program_analysis(config: dict[str, Any]) -> dict[str, Any]:
1252
+ settings = _ccc_settings(config)
1253
+ base_dir = Path(str(config.get("base_dir", "."))).expanduser().resolve()
1254
+ output_dir = ensure_directory(_resolve_path(base_dir, settings["output_dir"]))
1255
+ _set_seed(settings["seed"])
1256
+
1257
+ network_dir_soma = _resolve_path(base_dir, settings["network_dir_soma"])
1258
+ network_dir_germ = _resolve_path(base_dir, settings["network_dir_germ"])
1259
+ tg_annot_soma = _resolve_path(base_dir, settings["tg_annot_soma"])
1260
+ tg_annot_germ = _resolve_path(base_dir, settings["tg_annot_germ"])
1261
+ tf_annot_soma = _resolve_path(base_dir, settings["tf_annot_soma"])
1262
+ tf_annot_germ = _resolve_path(base_dir, settings["tf_annot_germ"])
1263
+ ccc_csv = _resolve_path(base_dir, settings["ccc_csv"])
1264
+ tf_filter_path, tf_filter_fallback = _resolve_tf_filter_path(
1265
+ base_dir,
1266
+ settings["tf_filter_path"],
1267
+ tf_annot_soma,
1268
+ )
1269
+
1270
+ act_s_raw, times_s = load_activity_from_grn(network_dir_soma, tg_annot_soma, prob_col="prob")
1271
+ act_g_raw, times_g = load_activity_from_grn(network_dir_germ, tg_annot_germ, prob_col="prob")
1272
+ act_s = gaussian_smooth_over_time(act_s_raw, times_s, settings["sigma_time"])
1273
+ act_g = gaussian_smooth_over_time(act_g_raw, times_g, settings["sigma_time"])
1274
+ act_s, _times_s = collapse_duplicate_timecols(act_s)
1275
+ act_g, _times_g = collapse_duplicate_timecols(act_g)
1276
+ lr_df = load_lr_candidates(ccc_csv, act_s, act_g)
1277
+
1278
+ times_s_net, mats_s, tf_s, tg_s = _load_network_series(network_dir_soma, tf_annot_soma, tg_annot_soma, prob_col="prob")
1279
+ times_g_net, mats_g, tf_g, tg_g = _load_network_series(network_dir_germ, tf_annot_germ, tg_annot_germ, prob_col="prob")
1280
+ tf_common = sorted(set(tf_s) & set(tf_g))
1281
+ tg_common = sorted(set(tg_s) & set(tg_g))
1282
+ if len(tf_common) < 5 or len(tg_common) < 5:
1283
+ raise ValueError(f"Common TF/TG is too small: TF={len(tf_common)}, TG={len(tg_common)}")
1284
+ mats_s = _restrict_to_common(mats_s, tf_s, tg_s, tf_common, tg_common)
1285
+ mats_g = _restrict_to_common(mats_g, tf_g, tg_g, tf_common, tg_common)
1286
+
1287
+ fs_list: list[np.ndarray] = []
1288
+ cs_list: list[np.ndarray] = []
1289
+ for matrix in mats_s:
1290
+ abar = _normalize_bipartite(matrix, settings)
1291
+ fs_list.append(_top_r_svals(abar, settings["finger_r"]))
1292
+ cs_list.append(_tf_centrality(abar))
1293
+ fg_list: list[np.ndarray] = []
1294
+ cg_list: list[np.ndarray] = []
1295
+ for matrix in mats_g:
1296
+ abar = _normalize_bipartite(matrix, settings)
1297
+ fg_list.append(_top_r_svals(abar, settings["finger_r"]))
1298
+ cg_list.append(_tf_centrality(abar))
1299
+
1300
+ fs = np.vstack(fs_list)
1301
+ fg = np.vstack(fg_list)
1302
+ c_s = pd.DataFrame(np.vstack(cs_list).T, index=tf_common, columns=times_s_net)
1303
+ c_g = pd.DataFrame(np.vstack(cg_list).T, index=tf_common, columns=times_g_net)
1304
+ fs = _zscore_cols(fs)
1305
+ fg = _zscore_cols(fg)
1306
+ c_s_z = pd.DataFrame(_zscore_rows(c_s.values), index=c_s.index, columns=c_s.columns)
1307
+ c_g_z = pd.DataFrame(_zscore_rows(c_g.values), index=c_g.index, columns=c_g.columns)
1308
+ tau_s_net = _normalize_time_to_01(times_s_net)
1309
+ tau_g_net = _normalize_time_to_01(times_g_net)
1310
+
1311
+ w_lin_norm_on_s_net = tau_s_net.copy()
1312
+ t_germ_on_s_net_lin = times_g_net.min() + w_lin_norm_on_s_net * (times_g_net.max() - times_g_net.min())
1313
+ c_g_lin_on_s = interp_df_time(c_g_z, times_g_net, t_germ_on_s_net_lin)
1314
+ c_g_lin_on_s.columns = times_s_net
1315
+
1316
+ ent_s_on_s_net, ent_g_on_g_net = prepare_entropy_on_net_grid(
1317
+ c_s_z,
1318
+ c_g_z,
1319
+ tau_s_net,
1320
+ tau_g_net,
1321
+ tf_filter_path=tf_filter_path,
1322
+ )
1323
+
1324
+ try:
1325
+ torch.use_deterministic_algorithms(True, warn_only=True)
1326
+ except Exception:
1327
+ pass
1328
+
1329
+ w_cont_norm_on_s_net = learn_monotone_warp_continuous(
1330
+ tau_s_net,
1331
+ fs,
1332
+ tau_g_net,
1333
+ fg,
1334
+ ent_s=ent_s_on_s_net,
1335
+ ent_g=ent_g_on_g_net,
1336
+ fp_w=settings["warp_fp_w"],
1337
+ ent_w=settings["warp_ent_w"],
1338
+ lam_d2=settings["warp_lam_d2"],
1339
+ steps=settings["warp_steps"],
1340
+ lr=settings["warp_lr"],
1341
+ )
1342
+ t_germ_on_s_net_cont = times_g_net.min() + w_cont_norm_on_s_net * (times_g_net.max() - times_g_net.min())
1343
+ c_g_cont_on_s = interp_df_time(c_g_z, times_g_net, t_germ_on_s_net_cont)
1344
+ c_g_cont_on_s.columns = times_s_net
1345
+
1346
+ act_g_u = act_g.copy()
1347
+ act_g_u.columns = [float(column) for column in act_g_u.columns]
1348
+ act_g_u = act_g_u.T.groupby(level=0).mean().T
1349
+ act_g_u = act_g_u.loc[:, sorted(act_g_u.columns)]
1350
+ times_g_act = act_g_u.columns.to_numpy(dtype=float)
1351
+
1352
+ act_s_u = act_s.copy()
1353
+ act_s_u.columns = [float(column) for column in act_s_u.columns]
1354
+ act_s_u = act_s_u.T.groupby(level=0).mean().T
1355
+ act_s_u = act_s_u.loc[:, sorted(act_s_u.columns)]
1356
+ times_s_act = act_s_u.columns.to_numpy(dtype=float)
1357
+
1358
+ w_cont_norm_on_s_act = np.interp(
1359
+ times_s_act,
1360
+ times_s_net,
1361
+ w_cont_norm_on_s_net,
1362
+ left=w_cont_norm_on_s_net[0],
1363
+ right=w_cont_norm_on_s_net[-1],
1364
+ )
1365
+ t_germ_on_s_act_cont = times_g_act.min() + w_cont_norm_on_s_act * (times_g_act.max() - times_g_act.min())
1366
+ act_g_cont = interp_df_over_time(act_g_u, times_g_act, t_germ_on_s_act_cont)
1367
+ act_g_cont.columns = times_s_act
1368
+
1369
+ cost_fp = ((fs[:, None, :] - fg[None, :, :]) ** 2).sum(axis=2)
1370
+ cost_ent = (ent_s_on_s_net[:, None] - ent_g_on_g_net[None, :]) ** 2
1371
+ cost_fp = cost_fp / (cost_fp.mean() + 1e-12)
1372
+ cost_ent = cost_ent / (cost_ent.mean() + 1e-12)
1373
+ total_cost = settings["dtw_fp_w"] * cost_fp + settings["dtw_ent_w"] * cost_ent
1374
+ band = settings["dtw_band"]
1375
+ band_value = None if band is None else int(band)
1376
+ path = dtw_path(total_cost, band=band_value)
1377
+
1378
+ t_s_count = fs.shape[0]
1379
+ matches: list[list[float]] = [[] for _ in range(t_s_count)]
1380
+ for i_idx, j_idx in path:
1381
+ if 0 <= i_idx < t_s_count and 0 <= j_idx < fg.shape[0]:
1382
+ matches[i_idx].append(float(tau_g_net[j_idx]))
1383
+ w_dtw_norm_on_s_net = np.zeros(t_s_count, dtype=float)
1384
+ for idx in range(t_s_count):
1385
+ if matches[idx]:
1386
+ w_dtw_norm_on_s_net[idx] = float(np.mean(matches[idx]))
1387
+ elif idx > 0:
1388
+ w_dtw_norm_on_s_net[idx] = w_dtw_norm_on_s_net[idx - 1]
1389
+ else:
1390
+ w_dtw_norm_on_s_net[idx] = 0.0
1391
+ w_dtw_norm_on_s_net = np.clip(w_dtw_norm_on_s_net, 0.0, 1.0)
1392
+ w_dtw_norm_on_s_net[0] = 0.0
1393
+ w_dtw_norm_on_s_net[-1] = 1.0
1394
+ w_dtw_norm_on_s_net = smooth_warp_d2_monotone(
1395
+ w_dtw_norm_on_s_net,
1396
+ lam=settings["dtw_lam_d2"],
1397
+ n_iter=settings["dtw_n_iter"],
1398
+ clip01=True,
1399
+ enforce_endpoints=True,
1400
+ )
1401
+ t_germ_on_s_net_dtw = times_g_net.min() + w_dtw_norm_on_s_net * (times_g_net.max() - times_g_net.min())
1402
+ c_g_dtw_on_s = interp_df_time(c_g_z, times_g_net, t_germ_on_s_net_dtw)
1403
+ c_g_dtw_on_s.columns = times_s_net
1404
+
1405
+ w_dtw_norm_on_s_act = np.interp(
1406
+ times_s_act,
1407
+ times_s_net,
1408
+ w_dtw_norm_on_s_net,
1409
+ left=w_dtw_norm_on_s_net[0],
1410
+ right=w_dtw_norm_on_s_net[-1],
1411
+ )
1412
+ t_germ_on_s_act_dtw = times_g_act.min() + w_dtw_norm_on_s_act * (times_g_act.max() - times_g_act.min())
1413
+ act_g_dtw = interp_df_over_time(act_g_u, times_g_act, t_germ_on_s_act_dtw)
1414
+ act_g_dtw.columns = times_s_act
1415
+
1416
+ warp_cont_path = output_dir / settings["warp_cont_tsv"]
1417
+ pd.DataFrame({"t_soma_net": times_s_net, "t_germ_warped": t_germ_on_s_net_cont}).to_csv(
1418
+ warp_cont_path,
1419
+ sep="\t",
1420
+ index=False,
1421
+ )
1422
+ warp_dtw_path = output_dir / settings["warp_dtw_tsv"]
1423
+ pd.DataFrame({"t_soma_net": times_s_net, "t_germ_warped": t_germ_on_s_net_dtw}).to_csv(
1424
+ warp_dtw_path,
1425
+ sep="\t",
1426
+ index=False,
1427
+ )
1428
+
1429
+ requested_method = settings["alignment_method"].strip().lower()
1430
+ if requested_method == "auto":
1431
+ chosen_method, alignment_metrics = pick_alignment_method(
1432
+ c_s_z,
1433
+ c_g_cont_on_s,
1434
+ c_g_dtw_on_s,
1435
+ min_common_times=settings["min_common_times"],
1436
+ n_boot=settings["alignment_n_boot"],
1437
+ seed_cont=1,
1438
+ seed_dtw=2,
1439
+ tie_tol=settings["tie_tol"],
1440
+ prefer_on_tie=settings["prefer_on_tie"],
1441
+ )
1442
+ elif requested_method in {"warping", "dtw"}:
1443
+ chosen_method = "Warping" if requested_method == "warping" else "DTW"
1444
+ _, alignment_metrics = pick_alignment_method(
1445
+ c_s_z,
1446
+ c_g_cont_on_s,
1447
+ c_g_dtw_on_s,
1448
+ min_common_times=settings["min_common_times"],
1449
+ n_boot=settings["alignment_n_boot"],
1450
+ seed_cont=1,
1451
+ seed_dtw=2,
1452
+ tie_tol=settings["tie_tol"],
1453
+ prefer_on_tie=settings["prefer_on_tie"],
1454
+ )
1455
+ alignment_metrics["chosen_method"] = chosen_method
1456
+ else:
1457
+ raise ValueError("ccc.alignment_method must be auto, warping, or dtw.")
1458
+
1459
+ ent_linear, n_linear = entropy_corr_score(
1460
+ _canon_timecols(c_s_z),
1461
+ _canon_timecols(c_g_lin_on_s),
1462
+ min_common_times=settings["min_common_times"],
1463
+ n_boot=settings["alignment_n_boot"],
1464
+ seed=0,
1465
+ )
1466
+ if not np.isfinite(ent_linear):
1467
+ raise ValueError(f"Invalid entropy corr value for linear alignment: {ent_linear}")
1468
+ alignment_metrics["entropy_corr_linear"] = float(ent_linear)
1469
+ alignment_metrics["n_common_times_linear"] = int(n_linear)
1470
+ alignment_comparison = _build_alignment_comparison_outputs(
1471
+ output_dir=output_dir,
1472
+ settings=settings,
1473
+ chosen_method=chosen_method,
1474
+ metrics=alignment_metrics,
1475
+ )
1476
+
1477
+ act_g_selected = act_g_cont if chosen_method == "Warping" else act_g_dtw
1478
+ act_s_aligned = _canon_timecols(act_s)
1479
+ act_g_aligned = _canon_timecols(act_g_selected)
1480
+ act_g_aligned = act_g_aligned.reindex(columns=act_s_aligned.columns)
1481
+ if act_g_aligned.isna().any().any():
1482
+ missing = act_s_aligned.columns[act_g_aligned.isna().all(axis=0)]
1483
+ raise ValueError(f"Aligned act_g is missing columns on soma grid: {missing[:10].tolist()}")
1484
+ common_times = act_s_aligned.columns.to_numpy(dtype=float)
1485
+ if len(common_times) < 3:
1486
+ raise ValueError(f"Too few aligned timepoints: T={len(common_times)}")
1487
+
1488
+ receptors = sorted(lr_df["receptor"].unique())
1489
+ programs = compute_receptor_programs(
1490
+ act_g_aligned,
1491
+ receptors,
1492
+ corr_thresh=settings["corr_thresh"],
1493
+ top_k=settings["top_k_prog"],
1494
+ )
1495
+ prog_df = compute_program_curves(programs, act_g_aligned)
1496
+ receptor_to_tfs = build_receptor_tfs_from_grn(
1497
+ network_dir_germ,
1498
+ tf_annot_germ,
1499
+ tg_annot_germ,
1500
+ programs,
1501
+ )
1502
+
1503
+ segments, stage_df = _compute_stage_segments(act_s_aligned, act_g_aligned)
1504
+ stage_path = output_dir / settings["stage_table"]
1505
+ stage_df.to_csv(stage_path, sep="\t", index=False)
1506
+
1507
+ stage_score_paths: dict[str, str] = {}
1508
+ for name, idxs in segments.items():
1509
+ if len(idxs) == 0:
1510
+ continue
1511
+ act_s_seg = act_s_aligned.iloc[:, idxs]
1512
+ prog_seg = prog_df.iloc[:, idxs]
1513
+ _curves_seg, scores_seg, _times_seg = compute_prog_comm_curves(lr_df, act_s_seg, prog_seg)
1514
+ scores_seg["tf_germline"] = scores_seg["receptor"].map(receptor_to_tfs).fillna("")
1515
+ out_path = output_dir / f"comm_scores_LR_program_{name}.tsv"
1516
+ scores_seg.to_csv(out_path, sep="\t", index=False)
1517
+ stage_score_paths[name] = str(out_path)
1518
+
1519
+ curves_all, scores_all, times_all = compute_prog_comm_curves(lr_df, act_s_aligned, prog_df)
1520
+ heatmap_report = _build_heatmap_outputs(curves_all, scores_all, times_all, output_dir, settings)
1521
+
1522
+ report = {
1523
+ "analysis": "ccc",
1524
+ "output_dir": str(output_dir),
1525
+ "network_dir_soma": str(network_dir_soma),
1526
+ "network_dir_germ": str(network_dir_germ),
1527
+ "ccc_csv": str(ccc_csv),
1528
+ "seed": int(settings["seed"]),
1529
+ "lr_candidate_count": int(len(lr_df)),
1530
+ "program_receptor_count": int(len(programs)),
1531
+ "chosen_alignment": str(chosen_method),
1532
+ "alignment_metrics": alignment_metrics,
1533
+ "alignment_comparison": alignment_comparison,
1534
+ "warp_cont_path": str(warp_cont_path),
1535
+ "warp_dtw_path": str(warp_dtw_path),
1536
+ "stage_table": str(stage_path),
1537
+ "stage_score_paths": stage_score_paths,
1538
+ "heatmap": heatmap_report,
1539
+ "tf_filter_path": str(tf_filter_path),
1540
+ "tf_filter_fallback_to_tf_list": bool(tf_filter_fallback),
1541
+ "settings": settings,
1542
+ }
1543
+ save_checkpoint_metadata(output_dir / "ccc_report.json", report)
1544
+ return report
1545
+
1546
+
1547
+ def run_ccc_analysis_from_config(config: dict[str, Any]) -> dict[str, Any]:
1548
+ """Run the communication analysis selected by ccc.score_mode."""
1549
+ mode = _section(config, "ccc").get("score_mode", "receptor_centrality")
1550
+ if mode == "program":
1551
+ return _run_program_analysis(config)
1552
+ if mode != "receptor_centrality":
1553
+ raise ValueError("ccc.score_mode must be receptor_centrality or program.")
1554
+ from .ccc_timing import run_receptor_ccc
1555
+
1556
+ return run_receptor_ccc(config)
1557
+
1558
+
1559
+ def run_ccc_analysis(config: dict[str, Any] | str | Path) -> dict[str, Any]:
1560
+ if isinstance(config, (str, Path)):
1561
+ path = Path(config).resolve()
1562
+ loaded = load_yaml_config(path)
1563
+ loaded.setdefault("base_dir", str(Path(".").resolve()))
1564
+ report = run_ccc_analysis_from_config(loaded)
1565
+ report["config_path"] = str(path)
1566
+ return report
1567
+ return run_ccc_analysis_from_config(config)