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/io.py ADDED
@@ -0,0 +1,101 @@
1
+ """Input helpers for draft_unpaired."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from draft_paired.io import resolve_copy_suffix_path, save_text_report, strip_copy_suffix
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class InputPaths:
14
+ base_dir: Path
15
+ tf_list: Path
16
+ tg_list: Path
17
+ rna_h5ad: Path
18
+ annotation: Path
19
+ tree: Path
20
+ tf_tg_prior: Path
21
+ tf_filter_file: Path | None
22
+ node_tf_scope: Path | None
23
+ node_tg_scope: Path | None
24
+
25
+ @classmethod
26
+ def from_config(cls, config: dict[str, Any]) -> "InputPaths":
27
+ data = config.get("data", {})
28
+ base_dir = Path(str(config.get("base_dir", "."))).expanduser().resolve()
29
+ lineage = str(config.get("lineage", "")).strip() or "lineage1"
30
+ folder = str(config.get("lineage_data_dir") or f"data/{lineage}")
31
+
32
+ def _resolve(key: str, name: str) -> Path:
33
+ """Path from the config, or the file `name` in the lineage folder."""
34
+ target = (base_dir / str(data[key] if key in data else f"{folder}/{name}")).resolve()
35
+ if not target.exists():
36
+ copy = resolve_copy_suffix_path(target)
37
+ if copy is not None:
38
+ return copy.resolve()
39
+ return target
40
+
41
+ def _resolve_optional(key: str) -> Path | None:
42
+ raw = str(data.get(key, "")).strip()
43
+ if not raw:
44
+ return None
45
+ target = (base_dir / raw).resolve()
46
+ if target.exists():
47
+ return target
48
+ copy = resolve_copy_suffix_path(target)
49
+ if copy is not None:
50
+ return copy.resolve()
51
+ return None
52
+
53
+ tf_filter_value = data.get("tf_filter_file")
54
+ tf_filter_path = _resolve("tf_filter_file", "") if tf_filter_value else None
55
+ return cls(
56
+ base_dir=base_dir,
57
+ tf_list=_resolve("tf_list", "TF.tsv"),
58
+ tg_list=_resolve("tg_list", "TG.tsv"),
59
+ rna_h5ad=_resolve("rna_h5ad", "rna.h5ad"),
60
+ annotation=_resolve("annotation", "rna_cells.tsv"),
61
+ tree=_resolve("tree", "tree.tsv"),
62
+ tf_tg_prior=_resolve("tf_tg_prior", "tf_tg_prior.tsv"),
63
+ tf_filter_file=tf_filter_path,
64
+ node_tf_scope=_resolve_optional("node_tf_scope"),
65
+ node_tg_scope=_resolve_optional("node_tg_scope"),
66
+ )
67
+
68
+
69
+ def summarize_input_paths(paths: InputPaths) -> dict[str, str]:
70
+ payload = {
71
+ "base_dir": str(paths.base_dir),
72
+ "tf_list": str(paths.tf_list),
73
+ "tg_list": str(paths.tg_list),
74
+ "rna_h5ad": str(paths.rna_h5ad),
75
+ "annotation": str(paths.annotation),
76
+ "tree": str(paths.tree),
77
+ "tf_tg_prior": str(paths.tf_tg_prior),
78
+ }
79
+ if paths.tf_filter_file is not None:
80
+ payload["tf_filter_file"] = str(paths.tf_filter_file)
81
+ if paths.node_tf_scope is not None:
82
+ payload["node_tf_scope"] = str(paths.node_tf_scope)
83
+ if paths.node_tg_scope is not None:
84
+ payload["node_tg_scope"] = str(paths.node_tg_scope)
85
+ return payload
86
+
87
+
88
+ def has_explicit_tree_config(config: dict[str, Any]) -> bool:
89
+ data = config.get("data", {})
90
+ if not isinstance(data, dict):
91
+ return False
92
+ return bool(str(data.get("tree", "")).strip())
93
+
94
+
95
+ __all__ = [
96
+ "InputPaths",
97
+ "has_explicit_tree_config",
98
+ "save_text_report",
99
+ "strip_copy_suffix",
100
+ "summarize_input_paths",
101
+ ]
@@ -0,0 +1,5 @@
1
+ """Tree-loading helpers reused by draft_unpaired."""
2
+
3
+ from draft_paired.lineage import load_tree_table
4
+
5
+ __all__ = ["load_tree_table"]
@@ -0,0 +1,5 @@
1
+ """Model package for draft_unpaired."""
2
+
3
+ from .gnn import PairNorm, TreeUnpairedTFTGModel, build_model
4
+
5
+ __all__ = ["PairNorm", "TreeUnpairedTFTGModel", "build_model"]
@@ -0,0 +1,187 @@
1
+ """TF-TG graph neural network for unpaired trajectories."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+ from torch_geometric.data import HeteroData
11
+ from torch_geometric.nn import GATConv, HeteroConv
12
+
13
+
14
+ class PairNorm(nn.Module):
15
+ """Normalize centered node features by their mean row norm."""
16
+
17
+ def __init__(self, scale: float = 1.0) -> None:
18
+ super().__init__()
19
+ self.scale = scale
20
+
21
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
22
+ mean = x.mean(dim=0, keepdim=True)
23
+ centered = x - mean
24
+ norm = centered.pow(2).sum(dim=1, keepdim=True).sqrt().mean()
25
+ return self.scale * centered / (norm + 1e-6)
26
+
27
+
28
+ class TreeUnpairedTFTGModel(nn.Module):
29
+ def __init__(
30
+ self,
31
+ in_channels: int,
32
+ hidden_channels: int,
33
+ out_channels: int,
34
+ heads: int = 2,
35
+ dropout_rate: float = 0.4,
36
+ ) -> None:
37
+ super().__init__()
38
+ gat_out = hidden_channels * heads
39
+
40
+ self.hidden_channels = hidden_channels
41
+ self.out_channels = out_channels
42
+ self.dropout = nn.Dropout(dropout_rate)
43
+
44
+ self.conv1 = HeteroConv(
45
+ {
46
+ ("TF", "regulate", "TG"): GATConv(
47
+ in_channels,
48
+ hidden_channels,
49
+ heads=heads,
50
+ add_self_loops=False,
51
+ ),
52
+ ("TG", "regulated_by", "TF"): GATConv(
53
+ in_channels,
54
+ hidden_channels,
55
+ heads=heads,
56
+ add_self_loops=False,
57
+ ),
58
+ },
59
+ aggr="sum",
60
+ )
61
+ self.conv2 = HeteroConv(
62
+ {
63
+ ("TF", "regulate", "TG"): GATConv(
64
+ gat_out,
65
+ hidden_channels,
66
+ heads=heads,
67
+ add_self_loops=False,
68
+ ),
69
+ ("TG", "regulated_by", "TF"): GATConv(
70
+ gat_out,
71
+ hidden_channels,
72
+ heads=heads,
73
+ add_self_loops=False,
74
+ ),
75
+ },
76
+ aggr="sum",
77
+ )
78
+
79
+ self.bn_tf1 = nn.BatchNorm1d(gat_out)
80
+ self.bn_tg1 = nn.BatchNorm1d(gat_out)
81
+ self.bn_tf2 = nn.BatchNorm1d(gat_out)
82
+ self.bn_tg2 = nn.BatchNorm1d(gat_out)
83
+
84
+ self.pn_tf = PairNorm(scale=1.0)
85
+ self.pn_tg = PairNorm(scale=1.0)
86
+
87
+ self.res_tf = nn.Linear(in_channels, gat_out)
88
+ self.res_tg = nn.Linear(in_channels, gat_out)
89
+
90
+ self.gru_tf = nn.GRUCell(gat_out, hidden_channels)
91
+ self.gru_tg = nn.GRUCell(gat_out, hidden_channels)
92
+ self.gru_skip_tf = nn.Linear(gat_out, hidden_channels)
93
+ self.gru_skip_tg = nn.Linear(gat_out, hidden_channels)
94
+
95
+ self.fc_tf = nn.Linear(hidden_channels, out_channels)
96
+ self.fc_tg = nn.Linear(hidden_channels, out_channels)
97
+
98
+ def spatial(self, data: HeteroData) -> tuple[torch.Tensor, torch.Tensor]:
99
+ x_tf0 = data["TF"].x
100
+ x_tg0 = data["TG"].x
101
+ x_dict = {"TF": x_tf0, "TG": x_tg0}
102
+ edge_index_dict = {
103
+ ("TF", "regulate", "TG"): data["TF", "regulate", "TG"].edge_index,
104
+ ("TG", "regulated_by", "TF"): data["TG", "regulated_by", "TF"].edge_index,
105
+ }
106
+
107
+ h1 = self.conv1(x_dict, edge_index_dict)
108
+ h_tf = self.dropout(self.bn_tf1(h1["TF"]))
109
+ h_tg = self.dropout(self.bn_tg1(h1["TG"]))
110
+
111
+ h2 = self.conv2({"TF": h_tf, "TG": h_tg}, edge_index_dict)
112
+ h_tf2 = self.bn_tf2(h2["TF"])
113
+ h_tg2 = self.bn_tg2(h2["TG"])
114
+
115
+ h_tf2 = self.pn_tf(h_tf2)
116
+ h_tg2 = self.pn_tg(h_tg2)
117
+
118
+ h_tf2 = self.dropout(h_tf2 + self.res_tf(x_tf0))
119
+ h_tg2 = self.dropout(h_tg2 + self.res_tg(x_tg0))
120
+ return h_tf2, h_tg2
121
+
122
+ def forward(
123
+ self,
124
+ graphs: list[Any],
125
+ topo_order: list[int],
126
+ parents_list: list[list[int]],
127
+ ) -> tuple[torch.Tensor, torch.Tensor]:
128
+ feat_tf: dict[int, torch.Tensor] = {}
129
+ feat_tg: dict[int, torch.Tensor] = {}
130
+ for time_idx, graph in enumerate(graphs):
131
+ feat_tf[time_idx], feat_tg[time_idx] = self.spatial(graph)
132
+
133
+ hidden_tf: dict[int, torch.Tensor] = {}
134
+ hidden_tg: dict[int, torch.Tensor] = {}
135
+ hidden_size = self.gru_tf.hidden_size
136
+
137
+ for time_idx in topo_order:
138
+ x_tf = feat_tf[time_idx]
139
+ x_tg = feat_tg[time_idx]
140
+ parent_indices = [parent for parent in parents_list[time_idx] if parent is not None and parent >= 0]
141
+
142
+ if len(parent_indices) == 0:
143
+ h0_tf = x_tf.new_zeros(x_tf.size(0), hidden_size)
144
+ h0_tg = x_tg.new_zeros(x_tg.size(0), hidden_size)
145
+ elif len(parent_indices) == 1:
146
+ h0_tf = hidden_tf[parent_indices[0]]
147
+ h0_tg = hidden_tg[parent_indices[0]]
148
+ else:
149
+ h0_tf = torch.stack([hidden_tf[parent] for parent in parent_indices], dim=0).mean(dim=0)
150
+ h0_tg = torch.stack([hidden_tg[parent] for parent in parent_indices], dim=0).mean(dim=0)
151
+
152
+ hidden_tf[time_idx] = self.gru_tf(x_tf, h0_tf) + self.gru_skip_tf(x_tf)
153
+ hidden_tg[time_idx] = self.gru_tg(x_tg, h0_tg) + self.gru_skip_tg(x_tg)
154
+
155
+ tf_stack = torch.stack([hidden_tf[time_idx] for time_idx in topo_order], dim=1)
156
+ tg_stack = torch.stack([hidden_tg[time_idx] for time_idx in topo_order], dim=1)
157
+ return self.fc_tf(tf_stack), self.fc_tg(tg_stack)
158
+
159
+
160
+ def cosine_abs_prob(out_tf: torch.Tensor, out_tg: torch.Tensor, eps: float = 1e-6) -> tuple[list[torch.Tensor], list[torch.Tensor]]:
161
+ sims: list[torch.Tensor] = []
162
+ probs: list[torch.Tensor] = []
163
+ time_count = int(out_tf.size(1))
164
+ for time_idx in range(time_count):
165
+ tf_vec = F.normalize(out_tf[:, time_idx, :], p=2, dim=-1, eps=1e-8)
166
+ tg_vec = F.normalize(out_tg[:, time_idx, :], p=2, dim=-1, eps=1e-8)
167
+ cos = torch.matmul(tf_vec, tg_vec.t())
168
+ prob = cos.abs().clamp(min=eps, max=1.0 - eps)
169
+ sims.append(prob.detach().cpu())
170
+ probs.append(prob)
171
+ return sims, probs
172
+
173
+
174
+ def build_model(
175
+ in_channels: int,
176
+ hidden_channels: int,
177
+ out_channels: int,
178
+ heads: int = 2,
179
+ dropout_rate: float = 0.4,
180
+ ) -> TreeUnpairedTFTGModel:
181
+ return TreeUnpairedTFTGModel(
182
+ in_channels=in_channels,
183
+ hidden_channels=hidden_channels,
184
+ out_channels=out_channels,
185
+ heads=heads,
186
+ dropout_rate=dropout_rate,
187
+ )
@@ -0,0 +1,88 @@
1
+ """Unified unpaired DRAFT pipeline orchestration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from .checkpoint import save_checkpoint_metadata
9
+ from .reproduce import reproduce_lineage_model
10
+ from .train import train_lineage_model
11
+ from .utils import ensure_directory, load_yaml_config, resolve_config_path
12
+
13
+
14
+ def _section(config: dict[str, Any], key: str) -> dict[str, Any]:
15
+ value = config.get(key, {})
16
+ return value if isinstance(value, dict) else {}
17
+
18
+
19
+ def _analysis_enabled(config: dict[str, Any], key: str) -> bool:
20
+ return bool(_section(config, key).get("enabled", False))
21
+
22
+
23
+ def run_draft_pipeline(config_path: str | Path) -> dict[str, Any]:
24
+ from .prior import prepare_training_config
25
+
26
+ requested_config = config_path
27
+ config_path, preparation = prepare_training_config(config_path)
28
+ from .analysis.continuous_activity import run_continuous_activity
29
+ from .analysis.edge_cluster import run_edge_cluster
30
+ from .analysis.network import export_lineage_networks
31
+ from .analysis.single_tf import run_single_tf_analysis
32
+ from .analysis.topic import run_topic_analysis
33
+
34
+ config = load_yaml_config(config_path)
35
+ lineage_name = str(config.get("lineage", "unpaired")).strip() or "unpaired"
36
+ pipeline_cfg = _section(config, "pipeline")
37
+ output_dir = ensure_directory(
38
+ resolve_config_path(config, pipeline_cfg.get("output_dir", f"result/{lineage_name}/pipeline"))
39
+ )
40
+
41
+ training = train_lineage_model(config_path)
42
+ reproduction = reproduce_lineage_model(config_path)
43
+ network = export_lineage_networks(config_path)
44
+
45
+ analyses: dict[str, Any] = {}
46
+ executed: list[str] = []
47
+ skipped: list[str] = []
48
+ if _analysis_enabled(config, "edge_cluster"):
49
+ analyses["edge_cluster"] = run_edge_cluster(config)
50
+ executed.append("edge_cluster")
51
+ else:
52
+ skipped.append("edge_cluster")
53
+ if _analysis_enabled(config, "single_tf"):
54
+ analyses["single_tf"] = run_single_tf_analysis(config)
55
+ executed.append("single_tf")
56
+ else:
57
+ skipped.append("single_tf")
58
+ if _analysis_enabled(config, "topic"):
59
+ analyses["topic"] = run_topic_analysis(config)
60
+ executed.append("topic")
61
+ else:
62
+ skipped.append("topic")
63
+ if _analysis_enabled(config, "continuous_activity"):
64
+ analyses["continuous_activity"] = run_continuous_activity(config)
65
+ executed.append("continuous_activity")
66
+ else:
67
+ skipped.append("continuous_activity")
68
+
69
+ report = {
70
+ "lineage": lineage_name,
71
+ "method_profile": config.get("method_profile"),
72
+ "config_path": str(Path(config_path).resolve()),
73
+ "requested_config_path": str(Path(requested_config).resolve()),
74
+ "prior_preparation": {"report_path": str(Path(preparation["output_dir"]) / "prior_report.json"), "reused": preparation["reused"]} if preparation else None,
75
+ "output_dir": str(output_dir),
76
+ "training": training,
77
+ "reproduction": reproduction,
78
+ "network": network,
79
+ "analyses": analyses,
80
+ "executed_analyses": executed,
81
+ "skipped_analyses": skipped,
82
+ "status": "completed",
83
+ }
84
+ save_checkpoint_metadata(output_dir / "pipeline_report.json", report)
85
+ return report
86
+
87
+
88
+ __all__ = ["run_draft_pipeline"]