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,235 @@
1
+ """Align lineage stages using regulatory-network fingerprints and DTW."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from .gene_keys import GeneKeys
13
+
14
+
15
+ def fingerprint_dtw(
16
+ soma: np.ndarray,
17
+ germ: np.ndarray,
18
+ *,
19
+ band: int | None = 6,
20
+ curvature: float = 1.0,
21
+ n_iter: int = 50,
22
+ entropy_weight: float = 0.0,
23
+ entropy_soma: np.ndarray | None = None,
24
+ entropy_germ: np.ndarray | None = None,
25
+ ) -> np.ndarray:
26
+ """Return normalized second-lineage time for each first-lineage fingerprint.
27
+
28
+ Fingerprints are standardized by the caller. Entropy is an explicit
29
+ sensitivity option; weight zero never reads or validates entropy arrays.
30
+ """
31
+ from .ccc import dtw_path, smooth_warp_d2_monotone
32
+
33
+ soma, germ = np.asarray(soma, float), np.asarray(germ, float)
34
+ if (
35
+ soma.ndim != 2
36
+ or germ.ndim != 2
37
+ or soma.shape[1] != germ.shape[1]
38
+ or min(len(soma), len(germ)) < 2
39
+ ):
40
+ raise ValueError(
41
+ "DTW needs at least two grid points per lineage and equal fingerprint widths."
42
+ )
43
+ if not np.isfinite(soma).all() or not np.isfinite(germ).all():
44
+ raise ValueError("Network fingerprints must be finite.")
45
+ if not np.isfinite(entropy_weight) or entropy_weight < 0:
46
+ raise ValueError("dtw_ent_w must be finite and nonnegative.")
47
+ if not np.isfinite(curvature) or curvature < 0 or n_iter < 1:
48
+ raise ValueError("DTW curvature must be nonnegative and dtw_n_iter positive.")
49
+ cost = ((soma[:, None, :] - germ[None, :, :]) ** 2).sum(axis=2)
50
+ if entropy_weight:
51
+ es, eg = np.asarray(entropy_soma, float), np.asarray(entropy_germ, float)
52
+ if es.shape != (len(soma),) or eg.shape != (len(germ),):
53
+ raise ValueError(
54
+ "Nonzero entropy weight requires one entropy value per grid point."
55
+ )
56
+ if not np.isfinite(es).all() or not np.isfinite(eg).all():
57
+ raise ValueError("Entropy curves must be finite when dtw_ent_w is nonzero.")
58
+ # Scale both costs by their means when combining them.
59
+ extra = (es[:, None] - eg[None, :]) ** 2
60
+ cost = cost / (cost.mean() + 1e-12) + entropy_weight * extra / (
61
+ extra.mean() + 1e-12
62
+ )
63
+ path = dtw_path(cost, band)
64
+ matches: list[list[float]] = [[] for _ in soma]
65
+ for i, j in path:
66
+ matches[i].append(j / (len(germ) - 1))
67
+ warp = np.asarray([np.mean(values) for values in matches])
68
+ warp[0], warp[-1] = 0.0, 1.0
69
+ return smooth_warp_d2_monotone(warp, curvature, n_iter, enforce_endpoints=True)
70
+
71
+
72
+ def network_alignment(
73
+ config: dict[str, Any], output_dir: Path
74
+ ) -> tuple[pd.DataFrame, dict[str, Any]]:
75
+ from ..utils import resolve_config_path
76
+ from .ccc import (
77
+ _ccc_settings,
78
+ _normalize_bipartite,
79
+ _normalize_time_to_01,
80
+ _restrict_to_common,
81
+ _tf_centrality,
82
+ _top_r_svals,
83
+ _zscore_cols,
84
+ _zscore_rows,
85
+ prepare_entropy_on_net_grid,
86
+ )
87
+
88
+ settings = _ccc_settings(config)
89
+ section = config.get("ccc", {})
90
+ aliases = section.get("_lineage_aliases", {})
91
+ columns = {f"{name}_tau": f"{key}_tau" for key, name in aliases.items()}
92
+ if settings["alignment_method"].lower() != "dtw":
93
+ raise ValueError("Receptor-centrality CCC uses ccc.alignment_method: dtw.")
94
+ stored = section.get("alignment_path")
95
+ if stored:
96
+ source = resolve_config_path(config, stored)
97
+ table = pd.read_csv(source, sep="\t")
98
+ table = table.rename(columns=columns)
99
+ if table.columns.duplicated().any():
100
+ raise ValueError("Alignment contains ambiguous lineage coordinate columns.")
101
+ if not {"soma_tau", "germ_tau"}.issubset(table.columns):
102
+ raise ValueError(
103
+ "Stored alignment requires soma_tau and germ_tau columns in [0, 1]."
104
+ )
105
+ report = {
106
+ "source": "stored",
107
+ "path": str(source),
108
+ "sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
109
+ "settings": section.get("alignment_provenance", {}),
110
+ }
111
+ else:
112
+ from .ccc_networks import alignment_series
113
+
114
+ series = [
115
+ alignment_series(config, lineage, settings) for lineage in ("soma", "germ")
116
+ ]
117
+ # Genes match across lineages without regard to case unless case
118
+ # separates genes in either lineage (for example H and h).
119
+ keys = GeneKeys(*(names for item in series for names in (item.tf_names, item.tg_names)))
120
+ tf_keys = [keys.keys(item.tf_names) for item in series]
121
+ tg_keys = [keys.keys(item.tg_names) for item in series]
122
+ tf_common = sorted(set(tf_keys[0]) & set(tf_keys[1]))
123
+ tg_common = sorted(set(tg_keys[0]) & set(tg_keys[1]))
124
+ if min(len(tf_common), len(tg_common)) < 2:
125
+ raise ValueError(
126
+ "Spectral alignment needs at least two shared TFs and TGs."
127
+ )
128
+ features, time_grids, centralities = [], [], []
129
+ for item, item_tfs, item_tgs in zip(series, tf_keys, tg_keys):
130
+ fingerprints, times, centrality = [], [], []
131
+
132
+ def collect(
133
+ time,
134
+ matrix,
135
+ item_tfs=item_tfs,
136
+ item_tgs=item_tgs,
137
+ fingerprints=fingerprints,
138
+ times=times,
139
+ centrality=centrality,
140
+ ):
141
+ shared = _restrict_to_common(
142
+ [matrix], item_tfs, item_tgs, tf_common, tg_common
143
+ )[0]
144
+ normalized = _normalize_bipartite(shared, settings)
145
+ fingerprints.append(_top_r_svals(normalized, settings["finger_r"]))
146
+ times.append(time)
147
+ if settings["dtw_ent_w"]:
148
+ centrality.append(_tf_centrality(normalized))
149
+
150
+ item.visit(collect)
151
+ if len(times) < 2:
152
+ raise ValueError(
153
+ "Alignment requires at least two network timepoints per lineage."
154
+ )
155
+ order = np.argsort(times)
156
+ features.append(_zscore_cols(np.vstack(fingerprints)[order]))
157
+ time_grids.append(np.asarray(times)[order])
158
+ if settings["dtw_ent_w"]:
159
+ centralities.append(np.vstack(centrality)[order])
160
+ ts, tg = time_grids
161
+ es = eg = None
162
+ if settings["dtw_ent_w"]:
163
+ cs, cg = [
164
+ pd.DataFrame(
165
+ _zscore_rows(centrality.T),
166
+ index=tf_common,
167
+ columns=times,
168
+ )
169
+ for centrality, times in zip(centralities, (ts, tg))
170
+ ]
171
+ es, eg = prepare_entropy_on_net_grid(
172
+ cs,
173
+ cg,
174
+ _normalize_time_to_01(ts),
175
+ _normalize_time_to_01(tg),
176
+ resolve_config_path(config, settings["tf_filter_path"]),
177
+ )
178
+ warp = fingerprint_dtw(
179
+ features[0],
180
+ features[1],
181
+ band=None if settings["dtw_band"] is None else int(settings["dtw_band"]),
182
+ curvature=settings["dtw_lam_d2"],
183
+ n_iter=settings["dtw_n_iter"],
184
+ entropy_weight=settings["dtw_ent_w"],
185
+ entropy_soma=es,
186
+ entropy_germ=eg,
187
+ )
188
+ table = pd.DataFrame({"soma_tau": _normalize_time_to_01(ts), "germ_tau": warp})
189
+ table["t_soma_net"] = ts
190
+ table["t_germ_warped"] = tg.min() + warp * (tg.max() - tg.min())
191
+ source = output_dir / settings["warp_dtw_tsv"]
192
+ exported = table.rename(columns={value: key for key, value in columns.items()})
193
+ if aliases:
194
+ exported = exported.rename(
195
+ columns={
196
+ "t_soma_net": f"t_{aliases['soma']}_net",
197
+ "t_germ_warped": f"t_{aliases['germ']}_warped",
198
+ }
199
+ )
200
+ exported.to_csv(source, sep="\t", index=False)
201
+ report = {
202
+ "source": "computed",
203
+ "path": str(source),
204
+ "sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
205
+ "shared_tf_count": len(tf_common),
206
+ "shared_tg_count": len(tg_common),
207
+ "settings": {
208
+ k: settings[k]
209
+ for k in (
210
+ "finger_r",
211
+ "dtw_ent_w",
212
+ "dtw_band",
213
+ "dtw_lam_d2",
214
+ "dtw_n_iter",
215
+ )
216
+ },
217
+ "network_sources": {
218
+ aliases.get(key, key): item.provenance
219
+ for key, item in zip(("soma", "germ"), series)
220
+ },
221
+ }
222
+ values = table[["soma_tau", "germ_tau"]].to_numpy(float)
223
+ if (
224
+ len(values) < 2
225
+ or not np.isfinite(values).all()
226
+ or np.any(values < 0)
227
+ or np.any(values > 1)
228
+ or np.any(np.diff(values[:, 0]) <= 0)
229
+ or np.any(np.diff(values[:, 1]) < 0)
230
+ or not np.allclose(values[[0, -1]], [[0, 0], [1, 1]], atol=1e-8)
231
+ ):
232
+ raise ValueError(
233
+ "Alignment must be finite, monotone, and fixed at (0,0) and (1,1)."
234
+ )
235
+ return table, report
@@ -0,0 +1,95 @@
1
+ """Resolve lineage IDs, directions and input specifications for two-series CCC."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import copy
6
+ import re
7
+ from typing import Any
8
+
9
+
10
+ def normalize_ccc_config(config: dict[str, Any]) -> dict[str, Any]:
11
+ section = config.get("ccc", {})
12
+ if "lineages" not in section:
13
+ return config
14
+ result = copy.deepcopy(config)
15
+ section = result["ccc"]
16
+ lineages = section.pop("lineages")
17
+ if not isinstance(lineages, dict) or len(lineages) != 2:
18
+ raise ValueError(
19
+ "ccc.lineages must contain exactly two named lineage specifications."
20
+ )
21
+ names = section.get("lineage_order", list(lineages))
22
+ if not isinstance(names, list) or len(names) != 2 or set(names) != set(lineages):
23
+ raise ValueError(
24
+ "ccc.lineage_order must list both lineage IDs once, in alignment-axis order."
25
+ )
26
+ if any(not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]*", n) or n == "hub" for n in names):
27
+ raise ValueError(
28
+ "CCC lineage IDs must start with a letter and use letters, digits, _ or -; hub is reserved."
29
+ )
30
+ if "soma" in section or "germ" in section:
31
+ raise ValueError(
32
+ "Use ccc.lineages or the soma/germ key layout, not both."
33
+ )
34
+ aliases = dict(zip(("soma", "germ"), names))
35
+ role = {name: key for key, name in aliases.items()}
36
+ for key, name in aliases.items():
37
+ spec = lineages[name]
38
+ if not isinstance(spec, dict):
39
+ raise ValueError(f"ccc.lineages.{name} must be a mapping.")
40
+ if spec.get("input_mode", "paired") not in {"paired", "unpaired"}:
41
+ raise ValueError(
42
+ f"Unknown input_mode for {name}; choose paired or unpaired."
43
+ )
44
+ if "early_stage_count" not in spec:
45
+ raise ValueError(
46
+ f"Define ccc.lineages.{name}.early_stage_count for your biological early window."
47
+ )
48
+ section[key] = spec
49
+ for field, target in (
50
+ ("network_dir", "network_dir"),
51
+ ("tf_list", "tf_annot"),
52
+ ("tg_list", "tg_annot"),
53
+ ):
54
+ if field in spec:
55
+ section[f"{target}_{key}"] = spec[field]
56
+ if not section.get("alignment_path") and not (spec.get("config") or spec.get("network_dir")):
57
+ raise ValueError(
58
+ f"ccc.lineages.{name} requires config or network_dir when computing an alignment."
59
+ )
60
+ directions = {
61
+ f"{names[0]}_to_{names[1]}": ("soma", "germ"),
62
+ f"{names[1]}_to_{names[0]}": ("germ", "soma"),
63
+ }
64
+ if len(directions) != 2:
65
+ raise ValueError(
66
+ "Lineage IDs produce ambiguous direction names; choose distinct simple IDs."
67
+ )
68
+ if section.get("hub_group"):
69
+ directions.update(
70
+ {f"hub_to_{name}": ("hub", key) for key, name in aliases.items()}
71
+ )
72
+ requested = section.get("directions", list(directions))
73
+ normalized = []
74
+ for item in requested:
75
+ if isinstance(item, dict):
76
+ sender, receiver = item.get("sender"), item.get("receiver")
77
+ if (
78
+ sender not in {*role, "hub"}
79
+ or receiver not in role
80
+ or sender == receiver
81
+ ):
82
+ raise ValueError(f"Invalid CCC sender/receiver: {item!r}.")
83
+ item = f"{sender}_to_{receiver}"
84
+ if item not in directions:
85
+ raise ValueError(
86
+ f"Unknown CCC direction {item!r}; choose from {list(directions)}."
87
+ )
88
+ normalized.append(item)
89
+ if not normalized or len(set(normalized)) != len(normalized):
90
+ raise ValueError("CCC directions must be nonempty and distinct.")
91
+ section["directions"] = normalized
92
+ section["_lineage_aliases"] = aliases
93
+ section["_direction_specs"] = directions
94
+ section.setdefault("warp_dtw_tsv", f"time_warp_{names[0]}_to_{names[1]}.tsv")
95
+ return result
@@ -0,0 +1,209 @@
1
+ """Stream interpolated network matrices from checkpoints when aligning lineages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ from scipy import sparse
13
+
14
+ from ..utils import load_yaml_config, resolve_config_path
15
+
16
+
17
+ @dataclass
18
+ class AlignmentSeries:
19
+ tf_names: list[str]
20
+ tg_names: list[str]
21
+ visit: Callable[[Callable[[float, Any], None]], None]
22
+ provenance: dict[str, Any]
23
+
24
+
25
+ def alignment_series(
26
+ config: dict[str, Any], lineage: str, settings: dict[str, Any]
27
+ ) -> AlignmentSeries:
28
+ from .ccc import EDGE_GLOBS, _load_network_series
29
+
30
+ spec = config.get("ccc", {}).get(lineage, {})
31
+ configured_dir = spec.get("network_dir") or config.get("ccc", {}).get(
32
+ f"network_dir_{lineage}"
33
+ )
34
+ if configured_dir and any(
35
+ next(resolve_config_path(config, configured_dir).glob(pattern), None)
36
+ is not None
37
+ for pattern in EDGE_GLOBS
38
+ ):
39
+ times, matrices, tfs, tgs = _load_network_series(
40
+ resolve_config_path(config, configured_dir),
41
+ resolve_config_path(config, settings[f"tf_annot_{lineage}"]),
42
+ resolve_config_path(config, settings[f"tg_annot_{lineage}"]),
43
+ keep_case=True,
44
+ )
45
+
46
+ def visit_saved(consume):
47
+ for time, matrix in zip(times, matrices):
48
+ consume(float(time), matrix)
49
+
50
+ return AlignmentSeries(
51
+ tfs,
52
+ tgs,
53
+ visit_saved,
54
+ {"source": "exported", "network_dir": str(configured_dir)},
55
+ )
56
+
57
+ if not spec.get("config"):
58
+ # Load an externally supplied network series.
59
+ directory = resolve_config_path(config, settings[f"network_dir_{lineage}"])
60
+ times, matrices, tfs, tgs = _load_network_series(
61
+ directory,
62
+ resolve_config_path(config, settings[f"tf_annot_{lineage}"]),
63
+ resolve_config_path(config, settings[f"tg_annot_{lineage}"]),
64
+ keep_case=True,
65
+ )
66
+
67
+ def visit_external(consume):
68
+ for time, matrix in zip(times, matrices):
69
+ consume(float(time), matrix)
70
+
71
+ return AlignmentSeries(
72
+ tfs,
73
+ tgs,
74
+ visit_external,
75
+ {"source": "exported", "network_dir": str(directory)},
76
+ )
77
+
78
+ config_path = resolve_config_path(config, spec["config"])
79
+ model_config = load_yaml_config(config_path)
80
+ mode = (
81
+ spec.get("input_mode")
82
+ or model_config.get("input_mode")
83
+ or ("unpaired" if model_config.get("data", {}).get("tf_tg_prior") else "paired")
84
+ )
85
+ if (
86
+ mode not in {"paired", "unpaired"}
87
+ or model_config.get("input_mode", mode) != mode
88
+ ):
89
+ raise ValueError(
90
+ "Alignment input_mode must match the paired/unpaired training config."
91
+ )
92
+ model_config.setdefault("base_dir", config.get("base_dir", "."))
93
+ return checkpoint_series(model_config, mode=mode, config_path=str(config_path))
94
+
95
+
96
+ def checkpoint_series(
97
+ model_config: dict[str, Any],
98
+ *,
99
+ mode: str | None = None,
100
+ config_path: str | None = None,
101
+ ) -> AlignmentSeries:
102
+ from .gene_keys import clean_symbol
103
+
104
+ mode = (
105
+ mode
106
+ or model_config.get("input_mode")
107
+ or ("unpaired" if model_config.get("data", {}).get("tf_tg_prior") else "paired")
108
+ )
109
+ if mode not in {"paired", "unpaired"}:
110
+ raise ValueError("Network model mode must be paired or unpaired.")
111
+ module = importlib.import_module(f"draft_{mode}.analysis.network")
112
+ context = module._network_context(model_config)
113
+ if mode == "paired":
114
+ tf_ids, tf_names = context["refs"]["tf_ids"], context["refs"]["tf_names"]
115
+ tg_names = context["refs"]["tg_names"]
116
+ tf_export, tg_export = tf_names, tg_names
117
+ else:
118
+ tf_ids = context["tf_names"]
119
+ tf_export, tg_export = context["tf_names"], context["tg_names"]
120
+ tf_names = context["common"].maps.get("tf_names", tf_export)
121
+ tg_names = context["common"].maps.get("tg_names", tg_export)
122
+
123
+ def clean(names):
124
+ return [clean_symbol(name) for name in names]
125
+
126
+ def positions(names):
127
+ """Exact spelling first; ignoring case only where that stays unique."""
128
+ exact = dict(zip(clean(names), range(len(names))))
129
+ folded: dict[str, set[int]] = {}
130
+ for name, index in exact.items():
131
+ folded.setdefault(name.lower(), set()).add(index)
132
+
133
+ def lookup(values):
134
+ cleaned = pd.Series(values, dtype=str).map(clean_symbol)
135
+ found = cleaned.map(exact)
136
+ missing = found.isna()
137
+ if missing.any():
138
+ unique = {k: next(iter(v)) for k, v in folded.items() if len(v) == 1}
139
+ found = found.where(~missing, cleaned.str.lower().map(unique))
140
+ if found.isna().any():
141
+ raise ValueError(
142
+ f"Exported network genes are missing from the model: {sorted(set(cleaned[found.isna()]))[:5]}"
143
+ )
144
+ return found.to_numpy(dtype=int)
145
+
146
+ return lookup
147
+
148
+ # Names keep their case; alignment decides how case is compared across lineages.
149
+ tfs, tgs = clean(tf_names), clean(tg_names)
150
+ tf_rows, tg_cols = positions(tf_export), positions(tg_export)
151
+ dense_settings = context["dense_settings"]
152
+
153
+ def visit_model(consume):
154
+ def frame_consumer(label, frame):
155
+ if "TF_idx" in frame and "TG_idx" in frame:
156
+ offset = int(dense_settings["use_one_based"])
157
+ rows = frame.TF_idx.to_numpy(dtype=int) - offset
158
+ cols = frame.TG_idx.to_numpy(dtype=int) - offset
159
+ else:
160
+ rows = tf_rows(frame.TF)
161
+ cols = tg_cols(frame.TG)
162
+ values = frame.prob.to_numpy(dtype=np.float32)
163
+ if not np.isfinite(values).all() or np.any(values < 0):
164
+ raise ValueError(
165
+ "Alignment network weights must be finite and nonnegative."
166
+ )
167
+ matrix = sparse.coo_matrix(
168
+ (values, (rows, cols)), shape=(len(tfs), len(tgs))
169
+ ).tocsr()
170
+ matrix.eliminate_zeros()
171
+ consume(float(label), matrix)
172
+
173
+ kwargs = {
174
+ "output_dir": None,
175
+ "out_tf": context["inference"]["out_tf"],
176
+ "out_tg": context["inference"]["out_tg"],
177
+ "tf_names": tf_export,
178
+ "tg_names": tg_export,
179
+ "settings": dense_settings,
180
+ "frame_consumer": frame_consumer,
181
+ }
182
+ if mode == "paired":
183
+ kwargs.update(
184
+ lineage=context["lineage"],
185
+ graphs_sel=context["graphs_sel"],
186
+ tf_ids=tf_ids,
187
+ tf_filter=context["tf_filter"],
188
+ )
189
+ else:
190
+ kwargs.update(
191
+ common=context["common"],
192
+ graphs=context["graphs"],
193
+ time_names=context["time_names"],
194
+ allowed_tfs=context["allowed_tfs"],
195
+ )
196
+ module._export_dense_networks(**kwargs)
197
+
198
+ return AlignmentSeries(
199
+ tfs,
200
+ tgs,
201
+ visit_model,
202
+ {
203
+ "source": "checkpoint",
204
+ "input_mode": mode,
205
+ "config_path": config_path,
206
+ "checkpoint_path": context["inference"]["checkpoint_path"],
207
+ "settings": dense_settings,
208
+ },
209
+ )