bdeivh 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.
@@ -0,0 +1,573 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Predict epidemiological parameters from a genomic tree using a trained PhyloCNN model.
4
+
5
+ This version supports models trained with pinball loss, producing prediction intervals:
6
+ 6 target parameters x 3 quantiles = 18 output values
7
+
8
+ Output columns:
9
+ Rvh_lower, Rvh, Rvh_upper
10
+ Rhv_lower, Rhv, Rhv_upper
11
+ Rhh_lower, Rhh, Rhh_upper
12
+ d_v_lower, d_v, d_v_upper
13
+ d_h_lower, d_h, d_h_upper
14
+ v2h_ratio_lower, v2h_ratio, v2h_ratio_upper
15
+ """
16
+
17
+ import os
18
+ import sys
19
+ import argparse
20
+ import warnings
21
+ import tempfile
22
+ import numpy as np
23
+ import pandas as pd
24
+ from tensorflow.keras.models import model_from_json
25
+ from keras.src.saving import serialization_lib
26
+
27
+ from bdeivh.Phylocnn_Encoding import process_tree
28
+
29
+ serialization_lib.enable_unsafe_deserialization()
30
+
31
+ from ete3 import Tree
32
+
33
+ warnings.filterwarnings("ignore")
34
+ sys.setrecursionlimit(100000)
35
+
36
+ TARGET_COLS = ["Rvh", "Rhv", "Rhh", "d_v", "d_h", "v2h_ratio"]
37
+ QUANTILES = ("lower", "median", "upper")
38
+ COLS_TO_RESCALE = ["d_v", "d_h"]
39
+
40
+ MODEL_DIR = os.path.join(os.path.dirname(__file__), 'models')
41
+
42
+ OROV = 'OROV'
43
+ TT = 'TT'
44
+
45
+
46
+ def genomic_tree_rescaling(original_tree, tree_scale):
47
+ """Rescale branch lengths to days when the supplied tree is in years.
48
+
49
+ tree_scale:
50
+ 0 = tree already in days
51
+ 1 = tree in years, converted to days
52
+ """
53
+ if tree_scale not in (0, 1):
54
+ raise ValueError("tree_scale must be 0 for days or 1 for years.")
55
+
56
+ scaled_tree = original_tree.copy(method="deepcopy")
57
+ if tree_scale == 1:
58
+ for node in scaled_tree.traverse():
59
+ node.dist *= 365.0
60
+ return scaled_tree
61
+
62
+
63
+ def encode_pad_0s_rootage_single(enc, max_len=400):
64
+ """Pad leaves and internal nodes to match the model input shape."""
65
+ enc_pad = []
66
+
67
+ for i in range(enc.shape[0]):
68
+ leaves = enc[i][enc[i, :, 3] == 1]
69
+ leaves = leaves[np.argsort(leaves[:, 1])]
70
+
71
+ if leaves.shape[0] > max_len:
72
+ raise ValueError(f"Too many leaves: {leaves.shape[0]} > {max_len}.")
73
+
74
+ leaves = np.pad(
75
+ leaves,
76
+ [(0, max_len - leaves.shape[0]), (0, 0)],
77
+ mode="constant",
78
+ )
79
+
80
+ nodes = enc[i][enc[i, :, 3] > 1]
81
+ nodes = nodes[np.argsort(nodes[:, 1])]
82
+
83
+ if nodes.shape[0] == 0:
84
+ raise ValueError("No internal nodes were found in the encoded tree.")
85
+
86
+ # Same behavior used in the training notebook: duplicate the last internal node.
87
+ nodes = np.append(nodes, nodes[-1].reshape(1, -1), axis=0)
88
+
89
+ if nodes.shape[0] > max_len:
90
+ raise ValueError(f"Too many internal nodes: {nodes.shape[0]} > {max_len}.")
91
+
92
+ nodes = np.pad(
93
+ nodes,
94
+ [(0, max_len - nodes.shape[0]), (0, 0)],
95
+ mode="constant",
96
+ )
97
+
98
+ enc_pad.append(np.stack((leaves, nodes), axis=2))
99
+
100
+ return np.array(enc_pad, dtype="float32")
101
+
102
+
103
+ def load_encoded_tree(encoded_file):
104
+ """Load a PhyloCNN encoded tree file and extract its rescaling factor."""
105
+ if not os.path.exists(encoded_file):
106
+ raise FileNotFoundError(f"Encoded file was not created: {encoded_file}")
107
+
108
+ enc_real_df = pd.read_csv(encoded_file, sep="\t", header=0)
109
+
110
+ drop_cols = [c for c in ("Index", "Unnamed: 0") if c in enc_real_df.columns]
111
+ if drop_cols:
112
+ enc_real_df = enc_real_df.drop(columns=drop_cols)
113
+
114
+ enc_real = enc_real_df.values.astype("float32")
115
+
116
+ rows_per_tree = 800
117
+ n_rows = enc_real.shape[0]
118
+ if n_rows % rows_per_tree != 0:
119
+ raise ValueError(
120
+ f"Encoded file has {n_rows} rows, which is not a multiple of {rows_per_tree}."
121
+ )
122
+
123
+ n_trees = n_rows // rows_per_tree
124
+ enc_real = enc_real.reshape(n_trees, rows_per_tree, enc_real.shape[1])
125
+
126
+ resc_factor_real = enc_real[:, -1, -1]
127
+ enc_real = np.delete(enc_real, -1, axis=1)
128
+
129
+ return enc_real, resc_factor_real
130
+
131
+
132
+ def add_sampling_probability(enc_real, sampling_probability):
133
+ """Add the sampling probability p as one extra feature column for every row."""
134
+ if not 0 <= sampling_probability <= 1:
135
+ raise ValueError("sampling_probability must be between 0 and 1.")
136
+
137
+ p_col = np.full(
138
+ (enc_real.shape[0], enc_real.shape[1], 1),
139
+ sampling_probability,
140
+ dtype="float32",
141
+ )
142
+ return np.concatenate((enc_real, p_col), axis=2)
143
+
144
+
145
+ def load_trained_model(model_json_file, model_weights_file):
146
+ """Load a trusted Keras model containing Lambda layers."""
147
+
148
+ if not os.path.exists(model_json_file):
149
+ raise FileNotFoundError(f"Model JSON not found: {model_json_file}")
150
+
151
+ if not os.path.exists(model_weights_file):
152
+ raise FileNotFoundError(f"Model weights not found: {model_weights_file}")
153
+
154
+ with open(model_json_file, "r") as json_file:
155
+ model_json = json_file.read()
156
+
157
+ # Required by this Keras version to deserialize trusted Lambda layers.
158
+ from keras.src.saving import serialization_lib
159
+ serialization_lib.enable_unsafe_deserialization()
160
+
161
+ model = model_from_json(model_json)
162
+ model.load_weights(model_weights_file)
163
+
164
+ return model
165
+
166
+
167
+ def predictions_to_dataframe(pred, resc_factor_real):
168
+ """Convert model output to a dataframe with lower/median/upper columns."""
169
+ expected_outputs = len(TARGET_COLS) * len(QUANTILES)
170
+
171
+ if len(pred.shape) != 2:
172
+ pred = np.reshape(pred, (pred.shape[0], -1))
173
+
174
+ if pred.shape[1] != expected_outputs:
175
+ raise ValueError(
176
+ f"Unexpected model output shape {pred.shape}. Expected {expected_outputs} columns "
177
+ f"({len(TARGET_COLS)} targets x {len(QUANTILES)} quantiles)."
178
+ )
179
+
180
+ pred = pred.reshape(-1, len(TARGET_COLS), len(QUANTILES))
181
+
182
+ pred_cols = []
183
+ for target in TARGET_COLS:
184
+ pred_cols.extend([f"{target}_lower", target, f"{target}_upper"])
185
+
186
+ predicted = pd.DataFrame(
187
+ pred.reshape(pred.shape[0], -1),
188
+ columns=pred_cols,
189
+ )
190
+
191
+ # d_v and d_h were trained in rescaled units, so all quantiles must be rescaled back.
192
+ for col in COLS_TO_RESCALE:
193
+ for q_col in (f"{col}_lower", col, f"{col}_upper"):
194
+ predicted[q_col] = predicted[q_col].values * resc_factor_real
195
+
196
+ return predicted
197
+
198
+
199
+ def predict_parameters(encoded_file, sampling_probability, model_json_file, model_weights_file):
200
+ enc_real, resc_factor_real = load_encoded_tree(encoded_file)
201
+ enc_real = add_sampling_probability(enc_real, sampling_probability)
202
+ enc_real = encode_pad_0s_rootage_single(enc_real)
203
+
204
+ model = load_trained_model(model_json_file, model_weights_file)
205
+ pred = model.predict(enc_real)
206
+
207
+ return predictions_to_dataframe(pred, resc_factor_real)
208
+
209
+
210
+
211
+ # Tree-size ranges used by the size-specific models.
212
+ # Boundaries are treated as [30, 50), [50, 150), [150, 250), [250, 350].
213
+ # If your simulation pipeline used a different convention for exact boundary
214
+ # values (50, 150, 250), adjust this table accordingly.
215
+ TEMPORAL_MODEL_BINS = (
216
+ (30, 50, "30_50"),
217
+ (50, 150, "50_150"),
218
+ (150, 250, "150_250"),
219
+ (250, 350, "250_350"),
220
+ )
221
+
222
+
223
+ def get_tree_height(tree):
224
+ """Return the maximum root-to-tip distance of a tree."""
225
+ leaves = tree.get_leaves()
226
+ if not leaves:
227
+ raise ValueError("The tree has no leaves.")
228
+ return max(tree.get_distance(leaf) for leaf in leaves)
229
+
230
+
231
+ def prune_tree_to_observed_tips(original_tree, cutoff_days, min_tips=2):
232
+ """Return the tree that would be observable up to ``cutoff_days``.
233
+
234
+ Only original tips whose root-to-tip distance is <= cutoff_days are kept.
235
+ Future tips are removed and no artificial tips are created at the cutoff.
236
+ This is the recommended mode for retrospective real-time analyses because
237
+ it avoids using lineages that are only known from future samples.
238
+ """
239
+ if cutoff_days < 0:
240
+ raise ValueError("cutoff_days must be >= 0.")
241
+
242
+ tree = original_tree.copy(method="deepcopy")
243
+ keep = [
244
+ leaf for leaf in tree.get_leaves()
245
+ if tree.get_distance(leaf) <= cutoff_days + 1e-9
246
+ ]
247
+
248
+ if len(keep) < min_tips:
249
+ return None
250
+
251
+ tree.prune(keep, preserve_branch_length=True)
252
+ return tree
253
+
254
+
255
+ def truncate_tree_geometrically(original_tree, cutoff_days):
256
+ """Geometrically truncate every lineage crossing ``cutoff_days``.
257
+
258
+ Branches crossing the time slice are shortened to the cutoff and their
259
+ descendants are removed, creating artificial tips at the slice. This is
260
+ useful for a literal time-slice analysis, but it is not equivalent to the
261
+ phylogeny that would have been observable in real time.
262
+ """
263
+ if cutoff_days < 0:
264
+ raise ValueError("cutoff_days must be >= 0.")
265
+
266
+ tree = original_tree.copy(method="deepcopy")
267
+ synthetic_tip_counter = [0]
268
+
269
+ def _walk(node, parent_age):
270
+ for child in list(node.children):
271
+ child_age = parent_age + child.dist
272
+
273
+ if child_age > cutoff_days + 1e-9:
274
+ # This branch crosses the requested time slice.
275
+ child.dist = max(cutoff_days - parent_age, 0.0)
276
+
277
+ for descendant in list(child.children):
278
+ descendant.detach()
279
+
280
+ synthetic_tip_counter[0] += 1
281
+ child.name = (
282
+ f"slice_{cutoff_days:g}d_"
283
+ f"{synthetic_tip_counter[0]:04d}"
284
+ )
285
+ else:
286
+ _walk(child, child_age)
287
+
288
+ _walk(tree, 0.0)
289
+ return tree
290
+
291
+
292
+ def select_temporal_model(n_tips, model_dir=MODEL_DIR, tree_type=OROV):
293
+ """Return (label, json_path, weights_path) for a tree-size-specific model."""
294
+ selected = None
295
+
296
+ for i, (lower, upper, label) in enumerate(TEMPORAL_MODEL_BINS):
297
+ is_last = i == len(TEMPORAL_MODEL_BINS) - 1
298
+ inside = (lower <= n_tips <= upper) if is_last else (lower <= n_tips < upper)
299
+ if inside:
300
+ selected = label
301
+ break
302
+
303
+ if selected is None:
304
+ return None
305
+
306
+ model_json = os.path.join(
307
+ model_dir,
308
+ f"{selected}_{tree_type}_BDEIVH.json",
309
+ )
310
+ model_weights = os.path.join(
311
+ model_dir,
312
+ f"{selected}_{tree_type}_BDEIVH.weights.h5",
313
+ )
314
+
315
+ return selected, model_json, model_weights
316
+
317
+
318
+ def predict_tree_object(
319
+ tree,
320
+ sampling_probability,
321
+ model,
322
+ workdir,
323
+ prefix,
324
+ ):
325
+ """Encode one ETE tree and predict its epidemiological parameters."""
326
+ tree_file = os.path.join(workdir, f"{prefix}.nwk")
327
+ encoded_file = os.path.join(workdir, f"{prefix}.tsv")
328
+
329
+ tree.write(outfile=tree_file, format=1)
330
+ encode_tree(tree_file, encoded_file)
331
+
332
+ enc_real, resc_factor_real = load_encoded_tree(encoded_file)
333
+ enc_real = add_sampling_probability(enc_real, sampling_probability)
334
+ enc_real = encode_pad_0s_rootage_single(enc_real)
335
+
336
+ pred = model.predict(enc_real, verbose=0)
337
+ return predictions_to_dataframe(pred, resc_factor_real)
338
+
339
+
340
+ def encode_tree(tree_file: str, encoded_file: str):
341
+ result = process_tree(tree_file)
342
+ if isinstance(result, pd.DataFrame):
343
+ result.to_csv(encoded_file, sep="\t", index=True)
344
+ if isinstance(result, np.ndarray):
345
+ pd.DataFrame(result).to_csv(encoded_file, sep="\t", index=True)
346
+
347
+
348
+ def predict_every_n_days(
349
+ original_tree,
350
+ sampling_probability,
351
+ step_days=7.0,
352
+ model_dir=MODEL_DIR,
353
+ tree_type=OROV,
354
+ include_final=True,
355
+ ):
356
+ """Predict BDEIVH parameters from sequential time slices of one tree.
357
+
358
+ Parameters
359
+ ----------
360
+ original_tree : ete3.Tree
361
+ Tree already expressed in days. Apply ``genomic_tree_rescaling`` first
362
+ when the input tree is in years.
363
+ sampling_probability : float
364
+ Sampling probability p supplied to the PhyloCNN, as in the original
365
+ prediction script. This function assumes p is constant through time.
366
+ step_days : float, default=7
367
+ Interval between successive cutoffs measured from the root.
368
+ model_dir : str
369
+ Directory containing the four tree-size-specific trained models.
370
+ tree_type : str
371
+ Type of tree being analyzed (e.g., 'OROV' or 'TRANSMISSION').
372
+ include_final : bool
373
+ Also analyse the full-tree height when it is not an exact multiple of
374
+ ``step_days``.
375
+
376
+ Returns
377
+ -------
378
+ pandas.DataFrame
379
+ One row per cutoff, including cutoff time, tip count, model used,
380
+ status, and the 18 lower/median/upper predictions when inference was
381
+ possible.
382
+ """
383
+ if step_days <= 0:
384
+ raise ValueError("step_days must be > 0.")
385
+ if not 0 <= sampling_probability <= 1:
386
+ raise ValueError("sampling_probability must be between 0 and 1.")
387
+
388
+ max_age = get_tree_height(original_tree)
389
+ cutoffs = list(np.arange(step_days, max_age + 1e-9, step_days))
390
+
391
+ if include_final and (not cutoffs or not np.isclose(cutoffs[-1], max_age)):
392
+ cutoffs.append(max_age)
393
+
394
+ rows = []
395
+ model_cache = {}
396
+
397
+ with tempfile.TemporaryDirectory(prefix="phylocnn_temporal_") as workdir:
398
+ for idx, cutoff in enumerate(cutoffs, start=1):
399
+ cut_tree = prune_tree_to_observed_tips(original_tree, cutoff)
400
+
401
+ if cut_tree is None:
402
+ rows.append({
403
+ "cutoff_days": float(cutoff),
404
+ "n_tips": 0,
405
+ "model_size": None,
406
+ "status": "skipped: fewer than 2 observed tips",
407
+ })
408
+ continue
409
+
410
+ n_tips = len(cut_tree.get_leaves())
411
+ model_info = select_temporal_model(
412
+ n_tips=n_tips,
413
+ model_dir=model_dir,
414
+ tree_type=tree_type,
415
+ )
416
+
417
+ if model_info is None:
418
+ rows.append({
419
+ "cutoff_days": float(cutoff),
420
+ "n_tips": int(n_tips),
421
+ "model_size": None,
422
+ "status": "skipped: tip count outside trained ranges (30-350)",
423
+ })
424
+ continue
425
+
426
+ model_label, model_json, model_weights = model_info
427
+
428
+ if model_label not in model_cache:
429
+ model_cache[model_label] = load_trained_model(
430
+ model_json_file=model_json,
431
+ model_weights_file=model_weights,
432
+ )
433
+
434
+ predicted = predict_tree_object(
435
+ tree=cut_tree,
436
+ sampling_probability=sampling_probability,
437
+ model=model_cache[model_label],
438
+ workdir=workdir,
439
+ prefix=f"slice_{idx:04d}",
440
+ )
441
+
442
+ if predicted.shape[0] != 1:
443
+ raise ValueError(
444
+ f"Expected one prediction for cutoff {cutoff}, "
445
+ f"but received {predicted.shape[0]}."
446
+ )
447
+
448
+ row = {
449
+ "cutoff_days": float(cutoff),
450
+ "n_tips": int(n_tips),
451
+ "model_size": model_label,
452
+ "status": "predicted",
453
+ }
454
+ row.update(predicted.iloc[0].to_dict())
455
+ rows.append(row)
456
+
457
+ return pd.DataFrame(rows)
458
+
459
+ def print_predictions_summary(predicted):
460
+ print("\nPredictions summary:")
461
+ for target in TARGET_COLS:
462
+ lower = f"{target}_lower"
463
+ median = target
464
+ upper = f"{target}_upper"
465
+ print(f"\n{target}:")
466
+ print(f" Median lower: {np.median(predicted[lower])}")
467
+ print(f" Median prediction: {np.median(predicted[median])}")
468
+ print(f" Median upper: {np.median(predicted[upper])}")
469
+ print(f" Std prediction: {np.std(predicted[median])}")
470
+
471
+
472
+ def main():
473
+ parser = argparse.ArgumentParser(
474
+ description="Prepare a genomic tree and predict epidemiological parameters with prediction intervals."
475
+ )
476
+ parser.add_argument("-t", "--tree", required=True, help="Tree file in .nwk format.")
477
+ parser.add_argument(
478
+ "-p", "--sampling_probability", required=True, type=float,
479
+ help="Sampling probability p."
480
+ )
481
+ parser.add_argument(
482
+ "-ts", "--tree_scale", default=1, type=int,
483
+ help="Date scale used in the supplied tree: 0 = days, 1 = years."
484
+ )
485
+ parser.add_argument(
486
+ "--tree_type", default=OROV, type=str, choices=(OROV, TT),
487
+ help="Type of tree: OROV = Oropouche-like trees, TT = perfectly resolved transmission trees."
488
+ )
489
+ parser.add_argument(
490
+ "--keep_intermediate", action="store_true",
491
+ help="Keep rescaled tree and encoded TSV files."
492
+ )
493
+ parser.add_argument(
494
+ "--temporal", action="store_true",
495
+ help="Run sequential predictions at regular time intervals from the root."
496
+ )
497
+ parser.add_argument(
498
+ "--step_days", type=float, default=7.0,
499
+ help="Temporal interval in days when --temporal is used (default: 7)."
500
+ )
501
+ parser.add_argument(
502
+ "--model_dir", default=MODEL_DIR,
503
+ help="Directory containing pretrained models."
504
+ )
505
+
506
+ args = parser.parse_args()
507
+
508
+ base_name = os.path.splitext(args.tree)[0]
509
+ rescaled_output = f"{base_name}_rescaled_trees.nwk"
510
+ encoded_output = f"{base_name}_encoded_trees.tsv"
511
+ prediction_output = f"{base_name}_predicted_parameters.csv"
512
+
513
+ scaled_tree = genomic_tree_rescaling(
514
+ original_tree=Tree(args.tree),
515
+ tree_scale=args.tree_scale,
516
+ )
517
+
518
+ if args.temporal:
519
+ prediction_output = f"{base_name}_temporal_predictions.csv"
520
+ temporal_predictions = predict_every_n_days(
521
+ original_tree=scaled_tree,
522
+ sampling_probability=args.sampling_probability,
523
+ step_days=args.step_days,
524
+ model_dir=args.model_dir,
525
+ tree_type=args.tree_type,
526
+ include_final=True,
527
+ )
528
+ temporal_predictions.to_csv(prediction_output, index=False)
529
+ print(temporal_predictions.to_string(index=False))
530
+ print(f"\nSaved temporal predictions to: {prediction_output}")
531
+ return
532
+
533
+ model_info = select_temporal_model(
534
+ n_tips=len(scaled_tree),
535
+ model_dir=args.model_dir,
536
+ tree_type=args.tree_type,
537
+ )
538
+
539
+ if model_info is None:
540
+ raise ValueError(
541
+ f"Tree has {len(scaled_tree)} tips, which is outside the trained ranges (30-350)."
542
+ )
543
+
544
+ _, model_json, model_weights = model_info
545
+
546
+ # Save the rescaled tree before calling the encoder.
547
+ scaled_tree.write(outfile=rescaled_output, format=1)
548
+
549
+ encode_tree(
550
+ tree_file=rescaled_output,
551
+ encoded_file=encoded_output,
552
+ )
553
+
554
+ predicted = predict_parameters(
555
+ encoded_file=encoded_output,
556
+ sampling_probability=args.sampling_probability,
557
+ model_json_file=model_json,
558
+ model_weights_file=model_weights,
559
+ )
560
+
561
+ print_predictions_summary(predicted)
562
+
563
+ predicted.to_csv(prediction_output, index=False)
564
+ print(f"\nSaved predictions to: {prediction_output}")
565
+
566
+ if not args.keep_intermediate:
567
+ for path in (rescaled_output, encoded_output):
568
+ if os.path.exists(path):
569
+ os.remove(path)
570
+
571
+
572
+ if __name__ == "__main__":
573
+ main()