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
draft_unpaired/cli.py ADDED
@@ -0,0 +1,200 @@
1
+ """Command line interface for draft_unpaired workflows."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ from typing import Any
7
+
8
+ from draft_paired.cli_options import add_run_options, command_config
9
+
10
+ from .utils import emit_progress
11
+
12
+
13
+ def _result_location(command: str, result: dict[str, Any]) -> str | None:
14
+ if command == "train":
15
+ training = result.get("training", {})
16
+ if isinstance(training, dict):
17
+ return training.get("checkpoint_path") or training.get("artifact_path")
18
+ if command == "reproduce":
19
+ return result.get("output_dir")
20
+ if command == "network-export":
21
+ strict = result.get("strict", {})
22
+ if isinstance(strict, dict):
23
+ return strict.get("output_dir")
24
+ if command in {"single-tf", "edge-cluster", "topic"}:
25
+ return result.get("output_dir")
26
+ if command == "continuous-activity":
27
+ return result.get("figure_path") or result.get("table_path")
28
+ if command == "pipeline":
29
+ network = result.get("network", {})
30
+ if isinstance(network, dict):
31
+ strict = network.get("strict", {})
32
+ if isinstance(strict, dict):
33
+ return strict.get("output_dir")
34
+ return result.get("output_dir")
35
+ if command == "init-config":
36
+ return result.get("output_path")
37
+ return result.get("output_dir")
38
+
39
+
40
+ def build_parser(prog: str = "draft_unpaired") -> argparse.ArgumentParser:
41
+ parser = argparse.ArgumentParser(prog=prog)
42
+ subparsers = parser.add_subparsers(dest="command", required=True)
43
+
44
+ preprocess = subparsers.add_parser("preprocess", help="Prepare stage priors when enabled, stage graphs and a shared training config")
45
+ preprocess.add_argument("--config", required=True, help="Unpaired input YAML")
46
+ preprocess.add_argument("--output", required=True, help="Directory for graphs.pt and train.yaml")
47
+ preprocess.add_argument("--force", action="store_true", help="Replace existing prepared outputs")
48
+
49
+ for name, help_text in [
50
+ ("train", "Run unpaired lineage model training"),
51
+ ("reproduce", "Export embeddings and smoothness summaries"),
52
+ ("network-export", "Export stage-specific TF-TG networks"),
53
+ ("single-tf", "Run single-TF activity and regulon analysis"),
54
+ ("edge-cluster", "Run edge-cluster analysis from exported networks"),
55
+ ("topic", "Run topic analysis from exported networks"),
56
+ ("continuous-activity", "Plot interpolated TF activity from a trained model"),
57
+ ("pipeline", "Run the unified unpaired pipeline"),
58
+ ]:
59
+ subparser = subparsers.add_parser(name, help=help_text)
60
+ subparser.add_argument("--config", required=True, help="Path to a YAML config file")
61
+ add_run_options(subparser, name)
62
+ if name == "network-export":
63
+ subparser.add_argument("--dense", action="store_true", help="Also save interpolated network tables")
64
+
65
+ prior_parser = subparsers.add_parser("prepare-prior", help="Build staged TF-TG candidates from annotated ATAC and TF-RE/RE-TG relations")
66
+ prior_parser.add_argument("--config", required=True, help="Unpaired YAML with optional ATAC preparation inputs")
67
+ prior_parser.add_argument("--output", required=True, help="Directory for the prior, scopes, report and training config")
68
+ prior_parser.add_argument("--force", action="store_true", help="Overwrite previously prepared output files")
69
+
70
+ init_parser = subparsers.add_parser(
71
+ "init-config",
72
+ help="Write the packaged unpaired YAML template to the current directory",
73
+ )
74
+ init_parser.add_argument(
75
+ "--kind", choices=["lineage", "motif", "staged-prior"], default="lineage",
76
+ help="RNA/ATAC with relation tables, supplied called peaks (scMTNI), or an existing stage prior",
77
+ )
78
+ init_parser.add_argument(
79
+ "--output",
80
+ help="Output path for the generated config file",
81
+ )
82
+ init_parser.add_argument("--profile", choices=["methods"], help="Named unpaired parameter profile")
83
+ init_parser.add_argument("--lineage", help="User-defined lineage identifier")
84
+ init_parser.add_argument("--example", choices=["mouse_development", "mouse_motifs"], help="Application presets for manuscript reproduction")
85
+ init_parser.add_argument(
86
+ "--force",
87
+ action="store_true",
88
+ help="Overwrite the output file if it already exists",
89
+ )
90
+
91
+ add_run_options(preprocess, "preprocess", output=False)
92
+ add_run_options(prior_parser, "prepare-prior", output=False)
93
+ return parser
94
+
95
+
96
+ def main(argv: list[str] | None = None, prog: str = "draft_unpaired") -> int:
97
+ parser = build_parser(prog)
98
+ args = parser.parse_args(argv)
99
+ if args.command != "init-config":
100
+ try:
101
+ args.config = command_config(args)
102
+ except (ValueError, TypeError) as exc:
103
+ parser.error(str(exc))
104
+
105
+ if args.command == "preprocess":
106
+ from draft_paired.workflow import preprocess_lineage
107
+
108
+ emit_progress("START", "preprocess", args.config)
109
+ result = preprocess_lineage(args.config, "unpaired", args.output, force=args.force)
110
+ emit_progress("DONE", "preprocess", result["graph_path"])
111
+ emit_progress("NEXT", "train", f"draft train --config \"{result['config_path']}\"")
112
+ return 0
113
+
114
+ if args.command == "prepare-prior":
115
+ from .prior import prepare_stage_prior
116
+
117
+ emit_progress("START", "prepare-prior", args.config)
118
+ result = prepare_stage_prior(args.config, args.output, force=args.force)
119
+ emit_progress("DONE", "prepare-prior", result["config_path"])
120
+ return 0
121
+
122
+ if args.command == "train":
123
+ from .train import train_lineage_model
124
+
125
+ emit_progress("START", "train", args.config)
126
+ result = train_lineage_model(args.config)
127
+ emit_progress("DONE", "train", _result_location(args.command, result))
128
+ return 0
129
+
130
+ if args.command == "reproduce":
131
+ from .reproduce import reproduce_lineage_model
132
+
133
+ emit_progress("START", "reproduce", args.config)
134
+ result = reproduce_lineage_model(args.config)
135
+ emit_progress("DONE", "reproduce", _result_location(args.command, result))
136
+ return 0
137
+
138
+ if args.command == "network-export":
139
+ from .analysis.network import export_lineage_networks
140
+
141
+ emit_progress("START", "network-export", args.config)
142
+ result = export_lineage_networks(args.config, dense=args.dense)
143
+ emit_progress("DONE", "network-export", _result_location(args.command, result))
144
+ return 0
145
+
146
+ if args.command == "single-tf":
147
+ from .analysis.single_tf import run_single_tf_analysis
148
+
149
+ emit_progress("START", "single-tf", args.config)
150
+ result = run_single_tf_analysis(args.config)
151
+ emit_progress("DONE", "single-tf", _result_location(args.command, result))
152
+ return 0
153
+
154
+ if args.command == "edge-cluster":
155
+ from .analysis.edge_cluster import run_edge_cluster
156
+
157
+ emit_progress("START", "edge-cluster", args.config)
158
+ result = run_edge_cluster(args.config)
159
+ emit_progress("DONE", "edge-cluster", _result_location(args.command, result))
160
+ return 0
161
+
162
+ if args.command == "topic":
163
+ from .analysis.topic import run_topic_analysis
164
+
165
+ emit_progress("START", "topic", args.config)
166
+ result = run_topic_analysis(args.config)
167
+ emit_progress("DONE", "topic", _result_location(args.command, result))
168
+ return 0
169
+
170
+ if args.command == "continuous-activity":
171
+ from .analysis.continuous_activity import run_continuous_activity
172
+
173
+ emit_progress("START", "continuous-activity", args.config)
174
+ result = run_continuous_activity(args.config)
175
+ emit_progress("DONE", "continuous-activity", _result_location(args.command, result))
176
+ return 0
177
+
178
+ if args.command == "pipeline":
179
+ from .pipeline import run_draft_pipeline
180
+
181
+ emit_progress("START", "pipeline", args.config)
182
+ result = run_draft_pipeline(args.config)
183
+ emit_progress("DONE", "pipeline", _result_location(args.command, result))
184
+ return 0
185
+
186
+ if args.command == "init-config":
187
+ from .config_init import init_config
188
+
189
+ emit_progress("START", "init-config", "unpaired")
190
+ result = init_config(kind=args.kind, output=args.output, force=bool(args.force), profile=args.profile,
191
+ lineage=args.lineage, example=args.example)
192
+ emit_progress("DONE", "init-config", _result_location(args.command, result))
193
+ return 0
194
+
195
+ parser.error(f"Unsupported command: {args.command}")
196
+ return 1
197
+
198
+
199
+ if __name__ == "__main__":
200
+ raise SystemExit(main())
@@ -0,0 +1,81 @@
1
+ """Template config generation for draft_unpaired."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ from draft_paired.utils import (
8
+ read_packaged_text,
9
+ write_config_text,
10
+ write_packaged_text,
11
+ )
12
+
13
+
14
+ def init_config(
15
+ *,
16
+ kind: str = "lineage",
17
+ output: str | Path | None = None,
18
+ force: bool = False,
19
+ profile: str | None = None,
20
+ lineage: str | None = None,
21
+ example: str | None = None,
22
+ ) -> dict[str, str]:
23
+ template_names = {
24
+ "lineage": "draft_unpaired_template.yaml",
25
+ "motif": "draft_motif_template.yaml",
26
+ "staged-prior": "draft_staged_prior_template.yaml",
27
+ }
28
+ if kind not in template_names:
29
+ raise ValueError(
30
+ "Choose lineage, motif or staged-prior for the unpaired input layout."
31
+ )
32
+ if example is not None and kind != "lineage":
33
+ raise ValueError(
34
+ "Application examples already define their input layout; omit --kind."
35
+ )
36
+ if example is not None and example not in {"mouse_development", "mouse_motifs"}:
37
+ raise ValueError(
38
+ "Choose mouse_development or mouse_motifs for unpaired application settings."
39
+ )
40
+ package = "draft_paired" if example else "draft_unpaired"
41
+ template = (
42
+ f"templates/draft_example_{example}.yaml"
43
+ if example
44
+ else f"templates/{template_names[kind]}"
45
+ )
46
+ target = (
47
+ Path(output)
48
+ if output is not None
49
+ else Path(
50
+ f"configs/examples/{example}.yaml"
51
+ if example
52
+ else f"configs/{template_names[kind]}"
53
+ )
54
+ )
55
+ if profile is not None or lineage is not None:
56
+ from draft_paired.config_profiles import profile_config
57
+
58
+ content = read_packaged_text(package, template)
59
+ if profile is not None:
60
+ content = profile_config(content, profile, "unpaired", lineage)
61
+ else:
62
+ import yaml
63
+
64
+ config = yaml.safe_load(content)
65
+ config["lineage"] = lineage
66
+ content = yaml.safe_dump(config, sort_keys=False)
67
+ written = write_config_text(content, target, overwrite=force)
68
+ else:
69
+ written = write_packaged_text(
70
+ package,
71
+ template,
72
+ target,
73
+ overwrite=force,
74
+ )
75
+ return {
76
+ "kind": "unpaired",
77
+ "output_path": str(written),
78
+ }
79
+
80
+
81
+ __all__ = ["init_config"]
@@ -0,0 +1,220 @@
1
+ """Graph construction for draft_unpaired."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import numpy as np
8
+ import pandas as pd
9
+ import torch
10
+ from torch_geometric.data import HeteroData
11
+
12
+ from .preprocess import CommonInputs, prepare_common_inputs
13
+
14
+
15
+ def zscore_rows(values: np.ndarray, eps: float = 1e-8) -> np.ndarray:
16
+ mean = values.mean(axis=1, keepdims=True)
17
+ std = values.std(axis=1, keepdims=True) + eps
18
+ return (values - mean) / std
19
+
20
+
21
+ def pad_to(values: np.ndarray, target_cols: int) -> np.ndarray:
22
+ if values.shape[1] >= target_cols:
23
+ return values
24
+ pad = np.zeros((values.shape[0], target_cols - values.shape[1]), dtype=values.dtype)
25
+ return np.concatenate([values, pad], axis=1)
26
+
27
+
28
+ def _split_parent_tokens(raw_value: str) -> list[str]:
29
+ return [
30
+ item.strip()
31
+ for item in str(raw_value).replace(";", "|").replace(",", "|").split("|")
32
+ if item.strip()
33
+ ]
34
+
35
+
36
+ def ordered_tree_table(tree_df: pd.DataFrame) -> pd.DataFrame:
37
+ base = tree_df.copy()
38
+ base["node_id"] = base["node_id"].astype(str).str.strip()
39
+ base["parent_id"] = base["parent_id"].astype(str).str.strip()
40
+ base["stage_id"] = pd.to_numeric(base["stage_id"], errors="coerce").fillna(0).astype(int)
41
+ if "branch" not in base.columns:
42
+ base["branch"] = ""
43
+ base["branch"] = base["branch"].astype(str).str.strip()
44
+
45
+ names = base["node_id"].astype(str).tolist()
46
+ row_by_name = {str(row.node_id): row for row in base.itertuples(index=False)}
47
+ parents_by_name: dict[str, list[str]] = {name: [] for name in names}
48
+ children_by_name: dict[str, list[str]] = {name: [] for name in names}
49
+
50
+ for row in base.itertuples(index=False):
51
+ node_name = str(row.node_id)
52
+ parent_names = [item for item in _split_parent_tokens(str(row.parent_id)) if item in row_by_name]
53
+ parents_by_name[node_name] = parent_names
54
+ for parent_name in parent_names:
55
+ children_by_name.setdefault(parent_name, []).append(node_name)
56
+
57
+ roots = [name for name in names if len(parents_by_name.get(name, [])) == 0]
58
+ if not roots and names:
59
+ roots = [names[0]]
60
+
61
+ subtree_sizes: dict[str, int] = {}
62
+
63
+ def _subtree_size(node_name: str) -> int:
64
+ cached = subtree_sizes.get(node_name)
65
+ if cached is not None:
66
+ return cached
67
+ total = 1
68
+ for child_name in children_by_name.get(node_name, []):
69
+ total += _subtree_size(child_name)
70
+ subtree_sizes[node_name] = total
71
+ return total
72
+
73
+ def _node_sort_key(node_name: str) -> tuple[int, int, str]:
74
+ row = row_by_name[node_name]
75
+ return (int(getattr(row, "stage_id", 0)), -_subtree_size(node_name), str(node_name))
76
+
77
+ def _child_sort_key(node_name: str) -> tuple[int, int, str]:
78
+ row = row_by_name[node_name]
79
+ return (-_subtree_size(node_name), int(getattr(row, "stage_id", 0)), str(node_name))
80
+
81
+ ordered_names: list[str] = []
82
+ visited: set[str] = set()
83
+
84
+ def _dfs(node_name: str) -> None:
85
+ if node_name in visited:
86
+ return
87
+ visited.add(node_name)
88
+ ordered_names.append(node_name)
89
+ for child_name in sorted(children_by_name.get(node_name, []), key=_child_sort_key):
90
+ _dfs(child_name)
91
+
92
+ for root_name in sorted(roots, key=_node_sort_key):
93
+ _dfs(root_name)
94
+
95
+ for node_name in names:
96
+ if node_name not in visited:
97
+ _dfs(node_name)
98
+
99
+ return base.set_index("node_id").loc[ordered_names].reset_index()
100
+
101
+
102
+ def _tree_parents(tree_df: pd.DataFrame) -> tuple[list[int], list[list[int]], list[str]]:
103
+ ordered = ordered_tree_table(tree_df)
104
+ names = ordered["node_id"].astype(str).tolist()
105
+ index_by_name = {name: idx for idx, name in enumerate(names)}
106
+ parents: list[list[int]] = [[] for _ in names]
107
+ for idx, raw_value in enumerate(ordered["parent_id"].astype(str).tolist()):
108
+ parents[idx] = [index_by_name[item] for item in _split_parent_tokens(raw_value) if item in index_by_name]
109
+ topo = list(range(len(names)))
110
+ return topo, parents, names
111
+
112
+
113
+ def _node_graphs(common: CommonInputs, ordered_tree: pd.DataFrame) -> tuple[list[HeteroData], int]:
114
+ tf_list = common.tf_list
115
+ tg_list = common.tg_list
116
+ expr_df = common.expr_df
117
+ anno = common.anno
118
+ prior_df = common.prior_df
119
+ node_names = ordered_tree["node_id"].astype(str).tolist()
120
+ max_cells = max(int(len(subanno)) for _, subanno in anno.groupby("cell_type"))
121
+ tf_index = {str(name): idx for idx, name in enumerate(tf_list)}
122
+ tg_index = {str(name): idx for idx, name in enumerate(tg_list)}
123
+
124
+ graphs: list[HeteroData] = []
125
+ for node_id in node_names:
126
+ subanno = anno[anno["cell_type"].astype(str) == str(node_id)].copy()
127
+ cells = subanno["cell_id"].astype(str).tolist()
128
+ edges_frame = prior_df[prior_df["node_id"].astype(str) == str(node_id)]
129
+ explicit_tf_scope = [name for name in common.node_tf_scope.get(str(node_id), []) if name in tf_index]
130
+ explicit_tg_scope = [name for name in common.node_tg_scope.get(str(node_id), []) if name in tg_index]
131
+ node_tf_names = (
132
+ set(explicit_tf_scope)
133
+ if explicit_tf_scope
134
+ else {
135
+ str(value)
136
+ for value in edges_frame["TF"].astype(str).tolist()
137
+ if str(value) in tf_index
138
+ }
139
+ )
140
+ node_tg_names = (
141
+ set(explicit_tg_scope)
142
+ if explicit_tg_scope
143
+ else {
144
+ str(value)
145
+ for value in edges_frame["TG"].astype(str).tolist()
146
+ if str(value) in tg_index
147
+ }
148
+ )
149
+
150
+ # Features outside the node-local gene scope are zeroed.
151
+ # Without explicit scope tables, genes are selected from that node's prior.
152
+ tf_expr = np.zeros((len(tf_list), len(cells)), dtype=np.float32)
153
+ tg_expr = np.zeros((len(tg_list), len(cells)), dtype=np.float32)
154
+ if node_tf_names:
155
+ tf_rows = [tf_index[name] for name in tf_list if name in node_tf_names]
156
+ tf_values = expr_df.loc[[tf_list[idx] for idx in tf_rows], cells].fillna(0.0).to_numpy(dtype=np.float32)
157
+ tf_expr[tf_rows, :] = tf_values
158
+ if node_tg_names:
159
+ tg_rows = [tg_index[name] for name in tg_list if name in node_tg_names]
160
+ tg_values = expr_df.loc[[tg_list[idx] for idx in tg_rows], cells].fillna(0.0).to_numpy(dtype=np.float32)
161
+ tg_expr[tg_rows, :] = tg_values
162
+ tf_expr = pad_to(zscore_rows(np.log1p(tf_expr)), max_cells)
163
+ tg_expr = pad_to(zscore_rows(np.log1p(tg_expr)), max_cells)
164
+
165
+ tf_idx = np.array([tf_index[value] for value in edges_frame["TF"].astype(str).tolist()], dtype=np.int64)
166
+ tg_idx = np.array([tg_index[value] for value in edges_frame["TG"].astype(str).tolist()], dtype=np.int64)
167
+ edge_index = (
168
+ np.stack([tf_idx, tg_idx], axis=0)
169
+ if len(tf_idx) > 0
170
+ else np.zeros((2, 0), dtype=np.int64)
171
+ )
172
+
173
+ graph = HeteroData()
174
+ graph["TF"].x = torch.tensor(tf_expr, dtype=torch.float32, device=common.device)
175
+ graph["TG"].x = torch.tensor(tg_expr, dtype=torch.float32, device=common.device)
176
+ graph["TF", "regulate", "TG"].edge_index = torch.tensor(edge_index, dtype=torch.long, device=common.device)
177
+ graph["TG", "regulated_by", "TF"].edge_index = torch.tensor(edge_index[::-1].copy(), dtype=torch.long, device=common.device)
178
+ graphs.append(graph)
179
+
180
+ return graphs, max_cells
181
+
182
+
183
+ def build_lineage_graph_artifacts(
184
+ config: dict[str, Any], *, device: torch.device | None = None,
185
+ ) -> dict[str, Any]:
186
+ from draft_paired.graph_input import has_graph_input, load_graph_artifacts
187
+
188
+ if has_graph_input(config):
189
+ return load_graph_artifacts(config, "unpaired")
190
+ common = prepare_common_inputs(config, device=device)
191
+ ordered_tree = ordered_tree_table(common.tree_df)
192
+ graphs, max_cells = _node_graphs(common, ordered_tree)
193
+ topo_order, parents_list, time_names = _tree_parents(ordered_tree)
194
+ summary_lines = list(common.summary_lines) + [
195
+ f"Graphs : {len(graphs)}",
196
+ f"Max cells per node : {max_cells}",
197
+ (
198
+ "Node feature scope : explicit node TF/TG scope tables"
199
+ if common.node_tf_scope or common.node_tg_scope
200
+ else "Node feature scope : prior-derived TF/TG rows kept, others zeroed"
201
+ ),
202
+ f"Ordered nodes : {', '.join(time_names)}",
203
+ ]
204
+ return {
205
+ "mode": "tree",
206
+ "common": common,
207
+ "ordered_tree": ordered_tree,
208
+ "graphs_lineage": graphs,
209
+ "topo_order": topo_order,
210
+ "parents_list": parents_list,
211
+ "time_names": time_names,
212
+ "maps": common.maps,
213
+ "in_channels": int(max_cells),
214
+ "num_nodes": len(graphs),
215
+ "device": str(common.device),
216
+ "summary_lines": summary_lines,
217
+ }
218
+
219
+
220
+ __all__ = ["build_lineage_graph_artifacts", "ordered_tree_table", "pad_to", "zscore_rows"]
@@ -0,0 +1,128 @@
1
+ """Inference helpers for unpaired TF-TG lineage checkpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import torch
9
+
10
+ from .checkpoint import find_latest_checkpoint, torch_load_compat
11
+ from .models.gnn import build_model
12
+ from .utils import resolve_config_path
13
+
14
+
15
+ def _select_runtime_device() -> torch.device:
16
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
+
18
+
19
+ def _section(config: dict[str, Any], key: str) -> dict[str, Any]:
20
+ value = config.get(key, {})
21
+ return value if isinstance(value, dict) else {}
22
+
23
+
24
+ def _artifact_filename(config: dict[str, Any]) -> str:
25
+ artifacts_cfg = _section(config, "artifacts")
26
+ explicit = str(artifacts_cfg.get("filename", "")).strip()
27
+ if explicit:
28
+ return explicit
29
+ lineage = str(config.get("lineage", "unpaired")).strip().lower() or "unpaired"
30
+ safe = "".join(ch if ch.isalnum() or ch in {"_", "-"} else "_" for ch in lineage)
31
+ return f"{safe}_graphs.pt"
32
+
33
+
34
+ def _artifact_path(config: dict[str, Any]) -> Path:
35
+ if config.get("data", {}).get("graphs"):
36
+ return resolve_config_path(config, config["data"]["graphs"])
37
+ reproduce_cfg = _section(config, "reproduce")
38
+ explicit = reproduce_cfg.get("artifact_path")
39
+ if explicit:
40
+ return resolve_config_path(config, explicit)
41
+ artifacts_cfg = _section(config, "artifacts")
42
+ artifact_dir = resolve_config_path(
43
+ config,
44
+ artifacts_cfg.get("dir", f"result/{config.get('lineage', 'unpaired')}/train/artifacts"),
45
+ )
46
+ return artifact_dir / _artifact_filename(config)
47
+
48
+
49
+ def _checkpoint_path(config: dict[str, Any]) -> Path:
50
+ reproduce_cfg = _section(config, "reproduce")
51
+ explicit = reproduce_cfg.get("checkpoint_path")
52
+ if explicit:
53
+ return resolve_config_path(config, explicit)
54
+ checkpoints_cfg = _section(config, "checkpoints")
55
+ checkpoint_dir = resolve_config_path(
56
+ config,
57
+ checkpoints_cfg.get("dir", f"result/{config.get('lineage', 'unpaired')}/model"),
58
+ )
59
+ pattern = str(reproduce_cfg.get("checkpoint_pattern", "*.pt"))
60
+ return find_latest_checkpoint(checkpoint_dir, pattern=pattern)
61
+
62
+
63
+ def reload_tree_from_checkpoint(config: dict[str, Any]) -> dict[str, Any]:
64
+ artifact_path = _artifact_path(config)
65
+ checkpoint_path = _checkpoint_path(config)
66
+ if not artifact_path.exists():
67
+ raise FileNotFoundError(f"Lineage artifact was not found: {artifact_path}")
68
+ if not checkpoint_path.exists():
69
+ raise FileNotFoundError(f"Lineage checkpoint was not found: {checkpoint_path}")
70
+
71
+ device = _select_runtime_device()
72
+ artifact = torch_load_compat(artifact_path, map_location="cpu")
73
+ graphs = [graph.to(device) for graph in artifact["graphs"]]
74
+ topo_order = list(artifact["topo_order"])
75
+ parents_list = [list(item) for item in artifact["parents_list"]]
76
+ time_names = list(artifact["time_names"])
77
+ in_channels = int(artifact["in_channels"])
78
+
79
+ checkpoint = torch_load_compat(checkpoint_path, map_location=device)
80
+ hp = checkpoint.get("hp")
81
+ if hp is None:
82
+ raise RuntimeError("The unpaired checkpoint does not contain 'hp'; model reconstruction failed.")
83
+
84
+ model = build_model(
85
+ in_channels=in_channels,
86
+ hidden_channels=int(hp["hidden_channels"]),
87
+ out_channels=int(hp["out_channels"]),
88
+ heads=int(hp["gat_heads"]),
89
+ dropout_rate=float(hp["dropout_rate"]),
90
+ ).to(device)
91
+ state_dict = checkpoint.get("state_dict")
92
+ if state_dict is None:
93
+ raise RuntimeError("The unpaired checkpoint does not contain 'state_dict'.")
94
+ model.load_state_dict(state_dict)
95
+ model.eval()
96
+
97
+ with torch.no_grad():
98
+ out_tf, out_tg = model(graphs, topo_order, parents_list)
99
+
100
+ meta = checkpoint.get("meta", {})
101
+ extra = checkpoint.get("extra", {})
102
+ return {
103
+ "lineage": str(meta.get("lineage_name", config.get("lineage", "unpaired"))),
104
+ "device": str(device),
105
+ "artifact_path": str(artifact_path),
106
+ "checkpoint_path": str(checkpoint_path),
107
+ "graphs": graphs,
108
+ "graphs_lineage": graphs,
109
+ "topo_order": topo_order,
110
+ "parents_list": parents_list,
111
+ "time_names": time_names,
112
+ "in_channels": in_channels,
113
+ "maps": artifact.get("maps", meta.get("maps", {})),
114
+ "hp": hp,
115
+ "meta": meta,
116
+ "extra": extra,
117
+ "checkpoint": checkpoint,
118
+ "model": model,
119
+ "out_tf": out_tf,
120
+ "out_tg": out_tg,
121
+ }
122
+
123
+
124
+ def run_inference(config: dict[str, Any]) -> dict[str, Any]:
125
+ return reload_tree_from_checkpoint(config)
126
+
127
+
128
+ __all__ = ["reload_tree_from_checkpoint", "run_inference"]