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,443 @@
1
+ """Continuous TF activity from saved networks or on-demand model interpolation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import glob
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ import pandas as pd
13
+ from scipy.interpolate import make_interp_spline
14
+
15
+ from ..checkpoint import save_checkpoint_metadata
16
+ from ..input_schema import read_gene_table
17
+ from ..io import strip_copy_suffix
18
+ from ..utils import ensure_directory, load_yaml_config
19
+ from .gene_keys import GeneKeys
20
+
21
+
22
+ def _section(config: dict[str, Any], key: str) -> dict[str, Any]:
23
+ value = config.get(key, {})
24
+ return value if isinstance(value, dict) else {}
25
+
26
+
27
+ def _default_dense_file_patterns() -> list[str]:
28
+ return ["TF_TG_dense_t*.tsv"]
29
+
30
+
31
+ def _continuous_activity_settings(config: dict[str, Any]) -> dict[str, Any]:
32
+ section = _section(config, "continuous_activity")
33
+ lineage = str(config.get("lineage", "")).lower()
34
+ tf_list = section.get("tf_list")
35
+ if tf_list is None:
36
+ tf_symbol = section.get("tf_symbol")
37
+ tf_list = [tf_symbol] if tf_symbol else []
38
+ elif not isinstance(tf_list, list):
39
+ tf_list = [tf_list]
40
+
41
+ colors = section.get("tf_colors", {})
42
+ if not isinstance(colors, dict):
43
+ colors = {}
44
+
45
+ data_cfg = _section(config, "data")
46
+ tf_annot_path = section.get("tf_annot_path", data_cfg.get("tf_list", "TF.tsv"))
47
+
48
+ return {
49
+ "enabled": bool(section.get("enabled", False)),
50
+ "network_dir": str(section.get("network_dir", f"result/{lineage}/network_dense")),
51
+ "output_dir": str(section.get("output_dir", f"result/{lineage}/continuous_activity")),
52
+ "file_patterns": section.get(
53
+ "file_patterns",
54
+ _default_dense_file_patterns(),
55
+ ),
56
+ "tf_annot_path": str(tf_annot_path),
57
+ "tf_gene_col": str(section.get("tf_gene_col", "gene_name")),
58
+ "tf_list": [str(value) for value in tf_list if str(value).strip()],
59
+ "sigma_time": float(section.get("sigma_time", 0.5)),
60
+ "output_figure": str(section.get("output_figure", "Figure_MultiTF_Centrality.pdf")),
61
+ "output_table": str(section.get("output_table", "multi_tf_activity.tsv")),
62
+ "save_fig": bool(section.get("save_fig", True)),
63
+ "save_table": bool(section.get("save_table", True)),
64
+ "show_raw_points": bool(section.get("show_raw_points", True)),
65
+ "prefer_prob": bool(section.get("prefer_prob", True)),
66
+ "index_base": str(section.get("index_base", "infer")),
67
+ "tf_colors": {str(key).lower(): str(value) for key, value in colors.items()},
68
+ "figure_width": float(section.get("figure_width", 7.0)),
69
+ "figure_height": float(section.get("figure_height", 5.5)),
70
+ "title": str(section.get("title", "Continuous Network Dynamics")),
71
+ "xlabel": str(section.get("xlabel", "Normalized Time")),
72
+ "ylabel": str(section.get("ylabel", "Centrality")),
73
+ }
74
+
75
+
76
+ def _parse_time_label(value: str) -> float | None:
77
+ try:
78
+ return float(str(value))
79
+ except ValueError:
80
+ return None
81
+
82
+
83
+ def extract_time_from_filename(path: str | Path) -> float | None:
84
+ match = re.match(r"^TF_TG_dense_t(.+)\.tsv$", Path(path).name)
85
+ if match is None:
86
+ return None
87
+ try:
88
+ return float(match.group(1))
89
+ except ValueError:
90
+ return None
91
+
92
+
93
+ def gaussian_smooth_1d(y: np.ndarray, t: np.ndarray, sigma: float) -> np.ndarray:
94
+ values = np.asarray(y, dtype=float)
95
+ times = np.asarray(t, dtype=float)
96
+
97
+ if np.any(np.isnan(values)):
98
+ series = pd.Series(values)
99
+ values = (
100
+ series.interpolate(limit_direction="both")
101
+ .bfill()
102
+ .ffill()
103
+ .to_numpy(dtype=float)
104
+ )
105
+
106
+ if len(times) > 1:
107
+ unique_times = np.sort(np.unique(times))
108
+ dt = float(np.median(np.diff(unique_times))) if len(unique_times) > 1 else 1.0
109
+ else:
110
+ dt = 1.0
111
+
112
+ radius = max(1, int(round(3 * sigma / dt)))
113
+ offsets = np.arange(-radius, radius + 1)
114
+ kernel_t = offsets * dt
115
+ weights = np.exp(-0.5 * (kernel_t / sigma) ** 2)
116
+ weights = weights / weights.sum()
117
+
118
+ padded = np.pad(values, (radius, radius), mode="edge")
119
+ return np.convolve(padded, weights, mode="valid")
120
+
121
+
122
+ def plot_smooth_curve(
123
+ ax: Any,
124
+ x: np.ndarray,
125
+ y_smooth: np.ndarray,
126
+ color: str,
127
+ label: str,
128
+ raw_y: np.ndarray | None = None,
129
+ ) -> None:
130
+ x_values = np.asarray(x, dtype=float)
131
+ y_values = np.asarray(y_smooth, dtype=float)
132
+
133
+ if raw_y is not None:
134
+ ax.scatter(x_values, raw_y, color=color, alpha=0.28, s=50, edgecolors="none", zorder=1)
135
+
136
+ unique_x = np.unique(x_values)
137
+ if len(unique_x) >= 4:
138
+ frame = pd.DataFrame({"x": x_values, "y": y_values}).groupby("x", as_index=False)["y"].mean()
139
+ x2 = frame["x"].to_numpy(dtype=float)
140
+ y2 = frame["y"].to_numpy(dtype=float)
141
+ if len(x2) >= 4:
142
+ try:
143
+ x_new = np.linspace(x2.min(), x2.max(), 300)
144
+ spline = make_interp_spline(x2, y2, k=3)
145
+ y_new = spline(x_new)
146
+ if np.min(y2) >= 0:
147
+ y_new = np.clip(y_new, 0, None)
148
+ ax.plot(x_new, y_new, color=color, linewidth=3.2, label=label, zorder=2)
149
+ return
150
+ except Exception:
151
+ pass
152
+
153
+ ax.plot(x_values, y_values, color=color, linewidth=3.2, label=label, zorder=2)
154
+
155
+
156
+ def pick_color(tf_lower: str, idx: int, default_cycle: list[str], user_colors: dict[str, str]) -> str:
157
+ if tf_lower in user_colors:
158
+ return user_colors[tf_lower]
159
+ return default_cycle[idx % len(default_cycle)]
160
+
161
+
162
+ def _load_tf_annotation(path: Path, gene_col: str) -> tuple[list[str], dict[int, str]]:
163
+ frame = read_gene_table(path)
164
+ if frame.shape[1] == 1 and str(frame.columns[0]).strip() not in {"gene_name", "symbol", "gene"}:
165
+ tf_names = [str(frame.columns[0]).strip()] + frame.iloc[:, 0].astype(str).tolist()
166
+ tf_names = [strip_copy_suffix(value) for value in tf_names if str(value).strip()]
167
+ idx2tf_name = {idx + 1: name for idx, name in enumerate(tf_names)}
168
+ return tf_names, idx2tf_name
169
+ if gene_col not in frame.columns:
170
+ lower = {str(column).lower(): str(column) for column in frame.columns}
171
+ if gene_col.lower() in lower:
172
+ gene_col = lower[gene_col.lower()]
173
+ elif "gene_name" in lower:
174
+ gene_col = lower["gene_name"]
175
+ elif "symbol" in lower:
176
+ gene_col = lower["symbol"]
177
+ else:
178
+ gene_col = str(frame.columns[0])
179
+ tf_names = frame[gene_col].astype(str).map(strip_copy_suffix).tolist()
180
+ idx2tf_name = {idx + 1: name for idx, name in enumerate(tf_names)}
181
+ return tf_names, idx2tf_name
182
+
183
+
184
+ def _clean_exported_tf_names(series: pd.Series) -> pd.Series:
185
+ return (
186
+ series.astype(str)
187
+ .str.replace("\ufeff", "", regex=False)
188
+ .str.strip()
189
+ .str.replace(r"^tf:", "", regex=True, case=False)
190
+ .map(strip_copy_suffix)
191
+ )
192
+
193
+
194
+ def _discover_dense_files(network_dir: Path, file_patterns: list[str]) -> list[tuple[float, Path]]:
195
+ pairs: list[tuple[float, Path]] = []
196
+ for pattern in file_patterns:
197
+ for path_str in glob.glob(str(network_dir / pattern)):
198
+ time_value = extract_time_from_filename(path_str)
199
+ if time_value is not None:
200
+ pairs.append((time_value, Path(path_str)))
201
+ dedup: dict[str, tuple[float, Path]] = {}
202
+ for time_value, path in pairs:
203
+ dedup[str(path.resolve())] = (time_value, path.resolve())
204
+ unique_pairs = list(dedup.values())
205
+ unique_pairs.sort(key=lambda item: (item[0], item[1].name))
206
+ return unique_pairs
207
+
208
+
209
+ def _find_col_by_lower(frame: pd.DataFrame, candidates: list[str]) -> str | None:
210
+ column_map = {str(column).lower(): str(column) for column in frame.columns}
211
+ for candidate in candidates:
212
+ if candidate in column_map:
213
+ return column_map[candidate]
214
+ return None
215
+
216
+
217
+ def _parse_tf_idx_series(series: pd.Series, index_base: str, tf_count: int) -> pd.Series:
218
+ parsed = pd.to_numeric(series, errors="coerce").astype("Int64")
219
+ base = index_base.lower()
220
+ if base == "zero":
221
+ return parsed + 1
222
+ if base == "one":
223
+ return parsed
224
+
225
+ valid = parsed.dropna().astype(int)
226
+ if valid.empty:
227
+ return parsed
228
+ if int(valid.min()) == 0:
229
+ return parsed + 1
230
+ if int(valid.max()) == tf_count:
231
+ return parsed
232
+ if int(valid.max()) < tf_count:
233
+ return parsed + 1
234
+ return parsed
235
+
236
+
237
+ def _centrality_series(frame: pd.DataFrame, prefer_prob: bool) -> pd.Series:
238
+ col_map = {str(column).lower(): str(column) for column in frame.columns}
239
+ if prefer_prob and "prob" in col_map:
240
+ column = col_map["prob"]
241
+ return frame.groupby("tf_name_lower")[column].sum()
242
+ if "prob" in col_map:
243
+ column = col_map["prob"]
244
+ return frame.groupby("tf_name_lower")[column].sum()
245
+ for candidate in ["score_cos", "score_dot", "score"]:
246
+ if candidate in col_map:
247
+ column = col_map[candidate]
248
+ return frame.groupby("tf_name_lower")[column].sum()
249
+
250
+ tg_column = _find_col_by_lower(frame, ["tg_idx", "tg"])
251
+ if tg_column is None:
252
+ tg_column = str(frame.columns[1] if len(frame.columns) > 1 else frame.columns[0])
253
+ return frame.groupby("tf_name_lower")[tg_column].nunique()
254
+
255
+
256
+ def run_continuous_activity_from_config(config: dict[str, Any]) -> dict[str, Any]:
257
+ settings = _continuous_activity_settings(config)
258
+ if not settings["tf_list"]:
259
+ raise ValueError(
260
+ "Select TFs with --tf TF_NAME, or set continuous_activity.tf_list in the config."
261
+ )
262
+
263
+ base_dir = Path(config.get("base_dir", ".")).expanduser().resolve()
264
+ network_dir = Path(settings["network_dir"]).expanduser()
265
+ if not network_dir.is_absolute():
266
+ network_dir = base_dir / network_dir
267
+ network_dir = network_dir.resolve()
268
+ output_dir = Path(settings["output_dir"]).expanduser()
269
+ if not output_dir.is_absolute():
270
+ output_dir = base_dir / output_dir
271
+ output_dir = ensure_directory(output_dir.resolve())
272
+
273
+ tf_annot_path = Path(settings["tf_annot_path"]).expanduser()
274
+ if not tf_annot_path.is_absolute():
275
+ tf_annot_path = base_dir / tf_annot_path
276
+ tf_names, idx2tf_name = _load_tf_annotation(tf_annot_path.resolve(), settings["tf_gene_col"])
277
+ genes = read_gene_table(tf_annot_path.resolve())
278
+ id_to_name = dict(zip(genes.gene_id, genes.gene_name))
279
+ settings["tf_list"] = list(dict.fromkeys(id_to_name.get(name, name) for name in settings["tf_list"]))
280
+
281
+ configured_patterns = [str(pattern) for pattern in settings["file_patterns"]]
282
+ pairs = _discover_dense_files(network_dir, configured_patterns)
283
+ used_patterns = configured_patterns
284
+ if not pairs:
285
+ fallback_patterns = _default_dense_file_patterns()
286
+ if configured_patterns != fallback_patterns:
287
+ pairs = _discover_dense_files(network_dir, fallback_patterns)
288
+ if pairs:
289
+ used_patterns = fallback_patterns
290
+ times = np.asarray([item[0] for item in pairs], dtype=float)
291
+ files = [item[1] for item in pairs]
292
+ source = None
293
+ if not pairs:
294
+ from .ccc_networks import checkpoint_series
295
+
296
+ source = checkpoint_series(config)
297
+ # TFs match without regard to case unless case separates them (Drosophila H and h).
298
+ keys = GeneKeys(tf_names, source.tf_names if source is not None else [])
299
+ tf_keys = []
300
+ for name in settings["tf_list"]:
301
+ key = keys(name)
302
+ if key is None:
303
+ raise ValueError(
304
+ f"TF '{name}' matches TFs that differ only by case; use the exact spelling or a gene ID."
305
+ )
306
+ tf_keys.append(key)
307
+ tf_list_lower = list(dict.fromkeys(tf_keys))
308
+ activity: dict[str, list[float]] = {value: [] for value in tf_list_lower}
309
+ model_source = None
310
+ if source is not None:
311
+ computed_times = []
312
+ source_keys = keys.keys(source.tf_names)
313
+
314
+ def collect(time, matrix):
315
+ centrality = pd.Series(np.asarray(matrix.sum(axis=1)).ravel(), index=source_keys).groupby(level=0).sum()
316
+ computed_times.append(time)
317
+ for tf_lower in tf_list_lower:
318
+ activity[tf_lower].append(float(centrality.get(tf_lower, 0.0)))
319
+
320
+ source.visit(collect)
321
+ times = np.asarray(computed_times, dtype=float)
322
+ if len(times) < 2:
323
+ raise ValueError("Continuous activity requires at least two network timepoints.")
324
+ model_source = source.provenance
325
+ for time_value, path in pairs:
326
+ try:
327
+ frame = pd.read_csv(path, sep="\t")
328
+ except Exception:
329
+ for tf_lower in tf_list_lower:
330
+ activity[tf_lower].append(0.0)
331
+ continue
332
+
333
+ frame = frame.copy()
334
+ tf_name_col = _find_col_by_lower(frame, ["tf", "tf_name", "tf_symbol", "tf_gene"])
335
+ if tf_name_col is not None:
336
+ frame["tf_name"] = _clean_exported_tf_names(frame[tf_name_col])
337
+ else:
338
+ tf_idx_col = _find_col_by_lower(frame, ["tf_idx", "tfid", "tf_index"])
339
+ if tf_idx_col is None:
340
+ for tf_lower in tf_list_lower:
341
+ activity[tf_lower].append(0.0)
342
+ continue
343
+ tf_idx_one_based = _parse_tf_idx_series(frame[tf_idx_col], settings["index_base"], len(tf_names))
344
+ frame["tf_name"] = tf_idx_one_based.map(idx2tf_name)
345
+ frame["tf_name"] = frame["tf_name"].map(lambda value: id_to_name.get(value, value))
346
+ frame = frame.dropna(subset=["tf_name"])
347
+ frame["tf_name_lower"] = keys.series(frame["tf_name"].astype(str))
348
+
349
+ centrality = _centrality_series(frame, settings["prefer_prob"])
350
+ for tf_lower in tf_list_lower:
351
+ value = float(centrality.get(tf_lower, 0.0))
352
+ activity[tf_lower].append(value)
353
+
354
+ for tf_lower in tf_list_lower:
355
+ activity[tf_lower] = list(np.asarray(activity[tf_lower], dtype=float))
356
+
357
+ if len(np.unique(times)) < len(times):
358
+ merged = pd.DataFrame({"time": times})
359
+ for tf_lower in tf_list_lower:
360
+ merged[tf_lower] = np.asarray(activity[tf_lower], dtype=float)
361
+ merged = merged.groupby("time", as_index=False).mean(numeric_only=True)
362
+ times = merged["time"].to_numpy(dtype=float)
363
+ for tf_lower in tf_list_lower:
364
+ activity[tf_lower] = list(merged[tf_lower].to_numpy(dtype=float))
365
+
366
+ smooth: dict[str, np.ndarray] = {}
367
+ for tf_lower in tf_list_lower:
368
+ smooth[tf_lower] = gaussian_smooth_1d(np.asarray(activity[tf_lower], dtype=float), times, settings["sigma_time"])
369
+
370
+ fig, ax = plt.subplots(figsize=(settings["figure_width"], settings["figure_height"]))
371
+ default_cycle = plt.rcParams["axes.prop_cycle"].by_key().get("color", ["#000000"])
372
+
373
+ for idx, (tf_name, tf_lower) in enumerate(zip(settings["tf_list"], tf_keys)):
374
+ color = pick_color(tf_lower.lower(), idx, default_cycle, settings["tf_colors"])
375
+ plot_smooth_curve(
376
+ ax,
377
+ times,
378
+ smooth[tf_lower],
379
+ color=color,
380
+ label=tf_name,
381
+ raw_y=np.asarray(activity[tf_lower], dtype=float) if settings["show_raw_points"] else None,
382
+ )
383
+
384
+ ax.set_title(settings["title"], loc="center", fontsize=20, pad=15)
385
+ ax.set_xlabel(settings["xlabel"], fontsize=18, fontweight="medium")
386
+ ax.set_ylabel(settings["ylabel"], fontsize=18, fontweight="medium")
387
+ ax.spines["top"].set_visible(False)
388
+ ax.spines["right"].set_visible(False)
389
+ y_max = max(float(np.max(np.asarray(activity[tf_lower], dtype=float))) for tf_lower in tf_list_lower)
390
+ ax.set_ylim(0, y_max * 1.05 if y_max > 0 else 1.0)
391
+
392
+ n_tf = len(settings["tf_list"])
393
+ ncol = 1 if n_tf <= 6 else 2
394
+ legend_fs = 16 if n_tf <= 6 else 12
395
+ ax.legend(frameon=False, fontsize=legend_fs, loc="upper right", ncol=ncol)
396
+ plt.tight_layout()
397
+
398
+ figure_path = output_dir / settings["output_figure"]
399
+ table_path = output_dir / settings["output_table"]
400
+
401
+ if settings["save_fig"]:
402
+ fig.savefig(figure_path, dpi=300, transparent=True)
403
+ plt.close(fig)
404
+
405
+ rows = []
406
+ for tf_name, tf_lower in zip(settings["tf_list"], tf_keys):
407
+ for time_value, raw_value, smooth_value in zip(times.tolist(), activity[tf_lower], smooth[tf_lower].tolist()):
408
+ rows.append(
409
+ {
410
+ "time": float(time_value),
411
+ "tf_query": str(tf_name),
412
+ "centrality_raw": float(raw_value),
413
+ "centrality_smooth": float(smooth_value),
414
+ }
415
+ )
416
+ table = pd.DataFrame(rows).sort_values(["tf_query", "time"], kind="mergesort").reset_index(drop=True)
417
+ if settings["save_table"]:
418
+ table.to_csv(table_path, sep="\t", index=False)
419
+
420
+ report = {
421
+ "analysis": "continuous_activity",
422
+ "output_dir": str(output_dir),
423
+ "network_dir": str(network_dir) if pairs else None,
424
+ "model_source": model_source,
425
+ "file_count": int(len(files)),
426
+ "used_file_patterns": used_patterns,
427
+ "times": [float(value) for value in times.tolist()],
428
+ "tf_list": settings["tf_list"],
429
+ "figure_path": str(figure_path) if settings["save_fig"] else None,
430
+ "table_path": str(table_path) if settings["save_table"] else None,
431
+ "settings": settings,
432
+ }
433
+ save_checkpoint_metadata(output_dir / "continuous_activity_report.json", report)
434
+ return report
435
+
436
+
437
+ def run_continuous_activity(config: dict[str, Any] | str | Path) -> dict[str, Any]:
438
+ if isinstance(config, (str, Path)):
439
+ loaded = load_yaml_config(config)
440
+ report = run_continuous_activity_from_config(loaded)
441
+ report["config_path"] = str(Path(config).resolve())
442
+ return report
443
+ return run_continuous_activity_from_config(config)