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,546 @@
1
+ """Cluster regulatory edges by their patterns across stages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import matplotlib as mpl
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ import pandas as pd
14
+ from sklearn.cluster import KMeans
15
+ from sklearn.preprocessing import StandardScaler
16
+
17
+ from ..checkpoint import save_checkpoint_metadata
18
+ from ..io import has_explicit_tree_config
19
+ from ..lineage import load_tree_table
20
+ from ..utils import ensure_directory, load_yaml_config, resolve_config_path
21
+ from .network import discover_network_time_indices, load_and_select_all
22
+
23
+
24
+ DEFAULT_GERM_CELLTYPES = [
25
+ "GSC",
26
+ "Gb",
27
+ "Sp-2",
28
+ "Sp-4",
29
+ "Sp-8",
30
+ "Sp-16",
31
+ "1deg Sc",
32
+ "1deg Sc",
33
+ "1deg Sc",
34
+ "2deg Sc",
35
+ "2deg Sc",
36
+ "2deg Sc",
37
+ "2deg Sc",
38
+ "2deg Sc",
39
+ "2deg Sc",
40
+ ]
41
+
42
+
43
+ def _section(config: dict[str, Any], key: str) -> dict[str, Any]:
44
+ value = config.get(key, {})
45
+ return value if isinstance(value, dict) else {}
46
+
47
+
48
+ def _edge_cluster_settings(config: dict[str, Any]) -> dict[str, Any]:
49
+ section = _section(config, "edge_cluster")
50
+ lineage = str(config.get("lineage", "")).lower()
51
+ clusters = section.get("clusters")
52
+ if clusters is not None and not isinstance(clusters, list):
53
+ clusters = [clusters]
54
+ celltypes = section.get("celltypes")
55
+ if celltypes is not None and not isinstance(celltypes, list):
56
+ celltypes = [celltypes]
57
+ selection_mode = str(section.get("selection_mode", "topk")).strip().lower()
58
+ if selection_mode not in {"topk", "threshold", "both", "all", "tf_rescue"}:
59
+ raise ValueError(f"Unsupported edge_cluster.selection_mode={selection_mode!r}.")
60
+ return {
61
+ "enabled": bool(section.get("enabled", False)),
62
+ "network_dir": str(section.get("network_dir", f"result/{lineage}/network")),
63
+ "output_dir": str(section.get("output_dir", f"result/{lineage}/edge_cluster")),
64
+ "clusters": [int(value) for value in clusters] if clusters is not None else None,
65
+ "celltypes": [str(value) for value in celltypes] if celltypes is not None else None,
66
+ "selection_mode": selection_mode,
67
+ "top_n_per_cluster": int(section.get("top_n_per_cluster", 10_000)),
68
+ "score_threshold": float(section.get("score_threshold", 0.80)),
69
+ "n_clusters": int(section.get("n_clusters", 12)),
70
+ "random_state": int(section.get("random_state", 4256)),
71
+ "save_fig": bool(section.get("save_fig", True)),
72
+ "top_tf_per_cluster": int(section.get("top_tf_per_cluster", 20)),
73
+ "top_tg_per_cluster": int(section.get("top_tg_per_cluster", 20)),
74
+ "heatmap_cmap": str(section.get("heatmap_cmap", "OrRd")),
75
+ "specificity_min_edges": int(section.get("specificity_min_edges", 50)),
76
+ "specificity_min_max_prop": float(section.get("specificity_min_max_prop", 0.45)),
77
+ "specificity_min_gap": float(section.get("specificity_min_gap", 0.15)),
78
+ "specificity_topk": int(section.get("specificity_topk", 3)),
79
+ "topk_per_ec": int(section.get("topk_per_ec", 10)),
80
+ "tf_grid_nrows": int(section.get("tf_grid_nrows", 3)),
81
+ "tf_grid_ncols": int(section.get("tf_grid_ncols", 4)),
82
+ "score_vmin": float(section.get("score_vmin", 0.5)),
83
+ "score_vmax": float(section.get("score_vmax", 1.0)),
84
+ }
85
+
86
+
87
+ def _tree_cluster_labels(config: dict[str, Any], clusters: list[int]) -> list[str] | None:
88
+ if not has_explicit_tree_config(config):
89
+ return None
90
+ data_cfg = _section(config, "data")
91
+ tree_value = data_cfg.get("tree")
92
+ if not tree_value:
93
+ return None
94
+ tree_df = load_tree_table(resolve_config_path(config, tree_value))
95
+ node_names = tree_df["node_id"].astype(str).tolist()
96
+ labels: list[str] = []
97
+ for cluster in clusters:
98
+ cluster_idx = int(cluster)
99
+ if cluster_idx < 0 or cluster_idx >= len(node_names):
100
+ return None
101
+ labels.append(str(node_names[cluster_idx]))
102
+ return labels
103
+
104
+
105
+ def _cluster_labels(settings: dict[str, Any], config: dict[str, Any], clusters: list[int]) -> list[str]:
106
+ if settings["celltypes"] is not None and len(settings["celltypes"]) == len(clusters):
107
+ return settings["celltypes"]
108
+ tree_labels = _tree_cluster_labels(config, clusters)
109
+ if tree_labels is not None and len(tree_labels) == len(clusters):
110
+ return tree_labels
111
+ lineage = str(config.get("lineage", "")).lower()
112
+ if lineage in {"germ", "germline"} and len(clusters) == len(DEFAULT_GERM_CELLTYPES):
113
+ return DEFAULT_GERM_CELLTYPES
114
+ return [f"t{cluster:02d}" for cluster in clusters]
115
+
116
+
117
+ def plot_heatmap_with_ec_bar(
118
+ matrix: np.ndarray,
119
+ xticklabels: list[str],
120
+ yticklabels: list[str],
121
+ title: str,
122
+ path: str | Path,
123
+ ec_counts: np.ndarray,
124
+ cmap_name: str,
125
+ ) -> str:
126
+ fig = plt.figure(figsize=(max(10, 0.8 * len(xticklabels) + 3.0), max(6, 0.55 * len(yticklabels) + 1.5)))
127
+ grid = fig.add_gridspec(1, 2, width_ratios=[1.25, 6.0], wspace=0.15)
128
+ ax_bar = fig.add_subplot(grid[0, 0])
129
+ ax_heat = fig.add_subplot(grid[0, 1])
130
+
131
+ y_pos = np.arange(len(yticklabels))
132
+ ax_bar.barh(y_pos, ec_counts, color="#b45a3c")
133
+ ax_bar.set_yticks(y_pos)
134
+ ax_bar.set_yticklabels([])
135
+ ax_bar.invert_yaxis()
136
+ ax_bar.set_xlabel("n", fontsize=12)
137
+ ax_bar.tick_params(axis="x", labelsize=11)
138
+ ax_bar.tick_params(axis="y", length=0)
139
+ ax_bar.spines["top"].set_visible(False)
140
+ ax_bar.spines["right"].set_visible(False)
141
+
142
+ image = ax_heat.imshow(matrix, aspect="auto", interpolation="nearest", cmap=cmap_name)
143
+ ax_heat.set_xticks(np.arange(len(xticklabels)))
144
+ ax_heat.set_xticklabels(xticklabels, rotation=45, ha="right", fontsize=12)
145
+ ax_heat.set_yticks(np.arange(len(yticklabels)))
146
+ ax_heat.set_yticklabels(yticklabels, fontsize=12)
147
+ ax_heat.set_title(title, fontsize=16)
148
+ colorbar = fig.colorbar(image, ax=ax_heat, fraction=0.046, pad=0.04)
149
+ colorbar.ax.tick_params(labelsize=11)
150
+ fig.tight_layout()
151
+
152
+ output_path = Path(path)
153
+ output_path.parent.mkdir(parents=True, exist_ok=True)
154
+ fig.savefig(output_path, dpi=300, bbox_inches="tight")
155
+ plt.close(fig)
156
+ return str(output_path)
157
+
158
+
159
+ def infer_ec_specificity_topmix(
160
+ prop_mat: np.ndarray,
161
+ counts_mat: np.ndarray,
162
+ xt_labels: list[str],
163
+ min_edges: int = 50,
164
+ min_max_prop: float = 0.45,
165
+ min_gap: float = 0.15,
166
+ topk: int = 3,
167
+ ) -> pd.DataFrame:
168
+ n_ec, n_clusters = prop_mat.shape
169
+ n_edges = counts_mat.sum(axis=1)
170
+ keep_topk = min(topk, n_clusters)
171
+ top_idx = np.argsort(-prop_mat, axis=1)[:, :keep_topk]
172
+ top_props = np.take_along_axis(prop_mat, top_idx, axis=1)
173
+ max_prop = top_props[:, 0]
174
+ second_prop = top_props[:, 1] if keep_topk >= 2 else np.zeros(n_ec, dtype=float)
175
+ gap = max_prop - second_prop
176
+
177
+ top_mix = []
178
+ for edge_cluster in range(n_ec):
179
+ pairs = [f"{xt_labels[top_idx[edge_cluster, rank]]}:{top_props[edge_cluster, rank]:.2f}" for rank in range(keep_topk)]
180
+ top_mix.append(", ".join(pairs))
181
+
182
+ is_specific = (n_edges >= min_edges) & (max_prop >= min_max_prop) & (gap >= min_gap)
183
+ specific_to = [
184
+ xt_labels[top_idx[edge_cluster, 0]] if is_specific[edge_cluster] else "mixed"
185
+ for edge_cluster in range(n_ec)
186
+ ]
187
+
188
+ return pd.DataFrame(
189
+ {
190
+ "edge_cluster": np.arange(n_ec, dtype=int),
191
+ "specific_to": specific_to,
192
+ "max_prop": max_prop,
193
+ "second_prop": second_prop,
194
+ "gap": gap,
195
+ "n_edges": n_edges,
196
+ "top_mix": top_mix,
197
+ }
198
+ )
199
+
200
+
201
+ def _export_selected_edges(
202
+ network_dir: str | Path,
203
+ clusters: list[int],
204
+ labels: list[str],
205
+ output_dir: Path,
206
+ settings: dict[str, Any],
207
+ ) -> tuple[dict[int, pd.DataFrame], pd.DataFrame]:
208
+ selected_by_cluster = load_and_select_all(
209
+ network_dir,
210
+ clusters,
211
+ mode=settings["selection_mode"],
212
+ top_n=settings["top_n_per_cluster"],
213
+ thr=settings["score_threshold"],
214
+ )
215
+ selection_suffix = settings["selection_mode"]
216
+ frames: list[pd.DataFrame] = []
217
+ for cluster, label in zip(clusters, labels):
218
+ frame = selected_by_cluster[cluster].copy()
219
+ if frame.empty:
220
+ continue
221
+ frame["cell_cluster"] = int(cluster)
222
+ frame["cell_type"] = str(label)
223
+ frame["tf_idx"] = frame["TF_idx"]
224
+ frame["tg_idx"] = frame["TG_idx"]
225
+ frame["tf_name"] = frame["TF_name"].astype(str)
226
+ frame["tg_name"] = frame["TG_name"].astype(str)
227
+ frame["score"] = frame["prob"].astype(float)
228
+ frame_out = frame[["cell_cluster", "cell_type", "tf_idx", "tg_idx", "tf_name", "tg_name", "score"]]
229
+ frame_out.to_csv(output_dir / f"edges_{label}_{selection_suffix}.csv", index=False)
230
+ frames.append(frame_out)
231
+
232
+ df_edges = (
233
+ pd.concat(frames, ignore_index=True)
234
+ if frames
235
+ else pd.DataFrame(columns=["cell_cluster", "cell_type", "tf_idx", "tg_idx", "tf_name", "tg_name", "score"])
236
+ )
237
+ df_edges.to_csv(output_dir / f"edges_selected_{selection_suffix}.csv", index=False)
238
+ return selected_by_cluster, df_edges
239
+
240
+
241
+ def _export_top_nodes_by_degree(
242
+ df_edges: pd.DataFrame,
243
+ labels_by_cluster: dict[int, str],
244
+ top_tf_per_cluster: int,
245
+ top_tg_per_cluster: int,
246
+ output_dir: Path,
247
+ selection_mode: str,
248
+ ) -> tuple[pd.DataFrame, pd.DataFrame]:
249
+ tf_degree = (
250
+ df_edges.groupby(["cell_cluster", "tf_idx", "tf_name"])["tg_idx"]
251
+ .nunique()
252
+ .reset_index(name="degree")
253
+ .sort_values(["cell_cluster", "degree", "tf_name"], ascending=[True, False, True], kind="mergesort")
254
+ )
255
+ tg_degree = (
256
+ df_edges.groupby(["cell_cluster", "tg_idx", "tg_name"])["tf_idx"]
257
+ .nunique()
258
+ .reset_index(name="degree")
259
+ .sort_values(["cell_cluster", "degree", "tg_name"], ascending=[True, False, True], kind="mergesort")
260
+ )
261
+ top_tf = tf_degree.groupby("cell_cluster", group_keys=False).head(top_tf_per_cluster).reset_index(drop=True)
262
+ top_tg = tg_degree.groupby("cell_cluster", group_keys=False).head(top_tg_per_cluster).reset_index(drop=True)
263
+ top_tf["cell_type"] = top_tf["cell_cluster"].map(labels_by_cluster)
264
+ top_tg["cell_type"] = top_tg["cell_cluster"].map(labels_by_cluster)
265
+ top_tf.to_csv(output_dir / f"top_TF_by_degree_{selection_mode}.csv", index=False)
266
+ top_tg.to_csv(output_dir / f"top_TG_by_degree_{selection_mode}.csv", index=False)
267
+ return top_tf, top_tg
268
+
269
+
270
+ def _edge_binary_matrix(df_edges: pd.DataFrame, clusters: list[int]) -> tuple[list[tuple[Any, Any]], np.ndarray]:
271
+ edge_tuples = pd.MultiIndex.from_frame(df_edges[["tf_idx", "tg_idx"]]).unique().tolist()
272
+ edge_to_row = {edge: row_idx for row_idx, edge in enumerate(edge_tuples)}
273
+ cluster_to_col = {cluster: col_idx for col_idx, cluster in enumerate(clusters)}
274
+ matrix = np.zeros((len(edge_tuples), len(clusters)), dtype=float)
275
+ for cluster, group in df_edges.groupby("cell_cluster"):
276
+ col_idx = cluster_to_col[int(cluster)]
277
+ for edge in pd.MultiIndex.from_frame(group[["tf_idx", "tg_idx"]]).unique().tolist():
278
+ matrix[edge_to_row[edge], col_idx] = 1.0
279
+ return edge_tuples, matrix
280
+
281
+
282
+ def _tf_centrality_summary(
283
+ df_edges: pd.DataFrame,
284
+ df_edge_clusters: pd.DataFrame,
285
+ df_ec_spec: pd.DataFrame,
286
+ output_dir: Path,
287
+ settings: dict[str, Any],
288
+ ) -> tuple[pd.DataFrame, list[str]]:
289
+ te_regex = re.compile(
290
+ r"(transposable[_\s-]*element|retrotranspos|transposon|^RR\d+_transposable_element$)",
291
+ flags=re.IGNORECASE,
292
+ )
293
+
294
+ def is_te(name: str) -> bool:
295
+ return bool(te_regex.search(str(name))) if name is not None else False
296
+
297
+ edge_with_ec = pd.merge(
298
+ df_edges[["tf_idx", "tg_idx", "tf_name", "tg_name", "score"]],
299
+ df_edge_clusters[["tf_idx", "tg_idx", "edge_cluster"]],
300
+ on=["tf_idx", "tg_idx"],
301
+ how="left",
302
+ )
303
+ edge_with_ec_no_te = edge_with_ec[~edge_with_ec["tf_name"].apply(is_te)].copy()
304
+ df_edge_clusters_no_te = df_edge_clusters[~df_edge_clusters["tf_name"].apply(is_te)].copy()
305
+
306
+ deg_per_ec_tf = (
307
+ df_edge_clusters_no_te.groupby(["edge_cluster", "tf_idx", "tf_name"])["tg_idx"]
308
+ .nunique()
309
+ .reset_index(name="degree")
310
+ )
311
+ score_per_ec_tf = (
312
+ edge_with_ec_no_te.groupby(["edge_cluster", "tf_idx", "tf_name"])["score"]
313
+ .mean()
314
+ .reset_index(name="mean_score")
315
+ )
316
+ stats_tf = pd.merge(
317
+ deg_per_ec_tf,
318
+ score_per_ec_tf,
319
+ on=["edge_cluster", "tf_idx", "tf_name"],
320
+ how="left",
321
+ )
322
+
323
+ summary_rows: list[pd.DataFrame] = []
324
+ for edge_cluster in sorted(stats_tf["edge_cluster"].unique().tolist()):
325
+ sub = stats_tf[stats_tf["edge_cluster"] == edge_cluster].copy()
326
+ if sub.empty:
327
+ continue
328
+ sub.sort_values(["degree", "mean_score", "tf_name"], ascending=[False, False, True], inplace=True, kind="mergesort")
329
+ sub = sub.head(settings["topk_per_ec"]).reset_index(drop=True)
330
+ sub.insert(1, "rank", np.arange(1, len(sub) + 1))
331
+ spec_row = df_ec_spec[df_ec_spec["edge_cluster"] == edge_cluster]
332
+ if not spec_row.empty:
333
+ sub["specific_to"] = str(spec_row.iloc[0]["specific_to"])
334
+ sub["top_mix"] = str(spec_row.iloc[0]["top_mix"])
335
+ summary_rows.append(sub)
336
+
337
+ summary = (
338
+ pd.concat(summary_rows, ignore_index=True)
339
+ if summary_rows
340
+ else pd.DataFrame(columns=["edge_cluster", "rank", "tf_idx", "tf_name", "degree", "mean_score", "specific_to", "top_mix"])
341
+ )
342
+ summary_path = output_dir / f"ec_top{settings['topk_per_ec']}_TF_centrality_bar_data_{settings['selection_mode']}.csv"
343
+ summary.to_csv(summary_path, index=False)
344
+
345
+ saved_figures: list[str] = []
346
+ if settings["save_fig"] and not summary.empty:
347
+ cmap = mpl.colormaps[settings["heatmap_cmap"]].copy()
348
+ cmap.set_bad((0.85, 0.85, 0.85, 1.0))
349
+ norm = mpl.colors.Normalize(vmin=settings["score_vmin"], vmax=settings["score_vmax"])
350
+
351
+ nrows = settings["tf_grid_nrows"]
352
+ ncols = settings["tf_grid_ncols"]
353
+ per_page = nrows * ncols
354
+ ecs = sorted(summary["edge_cluster"].unique().tolist())
355
+ n_pages = int(math.ceil(len(ecs) / per_page))
356
+
357
+ for page in range(n_pages):
358
+ chunk = ecs[page * per_page : (page + 1) * per_page]
359
+ fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(20, 12))
360
+ axes_arr = np.asarray(axes).ravel()
361
+ for axis_idx, ax in enumerate(axes_arr):
362
+ if axis_idx >= len(chunk):
363
+ ax.axis("off")
364
+ continue
365
+ edge_cluster = int(chunk[axis_idx])
366
+ sub = summary[summary["edge_cluster"] == edge_cluster].copy()
367
+ if sub.empty:
368
+ ax.axis("off")
369
+ continue
370
+ sub = sub.sort_values(["degree", "mean_score"], ascending=[True, True], kind="mergesort")
371
+ colors = cmap(norm(sub["mean_score"].fillna(settings["score_vmin"]).to_numpy()))
372
+ ax.barh(sub["tf_name"], sub["degree"], color=colors)
373
+ first = sub.iloc[0]
374
+ title = f"EC{edge_cluster} | {first.get('specific_to', 'mixed')}"
375
+ ax.set_title(title, fontsize=12)
376
+ ax.set_xlabel("Degree", fontsize=12)
377
+ ax.tick_params(axis="x", labelsize=12)
378
+ ax.tick_params(axis="y", labelsize=14)
379
+ ax.spines["top"].set_visible(False)
380
+ ax.spines["right"].set_visible(False)
381
+ fig.suptitle("Top TF centrality per edge cluster", fontsize=18)
382
+ fig.tight_layout()
383
+ out_path = output_dir / (
384
+ f"ec_TF_centrality_grid_{nrows}x{ncols}_page{page + 1:02d}_{settings['selection_mode']}.png"
385
+ )
386
+ fig.savefig(out_path, dpi=300, bbox_inches="tight")
387
+ plt.close(fig)
388
+ saved_figures.append(str(out_path))
389
+
390
+ return summary, saved_figures
391
+
392
+
393
+ def run_edge_cluster_from_config(config: dict[str, Any]) -> dict[str, Any]:
394
+ settings = _edge_cluster_settings(config)
395
+ output_dir = ensure_directory(resolve_config_path(config, settings["output_dir"]))
396
+ network_dir = resolve_config_path(config, settings["network_dir"])
397
+ clusters = settings["clusters"] or discover_network_time_indices(network_dir)
398
+ labels = _cluster_labels(settings, config, clusters)
399
+ labels_by_cluster = {cluster: label for cluster, label in zip(clusters, labels)}
400
+
401
+ _, df_edges = _export_selected_edges(
402
+ network_dir=network_dir,
403
+ clusters=clusters,
404
+ labels=labels,
405
+ output_dir=output_dir,
406
+ settings=settings,
407
+ )
408
+ _export_top_nodes_by_degree(
409
+ df_edges=df_edges,
410
+ labels_by_cluster=labels_by_cluster,
411
+ top_tf_per_cluster=settings["top_tf_per_cluster"],
412
+ top_tg_per_cluster=settings["top_tg_per_cluster"],
413
+ output_dir=output_dir,
414
+ selection_mode=settings["selection_mode"],
415
+ )
416
+
417
+ if df_edges.empty:
418
+ raise ValueError(f"No edges were selected from {network_dir} with mode={settings['selection_mode']}.")
419
+
420
+ edge_tuples, matrix = _edge_binary_matrix(df_edges, clusters)
421
+ scaler = StandardScaler(with_mean=True, with_std=True)
422
+ matrix_z = scaler.fit_transform(matrix) if matrix.shape[0] > 1 else matrix
423
+ km = KMeans(n_clusters=settings["n_clusters"], n_init=10, random_state=settings["random_state"])
424
+ labels_pred = km.fit_predict(matrix_z) if matrix.shape[0] > 1 else np.zeros((matrix.shape[0],), dtype=int)
425
+
426
+ tf_name_map = (
427
+ df_edges.groupby(["tf_idx", "tg_idx"])["tf_name"]
428
+ .first()
429
+ .to_dict()
430
+ )
431
+ tg_name_map = (
432
+ df_edges.groupby(["tf_idx", "tg_idx"])["tg_name"]
433
+ .first()
434
+ .to_dict()
435
+ )
436
+ df_edge_clusters = pd.DataFrame(
437
+ {
438
+ "tf_idx": [edge[0] for edge in edge_tuples],
439
+ "tg_idx": [edge[1] for edge in edge_tuples],
440
+ "tf_name": [tf_name_map[(edge[0], edge[1])] for edge in edge_tuples],
441
+ "tg_name": [tg_name_map[(edge[0], edge[1])] for edge in edge_tuples],
442
+ "edge_cluster": labels_pred,
443
+ }
444
+ )
445
+ edge_clusters_path = output_dir / f"edge_clusters_{settings['n_clusters']}k_{settings['selection_mode']}.csv"
446
+ df_edge_clusters.to_csv(edge_clusters_path, index=False)
447
+
448
+ edge_with_ec = pd.merge(
449
+ df_edges,
450
+ df_edge_clusters[["tf_idx", "tg_idx", "edge_cluster"]],
451
+ on=["tf_idx", "tg_idx"],
452
+ how="left",
453
+ )
454
+ counts_df = (
455
+ pd.crosstab(edge_with_ec["edge_cluster"], edge_with_ec["cell_cluster"])
456
+ .reindex(index=range(settings["n_clusters"]), columns=clusters, fill_value=0)
457
+ )
458
+ counts = counts_df.to_numpy(dtype=float)
459
+ with np.errstate(divide="ignore", invalid="ignore"):
460
+ prop = np.divide(counts, np.maximum(counts.sum(axis=1, keepdims=True), 1e-12))
461
+ prop_df = pd.DataFrame(prop, index=counts_df.index, columns=counts_df.columns)
462
+ counts_path = output_dir / f"edgeCluster_x_cellCluster_counts_{settings['selection_mode']}.csv"
463
+ prop_path = output_dir / f"edgeCluster_x_cellCluster_prop_{settings['selection_mode']}.csv"
464
+ counts_df.to_csv(counts_path)
465
+ prop_df.to_csv(prop_path)
466
+
467
+ heatmap_paths: list[str] = []
468
+ if settings["save_fig"]:
469
+ xt = [labels_by_cluster[cluster] for cluster in clusters]
470
+ yt = [f"EC{k}" for k in range(settings["n_clusters"])]
471
+ ec_edge_counts = counts.sum(axis=1)
472
+ heatmap_paths.append(
473
+ plot_heatmap_with_ec_bar(
474
+ counts,
475
+ xticklabels=xt,
476
+ yticklabels=yt,
477
+ title="Edge cluster",
478
+ path=output_dir / f"heatmap_counts_{settings['n_clusters']}k_{settings['selection_mode']}.png",
479
+ ec_counts=ec_edge_counts,
480
+ cmap_name=settings["heatmap_cmap"],
481
+ )
482
+ )
483
+ heatmap_paths.append(
484
+ plot_heatmap_with_ec_bar(
485
+ prop,
486
+ xticklabels=xt,
487
+ yticklabels=yt,
488
+ title="Edge cluster",
489
+ path=output_dir / f"heatmap_prop_{settings['n_clusters']}k_{settings['selection_mode']}.png",
490
+ ec_counts=ec_edge_counts,
491
+ cmap_name=settings["heatmap_cmap"],
492
+ )
493
+ )
494
+
495
+ df_ec_spec = infer_ec_specificity_topmix(
496
+ prop,
497
+ counts,
498
+ _cluster_labels(settings, config, clusters),
499
+ min_edges=settings["specificity_min_edges"],
500
+ min_max_prop=settings["specificity_min_max_prop"],
501
+ min_gap=settings["specificity_min_gap"],
502
+ topk=settings["specificity_topk"],
503
+ )
504
+ specificity_path = output_dir / f"edgeCluster_specificity_{settings['selection_mode']}.csv"
505
+ df_ec_spec.to_csv(specificity_path, index=False)
506
+
507
+ tf_summary, tf_figures = _tf_centrality_summary(
508
+ df_edges=df_edges,
509
+ df_edge_clusters=df_edge_clusters,
510
+ df_ec_spec=df_ec_spec,
511
+ output_dir=output_dir,
512
+ settings=settings,
513
+ )
514
+
515
+ report = {
516
+ "analysis": "edge_cluster",
517
+ "output_dir": str(output_dir),
518
+ "network_dir": str(network_dir),
519
+ "clusters": clusters,
520
+ "cluster_labels": labels,
521
+ "selection_mode": settings["selection_mode"],
522
+ "selected_edge_count": int(len(df_edges)),
523
+ "union_edge_count": int(len(edge_tuples)),
524
+ "n_edge_clusters": int(settings["n_clusters"]),
525
+ "edge_clusters_path": str(edge_clusters_path),
526
+ "counts_path": str(counts_path),
527
+ "prop_path": str(prop_path),
528
+ "specificity_path": str(specificity_path),
529
+ "heatmap_paths": heatmap_paths,
530
+ "tf_summary_path": str(
531
+ output_dir / f"ec_top{settings['topk_per_ec']}_TF_centrality_bar_data_{settings['selection_mode']}.csv"
532
+ ),
533
+ "tf_figure_paths": tf_figures,
534
+ "settings": settings,
535
+ }
536
+ save_checkpoint_metadata(output_dir / "edge_cluster_report.json", report)
537
+ return report
538
+
539
+
540
+ def run_edge_cluster(config: dict[str, Any] | str | Path) -> dict[str, Any]:
541
+ if isinstance(config, (str, Path)):
542
+ loaded = load_yaml_config(config)
543
+ report = run_edge_cluster_from_config(loaded)
544
+ report["config_path"] = str(Path(config).resolve())
545
+ return report
546
+ return run_edge_cluster_from_config(config)
@@ -0,0 +1,122 @@
1
+ """Gene-symbol keys that ignore case except where case separates genes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import defaultdict
7
+ from collections.abc import Iterable, Iterator, Mapping
8
+
9
+ import pandas as pd
10
+
11
+ _PREFIX = re.compile(r"^(tf:|tg:)", re.IGNORECASE)
12
+
13
+
14
+ def clean_symbol(value: object) -> str:
15
+ """Strip a byte-order mark, surrounding spaces and a TF:/TG: prefix; keep the case."""
16
+ return _PREFIX.sub("", str(value).replace("", "").strip())
17
+
18
+
19
+ class GeneKeys:
20
+ """Match gene symbols without regard to case unless case distinguishes genes.
21
+
22
+ Symbols are compared in lowercase, so tables written in different case
23
+ conventions still match. When the vocabulary has spellings that differ
24
+ only by case, such as the Drosophila genes ``H`` (Hairless) and ``h``
25
+ (hairy), each spelling is its own key. A symbol that reaches such a group
26
+ only by ignoring case, such as ``HDC`` for ``Hdc``/``hdc``, is ambiguous
27
+ and has no key.
28
+ """
29
+
30
+ def __init__(self, *vocabularies: Iterable[object]):
31
+ spellings: dict[str, set[str]] = defaultdict(set)
32
+ for names in vocabularies:
33
+ for name in names:
34
+ symbol = clean_symbol(name)
35
+ spellings[symbol.lower()].add(symbol)
36
+ self.case_sensitive = {
37
+ low for low, forms in spellings.items() if len(forms) > 1
38
+ }
39
+ self._forms = {
40
+ low: next(iter(forms))
41
+ for low, forms in spellings.items()
42
+ if low not in self.case_sensitive
43
+ }
44
+ self._exact = {form for low in self.case_sensitive for form in spellings[low]}
45
+
46
+ def __call__(self, name: object) -> str | None:
47
+ symbol = clean_symbol(name)
48
+ lower = symbol.lower()
49
+ if lower not in self.case_sensitive:
50
+ return lower
51
+ return symbol if symbol in self._exact else None
52
+
53
+ def keys(self, names: Iterable[object]) -> list[str | None]:
54
+ return [self(name) for name in names]
55
+
56
+ def series(self, names: pd.Series) -> pd.Series:
57
+ return names.map(self)
58
+
59
+ def spelling(self, key: str) -> str:
60
+ """The vocabulary spelling of a key (the key itself when unknown)."""
61
+ return self._forms.get(key, key)
62
+
63
+ def request(self, genes: Iterable[str]) -> RequestedGenes:
64
+ return RequestedGenes(self, genes)
65
+
66
+
67
+ class RequestedGenes(Mapping):
68
+ """Gene keys to look up in another table, with their gene-table spellings."""
69
+
70
+ def __init__(self, rule: GeneKeys, genes: Iterable[str]):
71
+ self.rule = rule
72
+ self._spellings = {str(g): rule.spelling(str(g)) for g in dict.fromkeys(genes)}
73
+
74
+ def __getitem__(self, key: str) -> str:
75
+ return self._spellings[key]
76
+
77
+ def __iter__(self) -> Iterator[str]:
78
+ return iter(self._spellings)
79
+
80
+ def __len__(self) -> int:
81
+ return len(self._spellings)
82
+
83
+
84
+ def as_request(genes: Iterable[str]) -> RequestedGenes:
85
+ """Plain gene lists use the case rule of the listed keys themselves."""
86
+ if isinstance(genes, RequestedGenes):
87
+ return genes
88
+ genes = [str(g) for g in genes]
89
+ return GeneKeys(genes).request(genes)
90
+
91
+
92
+ def match_symbol(symbol: object, candidates: Iterable[object]) -> int | None:
93
+ """Position of a requested gene: exact spelling first, else ignoring case when unique."""
94
+ wanted = clean_symbol(symbol)
95
+ values = [clean_symbol(value) for value in candidates]
96
+ if wanted in values:
97
+ return values.index(wanted)
98
+ folded = [i for i, value in enumerate(values) if value.lower() == wanted.lower()]
99
+ spellings = sorted({values[i] for i in folded})
100
+ if len(spellings) > 1:
101
+ raise ValueError(
102
+ f"'{wanted}' matches genes that differ only by case ({', '.join(spellings)}); "
103
+ "use the exact spelling or a gene ID."
104
+ )
105
+ return folded[0] if folded else None
106
+
107
+
108
+ def resolve_symbols(symbols: pd.Series, genes: RequestedGenes) -> pd.Series:
109
+ """Key each symbol of another gene table (such as RNA genes) to a requested gene.
110
+
111
+ When several symbols reach one key, the one spelled as in the gene table is
112
+ kept; any other duplicates remain for the caller to report.
113
+ """
114
+ cleaned = symbols.astype(str).map(clean_symbol)
115
+ resolved = cleaned.map(genes.rule)
116
+ shared = resolved.isin(set(genes)) & resolved.duplicated(keep=False)
117
+ if shared.any():
118
+ preferred = shared & cleaned.eq(resolved.map(lambda key: genes.get(key)))
119
+ winners = resolved[preferred]
120
+ unique_winners = set(winners[~winners.duplicated(keep=False)])
121
+ resolved = resolved.mask(shared & ~preferred & resolved.isin(unique_winners))
122
+ return resolved