deepplv 1.0.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.
DeepPLV.py ADDED
@@ -0,0 +1,2506 @@
1
+ #!/usr/bin/env python3
2
+ """DeepPLV v1.0.0: PLV identification in eukaryotic genome assemblies."""
3
+ from __future__ import annotations
4
+ import argparse
5
+ import csv
6
+ import gzip
7
+ import logging
8
+ import math
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import time
15
+ from bisect import bisect_left
16
+ from collections import Counter, defaultdict
17
+ from concurrent.futures import ThreadPoolExecutor
18
+ from dataclasses import dataclass, field
19
+ from datetime import datetime
20
+ from pathlib import Path
21
+ from typing import Any, Iterator, Dict, Iterable, List, Optional, Sequence, Tuple
22
+ from urllib.parse import unquote
23
+ import numpy as np
24
+ import torch
25
+ from torch import nn
26
+ from torch.nn import functional as F
27
+
28
+ DEFAULTS = dict(
29
+ gpu="auto", # "auto", "cpu", or CUDA device index
30
+ window=8192, step=4096,
31
+ refine_window=4096, refine_step=1024,
32
+ refine_flank=12288, batch_size=16, rc_average=True,
33
+ min_score=0.90,
34
+ extend_score=0.50,
35
+ annotation=True, tir_tsd=True,
36
+ max_n_fraction=0.05,
37
+ min_plv_length=3000, max_plv_length=50000,
38
+ coarse_merge_gap=0, refined_merge_gap=0,
39
+ adaptive_step=128, adaptive_flank=2048, adaptive_edge=True,
40
+ valley_score=0.30, valley_min_windows=3,
41
+ max_tir_flank=25000, min_tir_coverage=0.60,
42
+ tir_max_hallmark_extension=10000,
43
+ tir_min_insert=6000, tir_max_insert=50000,
44
+ tir_min_len=100, tir_max_len=2000, tir_min_id=65.0,
45
+ tir_min_entropy=2.0, tir_max_kmer_frac=0.70,
46
+ tir_max_tandem_frac=0.70, tir_max_tandem_period=12,
47
+ tsd_min=4, tsd_max=20, tsd_max_slide=2,
48
+ hmm_evalue=1e-5,
49
+ pgap_enabled=True,
50
+ pgap_unannotated_only=True,
51
+ host_gene_max_overlap_bp=0,
52
+ max_coarse_island=100000,
53
+ orf_flank=10000,
54
+ orf_max_extension=10000,
55
+ candidate_tir_only_min_id=85.0,
56
+ candidate_tir_only_min_len=150,
57
+ candidate_tir_only_min_geometry=0.30,
58
+ candidate_tir_only_min_model=0.95,
59
+ candidate_tir_only_min_distinct_windows=2,
60
+ )
61
+
62
+
63
+ STRIDE = 128
64
+ LOG = logging.getLogger("DeepPLV")
65
+ _LOG = LOG
66
+ MCP_LABEL = "MCP"
67
+ CORE_CAPSID = frozenset(("MCP", "mCP"))
68
+ PLV_HALLMARK_ORDER = ["MCP", "mCP", "ATPase", "endonuc", "MTase", "pPolB", "RVE", "Tet", "Tlr6FP", "YR", "Lipase", "Laminin_G_3", "Peptidase_S74", "SF3_Helicase", "VLTF3"]
69
+ VERSION = "1.0.0"
70
+
71
+
72
+ HELP_TEXT = """\
73
+ DeepPLV.py v1.0.0 - Identify PLV in eukaryotic genome assembly.
74
+
75
+ Usage: DeepPLV.py -db <database path> <genome.fa> [OPTIONS]
76
+
77
+ Mandatory:
78
+ -db, --db Database directory that contain HMM profile and DeepPLV weights
79
+ genome Specify eukaryotic genome in FASTA file (.gz is accepted)
80
+
81
+ Optionals:
82
+ -p, --prefix Prefix for output files and PLV identifiers [default: DeepPLV]
83
+ -o, --outdir Specify output directory name [default: ./DeepPLV_<YYYYMMDD>]
84
+ -t, --threads Specify CPU threads for this task [default: 4]
85
+ -g, --gff Host eukaryotic GFF/GFF3/GTF gene annotation file [default: none]
86
+ --version Show the DeepPLV version and exit
87
+ -h, --help Show this help message and exit
88
+ """
89
+ USAGE_TEXT = "Usage: DeepPLV.py -db <database path> [-p <prefix>] <genome.fa> [OPTIONS]\n"
90
+
91
+
92
+ def format_plv_id(prefix: str, index: int, candidate: bool = False) -> str:
93
+ base = prefix if prefix.lower().endswith("plv") else f"{prefix}PLV"
94
+ return f"{base}cand_{index:03d}" if candidate else f"{base}_{index:03d}"
95
+
96
+ _BLASTN_OUTFMT = "6 qstart qend sstart send length nident pident gaps evalue bitscore"
97
+ _GFF_GENE_FEATURES = {"gene","pseudogene","protein_coding_gene","transposable_element_gene"}
98
+ _GFF_TRANSCRIPT_FEATURES = {"mrna","transcript","primary_transcript","pseudogenic_transcript",
99
+ "lncrna","lnc_rna","ncrna","rrna","trna","snrna","snorna","mirna","pre_mirna","srna"}
100
+ _GFF_GENE_ID_KEYS = ("gene_id","geneid","locus_tag")
101
+ _GFF_TRANSCRIPT_ID_KEYS = ("transcript_id","transcriptid","transcript","mrna_id","rna_id")
102
+ _NATKEY_RE = re.compile(r"(\d+)")
103
+ BASES = np.full(256, 4, dtype=np.uint8)
104
+ for _b, _i in (("A",0),("C",1),("G",2),("T",3)):
105
+ BASES[ord(_b)] = _i
106
+ RC_IDS = np.array([3,2,1,0,4,5,6], dtype=np.uint8)
107
+
108
+ class PositionLayerNorm(nn.Module):
109
+ """Normalize channels separately per position; do not normalize across padding."""
110
+
111
+ def __init__(self, channels: int):
112
+ super().__init__()
113
+ self.norm = nn.LayerNorm(channels)
114
+
115
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
116
+ return self.norm(x.transpose(1, 2)).transpose(1, 2)
117
+
118
+ def position_mask(lengths: torch.Tensor, width: int, stride: int) -> torch.Tensor:
119
+ """True for padded positions. Convolutions use ceil(length/stride)."""
120
+ valid_lengths = torch.div(lengths + stride - 1, stride, rounding_mode="floor")
121
+ return torch.arange(width, device=lengths.device)[None, :] >= valid_lengths[:, None]
122
+
123
+ class ResidualConv(nn.Module):
124
+ def __init__(self, cin: int, cout: int, stride: int, dropout: float):
125
+ super().__init__()
126
+ self.conv1 = nn.Conv1d(cin, cout, kernel_size=7, stride=stride, padding=3, bias=False)
127
+ self.norm1 = PositionLayerNorm(cout)
128
+ self.conv2 = nn.Conv1d(cout, cout, kernel_size=5, padding=2, bias=False)
129
+ self.norm2 = PositionLayerNorm(cout)
130
+ self.dropout = nn.Dropout(dropout)
131
+ self.skip = nn.Identity() if cin == cout and stride == 1 else nn.Conv1d(cin, cout, 1, stride=stride, bias=False)
132
+
133
+ def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
134
+ z = self.dropout(F.gelu(self.norm1(self.conv1(x))))
135
+ z = z.masked_fill(mask[:, None, :], 0)
136
+ z = self.norm2(self.conv2(z))
137
+ result = F.gelu(z + self.skip(x))
138
+ return result.masked_fill(mask[:, None, :], 0)
139
+
140
+ class CNNStem(nn.Module):
141
+ """One-hot A,C,G,T,N,MASK/PAD input -> [B, T/128, hidden_dim]."""
142
+
143
+ def __init__(self, channels: list[int], dropout: float):
144
+ super().__init__()
145
+ if len(channels) != 4 or any(c <= 0 for c in channels):
146
+ raise ValueError("model.channels must contain four positive integers")
147
+ a, b, c, d = channels
148
+ self.conv = nn.Conv1d(6, a, 15, stride=4, padding=7, bias=False)
149
+ self.norm = PositionLayerNorm(a)
150
+ self.same = ResidualConv(a, a, 1, dropout)
151
+ self.down16 = ResidualConv(a, b, 4, dropout)
152
+ self.down64 = ResidualConv(b, c, 4, dropout)
153
+ self.down128 = ResidualConv(c, d, 2, dropout)
154
+
155
+ def forward(self, ids: torch.Tensor, lengths: torch.Tensor):
156
+ if ids.ndim != 2 or lengths.ndim != 1 or ids.shape[0] != lengths.shape[0]:
157
+ raise ValueError("Expected ids [batch, bases] and lengths [batch]")
158
+ if not torch.all((lengths > 0) & (lengths <= ids.shape[1])):
159
+ raise ValueError("Sequence lengths must be positive and <= padded width")
160
+ if ids.min() < 0 or ids.max() > 6:
161
+ raise ValueError("DNA token IDs must be in 0..6")
162
+ valid = ids.ne(6)
163
+ x = F.one_hot(ids.clamp(max=5), 6).permute(0, 2, 1).to(torch.float32)
164
+ x = x * valid.unsqueeze(1)
165
+ x = F.gelu(self.norm(self.conv(x)))
166
+ mask4 = position_mask(lengths, x.shape[-1], 4)
167
+ x = self.same(x.masked_fill(mask4[:, None, :], 0), mask4)
168
+ x = self.down16(x, position_mask(lengths, (x.shape[-1] + 3) // 4, 16))
169
+ x = self.down64(x, position_mask(lengths, (x.shape[-1] + 3) // 4, 64))
170
+ x = self.down128(x, position_mask(lengths, (x.shape[-1] + 1) // 2, 128))
171
+ tokens = x.transpose(1, 2)
172
+ mask = position_mask(lengths, tokens.shape[1], STRIDE)
173
+ return tokens, mask
174
+
175
+ class SequenceHead(nn.Module):
176
+ def __init__(self, hidden_dim: int, num_classes: int, dropout: float):
177
+ super().__init__()
178
+ self.classifier = nn.Sequential(nn.Linear(2 * hidden_dim, hidden_dim), nn.GELU(),
179
+ nn.Dropout(dropout), nn.Linear(hidden_dim, num_classes))
180
+
181
+ def forward(self, tokens: torch.Tensor, padding: torch.Tensor) -> torch.Tensor:
182
+ valid = (~padding).unsqueeze(-1)
183
+ mean = tokens.masked_fill(padding.unsqueeze(-1), 0).sum(1) / valid.sum(1).clamp(min=1)
184
+ maximum = tokens.masked_fill(padding.unsqueeze(-1), torch.finfo(tokens.dtype).min).max(1).values
185
+ return self.classifier(torch.cat((mean, maximum), dim=-1))
186
+
187
+ class PLVModel(nn.Module):
188
+ """Common model interface: forward(ids, lengths) -> logits."""
189
+
190
+ def __init__(self, cfg: dict, context: nn.Module, num_classes: int, strategy: str):
191
+ super().__init__()
192
+ dim = int(cfg["hidden_dim"])
193
+ if cfg["channels"][-1] != dim:
194
+ raise ValueError("Last model.channels value must equal model.hidden_dim")
195
+ self.stem = CNNStem(cfg["channels"], cfg["dropout"])
196
+ self.context = context
197
+ self.norm = nn.LayerNorm(dim)
198
+ if strategy != "multiclass":
199
+ raise ValueError("DeepPLV inference requires the trained multiclass CNN-BiLSTM model")
200
+ self.head = SequenceHead(dim, num_classes, cfg["dropout"])
201
+ self.strategy = strategy
202
+
203
+ def forward(self, ids: torch.Tensor, lengths: torch.Tensor) -> torch.Tensor:
204
+ tokens, mask = self.stem(ids, lengths)
205
+ tokens = self.norm(self.context(tokens, mask))
206
+ tokens = tokens.masked_fill(mask.unsqueeze(-1), 0)
207
+ return self.head(tokens, mask)
208
+
209
+ class BiLSTMContext(nn.Module):
210
+ def __init__(self, dim: int, layers: int, dropout: float):
211
+ super().__init__()
212
+ if dim % 2:
213
+ raise ValueError("BiLSTM hidden_dim must be even")
214
+ self.rnn = nn.LSTM(dim, dim // 2, num_layers=layers, bidirectional=True,
215
+ batch_first=True, dropout=dropout if layers > 1 else 0)
216
+ self.norm = nn.LayerNorm(dim)
217
+
218
+ def forward(self, x: torch.Tensor, mask: torch.Tensor):
219
+ lengths = (~mask).sum(1).cpu()
220
+ packed = nn.utils.rnn.pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)
221
+ result, _ = self.rnn(packed)
222
+ output, _ = nn.utils.rnn.pad_packed_sequence(result, batch_first=True, total_length=x.shape[1])
223
+ return self.norm(output + x).masked_fill(mask.unsqueeze(-1), 0)
224
+
225
+ def build(cfg: dict, num_classes: int, strategy: str):
226
+ ctx = BiLSTMContext(cfg["hidden_dim"], cfg["layers"], cfg["dropout"])
227
+ return PLVModel(cfg, ctx, num_classes, strategy)
228
+
229
+ def _natural_key(s: str):
230
+ return [int(t) if t.isdigit() else t.lower() for t in _NATKEY_RE.split(str(s))]
231
+
232
+ def _hallmark_sort_key(name: str):
233
+ name = str(name)
234
+ try:
235
+ return (0, PLV_HALLMARK_ORDER.index(name))
236
+ except ValueError:
237
+ return (1, _natural_key(name))
238
+
239
+ def _fetch_seq(fa: pyfastx.Fasta, genome_path: str | Path, contig: str, start: int, end: int) -> str:
240
+ start = max(1, int(start))
241
+ end = max(start, int(end))
242
+ try:
243
+ return fa.fetch(contig, (start, end))
244
+ except UnicodeDecodeError:
245
+ opener = gzip.open if str(genome_path).endswith(".gz") else open
246
+ target = contig.encode()
247
+ seq = bytearray()
248
+ in_target = False
249
+ with opener(genome_path, "rb") as fh:
250
+ for raw in fh:
251
+ if raw.startswith(b">"):
252
+ name = raw[1:].strip().split(None, 1)[0]
253
+ if in_target:
254
+ break
255
+ in_target = name == target
256
+ continue
257
+ if in_target:
258
+ seq.extend(raw.strip())
259
+ if len(seq) >= end:
260
+ break
261
+ if not seq:
262
+ raise
263
+ return bytes(seq[start - 1:end]).decode("ascii", "replace").upper()
264
+
265
+ def gc_of_seq(seq: str) -> float:
266
+ if not seq:
267
+ return float("nan")
268
+ seq = seq.upper()
269
+ gc = seq.count("G") + seq.count("C")
270
+ at = seq.count("A") + seq.count("T")
271
+ return 100.0 * gc / (gc + at) if (gc + at) else float("nan")
272
+
273
+ def _revcomp(seq: str) -> str:
274
+ return seq.translate(str.maketrans("ACGTacgtNn", "TGCAtgcaNn"))[::-1]
275
+
276
+ @dataclass
277
+ class Orf:
278
+ orf_id: str
279
+ contig: str
280
+ start: int
281
+ end: int
282
+ strand: int
283
+ protein: str
284
+ partial: bool
285
+ hallmark_hits: Dict[str, Tuple[float, float]] = field(default_factory=dict)
286
+ family: Optional[str] = None
287
+ family_bitscore: float = 0.0
288
+ family_evalue: float = float("inf")
289
+ family_source: Optional[str] = None
290
+ plv_mcp_bitscore: float = 0.0
291
+ plv_mcp_evalue: float = float("inf")
292
+ nonplv_mcp_bitscore: float = 0.0
293
+ nonplv_mcp_evalue: float = float("inf")
294
+ nonplv_mcp_name: Optional[str] = None
295
+ best_pfam_acc: Optional[str] = None
296
+ best_pfam_name: Optional[str] = None
297
+ best_pfam_bitscore: float = 0.0
298
+ best_pfam_evalue: float = float("inf")
299
+ best_pgap_acc: Optional[str] = None
300
+ best_pgap_name: Optional[str] = None
301
+ best_pgap_label: Optional[str] = None
302
+ best_pgap_bitscore: float = 0.0
303
+ best_pgap_evalue: float = float("inf")
304
+
305
+ @dataclass
306
+ class TirPair:
307
+ left_start: int
308
+ left_end: int
309
+ right_start: int
310
+ right_end: int
311
+ tir_length: int
312
+ insert_size: int
313
+ tir_identity: float
314
+ score: float
315
+ matches: int
316
+ total: int
317
+ gaps: int
318
+ tir_evalue: float = float("nan")
319
+
320
+ @dataclass
321
+ class Tsd:
322
+ sequence_left: str
323
+ sequence_right: str
324
+ length: int
325
+ mismatches: int
326
+ identity: float
327
+ left_shift: int
328
+ right_shift: int
329
+
330
+ @dataclass
331
+ class Plv:
332
+ plv_id: str
333
+ contig: str
334
+ contig_length: int
335
+ start: int
336
+ end: int
337
+ length: int
338
+ orfs: List[Orf]
339
+ families_present: List[str]
340
+ n_families: int
341
+ mcp_best_bitscore: float
342
+ gc_plv: float
343
+ boundary_method: str
344
+ boundary_status: str = "Window"
345
+ tir: Optional[TirPair] = None
346
+ tsd: Optional[Tsd] = None
347
+
348
+ @property
349
+ def has_tir(self) -> bool:
350
+ return self.tir is not None
351
+
352
+ def _merge_intervals(intervals: Sequence[Tuple[int, int]]) -> List[Tuple[int, int]]:
353
+ if not intervals:
354
+ return []
355
+ ordered = sorted((min(s, e), max(s, e)) for s, e in intervals)
356
+ merged: List[Tuple[int, int]] = []
357
+ for s, e in ordered:
358
+ if merged and s <= merged[-1][1] + 1:
359
+ merged[-1] = (merged[-1][0], max(merged[-1][1], e))
360
+ else:
361
+ merged.append((s, e))
362
+ return merged
363
+
364
+ def _parse_annotation_attributes(attr_text: str) -> Dict[str, str]:
365
+ attrs: Dict[str, str] = {}
366
+ attr_text = attr_text.strip()
367
+ if not attr_text or attr_text == ".":
368
+ return attrs
369
+ for raw_part in attr_text.split(";"):
370
+ part = raw_part.strip()
371
+ if not part:
372
+ continue
373
+ if "=" in part:
374
+ key, value = part.split("=", 1)
375
+ else:
376
+ fields = part.split(None, 1)
377
+ if len(fields) != 2:
378
+ continue
379
+ key, value = fields
380
+ key = key.strip().lower()
381
+ value = unquote(value.strip().strip('"').strip("'"))
382
+ if key and value:
383
+ attrs[key] = value
384
+ return attrs
385
+
386
+ def _first_attr(attrs: Dict[str, str], keys: Sequence[str]) -> Optional[str]:
387
+ for key in keys:
388
+ value = attrs.get(key)
389
+ if value:
390
+ return value
391
+ return None
392
+
393
+ def _split_attr_ids(value: Optional[str]) -> List[str]:
394
+ if not value:
395
+ return []
396
+ return [part.strip() for part in value.split(",") if part.strip()]
397
+
398
+ def _extend_span(spans: Dict[Tuple[str, str], List[int]], key: Tuple[str, str], start: int, end: int) -> None:
399
+ span = spans.get(key)
400
+ if span is None:
401
+ spans[key] = [start, end]
402
+ else:
403
+ span[0] = min(span[0], start)
404
+ span[1] = max(span[1], end)
405
+
406
+ def parse_host_gene_intervals(gff_path: Path) -> Dict[str, List[Tuple[int, int]]]:
407
+ explicit_gene_intervals: Dict[str, List[Tuple[int, int]]] = defaultdict(list)
408
+ explicit_transcript_intervals: Dict[str, List[Tuple[int, int]]] = defaultdict(list)
409
+ gene_spans: Dict[Tuple[str, str], List[int]] = {}
410
+ transcript_spans: Dict[Tuple[str, str], List[int]] = {}
411
+ transcript_to_genes: Dict[Tuple[str, str], set[str]] = defaultdict(set)
412
+ explicit_gene_ids: set[Tuple[str, str]] = set()
413
+
414
+ n_rows = 0
415
+ n_gene_rows = 0
416
+ n_transcript_rows = 0
417
+ n_gene_id_rows = 0
418
+ n_parent_rows = 0
419
+
420
+ opener = gzip.open if str(gff_path).endswith(".gz") else open
421
+ with opener(gff_path, "rt", encoding="utf-8", errors="replace") as fh:
422
+ for raw in fh:
423
+ line = raw.strip()
424
+ if not line or line.startswith("#"):
425
+ continue
426
+ cols = line.split("\t")
427
+ if len(cols) < 5:
428
+ continue
429
+ try:
430
+ start, end = int(cols[3]), int(cols[4])
431
+ except (TypeError, ValueError):
432
+ continue
433
+ if start <= 0 or end <= 0:
434
+ continue
435
+
436
+ n_rows += 1
437
+ start, end = min(start, end), max(start, end)
438
+ contig = cols[0]
439
+ feature = cols[2].strip().lower() if len(cols) > 2 else ""
440
+ attrs = _parse_annotation_attributes(cols[8] if len(cols) >= 9 else "")
441
+
442
+ row_id = attrs.get("id")
443
+ parents = _split_attr_ids(attrs.get("parent"))
444
+ gene_id = _first_attr(attrs, _GFF_GENE_ID_KEYS)
445
+ transcript_id = _first_attr(attrs, _GFF_TRANSCRIPT_ID_KEYS)
446
+
447
+ if gene_id:
448
+ n_gene_id_rows += 1
449
+ _extend_span(gene_spans, (contig, gene_id), start, end)
450
+
451
+ if feature in _GFF_GENE_FEATURES or feature.endswith("_gene"):
452
+ explicit_gene_intervals[contig].append((start, end))
453
+ n_gene_rows += 1
454
+ gid = row_id or gene_id
455
+ if gid:
456
+ explicit_gene_ids.add((contig, gid))
457
+ _extend_span(gene_spans, (contig, gid), start, end)
458
+ continue
459
+
460
+ is_transcript = (
461
+ feature in _GFF_TRANSCRIPT_FEATURES
462
+ or "transcript" in feature
463
+ or feature.endswith("mrna")
464
+ )
465
+ if is_transcript:
466
+ n_transcript_rows += 1
467
+ explicit_transcript_intervals[contig].append((start, end))
468
+ tid = row_id or transcript_id
469
+ if tid:
470
+ _extend_span(transcript_spans, (contig, tid), start, end)
471
+ if gene_id:
472
+ transcript_to_genes[(contig, tid)].add(gene_id)
473
+ for parent in parents:
474
+ transcript_to_genes[(contig, tid)].add(parent)
475
+ elif gene_id:
476
+ _extend_span(gene_spans, (contig, gene_id), start, end)
477
+ continue
478
+
479
+ if transcript_id:
480
+ _extend_span(transcript_spans, (contig, transcript_id), start, end)
481
+ if gene_id:
482
+ transcript_to_genes[(contig, transcript_id)].add(gene_id)
483
+
484
+ if parents:
485
+ n_parent_rows += 1
486
+ for parent in parents:
487
+ if (contig, parent) in explicit_gene_ids:
488
+ _extend_span(gene_spans, (contig, parent), start, end)
489
+ else:
490
+ _extend_span(transcript_spans, (contig, parent), start, end)
491
+
492
+ for transcript_key, span in transcript_spans.items():
493
+ contig, transcript_id = transcript_key
494
+ parent_genes = transcript_to_genes.get(transcript_key, set())
495
+ if parent_genes:
496
+ for gene_id in parent_genes:
497
+ _extend_span(gene_spans, (contig, gene_id), span[0], span[1])
498
+
499
+ intervals_by_contig: Dict[str, List[Tuple[int, int]]] = defaultdict(list)
500
+ for contig, intervals in explicit_gene_intervals.items():
501
+ intervals_by_contig[contig].extend(intervals)
502
+ for contig, intervals in explicit_transcript_intervals.items():
503
+ intervals_by_contig[contig].extend(intervals)
504
+ for (contig, _gene_id), span in gene_spans.items():
505
+ intervals_by_contig[contig].append((span[0], span[1]))
506
+ for transcript_key, span in transcript_spans.items():
507
+ if not transcript_to_genes.get(transcript_key):
508
+ intervals_by_contig[transcript_key[0]].append((span[0], span[1]))
509
+
510
+ merged = {contig: _merge_intervals(iv) for contig, iv in intervals_by_contig.items() if iv}
511
+ n_gene_spans = len(gene_spans)
512
+ n_orphan_transcript_spans = sum(1 for key in transcript_spans if not transcript_to_genes.get(key))
513
+ _LOG.info(
514
+ f"Host gene mask: parsed {n_rows:,} feature row(s); gene rows={n_gene_rows:,}; "
515
+ f"transcript-like rows={n_transcript_rows:,}; rows with gene_id={n_gene_id_rows:,}; "
516
+ f"rows with Parent={n_parent_rows:,}; reconstructed gene spans={n_gene_spans:,}; "
517
+ f"fallback transcript spans={n_orphan_transcript_spans:,}; collapsed to "
518
+ f"{sum(len(v) for v in merged.values()):,} interval(s) on {len(merged):,} contig(s)"
519
+ )
520
+ if not merged:
521
+ _LOG.info('Host annotation contains no usable gene or transcript intervals')
522
+ return merged
523
+
524
+ def _host_overlap_bp(
525
+ contig_intervals: Sequence[Tuple[int, int]],
526
+ start: int,
527
+ end: int,
528
+ ) -> int:
529
+ if not contig_intervals or end < start:
530
+ return 0
531
+
532
+ lo, hi = 0, len(contig_intervals)
533
+ while lo < hi:
534
+ mid = (lo + hi) // 2
535
+ if contig_intervals[mid][1] < start:
536
+ lo = mid + 1
537
+ else:
538
+ hi = mid
539
+
540
+ overlap = 0
541
+ i = lo
542
+ while i < len(contig_intervals):
543
+ iv_start, iv_end = contig_intervals[i]
544
+ if iv_start > end:
545
+ break
546
+ overlap += max(0, min(end, iv_end) - max(start, iv_start) + 1)
547
+ i += 1
548
+ return overlap
549
+
550
+ def _digital_sequences(orfs: Iterable[Orf], alphabet: pyhmmer.easel.Alphabet) -> List[pyhmmer.easel.DigitalSequence]:
551
+ seqs = []
552
+ skipped = 0
553
+ for o in orfs:
554
+ try:
555
+ t = pyhmmer.easel.TextSequence(name=o.orf_id.encode(), sequence=o.protein)
556
+ seqs.append(t.digitize(alphabet))
557
+ except (ValueError, UnicodeError) as exc:
558
+ skipped += 1
559
+ _LOG.debug('HMM digitization skipped | orf=%s | detail=%s', o.orf_id, exc)
560
+ if skipped:
561
+ _LOG.info('HMM input preparation | skipped_orfs=%d', skipped)
562
+ return seqs
563
+
564
+ def _query_meta(top_hits) -> Tuple[str, Optional[str]]:
565
+ try:
566
+ name_attr = top_hits.query.name
567
+ acc_attr = top_hits.query.accession
568
+ except AttributeError:
569
+ name_attr = top_hits.query_name
570
+ acc_attr = top_hits.query_accession
571
+ name = name_attr.decode() if isinstance(name_attr, bytes) else str(name_attr)
572
+ if acc_attr:
573
+ acc = acc_attr.decode() if isinstance(acc_attr, bytes) else str(acc_attr)
574
+ acc = acc.split(".")[0]
575
+ else:
576
+ acc = None
577
+ return name, acc
578
+
579
+ def _hmm_profile_names(hmm_path: Path) -> List[str]:
580
+ with pyhmmer.plan7.HMMFile(str(hmm_path)) as hf:
581
+ hmms = list(hf)
582
+ if not hmms:
583
+ raise RuntimeError(f"No HMM profiles found in {hmm_path}")
584
+ names = []
585
+ for hmm in hmms:
586
+ name = hmm.name
587
+ names.append(name.decode() if isinstance(name, bytes) else str(name))
588
+ return names
589
+
590
+ def scan_hallmarks(
591
+ orfs_by_id: Dict[str, Orf],
592
+ hmm_path: Path,
593
+ evalue: float,
594
+ threads: int,
595
+ ) -> Tuple[int, int]:
596
+ """Scan predicted ORFs against PLV hallmark profiles."""
597
+ profile_names = _hmm_profile_names(hmm_path)
598
+ if MCP_LABEL not in profile_names:
599
+ raise RuntimeError(
600
+ f"{hmm_path} does not contain an exact 'MCP' profile; "
601
+ "MCP is required in the reference HMM collection for competing-MCP annotation"
602
+ )
603
+
604
+ alphabet = pyhmmer.easel.Alphabet.amino()
605
+ seqs = _digital_sequences(orfs_by_id.values(), alphabet)
606
+ with pyhmmer.plan7.HMMFile(str(hmm_path)) as hf:
607
+ hmms = list(hf)
608
+
609
+ n_hits = 0
610
+ n_orfs_with_hits = set()
611
+ for top_hits in pyhmmer.hmmsearch(hmms, seqs, cpus=threads, E=evalue, incE=evalue):
612
+ hmm_name, _ = _query_meta(top_hits)
613
+ for hit in top_hits:
614
+ if not hit.included:
615
+ continue
616
+ target = hit.name.decode() if isinstance(hit.name, bytes) else hit.name
617
+ o = orfs_by_id.get(target)
618
+ if o is None:
619
+ continue
620
+ score, ev = float(hit.score), float(hit.evalue)
621
+ previous = o.hallmark_hits.get(hmm_name)
622
+ if previous is None or score > previous[0]:
623
+ o.hallmark_hits[hmm_name] = (score, ev)
624
+ n_hits += 1
625
+ n_orfs_with_hits.add(target)
626
+
627
+ missing_expected = [name for name in PLV_HALLMARK_ORDER[:10] if name not in profile_names]
628
+ if missing_expected:
629
+ _LOG.info('Hallmark database | missing_expected_profiles=%s', ', '.join(missing_expected))
630
+ _LOG.debug(
631
+ f"PLV hallmark scan: {n_hits:,} included hit(s) across "
632
+ f"{len(n_orfs_with_hits):,} ORF(s); profiles={len(profile_names):,}"
633
+ )
634
+ return n_hits, len(n_orfs_with_hits)
635
+
636
+
637
+ def scan_nonplv_mcp(
638
+ orfs_by_id: Dict[str, Orf],
639
+ hmm_path: Path,
640
+ evalue: float,
641
+ threads: int,
642
+ ) -> int:
643
+ """Scan ORFs against the non-PLV MCP collection."""
644
+ alphabet = pyhmmer.easel.Alphabet.amino()
645
+ seqs = _digital_sequences(orfs_by_id.values(), alphabet)
646
+ with pyhmmer.plan7.HMMFile(str(hmm_path)) as hf:
647
+ hmms = list(hf)
648
+ if not hmms:
649
+ raise RuntimeError(f"No HMM profiles found in {hmm_path}")
650
+
651
+ n_hits = 0
652
+ for top_hits in pyhmmer.hmmsearch(hmms, seqs, cpus=threads, E=evalue, incE=evalue):
653
+ hmm_name, _ = _query_meta(top_hits)
654
+ for hit in top_hits:
655
+ if not hit.included:
656
+ continue
657
+ target = hit.name.decode() if isinstance(hit.name, bytes) else hit.name
658
+ o = orfs_by_id.get(target)
659
+ if o is None:
660
+ continue
661
+ score, ev = float(hit.score), float(hit.evalue)
662
+ if score > o.nonplv_mcp_bitscore:
663
+ o.nonplv_mcp_bitscore = score
664
+ o.nonplv_mcp_evalue = ev
665
+ o.nonplv_mcp_name = hmm_name
666
+ n_hits += 1
667
+
668
+ _LOG.debug(
669
+ f"{hmm_path.name}: {n_hits:,} included non-PLV MCP hit(s) "
670
+ f"at E-value <= {evalue:g}"
671
+ )
672
+ return n_hits
673
+
674
+ def _best_hallmark_except(o: Orf, excluded: Sequence[str]) -> Tuple[Optional[str], float, float]:
675
+ excluded_set = set(excluded)
676
+ candidates = [
677
+ (name, score, ev)
678
+ for name, (score, ev) in o.hallmark_hits.items()
679
+ if name not in excluded_set
680
+ ]
681
+ if not candidates:
682
+ return None, 0.0, float("inf")
683
+ candidates.sort(key=lambda x: (x[1], -x[2]), reverse=True)
684
+ return candidates[0]
685
+
686
+ def classify_hallmarks(
687
+ orfs_by_id: Dict[str, Orf],
688
+ mcp_score_margin: float,
689
+ ) -> Tuple[int, int, int]:
690
+ """Assign each ORF its strongest supported PLV hallmark."""
691
+ n_mcp = n_ambiguous = n_marked = 0
692
+ for o in orfs_by_id.values():
693
+ o.family = None
694
+ o.family_bitscore = 0.0
695
+ o.family_evalue = float("inf")
696
+ o.family_source = None
697
+ o.plv_mcp_bitscore = 0.0
698
+ o.plv_mcp_evalue = float("inf")
699
+ mcp = o.hallmark_hits.get(MCP_LABEL)
700
+ if mcp is not None:
701
+ o.plv_mcp_bitscore, o.plv_mcp_evalue = mcp
702
+ if o.nonplv_mcp_bitscore <= 0.0 or mcp[0] > o.nonplv_mcp_bitscore + mcp_score_margin:
703
+ o.family = MCP_LABEL
704
+ o.family_bitscore = mcp[0]
705
+ o.family_evalue = mcp[1]
706
+ o.family_source = "PLV_hallmark"
707
+ n_mcp += 1
708
+ else:
709
+ n_ambiguous += 1
710
+
711
+ if o.family is None:
712
+ name, score, ev = _best_hallmark_except(o, (MCP_LABEL,))
713
+ if name is not None:
714
+ o.family = name
715
+ o.family_bitscore = score
716
+ o.family_evalue = ev
717
+ o.family_source = "PLV_hallmark"
718
+ n_marked += 1
719
+ elif o.family == MCP_LABEL:
720
+ n_marked += 1
721
+
722
+ _LOG.debug(
723
+ f"PLV/non-PLV MCP classification: MCP={n_mcp:,}; "
724
+ f"non-PLV-dominated MCP={n_ambiguous:,}; PLV hallmark-classified ORFs={n_marked:,}"
725
+ )
726
+ return n_mcp, n_ambiguous, n_marked
727
+
728
+ def scan_pfam(
729
+ orfs_to_scan: List[Orf],
730
+ pfam_hmm_path: Path,
731
+ evalue: float,
732
+ threads: int,
733
+ ) -> None:
734
+ """Assign the best Pfam hit to each ORF."""
735
+ if not orfs_to_scan:
736
+ return
737
+ alphabet = pyhmmer.easel.Alphabet.amino()
738
+ seqs = _digital_sequences(orfs_to_scan, alphabet)
739
+ by_id = {o.orf_id: o for o in orfs_to_scan}
740
+ n_hits = 0
741
+
742
+ with pyhmmer.plan7.HMMFile(str(pfam_hmm_path)) as hf:
743
+ for top_hits in pyhmmer.hmmsearch(hf, seqs, cpus=threads, E=evalue, incE=evalue):
744
+ hmm_name, hmm_acc = _query_meta(top_hits)
745
+ acc_rec = hmm_acc or hmm_name
746
+ for hit in top_hits:
747
+ if not hit.included:
748
+ continue
749
+ target = hit.name.decode() if isinstance(hit.name, bytes) else hit.name
750
+ o = by_id.get(target)
751
+ if o is None:
752
+ continue
753
+ score, ev = float(hit.score), float(hit.evalue)
754
+ if score > o.best_pfam_bitscore:
755
+ o.best_pfam_acc = acc_rec
756
+ o.best_pfam_name = hmm_name
757
+ o.best_pfam_bitscore = score
758
+ o.best_pfam_evalue = ev
759
+ n_hits += 1
760
+
761
+ _LOG.debug(f"Pfam-A scan: {n_hits:,} included hit(s) for candidate-region proteins")
762
+
763
+ def _use_pgap_fallback(o: Orf) -> bool:
764
+ """Use PGAP when Pfam did not provide an informative functional assignment."""
765
+ if not o.best_pgap_acc:
766
+ return False
767
+ if not o.best_pfam_name:
768
+ return True
769
+ name = o.best_pfam_name.strip().lower()
770
+ return name.startswith(("duf", "uncharacterized", "unknown", "hypothetical"))
771
+
772
+ def _load_pgap_labels(database: Path) -> dict[str, str]:
773
+ path = database / 'hmm_PGAP.tsv'
774
+ if not path.is_file():
775
+ raise FileNotFoundError(f'PGAP profiles require their metadata table: {path}')
776
+ labels = {}
777
+ with path.open('r', encoding='utf-8-sig', errors='replace', newline='') as fh:
778
+ header = fh.readline().lstrip('#').rstrip('\r\n').split('\t')
779
+ header = [h.strip().lower() for h in header]
780
+ if 'ncbi_accession' not in header or 'label' not in header:
781
+ raise ValueError(f'Invalid hmm_PGAP.tsv header (need ncbi_accession and label): {path}')
782
+ reader = csv.DictReader(fh, fieldnames=header, delimiter='\t')
783
+ for row in reader:
784
+ label = (row.get('label') or row.get('product_name') or '').strip()
785
+ if not label or label in ('.', '-', 'NA'):
786
+ continue
787
+ for key in ('ncbi_accession', 'source_identifier', 'hmm_name', 'name_orig'):
788
+ value = (row.get(key) or '').strip()
789
+ if value and value not in ('.', '-', 'NA'):
790
+ labels[value] = label
791
+ labels[value.split('.')[0]] = label
792
+ LOG.info('PGAP annotation labels loaded | entries=%d', len(labels))
793
+ return labels
794
+
795
+ def _pgap_profile_paths(database: Path) -> list[Path]:
796
+ if not database.is_dir():
797
+ raise NotADirectoryError(f'PGAP HMM profile directory not found: {database}')
798
+ return sorted(p for p in database.rglob('*') if p.is_file()
799
+ and p.name.lower().endswith(('.hmm', '.hmm.gz')))
800
+
801
+ def _iter_pgap_hmms(paths: Sequence[Path]):
802
+ for path in paths:
803
+ with pyhmmer.plan7.HMMFile(str(path)) as hmm_file:
804
+ yield from hmm_file
805
+
806
+ def scan_pgap(orfs_to_scan: list[Orf], database: Path, evalue: float,
807
+ threads: int, labels: dict[str, str]) -> None:
808
+ if not orfs_to_scan:
809
+ return
810
+ seqs = _digital_sequences(orfs_to_scan, pyhmmer.easel.Alphabet.amino())
811
+ if not seqs:
812
+ return
813
+ by_id = {o.orf_id: o for o in orfs_to_scan}
814
+ profiles = _pgap_profile_paths(database)
815
+ count = 0
816
+ for top_hits in pyhmmer.hmmsearch(_iter_pgap_hmms(profiles), seqs,
817
+ cpus=threads, E=evalue, incE=evalue):
818
+ name, acc = _query_meta(top_hits)
819
+ accession = acc or name
820
+ label = (labels.get(name) or labels.get(accession) or
821
+ labels.get(name.split('.')[0]) or labels.get(accession.split('.')[0]))
822
+ for hit in top_hits:
823
+ if not hit.included:
824
+ continue
825
+ target = hit.name.decode() if isinstance(hit.name, bytes) else str(hit.name)
826
+ o = by_id.get(target)
827
+ if o is None:
828
+ continue
829
+ bits, ev = float(hit.score), float(hit.evalue)
830
+ if bits > o.best_pgap_bitscore:
831
+ o.best_pgap_acc = accession
832
+ o.best_pgap_name = name
833
+ o.best_pgap_label = label or name
834
+ o.best_pgap_bitscore = bits
835
+ o.best_pgap_evalue = ev
836
+ count += 1
837
+ LOG.info('PGAP annotation scan complete | proteins=%d | included_hits=%d | profiles=%d',
838
+ len(seqs), count, len(profiles))
839
+
840
+ def _is_plv_hallmark(o: Orf) -> bool:
841
+ return o.family_source == "PLV_hallmark" and o.family is not None
842
+
843
+ def parse_blastn_tabular(tab_path: Path) -> List[TirPair]:
844
+ if not tab_path.exists() or not tab_path.read_text().strip():
845
+ return []
846
+ pairs: List[TirPair] = []
847
+ for line in tab_path.read_text().splitlines():
848
+ fields = line.strip().split("\t")
849
+ if len(fields) < 10:
850
+ continue
851
+ try:
852
+ qstart, qend, sstart, send = map(int, fields[:4])
853
+ aln_len = int(fields[4])
854
+ nident = int(fields[5])
855
+ pident = float(fields[6])
856
+ gaps = int(fields[7])
857
+ evalue = float(fields[8])
858
+ bitscore = float(fields[9])
859
+ except ValueError:
860
+ continue
861
+ ls, le = min(qstart, qend), max(qstart, qend)
862
+ rs, re = min(sstart, send), max(sstart, send)
863
+ if le >= rs:
864
+ continue
865
+ tir_len = le - ls + 1
866
+ insert = rs - le - 1
867
+ pairs.append(TirPair(
868
+ left_start=ls, left_end=le, right_start=rs, right_end=re,
869
+ tir_length=tir_len, insert_size=insert, tir_identity=pident,
870
+ score=bitscore, matches=nident, total=aln_len, gaps=gaps,
871
+ tir_evalue=evalue,
872
+ ))
873
+ return pairs
874
+
875
+
876
+ def run_blastn_self(region_fa: Path, tab_out: Path) -> None:
877
+ cmd = [
878
+ "blastn", "-query", str(region_fa), "-subject", str(region_fa),
879
+ "-strand", "minus", "-task", "blastn", "-word_size", "7",
880
+ "-reward", "1", "-penalty", "-1", "-gapopen", "2", "-gapextend", "1",
881
+ "-evalue", "10.0", "-dust", "no", "-soft_masking", "false",
882
+ "-max_target_seqs", "10000", "-num_threads", "1",
883
+ "-outfmt", _BLASTN_OUTFMT, "-out", str(tab_out),
884
+ ]
885
+ proc = subprocess.run(cmd, capture_output=True, text=True)
886
+ if proc.returncode != 0:
887
+ detail = (proc.stderr or proc.stdout or "unknown BLASTN error").strip()
888
+ raise RuntimeError(f"TIR self-alignment failed (blastn exit {proc.returncode}): {detail}")
889
+
890
+ def _dinucleotide_entropy(seq: str) -> float:
891
+ seq = seq.upper()
892
+ counts = Counter(seq[i:i + 2] for i in range(len(seq) - 1) if "N" not in seq[i:i + 2])
893
+ total = sum(counts.values())
894
+ if total == 0:
895
+ return 0.0
896
+ return -sum((c / total) * math.log2(c / total) for c in counts.values())
897
+
898
+ def _max_kmer_frac(seq: str, k: int) -> float:
899
+ seq = seq.upper()
900
+ if len(seq) < k:
901
+ return 0.0
902
+ best = 0.0
903
+ for phase in range(k):
904
+ kmers = [
905
+ seq[i:i + k] for i in range(phase, len(seq) - k + 1, k)
906
+ if "N" not in seq[i:i + k]
907
+ ]
908
+ if not kmers:
909
+ continue
910
+ counts = Counter(kmers)
911
+ best = max(best, max(counts.values()) / len(kmers))
912
+ return best
913
+
914
+ def _max_tandem_period_fraction(seq: str, max_period: int) -> float:
915
+ seq = seq.upper()
916
+ best = 0.0
917
+ for p in range(1, min(max_period, len(seq) - 1) + 1):
918
+ valid = [(a, b) for a, b in zip(seq[:-p], seq[p:]) if a != "N" and b != "N"]
919
+ if not valid:
920
+ continue
921
+ frac = sum(a == b for a, b in valid) / len(valid)
922
+ best = max(best, frac)
923
+ return best
924
+
925
+ def _tir_is_low_complexity(seq: str, cfg: dict) -> bool:
926
+ if not seq or _dinucleotide_entropy(seq) < cfg["tir_min_entropy"]:
927
+ return True
928
+ if any(_max_kmer_frac(seq, k) > cfg["tir_max_kmer_frac"] for k in (1, 2, 3, 4)):
929
+ return True
930
+ return _max_tandem_period_fraction(seq, cfg["tir_max_tandem_period"]) > cfg["tir_max_tandem_frac"]
931
+
932
+ def find_tsd(left_flank: str, right_flank: str, k_min: int, k_max: int, max_slide: int) -> Optional[Tsd]:
933
+ left, right = left_flank.upper(), right_flank.upper()
934
+ best: Optional[Tsd] = None
935
+ for k in range(k_max, k_min - 1, -1):
936
+ if k > len(left) or k > len(right):
937
+ continue
938
+ max_mm = 0 if k <= 5 else (1 if k <= 8 else 2)
939
+ for sl in range(max_slide + 1):
940
+ if k + sl > len(left):
941
+ break
942
+ for sr in range(max_slide + 1):
943
+ if k + sr > len(right):
944
+ break
945
+ lk = left[len(left) - k - sl:len(left) - sl] if sl else left[-k:]
946
+ rk = right[sr:sr + k]
947
+ if "N" in lk or "N" in rk:
948
+ continue
949
+ mm = sum(a != b for a, b in zip(lk, rk))
950
+ if mm <= max_mm:
951
+ cand = Tsd(lk, rk, k, mm, 100.0 * (k - mm) / k, sl, sr)
952
+ if best is None or (cand.length, cand.identity) > (best.length, best.identity):
953
+ best = cand
954
+ if best is not None and best.length == k:
955
+ return best
956
+ return best
957
+
958
+ def _tsd_status(tsd: Optional[Tsd]) -> str:
959
+ if tsd is None:
960
+ return "NODETECT"
961
+ return "PERFECT" if tsd.mismatches == 0 else "IMPERFECT"
962
+
963
+ def _tir_fields(tir: Optional[TirPair]) -> dict:
964
+ if tir is None:
965
+ return dict(tir_length="NA", tir_identity_pct="NA")
966
+ return dict(
967
+ tir_length=tir.tir_length,
968
+ tir_identity_pct=f"{tir.tir_identity:.2f}",
969
+ )
970
+
971
+ def _tsd_fields(tsd: Optional[Tsd]) -> dict:
972
+ if tsd is None:
973
+ return dict(
974
+ tsd_len="NA", tsd_left="NA", tsd_right="NA",
975
+ tsd_conservation="NODETECT",
976
+ )
977
+ return dict(
978
+ tsd_len=tsd.length,
979
+ tsd_left=tsd.sequence_left,
980
+ tsd_right=tsd.sequence_right,
981
+ tsd_conservation=_tsd_status(tsd),
982
+ )
983
+
984
+ def _annotation_name(o: Orf) -> str:
985
+ """Return the GFF/inspection name: hallmark first, then Pfam, then hypothetical."""
986
+ if _is_plv_hallmark(o):
987
+ return o.family or "hypothetical"
988
+ if _use_pgap_fallback(o):
989
+ return o.best_pgap_label or o.best_pgap_name or o.best_pgap_acc
990
+ if o.best_pfam_name:
991
+ return o.best_pfam_name
992
+ return "hypothetical"
993
+
994
+ def write_func_tsv(plvs: List[Plv], path: Path) -> None:
995
+ columns = [
996
+ "plv_name", "orf", "start", "end", "strand", "name", "hallmark",
997
+ "hallmark_bitscore", "hallmark_evalue", "plv_mcp_bitscore",
998
+ "nonplv_mcp_bitscore", "pfam_id", "pfam_name", "pfam_bitscore", "pfam_evalue",
999
+ "pgap_id", "pgap_name", "pgap_label", "pgap_bitscore", "pgap_evalue",
1000
+ ]
1001
+ with open(path, "w", newline="") as fh:
1002
+ writer = csv.DictWriter(fh, fieldnames=columns, delimiter="\t", lineterminator="\n")
1003
+ writer.writeheader()
1004
+ for p in sorted(plvs, key=lambda x: _natural_key(x.plv_id)):
1005
+ for i, o in enumerate(p.orfs, start=1):
1006
+ writer.writerow(dict(
1007
+ plv_name=p.plv_id,
1008
+ orf=f"orf{i:05d}",
1009
+ start=o.start,
1010
+ end=o.end,
1011
+ strand="+" if o.strand >= 0 else "-",
1012
+ name=_annotation_name(o),
1013
+ hallmark=o.family if _is_plv_hallmark(o) else "NA",
1014
+ hallmark_bitscore=f"{o.family_bitscore:.1f}" if _is_plv_hallmark(o) and o.family_bitscore else "NA",
1015
+ hallmark_evalue=f"{o.family_evalue:.2e}" if _is_plv_hallmark(o) and math.isfinite(o.family_evalue) else "NA",
1016
+ plv_mcp_bitscore=f"{o.plv_mcp_bitscore:.1f}" if o.plv_mcp_bitscore else "NA",
1017
+ nonplv_mcp_bitscore=f"{o.nonplv_mcp_bitscore:.1f}" if o.nonplv_mcp_bitscore else "NA",
1018
+ pfam_id=o.best_pfam_acc or "NA",
1019
+ pfam_name=o.best_pfam_name or "NA",
1020
+ pfam_bitscore=f"{o.best_pfam_bitscore:.1f}" if o.best_pfam_bitscore else "NA",
1021
+ pfam_evalue=f"{o.best_pfam_evalue:.2e}" if math.isfinite(o.best_pfam_evalue) else "NA",
1022
+ pgap_id=o.best_pgap_acc or "NA",
1023
+ pgap_name=o.best_pgap_name or "NA",
1024
+ pgap_label=o.best_pgap_label or "NA",
1025
+ pgap_bitscore=f"{o.best_pgap_bitscore:.1f}" if o.best_pgap_acc else "NA",
1026
+ pgap_evalue=f"{o.best_pgap_evalue:.2e}" if o.best_pgap_acc else "NA",
1027
+ ))
1028
+
1029
+ def write_nucleotide_fasta(plvs: List[Plv], fa: pyfastx.Fasta, genome_path: Path, path: Path) -> None:
1030
+ with open(path, "w") as fh:
1031
+ for p in plvs:
1032
+ seq = _fetch_seq(fa, genome_path, p.contig, p.start, p.end)
1033
+ fh.write(
1034
+ f">{p.plv_id} contig={p.contig} start={p.start} end={p.end} "
1035
+ f"length={p.length} boundary={p.boundary_method}\n"
1036
+ )
1037
+ for i in range(0, len(seq), 80):
1038
+ fh.write(seq[i:i + 80] + "\n")
1039
+
1040
+ def write_protein_fasta(plvs: List[Plv], path: Path) -> None:
1041
+ with open(path, "w") as fh:
1042
+ for p in plvs:
1043
+ for i, o in enumerate(p.orfs, start=1):
1044
+ label = f"orf{i:05d}"
1045
+ annotation = _annotation_name(o)
1046
+ marker = f" marker={annotation}" if annotation else ""
1047
+ fh.write(f">{p.plv_id}_{label}{marker} length={len(o.protein)}\n")
1048
+ for j in range(0, len(o.protein), 80):
1049
+ fh.write(o.protein[j:j + 80] + "\n")
1050
+
1051
+ def write_cds_fasta(plvs: List[Plv], fa: pyfastx.Fasta, genome_path: Path, path: Path) -> None:
1052
+ with open(path, "w") as fh:
1053
+ for p in plvs:
1054
+ for i, o in enumerate(p.orfs, start=1):
1055
+ label = f"orf{i:05d}"
1056
+ seq = _fetch_seq(fa, genome_path, o.contig, o.start, o.end)
1057
+ if o.strand < 0:
1058
+ seq = _revcomp(seq)
1059
+ annotation = _annotation_name(o)
1060
+ marker = f" marker={annotation}" if annotation else ""
1061
+ fh.write(f">{p.plv_id}_{label}{marker} length={len(seq)}\n")
1062
+ for j in range(0, len(seq), 80):
1063
+ fh.write(seq[j:j + 80] + "\n")
1064
+
1065
+ def write_marker_peps(plvs: List[Plv], outdir: Path, prefix: str) -> List[Path]:
1066
+ marker_dir = outdir / "marker"
1067
+ marker_dir.mkdir(parents=True, exist_ok=True)
1068
+ by_marker: Dict[str, Dict[str, Orf]] = defaultdict(dict)
1069
+ for p in plvs:
1070
+ for o in p.orfs:
1071
+ if not _is_plv_hallmark(o):
1072
+ continue
1073
+ current = by_marker[o.family].get(p.plv_id)
1074
+ if current is None or o.family_bitscore > current.family_bitscore:
1075
+ by_marker[o.family][p.plv_id] = o
1076
+ written = []
1077
+ for marker in sorted(by_marker, key=_hallmark_sort_key):
1078
+ path = marker_dir / f"{prefix}.{marker}.pep"
1079
+ with open(path, "w") as fh:
1080
+ for plv_id, o in sorted(by_marker[marker].items(), key=lambda kv: _natural_key(kv[0])):
1081
+ fh.write(f">{plv_id}_{marker}\n")
1082
+ for i in range(0, len(o.protein), 80):
1083
+ fh.write(o.protein[i:i + 80] + "\n")
1084
+ written.append(path)
1085
+ return written
1086
+
1087
+ def _gff_escape(value: str) -> str:
1088
+ """Escape a GFF3 attribute value without introducing separators."""
1089
+ from urllib.parse import quote
1090
+ return quote(str(value), safe="._:-|+*")
1091
+
1092
+ def write_gff3(plvs: List[Plv], path: Path) -> None:
1093
+ with open(path, "w") as fh:
1094
+ fh.write("##gff-version 3\n")
1095
+ for p in plvs:
1096
+ pid = _gff_escape(p.plv_id)
1097
+ fh.write(
1098
+ f"{p.contig}\tDeepPLV\tPLV\t{p.start}\t{p.end}\t.\t+\t.\t"
1099
+ f"ID={pid};Name=PLV;boundary={_gff_escape(p.boundary_method)}\n"
1100
+ )
1101
+
1102
+ if p.tir:
1103
+ fh.write(
1104
+ f"{p.contig}\tDeepPLV\tTIR\t{p.tir.left_start}\t{p.tir.left_end}\t"
1105
+ f"{p.tir.score:.1f}\t+\t.\tID={pid}.TIR_left;Parent={pid};Name=TIR\n"
1106
+ )
1107
+ fh.write(
1108
+ f"{p.contig}\tDeepPLV\tTIR\t{p.tir.right_start}\t{p.tir.right_end}\t"
1109
+ f"{p.tir.score:.1f}\t-\t.\tID={pid}.TIR_right;Parent={pid};Name=TIR\n"
1110
+ )
1111
+
1112
+ if p.tsd and p.tir:
1113
+ l_end = p.tir.left_start - 1 - p.tsd.left_shift
1114
+ l_start = l_end - p.tsd.length + 1
1115
+ r_start = p.tir.right_end + 1 + p.tsd.right_shift
1116
+ r_end = r_start + p.tsd.length - 1
1117
+ fh.write(
1118
+ f"{p.contig}\tDeepPLV\tTSD\t{l_start}\t{l_end}\t.\t+\t.\t"
1119
+ f"ID={pid}.TSD_5p;Parent={pid};Name=TSD;"
1120
+ f"sequence={_gff_escape(p.tsd.sequence_left)}\n"
1121
+ )
1122
+ fh.write(
1123
+ f"{p.contig}\tDeepPLV\tTSD\t{r_start}\t{r_end}\t.\t+\t.\t"
1124
+ f"ID={pid}.TSD_3p;Parent={pid};Name=TSD;"
1125
+ f"sequence={_gff_escape(p.tsd.sequence_right)}\n"
1126
+ )
1127
+
1128
+ for i, o in enumerate(p.orfs, start=1):
1129
+ orf_label = f"orf{i:05d}"
1130
+ name = _annotation_name(o)
1131
+ if _is_plv_hallmark(o):
1132
+ score = o.family_bitscore
1133
+ score_field = f"{score:.1f}"
1134
+ attrs = (
1135
+ f"ID={pid}.{orf_label};Parent={pid};"
1136
+ f"Name={_gff_escape(name)};Orf={orf_label};"
1137
+ f"hallmark={_gff_escape(o.family)}"
1138
+ )
1139
+ elif o.best_pfam_name and not _use_pgap_fallback(o):
1140
+ score_field = f"{o.best_pfam_bitscore:.1f}"
1141
+ attrs = (
1142
+ f"ID={pid}.{orf_label};Parent={pid};"
1143
+ f"Name={_gff_escape(name)};Orf={orf_label};"
1144
+ f"Pfam={_gff_escape(o.best_pfam_acc or o.best_pfam_name)}"
1145
+ )
1146
+ elif _use_pgap_fallback(o):
1147
+ score_field = f"{o.best_pgap_bitscore:.1f}"
1148
+ attrs = (
1149
+ f"ID={pid}.{orf_label};Parent={pid};"
1150
+ f"Name={_gff_escape(name)};Orf={orf_label};"
1151
+ f"PGAP={_gff_escape(o.best_pgap_acc)}"
1152
+ )
1153
+ else:
1154
+ score_field = "."
1155
+ attrs = (
1156
+ f"ID={pid}.{orf_label};Parent={pid};"
1157
+ f"Name=hypothetical;Orf={orf_label}"
1158
+ )
1159
+ if o.partial:
1160
+ attrs += ";partial=true"
1161
+ fh.write(
1162
+ f"{p.contig}\tDeepPLV\tCDS\t{o.start}\t{o.end}\t"
1163
+ f"{score_field}\t{'+' if o.strand >= 0 else '-'}\t0\t{attrs}\n"
1164
+ )
1165
+
1166
+ @dataclass
1167
+ class Candidate:
1168
+ contig: str
1169
+ contig_length: int
1170
+ start: int
1171
+ end: int
1172
+ plv_score: float
1173
+ max_win_score: float
1174
+ plv_id: str = ""
1175
+ orfs: list = field(default_factory=list)
1176
+ tir: Any = None
1177
+ tsd: Any = None
1178
+ families: list[str] = field(default_factory=list)
1179
+ gc: float = float("nan")
1180
+ biological_score: int = 0
1181
+ category: str = ""
1182
+ core_start: Optional[int] = None
1183
+ core_end: Optional[int] = None
1184
+ tir_geometry: float = 0.0
1185
+ scan_start: Optional[int] = None
1186
+ scan_end: Optional[int] = None
1187
+ boundary_status: str = "Window"
1188
+ boundary_unresolved: bool = False
1189
+ boundary_conflicts: int = 0
1190
+ partial_hallmarks: int = 0
1191
+ context_orfs: list[Orf] = field(default_factory=list, repr=False)
1192
+ independent_support_windows: int = 0
1193
+ tir_hallmark_distance_rejected: int = 0
1194
+ @property
1195
+ def length(self) -> int:
1196
+ return self.end-self.start+1
1197
+
1198
+ def validate_settings(cfg: dict) -> None:
1199
+ for window, step in (("window", "step"), ("refine_window", "refine_step")):
1200
+ if not isinstance(cfg[window], int) or cfg[window] < 128 or cfg[window] % 128:
1201
+ raise ValueError(f"{window} must be a multiple of 128 and >=128")
1202
+ if not isinstance(cfg[step], int) or not 0 < cfg[step] <= cfg[window]:
1203
+ raise ValueError(f"{step} must be in (0, {window}]")
1204
+ if not isinstance(cfg["batch_size"], int) or cfg["batch_size"] < 1:
1205
+ raise ValueError("batch_size must be positive")
1206
+ if not 0 < cfg["extend_score"] < cfg["min_score"] <= 1:
1207
+ raise ValueError("Require 0 < extend_score < min_score <= 1")
1208
+ if not 0 < cfg["min_score"] <= 1:
1209
+ raise ValueError("min_score must be in (0, 1]")
1210
+ if cfg["min_plv_length"] < 1 or cfg["max_plv_length"] < cfg["min_plv_length"]:
1211
+ raise ValueError("Invalid PLV length limits")
1212
+ if cfg["max_coarse_island"] < cfg["window"]:
1213
+ raise ValueError("max_coarse_island must be >= window")
1214
+ for name in ('orf_flank', 'orf_max_extension', 'adaptive_flank'):
1215
+ if not isinstance(cfg[name], int) or cfg[name] < 0:
1216
+ raise ValueError(f'{name} must be a nonnegative integer')
1217
+ if cfg['orf_flank'] < cfg['orf_max_extension']:
1218
+ raise ValueError('orf_flank must be >= orf_max_extension to avoid missing complete ORFs')
1219
+ if cfg['adaptive_step'] <= 0 or cfg['adaptive_step'] > cfg['refine_step']:
1220
+ raise ValueError('adaptive_step must be positive and <= refine_step')
1221
+ if (not isinstance(cfg['tir_max_hallmark_extension'], int)
1222
+ or cfg['tir_max_hallmark_extension'] <= 0):
1223
+ raise ValueError('tir_max_hallmark_extension must be a positive integer')
1224
+
1225
+
1226
+ def cli(argv: list[str] | None = None):
1227
+ argv = list(sys.argv[1:] if argv is None else argv)
1228
+ if "-h" in argv or "--help" in argv:
1229
+ print(HELP_TEXT, end="")
1230
+ raise SystemExit(0)
1231
+ if "--version" in argv:
1232
+ print(f"DeepPLV {VERSION}")
1233
+ raise SystemExit(0)
1234
+ p = argparse.ArgumentParser(
1235
+ description="PLV identification in eukaryotic genome assemblies",
1236
+ usage=USAGE_TEXT.removeprefix("Usage: ").rstrip(),
1237
+ add_help=False,
1238
+ )
1239
+ p.add_argument("genome", type=Path, help="Genome FASTA (.fna/.fa/.fasta, optionally .gz)")
1240
+ p.add_argument("-db", "--db", required=True, type=Path,
1241
+ help="Database directory (checkpoint and HMM databases)")
1242
+ p.add_argument("-g", "--gff", type=Path,
1243
+ help="Host annotation .gff/.gff3/.gtf (optionally .gz)")
1244
+ p.add_argument("-p", "--prefix", type=str, default="DeepPLV",
1245
+ help="Output filename and PLV identifier prefix (default: DeepPLV)")
1246
+ p.add_argument("-o", "--outdir", type=Path,
1247
+ help="Output directory (default DeepPLV_YYYYMMDD)")
1248
+ p.add_argument("-t", "--threads", type=int, default=4,
1249
+ help="CPU HMMER threads (default 4)")
1250
+ args = p.parse_args(argv)
1251
+ return args
1252
+
1253
+
1254
+ def setup_log(path: Path):
1255
+ LOG.setLevel(logging.INFO)
1256
+ for old_handler in list(LOG.handlers):
1257
+ LOG.removeHandler(old_handler)
1258
+ old_handler.close()
1259
+ fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s", "%Y-%m-%d %H:%M:%S")
1260
+ for handler in (logging.StreamHandler(sys.stderr), logging.FileHandler(path, encoding="utf-8")):
1261
+ handler.setFormatter(fmt)
1262
+ LOG.addHandler(handler)
1263
+
1264
+
1265
+ def find_weights(folder: Path) -> Path:
1266
+ matches = sorted(folder.glob("*.pt"))
1267
+ preferred = folder / "deepplv.pt"
1268
+ if preferred.is_file():
1269
+ return preferred
1270
+ if len(matches) != 1:
1271
+ raise ValueError(f"Expected exactly one .pt checkpoint in {folder}, or deepplv.pt; found {len(matches)}")
1272
+ return matches[0]
1273
+
1274
+
1275
+ def get_device(gpu: Any):
1276
+ if str(gpu).lower() == "cpu":
1277
+ return torch.device("cpu")
1278
+ if str(gpu).lower() == "auto":
1279
+ return torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
1280
+ idx = int(gpu)
1281
+ if not torch.cuda.is_available() or idx >= torch.cuda.device_count() or idx < 0:
1282
+ raise ValueError(f"Requested CUDA GPU {idx} is unavailable")
1283
+ return torch.device(f"cuda:{idx}")
1284
+
1285
+
1286
+ def load_model(checkpoint: Path, device: torch.device):
1287
+ try:
1288
+ state = torch.load(checkpoint, map_location="cpu", weights_only=True)
1289
+ except Exception as exc:
1290
+ raise RuntimeError(f"Cannot safely load checkpoint {checkpoint}: {exc}") from exc
1291
+ if not isinstance(state, dict) or not isinstance(state.get("model"), dict):
1292
+ raise ValueError("Expected training checkpoint with model state_dict and config")
1293
+ cfg = state.get("config")
1294
+ if not isinstance(cfg, dict) or not isinstance(cfg.get("model"), dict) or not isinstance(cfg.get("data"), dict):
1295
+ raise ValueError("Checkpoint missing model/data training configuration")
1296
+ mcfg, dcfg = cfg["model"], cfg["data"]
1297
+ if mcfg.get("architecture") != "cnn_bilstm":
1298
+ raise ValueError(f"Checkpoint architecture {mcfg.get('architecture')!r} is not cnn_bilstm")
1299
+ if dcfg.get("strategy") != "multiclass" or dcfg.get("positive_label") != "PLV":
1300
+ raise ValueError("Use the selected multiclass CNN–BiLSTM PLV checkpoint")
1301
+ required_window = max(DEFAULTS["window"], DEFAULTS["refine_window"])
1302
+ if int(dcfg.get("max_window", 0)) < required_window:
1303
+ raise ValueError(
1304
+ f"Requested scan window ({required_window:,} bp) exceeds model training "
1305
+ f"max_window ({int(dcfg.get('max_window', 0)):,} bp)"
1306
+ )
1307
+ weights = state["model"]
1308
+ head_weight = weights.get("head.classifier.3.weight")
1309
+ if head_weight is None or head_weight.ndim != 2 or head_weight.shape[0] != 4:
1310
+ raise ValueError("Expected four output classes (NCLDV, PLV, Polintoviricetes, Virophage)")
1311
+ names = ("NCLDV", "PLV", "Polintoviricetes", "Virophage")
1312
+ model = build(mcfg, num_classes=4, strategy="multiclass")
1313
+ model.load_state_dict(weights, strict=True)
1314
+ model.to(device).eval()
1315
+ LOG.info("Model loaded | checkpoint=%s | epoch=%s | max_window=%s | device=%s",
1316
+ checkpoint.name, state.get("epoch"), dcfg["max_window"], device)
1317
+ return model, names.index("PLV")
1318
+
1319
+ def window_starts(length: int, width: int, step: int) -> Iterator[int]:
1320
+ """0-based starts; include tail window once, even on non-divisible contigs."""
1321
+ if length <= 0:
1322
+ return
1323
+ if length <= width:
1324
+ yield 0
1325
+ return
1326
+ last = length - width
1327
+ for x in range(0, last + 1, step):
1328
+ yield x
1329
+ if last % step:
1330
+ yield last
1331
+
1332
+ def _window_count(length: int, width: int, step: int) -> int:
1333
+ """Count starts generated by window_starts without materializing them."""
1334
+ if length <= 0:
1335
+ return 0
1336
+ take = min(width, length)
1337
+ if length <= take:
1338
+ return 1
1339
+ last = length - take
1340
+ return last // step + 1 + int(last % step != 0)
1341
+
1342
+
1343
+ class ProgressBar:
1344
+ """Interactive progress bar or timestamped milestones for redirected runs."""
1345
+
1346
+ def __init__(self, label: str, total: int, stream=None):
1347
+ self.label = label
1348
+ self.total = max(0, int(total))
1349
+ self.count = 0
1350
+ self.stream = stream if stream is not None else sys.stderr
1351
+ self.interactive = bool(getattr(self.stream, "isatty", lambda: False)())
1352
+ self.last_drawn = -1
1353
+ self.draw_interval = max(1, self.total // 200)
1354
+ self.next_report = 10
1355
+ if self.total:
1356
+ if self.interactive:
1357
+ self._draw(force=True)
1358
+ else:
1359
+ LOG.info('%s', self._line())
1360
+
1361
+ def _line(self) -> str:
1362
+ fraction = self.count / self.total if self.total else 1.0
1363
+ fraction = min(1.0, fraction)
1364
+ width = 24
1365
+ filled = min(width, int(fraction * width))
1366
+ bar = '=' * filled + ' ' * (width - filled)
1367
+ return (f'{self.label} [{bar}] {100 * fraction:5.1f}% '
1368
+ f'({self.count:,}/{self.total:,})')
1369
+
1370
+ def _draw(self, force: bool = False):
1371
+ if not self.interactive or not self.total:
1372
+ return
1373
+ if not force and self.count != self.total and self.count - self.last_drawn < self.draw_interval:
1374
+ return
1375
+ self.stream.write('\r' + self._line())
1376
+ self.stream.flush()
1377
+ self.last_drawn = self.count
1378
+
1379
+ def update(self, amount: int = 1):
1380
+ if not self.total:
1381
+ return
1382
+ self.count = min(self.total, self.count + max(0, int(amount)))
1383
+ if self.interactive:
1384
+ self._draw()
1385
+ elif self.count < self.total:
1386
+ percent = 100.0 * self.count / self.total
1387
+ if percent >= self.next_report:
1388
+ LOG.info('%s', self._line())
1389
+ self.next_report = (int(percent // 10) + 1) * 10
1390
+
1391
+ def close(self):
1392
+ if self.interactive and self.total:
1393
+ self.stream.write('\r\x1b[2K')
1394
+ self.stream.flush()
1395
+ if self.total == 0:
1396
+ LOG.info('%s | skipped (no eligible windows)', self.label)
1397
+ else:
1398
+ LOG.info('%s', self._line())
1399
+ self.interactive = False
1400
+
1401
+ def _expected_windows(fa, width: int, step: int, short_contig_min: Optional[int] = None) -> int:
1402
+ total = 0
1403
+ for rec in fa:
1404
+ length = len(rec)
1405
+ if length <= 0:
1406
+ continue
1407
+ if length < width:
1408
+ if short_contig_min is not None and length < short_contig_min:
1409
+ continue
1410
+ effective_width = length
1411
+ else:
1412
+ effective_width = width
1413
+ total += _window_count(length, effective_width, step)
1414
+ return total
1415
+
1416
+ def encode_batch(sequences: list[str], rc: bool) -> tuple[torch.Tensor, torch.Tensor]:
1417
+ if not sequences:
1418
+ raise ValueError("Empty inference batch")
1419
+ max_len = max(len(s) for s in sequences)
1420
+ width = math.ceil(max_len / 128) * 128
1421
+ ids = np.full((len(sequences), width), 6, dtype=np.int64)
1422
+ lengths = np.empty(len(sequences), dtype=np.int64)
1423
+ for i, seq in enumerate(sequences):
1424
+ data = np.frombuffer(seq.upper().encode("ascii", "replace"), dtype=np.uint8)
1425
+ encoded = BASES[data]
1426
+ if rc:
1427
+ encoded = RC_IDS[encoded[::-1]]
1428
+ ids[i, :len(encoded)] = encoded
1429
+ lengths[i] = len(encoded)
1430
+ return torch.from_numpy(ids), torch.from_numpy(lengths)
1431
+
1432
+ class Scorer:
1433
+ def __init__(self, model, plv_index: int, device: torch.device, batch_size: int, rc_average: bool):
1434
+ self.model, self.positive, self.device = model, plv_index, device
1435
+ self.batch_size, self.rc_average = batch_size, rc_average
1436
+
1437
+ @torch.inference_mode()
1438
+ def probabilities(self, seqs: list[str]) -> list[float]:
1439
+ ids, lengths = encode_batch(seqs, False)
1440
+ dev = self.device
1441
+ ids, lengths = ids.to(dev), lengths.to(dev)
1442
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=dev.type == "cuda"):
1443
+ raw = self.model(ids, lengths)
1444
+ probs = raw.float().softmax(-1)[:, self.positive]
1445
+ if self.rc_average:
1446
+ rid, rlen = encode_batch(seqs, True)
1447
+ rid, rlen = rid.to(dev), rlen.to(dev)
1448
+ with torch.autocast(device_type="cuda", dtype=torch.bfloat16, enabled=dev.type == "cuda"):
1449
+ reverse = self.model(rid, rlen).float().softmax(-1)[:, self.positive]
1450
+ probs = (probs + reverse) / 2
1451
+ return probs.cpu().tolist()
1452
+
1453
+ def score_windows(self, fa, contig: str, clen: int, start0: int, end0: int,
1454
+ width: int, step: int, max_n: float,
1455
+ progress: Optional[ProgressBar] = None,
1456
+ batch_size: Optional[int] = None):
1457
+ """Score sequence windows across a genomic interval."""
1458
+ interval_len = end0 - start0
1459
+ if interval_len <= 0:
1460
+ return []
1461
+ take = min(width, interval_len)
1462
+ batch_limit = self.batch_size if batch_size is None else int(batch_size)
1463
+ if batch_limit < 1:
1464
+ raise ValueError("Window-scoring batch_size must be positive")
1465
+ sequences, coords = [], []
1466
+ def flush():
1467
+ if sequences:
1468
+ scores = self.probabilities(sequences)
1469
+ output = [(s, e, p) for (s, e), p in zip(coords, scores)]
1470
+ sequences.clear(); coords.clear()
1471
+ if progress is not None:
1472
+ progress.update(len(output))
1473
+ return output
1474
+ return []
1475
+ for rel in window_starts(interval_len, take, step):
1476
+ s, e = start0 + rel, start0 + rel + take
1477
+ seq = fa.fetch(contig, (s + 1, e)).upper()
1478
+ if len(seq) != e - s:
1479
+ raise RuntimeError(f"FASTA fetch returned wrong length for {contig}:{s+1}-{e}")
1480
+ n_ambiguous = len(seq) - sum(seq.count(base) for base in "ACGT")
1481
+ if n_ambiguous / len(seq) > max_n:
1482
+ if progress is not None:
1483
+ progress.update()
1484
+ continue
1485
+ coords.append((s, e))
1486
+ sequences.append(seq)
1487
+ if len(sequences) >= batch_limit:
1488
+ yield from flush()
1489
+ yield from flush()
1490
+
1491
+
1492
+ def merge_intervals(records: list[tuple[int, int]], gap: int = 0) -> list[tuple[int, int]]:
1493
+ if not records:
1494
+ return []
1495
+ records = sorted(records)
1496
+ out = [list(records[0])]
1497
+ for s, e in records[1:]:
1498
+ if s <= out[-1][1] + gap:
1499
+ out[-1][1] = max(e, out[-1][1])
1500
+ else:
1501
+ out.append([s, e])
1502
+ return [(s, e) for s, e in out]
1503
+
1504
+ def aggregate_window_evidence(windows: list[tuple[int,int,float]],
1505
+ start0: int, end0: int,
1506
+ high_threshold: float) -> tuple[Optional[float], Optional[tuple[int,int]]]:
1507
+ """Aggregate overlapping window scores into regional evidence."""
1508
+ size=end0-start0
1509
+ if size <= 0:
1510
+ return None, 0.0, None
1511
+ ds=np.zeros(size+1,dtype=np.float64)
1512
+ dw=np.zeros(size+1,dtype=np.float64)
1513
+ for start,end,prob in windows:
1514
+ if start>=end0 or end<=start0:
1515
+ continue
1516
+ w=end-start
1517
+ lo=start+int(w*0.15); hi=end-int(w*0.15)
1518
+ for ss,ee,weight in ((start,lo,.5),(lo,hi,1.0),(hi,end,.5)):
1519
+ a=max(ss,start0)-start0; b=min(ee,end0)-start0
1520
+ if b<=a:
1521
+ continue
1522
+ ds[a]+=float(prob)*weight; ds[b]-=float(prob)*weight
1523
+ dw[a]+=weight; dw[b]-=weight
1524
+ scores=np.cumsum(ds[:-1]); weights=np.cumsum(dw[:-1])
1525
+ covered=weights>1e-8
1526
+ if not np.any(covered):
1527
+ return None, 0.0, None
1528
+ local=np.zeros(size,dtype=np.float64)
1529
+ local[covered]=np.clip(scores[covered]/weights[covered],0,1)
1530
+ confidence=float(np.mean(local[covered]))
1531
+ strong=covered & (local>=high_threshold)
1532
+ indices=np.flatnonzero(strong)
1533
+ core=(start0+int(indices[0])+1, start0+int(indices[-1])+1) if len(indices) else None
1534
+ return confidence, core
1535
+
1536
+
1537
+ def refresh_final_window_support(fa, scorer, candidates: list[Candidate], cfg: dict) -> None:
1538
+ """Recalculate model support on final marker-free candidates."""
1539
+ if not candidates:
1540
+ return
1541
+ unscorable = 0
1542
+ for c in candidates:
1543
+ windows=list(scorer.score_windows(
1544
+ fa,c.contig,c.contig_length,c.start-1,c.end,
1545
+ cfg['refine_window'],cfg['refine_step'],cfg['max_n_fraction']))
1546
+ regional,_=aggregate_window_evidence(
1547
+ windows,c.start-1,c.end,cfg['min_score'])
1548
+ if regional is None:
1549
+ c.plv_score=0.0
1550
+ c.max_win_score=0.0
1551
+ c.independent_support_windows=0
1552
+ unscorable += 1
1553
+ continue
1554
+ c.plv_score=float(regional)
1555
+ c.max_win_score=max((p for _,_,p in windows),default=0.0)
1556
+ c.independent_support_windows=_distinct_positive_windows(windows,cfg['min_score'],cfg['refine_step'])
1557
+ LOG.info('Marker-free candidate sequence screening complete | regions=%d | unscorable=%d',
1558
+ len(candidates), unscorable)
1559
+
1560
+
1561
+ def split_supported_regions(windows, start: int, end: int, cfg: dict):
1562
+ relevant = sorted((s, e, p) for s, e, p in windows if s < end and e > start)
1563
+ splits = []
1564
+ run = []
1565
+ for s, e, p in relevant + [(end, end, 1.0)]:
1566
+ if p <= cfg['valley_score']:
1567
+ run.append((s, e))
1568
+ continue
1569
+ if len(run) >= cfg['valley_min_windows']:
1570
+ mid = (run[0][0] + run[-1][1]) // 2
1571
+ if (start + cfg['min_plv_length'] <= mid <= end - cfg['min_plv_length'] and
1572
+ any(x < run[0][0] and z >= cfg['min_score'] for x, _, z in relevant) and
1573
+ any(x > run[-1][0] and z >= cfg['min_score'] for x, _, z in relevant)):
1574
+ splits.append(mid)
1575
+ run.clear()
1576
+ bounds = [start] + sorted(set(splits)) + [end]
1577
+ return [(a, b) for a, b in zip(bounds, bounds[1:])
1578
+ if b - a >= cfg['min_plv_length']]
1579
+
1580
+ def scan_candidates(fa, scorer: Scorer, cfg: dict) -> list[Candidate]:
1581
+ """Original 8-kb discovery strategy, with a single clean progress bar."""
1582
+ results = []
1583
+ n_coarse = n_seed = n_contigs = n_fine = oversized = 0
1584
+ progress = ProgressBar("8-kb scan", _expected_windows(fa, cfg['window'], cfg['step']))
1585
+ try:
1586
+ for rec in fa:
1587
+ contig, length = rec.name, len(rec)
1588
+ if length == 0:
1589
+ continue
1590
+ n_contigs += 1
1591
+ islands = []
1592
+ for s, e, p in scorer.score_windows(
1593
+ fa, contig, length, 0, length, cfg['window'], cfg['step'],
1594
+ cfg['max_n_fraction'], progress=progress):
1595
+ n_coarse += 1
1596
+ if p < cfg['min_score']:
1597
+ continue
1598
+ n_seed += 1
1599
+ if islands and s <= islands[-1][1] + cfg['coarse_merge_gap']:
1600
+ islands[-1] = (islands[-1][0], max(e, islands[-1][1]))
1601
+ else:
1602
+ islands.append((s, e))
1603
+ if not islands:
1604
+ continue
1605
+ ranges = []
1606
+ for s, e in islands:
1607
+ for sub in range(s, e, cfg['max_coarse_island']):
1608
+ lo = max(0, sub - cfg['refine_flank'])
1609
+ hi = min(length, min(e, sub + cfg['max_coarse_island']) + cfg['refine_flank'])
1610
+ ranges.append((lo, hi))
1611
+ bounded = []
1612
+ for rs, re_ in sorted(ranges):
1613
+ if (bounded and rs <= bounded[-1][1]
1614
+ and re_ - bounded[-1][0] <= cfg['max_coarse_island'] + 2 * cfg['refine_flank']):
1615
+ bounded[-1] = (bounded[-1][0], max(bounded[-1][1], re_))
1616
+ else:
1617
+ bounded.append((rs, re_))
1618
+ contig_regions = []
1619
+ fine_evidence = {}
1620
+ for rs, re_ in bounded:
1621
+ fine = list(scorer.score_windows(
1622
+ fa, contig, length, rs, re_, cfg['refine_window'],
1623
+ cfg['refine_step'], cfg['max_n_fraction']))
1624
+ n_fine += len(fine)
1625
+ for ss, ee, pp in fine:
1626
+ fine_evidence[(ss, ee)] = pp
1627
+ if not fine:
1628
+ continue
1629
+ ext = [(s, e) for s, e, p in fine if p >= cfg['extend_score']]
1630
+ groups = merge_intervals(ext, cfg['refined_merge_gap'])
1631
+ groups = [piece for a, b in groups for piece in split_supported_regions(fine, a, b, cfg)]
1632
+ for a, b in groups:
1633
+ local = [p for s, e, p in fine if s < b and e > a]
1634
+ if not local or max(local) < cfg['min_score']:
1635
+ continue
1636
+ if b - a < cfg['min_plv_length']:
1637
+ continue
1638
+ if b - a > cfg['max_plv_length']:
1639
+ oversized += 1
1640
+ continue
1641
+ neural, core = aggregate_window_evidence(fine, a, b, cfg['min_score'])
1642
+ if neural is None:
1643
+ continue
1644
+ cs, ce = core if core is not None else (a + 1, b)
1645
+ contig_regions.append(Candidate(
1646
+ contig, length, a + 1, b, neural, max(local),
1647
+ core_start=cs, core_end=ce,
1648
+ scan_start=a + 1, scan_end=b))
1649
+ contig_regions.sort(key=lambda x: (x.start, x.end))
1650
+ consolidated = []
1651
+ for cand in contig_regions:
1652
+ if consolidated and cand.start <= consolidated[-1].end + cfg['refined_merge_gap']:
1653
+ old = consolidated[-1]
1654
+ new_end = max(old.end, cand.end)
1655
+ if new_end - old.start + 1 <= cfg['max_plv_length']:
1656
+ old_len, add_len = old.length, cand.length
1657
+ old.end = new_end
1658
+ old.plv_score = (old.plv_score * old_len + cand.plv_score * add_len) / max(1, old_len + add_len)
1659
+ old.max_win_score = max(old.max_win_score, cand.max_win_score)
1660
+ old.core_start = min(old.core_start or old.start, cand.core_start or cand.start)
1661
+ old.core_end = max(old.core_end or old.end, cand.core_end or cand.end)
1662
+ old.scan_end = new_end
1663
+ continue
1664
+ consolidated.append(cand)
1665
+ evidence = [(a, b, p) for (a, b), p in fine_evidence.items()]
1666
+ for cand in consolidated:
1667
+ overlapping = [(a, b, p) for a, b, p in evidence if a < cand.end and b >= cand.start]
1668
+ neural, core = aggregate_window_evidence(
1669
+ overlapping, cand.start - 1, cand.end, cfg['min_score'])
1670
+ if neural is not None:
1671
+ cand.plv_score = neural
1672
+ cand.max_win_score = max((p for _, _, p in overlapping), default=0.0)
1673
+ cand.core_start, cand.core_end = core if core else (cand.start, cand.end)
1674
+ cand.scan_start, cand.scan_end = cand.start, cand.end
1675
+ results.extend(consolidated)
1676
+ finally:
1677
+ progress.close()
1678
+ LOG.info('Genome screening complete | mode=legacy | contigs=%s | coarse_windows=%s | '
1679
+ 'seed_windows=%s | refined_windows=%s | regions=%s | oversized_excluded=%s',
1680
+ f'{n_contigs:,}', f'{n_coarse:,}', f'{n_seed:,}', f'{n_fine:,}',
1681
+ f'{len(results):,}', f'{oversized:,}')
1682
+ return results
1683
+
1684
+
1685
+ def adaptive_refine_candidates(fa, scorer, candidates: list[Candidate], cfg: dict) -> None:
1686
+ if not cfg['adaptive_edge'] or not candidates:
1687
+ return
1688
+ width = cfg['refine_window']
1689
+ step = cfg['adaptive_step']
1690
+ flank = cfg['adaptive_flank']
1691
+ by_edge = defaultdict(list)
1692
+ batch_seqs, batch_meta = [], []
1693
+
1694
+ def flush():
1695
+ if not batch_seqs:
1696
+ return
1697
+ scores = scorer.probabilities(batch_seqs)
1698
+ if len(scores) != len(batch_meta):
1699
+ raise RuntimeError('Adaptive inference returned an unexpected number of scores')
1700
+ for (key, start, end), probability in zip(batch_meta, scores):
1701
+ by_edge[key].append((start, end, probability))
1702
+ batch_seqs.clear()
1703
+ batch_meta.clear()
1704
+
1705
+ for index, cand in enumerate(candidates):
1706
+ if cand.contig_length <= width:
1707
+ continue
1708
+ for side in ('left', 'right'):
1709
+ edge0 = cand.start - 1 if side == 'left' else cand.end
1710
+ anchor = edge0 if side == 'left' else edge0 - width
1711
+ first = max(0, anchor - flank)
1712
+ last = min(cand.contig_length - width, anchor + flank)
1713
+ if last <= first:
1714
+ continue
1715
+ interval = last + width - first
1716
+ take = min(width, interval)
1717
+ for rel in window_starts(interval, take, step):
1718
+ start0 = first + rel
1719
+ end0 = start0 + take
1720
+ seq = fa.fetch(cand.contig, (start0 + 1, end0)).upper()
1721
+ if len(seq) != end0 - start0:
1722
+ raise RuntimeError(f'FASTA fetch returned wrong length for {cand.contig}:{start0 + 1}-{end0}')
1723
+ n_ambiguous = len(seq) - sum(seq.count(base) for base in 'ACGT')
1724
+ if n_ambiguous / len(seq) > cfg['max_n_fraction']:
1725
+ continue
1726
+ batch_seqs.append(seq)
1727
+ batch_meta.append(((index, side), start0, end0))
1728
+ if len(batch_seqs) >= scorer.batch_size:
1729
+ flush()
1730
+ flush()
1731
+
1732
+ adjusted = 0
1733
+ for index, cand in enumerate(candidates):
1734
+ if cand.contig_length <= width:
1735
+ continue
1736
+ old_start, old_end = cand.start, cand.end
1737
+ for side in ('left', 'right'):
1738
+ edge0 = cand.start - 1 if side == 'left' else cand.end
1739
+ anchor = edge0 if side == 'left' else edge0 - width
1740
+ windows = sorted(by_edge.get((index, side), ()), key=lambda item: item[0])
1741
+ if len(windows) < 3:
1742
+ continue
1743
+ crossings = []
1744
+ for a, b in zip(windows, windows[1:]):
1745
+ if side == 'left' and a[2] < cfg['extend_score'] <= b[2]:
1746
+ crossings.append((abs((a[0]+b[0])/2 - anchor), int(round((a[0]+b[0])/2))))
1747
+ elif side == 'right' and a[2] >= cfg['extend_score'] > b[2]:
1748
+ crossings.append((abs((a[1]+b[1])/2 - edge0), int(round((a[1]+b[1])/2))))
1749
+ if not crossings:
1750
+ continue
1751
+ boundary = min(crossings)[1]
1752
+ if side == 'left':
1753
+ new_start = boundary + 1
1754
+ if (new_start < cand.end and new_start <= (cand.core_start or cand.end) and
1755
+ cfg['min_plv_length'] <= cand.end - new_start + 1 <= cfg['max_plv_length']):
1756
+ cand.start = new_start
1757
+ else:
1758
+ new_end = boundary
1759
+ if (new_end > cand.start and new_end >= (cand.core_end or cand.start) and
1760
+ cfg['min_plv_length'] <= new_end - cand.start + 1 <= cfg['max_plv_length']):
1761
+ cand.end = new_end
1762
+ if (cand.start, cand.end) != (old_start, old_end):
1763
+ cand.scan_start, cand.scan_end = cand.start, cand.end
1764
+ cand.boundary_unresolved = False
1765
+ adjusted += 1
1766
+ LOG.info('Adaptive boundary localization complete | regions=%d | adjusted=%d | step=%d bp',
1767
+ len(candidates), adjusted, step)
1768
+
1769
+ def tir_intersects_orf(tir: TirPair, orf: Orf) -> bool:
1770
+ return ((orf.start <= tir.left_end and orf.end >= tir.left_start) or
1771
+ (orf.start <= tir.right_end and orf.end >= tir.right_start))
1772
+
1773
+ def _tir_quality(t: TirPair) -> float:
1774
+ return 0.8 * (t.tir_identity / 100.0) + 0.2 * min(t.tir_length, 1000) / 1000.0
1775
+
1776
+ def _tsd_for_boundaries(fa, genome: Path, contig: str, length: int,
1777
+ ls: int, re: int, cfg: dict):
1778
+ left = _fetch_seq(fa, genome, contig, max(1, ls - 50), ls - 1) if ls > 1 else ''
1779
+ right = _fetch_seq(fa, genome, contig, re + 1, min(length, re + 50)) if re < length else ''
1780
+ if not left or not right:
1781
+ return None
1782
+ return find_tsd(left, right, cfg['tsd_min'], cfg['tsd_max'], cfg['tsd_max_slide'])
1783
+
1784
+ def _candidate_hallmark_core(cand: Candidate) -> list[Orf]:
1785
+ """Return candidate-core ORFs supported by the PLV hallmark HMM only."""
1786
+ markers = [o for o in cand.orfs if _is_plv_hallmark(o)]
1787
+ if markers:
1788
+ return markers
1789
+ scan_start = cand.scan_start or cand.start
1790
+ scan_end = cand.scan_end or cand.end
1791
+ return [o for o in cand.context_orfs
1792
+ if _is_plv_hallmark(o) and o.start <= scan_end and o.end >= scan_start]
1793
+
1794
+ def select_tir_for_candidate(pairs, offset1: int, region_seq: str,
1795
+ cand: Candidate, cfg: dict, fa=None, genome=None,
1796
+ forbidden: set[tuple[int, int]] | None = None,
1797
+ evaluation_cache: dict | None = None):
1798
+ """Select a structurally valid TIR pair close to the PLV-HMM hallmark core."""
1799
+ if evaluation_cache is not None and 'viable' in evaluation_cache:
1800
+ viable = [item for item in evaluation_cache['viable']
1801
+ if forbidden is None or (item[1].left_start, item[1].right_end) not in forbidden]
1802
+ if not viable:
1803
+ cand.tir_geometry = 0.0
1804
+ return None, None
1805
+ winner = viable[0]
1806
+ cand.tir_geometry = winner[3]
1807
+ return winner[1], winner[2]
1808
+ viable = []
1809
+ scan_start = cand.scan_start or cand.start
1810
+ scan_end = cand.scan_end or cand.end
1811
+ scan_len = scan_end - scan_start + 1
1812
+ markers = _candidate_hallmark_core(cand)
1813
+ hallmark_start = min((o.start for o in markers), default=None)
1814
+ hallmark_end = max((o.end for o in markers), default=None)
1815
+ max_extension = cfg['tir_max_hallmark_extension']
1816
+
1817
+ for t in pairs:
1818
+ if not (1 <= t.left_start <= t.left_end < t.right_start <=
1819
+ t.right_end <= len(region_seq)):
1820
+ continue
1821
+ ls, le = t.left_start + offset1 - 1, t.left_end + offset1 - 1
1822
+ rs, re = t.right_start + offset1 - 1, t.right_end + offset1 - 1
1823
+ if forbidden and (ls, re) in forbidden:
1824
+ continue
1825
+ span = re - ls + 1
1826
+ if not (cfg['tir_min_len'] <= t.tir_length <= cfg['tir_max_len'] and
1827
+ cfg['tir_min_len'] <= t.right_end - t.right_start + 1 <= cfg['tir_max_len'] and
1828
+ t.tir_identity >= cfg['tir_min_id'] and
1829
+ cfg['tir_min_insert'] <= t.insert_size <= cfg['tir_max_insert'] and
1830
+ cfg['min_plv_length'] <= span <= cfg['max_plv_length']):
1831
+ continue
1832
+ lseq = region_seq[t.left_start - 1:t.left_end]
1833
+ rseq = region_seq[t.right_start - 1:t.right_end]
1834
+ if _tir_is_low_complexity(lseq, cfg) or _tir_is_low_complexity(rseq, cfg):
1835
+ continue
1836
+ overlap = max(0, min(scan_end, re) - max(scan_start, ls) + 1)
1837
+ if overlap / max(1, scan_len) < cfg['min_tir_coverage']:
1838
+ continue
1839
+
1840
+ absolute = TirPair(ls, le, rs, re, t.tir_length, t.insert_size,
1841
+ t.tir_identity, t.score, t.matches, t.total,
1842
+ t.gaps, t.tir_evalue)
1843
+ if any(tir_intersects_orf(absolute, o) for o in cand.context_orfs
1844
+ if _is_plv_hallmark(o)):
1845
+ continue
1846
+
1847
+ distance_penalty = 0.0
1848
+ if markers:
1849
+ if any(not (le < o.start and o.end < rs) for o in markers):
1850
+ continue
1851
+ left_extension = max(0, hallmark_start - le - 1)
1852
+ right_extension = max(0, rs - hallmark_end - 1)
1853
+ max_gap = max(left_extension, right_extension)
1854
+ if max_gap > max_extension:
1855
+ if forbidden is not None:
1856
+ forbidden.add((ls, re))
1857
+ cand.tir_hallmark_distance_rejected += 1
1858
+ continue
1859
+ distance_penalty = 1.5 * (
1860
+ 0.7 * max_gap / max_extension
1861
+ + 0.3 * (left_extension + right_extension) / (2.0 * max_extension)
1862
+ )
1863
+
1864
+ tsd = (_tsd_for_boundaries(fa, genome, cand.contig, cand.contig_length,
1865
+ ls, re, cfg) if fa is not None else None)
1866
+ edge_distance = abs(ls - scan_start) + abs(re - scan_end)
1867
+ geometry = max(0.0, 1.0 - edge_distance / max(10000, scan_len * 2))
1868
+ rank = (5.0 * _tir_quality(absolute)
1869
+ + (0.9 if tsd is not None and tsd.length >= 5 and tsd.mismatches == 0 else 0.0)
1870
+ + 0.7 * geometry
1871
+ - distance_penalty)
1872
+ viable.append((rank, absolute, tsd, geometry))
1873
+
1874
+ viable.sort(key=lambda x: (x[0], x[1].tir_identity, -x[1].tir_length), reverse=True)
1875
+ if evaluation_cache is not None:
1876
+ evaluation_cache['viable'] = viable
1877
+ if not viable:
1878
+ cand.tir_geometry = 0.0
1879
+ return None, None
1880
+ winner = viable[0]
1881
+ cand.tir_geometry = winner[3]
1882
+ return winner[1], winner[2]
1883
+
1884
+ def _annotate_tir_context(fa, genome: Path, cand: Candidate, db: Path,
1885
+ threads: int, cfg: dict) -> list[Orf]:
1886
+ import pyrodigal
1887
+ import pyhmmer
1888
+ globals()['pyhmmer'] = pyhmmer
1889
+ left = max(1, cand.start - cfg['orf_flank'])
1890
+ right = min(cand.contig_length, cand.end + cfg['orf_flank'])
1891
+ seq = _fetch_seq(fa, genome, cand.contig, left, right)
1892
+ genes = pyrodigal.GeneFinder(meta=True).find_genes(seq.encode('ascii'))
1893
+ found = {}
1894
+ for j, gene in enumerate(genes, 1):
1895
+ protein = gene.translate().rstrip('*')
1896
+ if not protein:
1897
+ continue
1898
+ orf = Orf(f'tir_{cand.contig}_{cand.start}_{j}', cand.contig,
1899
+ left + int(gene.begin) - 1, left + int(gene.end) - 1,
1900
+ int(gene.strand), protein,
1901
+ bool(getattr(gene, 'partial_begin', False) or
1902
+ getattr(gene, 'partial_end', False)))
1903
+ found[orf.orf_id] = orf
1904
+ if found:
1905
+ scan_hallmarks(found, db/'PLV_hallmarks.hmm', cfg['hmm_evalue'], threads)
1906
+ scan_nonplv_mcp(found, db/'MCP_nonPLV.hmm', cfg['hmm_evalue'], threads)
1907
+ classify_hallmarks(found, 0.0)
1908
+ return list(found.values())
1909
+
1910
+
1911
+ def _blast_tir_region(job: tuple[int, str, int, str], directory: Path):
1912
+ index, sequence, left, _ = job
1913
+ fasta = directory / f'region_{index:08d}.fna'
1914
+ table = directory / f'hits_{index:08d}.tsv'
1915
+ try:
1916
+ with fasta.open('w', encoding='ascii') as handle:
1917
+ handle.write('>candidate\n')
1918
+ for offset in range(0, len(sequence), 80):
1919
+ handle.write(sequence[offset:offset + 80] + '\n')
1920
+ run_blastn_self(fasta, table)
1921
+ return left, sequence, parse_blastn_tabular(table)
1922
+ finally:
1923
+ fasta.unlink(missing_ok=True)
1924
+ table.unlink(missing_ok=True)
1925
+
1926
+ def refine_tir_tsd(fa, genome: Path, candidates: list[Candidate], cfg: dict,
1927
+ db: Path | None = None, threads: int = 1):
1928
+ if not cfg['tir_tsd']:
1929
+ return
1930
+ if not candidates:
1931
+ LOG.info('TIR/TSD identification complete | evaluated=0 | TIR_supported=0')
1932
+ return
1933
+ if shutil.which('blastn') is None:
1934
+ raise RuntimeError('blastn executable is required for TIR/TSD refinement')
1935
+ hits = 0
1936
+ workers = min(max(1, int(threads)), len(candidates))
1937
+ with tempfile.TemporaryDirectory(prefix='DeepPLV_TIR_') as tmp:
1938
+ directory = Path(tmp)
1939
+ with ThreadPoolExecutor(max_workers=workers) as executor:
1940
+ batch_size = max(1, workers * 2)
1941
+ for offset in range(0, len(candidates), batch_size):
1942
+ batch = candidates[offset:offset + batch_size]
1943
+ jobs = []
1944
+ for j, cand in enumerate(batch, offset):
1945
+ cand.tir_hallmark_distance_rejected = 0
1946
+ left = max(1, cand.start - cfg['max_tir_flank'])
1947
+ right = min(cand.contig_length, cand.end + cfg['max_tir_flank'])
1948
+ sequence = _fetch_seq(fa, genome, cand.contig, left, right)
1949
+ jobs.append((j, sequence, left, cand.contig))
1950
+ results = list(executor.map(lambda job: _blast_tir_region(job, directory), jobs))
1951
+ for cand, (left, seq, pairs) in zip(batch, results):
1952
+ forbidden: set[tuple[int, int]] = set()
1953
+ evaluation_cache = {}
1954
+ original = (cand.start, cand.end)
1955
+ for _ in range(min(12, len(pairs))):
1956
+ tir, tsd = select_tir_for_candidate(
1957
+ pairs, left, seq, cand, cfg, fa, genome, forbidden,
1958
+ evaluation_cache=evaluation_cache)
1959
+ if tir is None:
1960
+ break
1961
+ current_left = max(1, original[0] - cfg['orf_flank'])
1962
+ current_right = min(cand.contig_length, original[1] + cfg['orf_flank'])
1963
+ if tir.left_start < current_left or tir.right_end > current_right:
1964
+ if db is None:
1965
+ forbidden.add((tir.left_start, tir.right_end))
1966
+ continue
1967
+ cand.start, cand.end = tir.left_start, tir.right_end
1968
+ try:
1969
+ new_orfs = _annotate_tir_context(fa, genome, cand, db, threads, cfg)
1970
+ finally:
1971
+ cand.start, cand.end = original
1972
+ else:
1973
+ new_orfs = cand.context_orfs
1974
+ crossing = any(tir_intersects_orf(tir, o) for o in new_orfs
1975
+ if _is_plv_hallmark(o))
1976
+ crossing = crossing or any(
1977
+ _is_plv_hallmark(o) and
1978
+ o.start <= (cand.scan_end or cand.end) and
1979
+ o.end >= (cand.scan_start or cand.start) and
1980
+ not (tir.left_end < o.start and o.end < tir.right_start)
1981
+ for o in new_orfs)
1982
+ if crossing:
1983
+ forbidden.add((tir.left_start, tir.right_end))
1984
+ continue
1985
+ cand.context_orfs = new_orfs
1986
+ cand.tir, cand.tsd = tir, tsd
1987
+ cand.start, cand.end = tir.left_start, tir.right_end
1988
+ _collect_full_interval_orfs(cand, new_orfs)
1989
+ cand.gc = gc_of_seq(_fetch_seq(fa, genome, cand.contig, cand.start, cand.end))
1990
+ hits += 1
1991
+ break
1992
+ distance_rejected = sum(c.tir_hallmark_distance_rejected for c in candidates)
1993
+ unresolved_distance = sum(c.tir is None and c.tir_hallmark_distance_rejected > 0
1994
+ for c in candidates)
1995
+ LOG.info('TIR/TSD identification complete | evaluated=%d | TIR_supported=%d | '
1996
+ 'hallmark_distance_rejected_pairs=%d | no_TIR_after_distance_filter=%d',
1997
+ len(candidates), hits, distance_rejected, unresolved_distance)
1998
+
1999
+ def validate_tir_gene_boundaries(candidates: list[Candidate]) -> None:
2000
+ for c in candidates:
2001
+ if c.tir is None:
2002
+ continue
2003
+ conflict = next((o for o in c.context_orfs
2004
+ if _is_plv_hallmark(o) and tir_intersects_orf(c.tir, o)), None)
2005
+ if conflict is not None:
2006
+ raise RuntimeError(
2007
+ f'TIR intersects ORF {conflict.orf_id} at '
2008
+ f'{c.contig}:{conflict.start}-{conflict.end}; '
2009
+ 'the TIR boundary must be rejected before output')
2010
+
2011
+ def remove_host_overlaps(candidates:list[Candidate],host:dict,max_bp:int):
2012
+ kept=[]; excluded=0
2013
+ for c in candidates:
2014
+ bp=_host_overlap_bp(host.get(c.contig,()),c.start,c.end)
2015
+ if bp>max_bp:
2016
+ excluded+=1
2017
+ LOG.debug('Host gene overlap | contig=%s | start=%d | end=%d | bp=%d',c.contig,c.start,c.end,bp)
2018
+ else:
2019
+ kept.append(c)
2020
+ LOG.info('Host-gene exclusion complete | retained=%d | excluded=%d',len(kept),excluded)
2021
+ return kept
2022
+
2023
+ def _candidate_marker_coordinates(c: Candidate) -> set[tuple[str, int, int]]:
2024
+ return {(o.family, o.start, o.end) for o in c.orfs if _is_plv_hallmark(o)}
2025
+
2026
+ def _same_element(a: Candidate, b: Candidate) -> bool:
2027
+ """Only collapse convincing duplicates, not nested or overlapping insertions."""
2028
+ if a.contig != b.contig:
2029
+ return False
2030
+ intersection=max(0,min(a.end,b.end)-max(a.start,b.start)+1)
2031
+ if not intersection:
2032
+ return False
2033
+ reciprocal=intersection/max(a.length,b.length)
2034
+ if reciprocal>=0.90 and abs(a.start-b.start)<=1024 and abs(a.end-b.end)<=1024:
2035
+ return True
2036
+ shared=_candidate_marker_coordinates(a)&_candidate_marker_coordinates(b)
2037
+ return bool(shared and intersection/min(a.length,b.length)>=0.95)
2038
+
2039
+ def deduplicate_candidates(candidates: list[Candidate]):
2040
+ ordered = sorted(candidates, key=lambda c: (
2041
+ bool(set(c.families) & CORE_CAPSID),
2042
+ len(set(c.families) & CORE_CAPSID), bool(c.tir),
2043
+ len(c.families), c.max_win_score, -c.length), reverse=True)
2044
+ kept = []
2045
+ removed = 0
2046
+ for c in ordered:
2047
+ if any(_same_element(c, old) for old in kept):
2048
+ removed += 1
2049
+ continue
2050
+ kept.append(c)
2051
+ LOG.info('Duplicate resolution complete | input=%d | retained=%d | duplicates=%d',
2052
+ len(candidates), len(kept), removed)
2053
+ return kept
2054
+
2055
+ def enforce_nonoverlap(candidates: list[Candidate]) -> list[Candidate]:
2056
+ """Retain highest-priority intervals without clipping; 1-based inclusive."""
2057
+ ordered = sorted(candidates, key=lambda c: (
2058
+ c.category == 'PLV', c.biological_score,
2059
+ len(set(c.families) & CORE_CAPSID), len(c.families),
2060
+ bool(c.tir), c.max_win_score, -c.length), reverse=True)
2061
+ kept: list[Candidate] = []
2062
+ # Neighbors suffice: all previously retained intervals on a contig are disjoint.
2063
+ by_contig: dict[str, list[Candidate]] = defaultdict(list)
2064
+ starts: dict[str, list[int]] = defaultdict(list)
2065
+ rejected = 0
2066
+ for c in ordered:
2067
+ contig_starts = starts[c.contig]
2068
+ contig_intervals = by_contig[c.contig]
2069
+ idx = bisect_left(contig_starts, c.start)
2070
+ overlaps_previous = idx > 0 and contig_intervals[idx - 1].end >= c.start
2071
+ overlaps_next = idx < len(contig_intervals) and contig_intervals[idx].start <= c.end
2072
+ if overlaps_previous or overlaps_next:
2073
+ rejected += 1
2074
+ continue
2075
+ kept.append(c)
2076
+ contig_starts.insert(idx, c.start)
2077
+ contig_intervals.insert(idx, c)
2078
+ LOG.info('Final non-overlap filtering complete | retained=%d | overlaps_removed=%d',
2079
+ len(kept), rejected)
2080
+ return kept
2081
+
2082
+ def validate_retained_intervals(candidates: list[Candidate], host: dict | None = None) -> None:
2083
+ """Fail closed before output if any PLVs overlap each other or a host gene."""
2084
+ by_contig: dict[str, list[Candidate]] = defaultdict(list)
2085
+ for c in candidates:
2086
+ if not 1 <= c.start <= c.end <= c.contig_length:
2087
+ raise RuntimeError(f'Invalid retained interval: {c.contig}:{c.start}-{c.end}')
2088
+ if host and _host_overlap_bp(host.get(c.contig, ()), c.start, c.end):
2089
+ raise RuntimeError(f'Retained PLV overlaps a host gene: {c.contig}:{c.start}-{c.end}')
2090
+ by_contig[c.contig].append(c)
2091
+ for contig, items in by_contig.items():
2092
+ items.sort(key=lambda c: (c.start, c.end))
2093
+ for previous, current in zip(items, items[1:]):
2094
+ if previous.end >= current.start:
2095
+ raise RuntimeError(
2096
+ f'Retained PLVs overlap: {contig}:{previous.start}-{previous.end} '
2097
+ f'and {current.start}-{current.end}')
2098
+ LOG.info('Retained interval validation complete | PLVs=%d | coordinate_overlaps=0 | '
2099
+ 'host_gene_overlaps=0', len(candidates))
2100
+
2101
+
2102
+ def _marker_spans_near_boundary(c: Candidate, orfs: list[Orf], cfg: dict) -> tuple[int, int]:
2103
+ left, right = c.start, c.end
2104
+ for o in orfs:
2105
+ if not _is_plv_hallmark(o) or o.partial:
2106
+ continue
2107
+ if o.end < c.start or o.start > c.end:
2108
+ continue
2109
+ if o.start < c.start and c.start - o.start <= cfg['orf_max_extension']:
2110
+ left = min(left, o.start)
2111
+ if o.end > c.end and o.end - c.end <= cfg['orf_max_extension']:
2112
+ right = max(right, o.end)
2113
+ if right - left + 1 > cfg['max_plv_length']:
2114
+ return c.start, c.end
2115
+ return max(1, left), min(c.contig_length, right)
2116
+
2117
+
2118
+ def _collect_full_interval_orfs(c: Candidate, predicted_orfs: list[Orf]) -> None:
2119
+ c.orfs = sorted((o for o in predicted_orfs if c.start <= o.start and o.end <= c.end
2120
+ and (c.tir is None or not tir_intersects_orf(c.tir, o))),
2121
+ key=lambda o: (o.start, o.end, o.strand))
2122
+ c.families = sorted({o.family for o in c.orfs if _is_plv_hallmark(o)},
2123
+ key=_hallmark_sort_key)
2124
+ c.boundary_conflicts = sum(1 for o in predicted_orfs if _is_plv_hallmark(o)
2125
+ and o.start <= c.end and o.end >= c.start
2126
+ and (o.start < c.start or o.end > c.end))
2127
+ c.partial_hallmarks = sum(1 for o in c.orfs if _is_plv_hallmark(o) and o.partial)
2128
+ c.boundary_status = 'TIR' if c.tir is not None else 'Window'
2129
+
2130
+
2131
+ def annotate_candidates(fa, genome: Path, candidates: list[Candidate], db: Path,
2132
+ threads: int, cfg: dict, host: dict | None = None):
2133
+ """Predict ORFs, classify hallmark hits, and refine candidate boundaries."""
2134
+ if not candidates:
2135
+ LOG.info('Gene prediction and hallmark screening complete | regions=0 | orfs=0')
2136
+ return
2137
+ if not cfg['annotation']:
2138
+ raise ValueError('annotation=True is required for hallmark-based candidate classification')
2139
+ import pyrodigal
2140
+ import pyhmmer
2141
+ globals()['pyrodigal'] = pyrodigal
2142
+ globals()['pyhmmer'] = pyhmmer
2143
+ all_orfs: dict[str, Orf] = {}
2144
+ per_candidate_orfs: dict[int, list[Orf]] = {}
2145
+ flank = cfg['orf_flank']
2146
+ prediction_failures = 0
2147
+ for i, c in enumerate(candidates, 1):
2148
+ left = max(1, c.start-flank)
2149
+ right = min(c.contig_length, c.end+flank)
2150
+ seq = _fetch_seq(fa, genome, c.contig, left, right).upper()
2151
+ per_candidate_orfs[i] = []
2152
+ if len(seq) < 90:
2153
+ continue
2154
+ try:
2155
+ genes = pyrodigal.GeneFinder(meta=True).find_genes(seq.encode('ascii'))
2156
+ except Exception as exc:
2157
+ prediction_failures += 1
2158
+ LOG.debug('ORF prediction skipped | contig=%s | region=%d-%d | detail=%s',
2159
+ c.contig, left, right, exc)
2160
+ continue
2161
+ for j, gene in enumerate(genes, 1):
2162
+ protein = gene.translate().rstrip('*')
2163
+ if not protein:
2164
+ continue
2165
+ start = left+int(gene.begin)-1
2166
+ end = left+int(gene.end)-1
2167
+ orf = Orf(f'cand{i:06d}_orf{j:05d}', c.contig, start, end,
2168
+ int(gene.strand), protein,
2169
+ bool(getattr(gene, 'partial_begin', False) or
2170
+ getattr(gene, 'partial_end', False)))
2171
+ per_candidate_orfs[i].append(orf)
2172
+ all_orfs[orf.orf_id] = orf
2173
+ if all_orfs:
2174
+ scan_hallmarks(all_orfs, db/'PLV_hallmarks.hmm', cfg['hmm_evalue'], threads)
2175
+ scan_nonplv_mcp(all_orfs, db/'MCP_nonPLV.hmm', cfg['hmm_evalue'], threads)
2176
+ classify_hallmarks(all_orfs, 0.0)
2177
+ expanded = conflicts = partial = 0
2178
+ for i, c in enumerate(candidates, 1):
2179
+ original = (c.start, c.end)
2180
+ c.context_orfs = per_candidate_orfs[i]
2181
+ left, right = _marker_spans_near_boundary(c, per_candidate_orfs[i], cfg)
2182
+ if host and _host_overlap_bp(host.get(c.contig, ()), left, right) > cfg['host_gene_max_overlap_bp']:
2183
+ left, right = original
2184
+ c.start, c.end = left, right
2185
+ if left < original[0] or right > original[1]:
2186
+ expanded += 1
2187
+ _collect_full_interval_orfs(c, per_candidate_orfs[i])
2188
+ if c.boundary_unresolved and c.tir is None:
2189
+ c.boundary_status = 'Unresolved'
2190
+ c.gc = gc_of_seq(_fetch_seq(fa, genome, c.contig, c.start, c.end).upper())
2191
+ conflicts += c.boundary_conflicts
2192
+ partial += c.partial_hallmarks
2193
+ if c.boundary_conflicts:
2194
+ LOG.debug('Crossing hallmark ORF unresolved | contig=%s | region=%d-%d | count=%d',
2195
+ c.contig, c.start, c.end, c.boundary_conflicts)
2196
+ LOG.info('ORF-aware boundary refinement complete | regions=%d | extended=%d | '
2197
+ 'hallmark_boundary_conflicts=%d | partial_hallmark_orfs=%d | '
2198
+ 'predicted_orfs=%d | prediction_failures=%d',
2199
+ len(candidates), expanded, conflicts, partial, len(all_orfs), prediction_failures)
2200
+
2201
+
2202
+ def annotate_pfam_main(candidates: list[Candidate], db: Path, threads: int, cfg: dict) -> bool:
2203
+ pfam = db / 'Pfam-A.hmm'
2204
+ pgap_dir = db / 'hmm_PGAP'
2205
+ pfam_active = pfam.is_file()
2206
+ if pfam.exists() and not pfam_active:
2207
+ raise ValueError(f'Pfam database is not a regular file: {pfam}')
2208
+ if cfg['pgap_enabled'] and pgap_dir.exists() and not pgap_dir.is_dir():
2209
+ raise NotADirectoryError(f'PGAP database path is not a directory: {pgap_dir}')
2210
+ pgap_profiles = _pgap_profile_paths(pgap_dir) if cfg['pgap_enabled'] and pgap_dir.is_dir() else []
2211
+ pgap_active = bool(pgap_profiles)
2212
+ if pgap_active and not (db / 'hmm_PGAP.tsv').is_file():
2213
+ raise FileNotFoundError(f"PGAP metadata is required: {db / 'hmm_PGAP.tsv'}")
2214
+ LOG.info('Functional annotation databases | Pfam=%s | PGAP=%s',
2215
+ 'available' if pfam_active else 'unavailable',
2216
+ 'available' if pgap_active else 'unavailable')
2217
+ if not (pfam_active or pgap_active):
2218
+ return False
2219
+ orfs = [o for c in candidates for o in c.orfs]
2220
+ if not orfs:
2221
+ return True
2222
+ if pfam_active:
2223
+ scan_pfam(orfs, pfam, cfg['hmm_evalue'], threads)
2224
+ if pgap_active:
2225
+ targets = [o for o in orfs if not _is_plv_hallmark(o) and
2226
+ (not cfg['pgap_unannotated_only'] or not o.best_pfam_name or
2227
+ o.best_pfam_name.lower().startswith(('duf', 'unknown', 'uncharacterized', 'hypothetical')))]
2228
+ if targets:
2229
+ scan_pgap(targets, pgap_dir, cfg['hmm_evalue'], threads,
2230
+ _load_pgap_labels(db))
2231
+ return True
2232
+
2233
+
2234
+ def _distinct_positive_windows(windows: list[tuple[int, int, float]],
2235
+ threshold: float, step: int) -> int:
2236
+ """Count spatially distinct positive windows, not redundant overlapping votes."""
2237
+ selected: list[float] = []
2238
+ for a, b, p in sorted(windows, key=lambda x: x[2], reverse=True):
2239
+ if p < threshold:
2240
+ break
2241
+ center = (a+b)/2
2242
+ if all(abs(center-old) >= max(step, (b-a)/2) for old in selected):
2243
+ selected.append(center)
2244
+ return len(selected)
2245
+
2246
+
2247
+ def _tir_only_credible(c: Candidate, cfg: dict) -> bool:
2248
+ """Assess model and TIR support for hallmark-free candidates."""
2249
+ return bool(c.tir is not None
2250
+ and c.tir.tir_identity >= cfg['candidate_tir_only_min_id']
2251
+ and c.tir.tir_length >= cfg['candidate_tir_only_min_len']
2252
+ and c.tir_geometry >= cfg['candidate_tir_only_min_geometry']
2253
+ and c.max_win_score >= cfg['candidate_tir_only_min_model']
2254
+ and c.independent_support_windows >= cfg['candidate_tir_only_min_distinct_windows'])
2255
+
2256
+ def classify_candidates(candidates: list[Candidate], cfg: Optional[dict] = None):
2257
+ cfg = cfg if cfg is not None else DEFAULTS
2258
+ main, manual = [], []
2259
+ counts = Counter()
2260
+ for c in candidates:
2261
+ has_capsid = bool(set(c.families) & CORE_CAPSID)
2262
+ if has_capsid:
2263
+ c.category='PLV'; main.append(c)
2264
+ elif c.families:
2265
+ c.category='candPLV'; manual.append(c)
2266
+ elif c.tir is None:
2267
+ counts['no_capsid_no_tir_no_hallmark'] += 1
2268
+ elif _tir_only_credible(c, cfg):
2269
+ c.category='candPLV'; manual.append(c)
2270
+ else:
2271
+ counts['weak_tir_only'] += 1
2272
+ LOG.info('Evidence filtering complete | PLV=%d | candidate PLV=%d | discarded=%d',
2273
+ len(main), len(manual), sum(counts.values()))
2274
+ return main, manual
2275
+
2276
+ def calculate_plv_score(c: Candidate) -> int:
2277
+ """Calculate the biological evidence score."""
2278
+ families=set(c.families)
2279
+ capsid_count=len(families & CORE_CAPSID)
2280
+ n_accessory=len(families - CORE_CAPSID)
2281
+ tsd_bonus=1 if c.tsd is not None and c.tsd.mismatches == 0 else 0
2282
+ if capsid_count==2:
2283
+ if c.tir:
2284
+ score=96+min(3,n_accessory)+tsd_bonus
2285
+ else:
2286
+ score=92+min(3,n_accessory)
2287
+ elif capsid_count==1:
2288
+ if c.tir:
2289
+ score=89+min(2,n_accessory)+tsd_bonus
2290
+ else:
2291
+ score=85+min(3,n_accessory)
2292
+ elif c.tir is not None and n_accessory>=2:
2293
+ score=76+min(7,2*(n_accessory-2))+tsd_bonus
2294
+ elif c.tir is not None and n_accessory==1:
2295
+ score=69+min(4, n_accessory)+tsd_bonus
2296
+ elif c.tir is not None:
2297
+ score=40+tsd_bonus
2298
+ elif n_accessory >= 1:
2299
+ score=50+min(10, 3*(n_accessory-1))
2300
+ else:
2301
+ score=0
2302
+ c.biological_score=int(min(100,score))
2303
+ return c.biological_score
2304
+
2305
+ def summarize_confidence(c: Candidate):
2306
+ """HIGH >=90; MEDIUM 80-89; LOW <=79."""
2307
+ if c.biological_score >= 90:
2308
+ return 'HIGH'
2309
+ if c.biological_score >= 80:
2310
+ return 'MEDIUM'
2311
+ return 'LOW'
2312
+
2313
+ def to_plvs(candidates:list[Candidate]):
2314
+ return [Plv(c.plv_id,c.contig,c.contig_length,c.start,c.end,c.length,c.orfs,
2315
+ c.families,len(c.families),
2316
+ max((o.plv_mcp_bitscore for o in c.orfs),default=0.0),
2317
+ c.gc,'TIR' if c.tir else 'Window',c.boundary_status,c.tir,c.tsd)
2318
+ for c in candidates]
2319
+
2320
+ def write_summary(candidates:list[Candidate],path:Path):
2321
+ cols=['contig_id','plv_name','start','end','plv_length','gc','total_cds','n_hallmark',
2322
+ 'hallmarks','plv_score','confidence','has_tir','boundary','tir_len',
2323
+ 'tir_identity','tsd_len','tsd_left','tsd_right','tsd_conservation']
2324
+ with path.open('w',newline='',encoding='utf-8') as fh:
2325
+ writer=csv.DictWriter(fh,fieldnames=cols,delimiter='\t',lineterminator='\n')
2326
+ writer.writeheader()
2327
+ for c in candidates:
2328
+ tir=_tir_fields(c.tir)
2329
+ tsd=_tsd_fields(c.tsd)
2330
+ row=dict(contig_id=c.contig,plv_name=c.plv_id,start=c.start,end=c.end,
2331
+ plv_length=c.length,gc='NA' if math.isnan(c.gc) else f'{c.gc:.2f}',
2332
+ total_cds=len(c.orfs),n_hallmark=len(c.families),
2333
+ hallmarks=','.join(c.families) or 'NA',plv_score=c.biological_score,
2334
+ confidence=summarize_confidence(c),
2335
+ has_tir='true' if c.tir else 'false', boundary=c.boundary_status,
2336
+ tir_len=tir['tir_length'],tir_identity=tir['tir_identity_pct'])
2337
+ row.update(tsd)
2338
+ writer.writerow(row)
2339
+
2340
+ def write_outputs(main:list[Candidate],manual:list[Candidate],out:Path,prefix:str,genome:Path,fa, functional_annotation:bool=True):
2341
+ all_items=sorted(main+manual,key=lambda c:(-c.biological_score,
2342
+ c.contig,c.start))
2343
+ write_summary(all_items,out/f'{prefix}.summary.tsv')
2344
+ if main:
2345
+ records = to_plvs(main)
2346
+ if functional_annotation:
2347
+ write_func_tsv(records, out/f'{prefix}.func.tsv')
2348
+ write_nucleotide_fasta(records, fa, genome, out/f'{prefix}.plv.fna')
2349
+ write_protein_fasta(records, out/f'{prefix}.plv.pep')
2350
+ write_cds_fasta(records, fa, genome, out/f'{prefix}.plv.cds')
2351
+ write_gff3(records, out/f'{prefix}.plv.gff3')
2352
+ write_marker_peps(records, out, prefix)
2353
+ if manual:
2354
+ (out/'candidate').mkdir(exist_ok=True)
2355
+ cand_dir=out/'candidate';cprefix=f'{prefix}.candPLV'
2356
+ cand_records=to_plvs(manual)
2357
+ if functional_annotation:
2358
+ write_func_tsv(cand_records,cand_dir/f'{cprefix}.func.tsv')
2359
+ write_nucleotide_fasta(cand_records,fa,genome,cand_dir/f'{cprefix}.fna')
2360
+ write_protein_fasta(cand_records,cand_dir/f'{cprefix}.pep')
2361
+ write_cds_fasta(cand_records,fa,genome,cand_dir/f'{cprefix}.cds')
2362
+ write_gff3(cand_records,cand_dir/f'{cprefix}.gff3')
2363
+ gff=cand_dir/f'{cprefix}.gff3'
2364
+ content=gff.read_text()
2365
+ content=content.replace('\tPLV\t','\tcandPLV\t').replace('Name=PLV;','Name=candPLV;')
2366
+ gff.write_text(content)
2367
+ LOG.info('Outputs written | main=%d | candidates=%d | folder=%s',len(main),len(manual),out)
2368
+
2369
+
2370
+ def finish_no_plv(out: Path, genome: Path, started_at: float,
2371
+ reason: str) -> None:
2372
+ LOG.info('No PLV or candidate PLV retained | genome=%s | reason=%s',
2373
+ genome, reason)
2374
+ LOG.info('DeepPLV completed with no PLV | elapsed=%.1f s | file=No_PLV.log',
2375
+ time.monotonic() - started_at)
2376
+ log_path = (out / 'run.log').resolve()
2377
+ for handler in list(LOG.handlers):
2378
+ handler.flush()
2379
+ if isinstance(handler, logging.FileHandler) and Path(handler.baseFilename) == log_path:
2380
+ LOG.removeHandler(handler)
2381
+ handler.close()
2382
+ (out / 'run.log').replace(out / 'No_PLV.log')
2383
+
2384
+ def main(argv=None):
2385
+ start_time=time.monotonic()
2386
+ args=cli(argv)
2387
+ args.genome=args.genome.expanduser()
2388
+ args.db=args.db.expanduser()
2389
+ args.gff=args.gff.expanduser() if args.gff is not None else None
2390
+ args.outdir=args.outdir.expanduser() if args.outdir is not None else None
2391
+ validate_settings(DEFAULTS)
2392
+ if args.threads<1:
2393
+ raise ValueError('--threads must be positive')
2394
+ if not args.genome.is_file():raise FileNotFoundError(args.genome)
2395
+ if not args.db.is_dir():raise NotADirectoryError(args.db)
2396
+ if args.gff is not None and not args.gff.is_file():raise FileNotFoundError(args.gff)
2397
+ if args.gff and not str(args.gff).lower().endswith(('.gff','.gff3','.gtf','.gff.gz','.gff3.gz','.gtf.gz')):
2398
+ raise ValueError('-g accepts .gff, .gff3 or .gtf (optionally .gz)')
2399
+ prefix=args.prefix or "DeepPLV"
2400
+ if not prefix or any(ch in prefix for ch in '/\\\t\n '):
2401
+ raise ValueError('Invalid --prefix; use a single identifier without whitespace or slashes')
2402
+ out=args.outdir or Path('DeepPLV_'+datetime.now().strftime('%Y%m%d'))
2403
+ stale_log_only = False
2404
+ if out.exists():
2405
+ if not out.is_dir():
2406
+ raise FileExistsError(f'Output path is not a directory: {out}')
2407
+ existing = list(out.iterdir())
2408
+ stale_log_only = (len(existing) == 1 and existing[0].name == 'run.log'
2409
+ and existing[0].is_file())
2410
+ if existing and not stale_log_only:
2411
+ raise FileExistsError(
2412
+ f'Output directory already contains results: {out}. '
2413
+ 'Use -o to select a fresh output directory.')
2414
+ out.mkdir(parents=True,exist_ok=True)
2415
+ setup_log(out/'run.log')
2416
+ if stale_log_only:
2417
+ LOG.info('Previous incomplete run detected; restarting in %s', out)
2418
+ import pyfastx
2419
+ LOG.info('DeepPLV v%s | genome=%s | database=%s | output=%s', VERSION, args.genome,args.db,out)
2420
+ LOG.info('Screening configuration | window=%d | step=%d | fine_window=%d | fine_step=%d | threshold=%.2f',
2421
+ DEFAULTS['window'], DEFAULTS['step'], DEFAULTS['refine_window'],
2422
+ DEFAULTS['refine_step'], DEFAULTS['min_score'])
2423
+ if args.gff is None:
2424
+ LOG.info('Host-gene exclusion skipped | no GFF/GTF annotation supplied')
2425
+ if not DEFAULTS['tir_tsd']:
2426
+ LOG.info('TIR/TSD identification disabled | hallmark-negative candidates cannot be retained')
2427
+ if not DEFAULTS['annotation']:
2428
+ raise RuntimeError('annotation=True is required by the current evidence retention policy')
2429
+ if DEFAULTS['tir_tsd'] and shutil.which('blastn') is None:
2430
+ raise RuntimeError('BLAST+ blastn is required for default terminal-repeat refinement')
2431
+ for name in ('PLV_hallmarks.hmm','MCP_nonPLV.hmm'):
2432
+ if not (args.db/name).is_file():
2433
+ raise FileNotFoundError(f'Missing database: {args.db/name}')
2434
+ weights=find_weights(args.db)
2435
+ device=get_device(DEFAULTS['gpu'])
2436
+ if device.type == 'cpu':
2437
+ torch.set_num_threads(max(1,args.threads))
2438
+ LOG.info('CPU inference selected | torch_threads=%d | batch_size=%d',args.threads,DEFAULTS['batch_size'])
2439
+ model,plv_index=load_model(weights,device)
2440
+ fa=pyfastx.Fasta(str(args.genome),build_index=True,uppercase=True)
2441
+ host={}
2442
+ if args.gff is not None:
2443
+ host=parse_host_gene_intervals(args.gff)
2444
+ if not host:raise RuntimeError('Host annotation contains no usable gene intervals')
2445
+ fasta_ids={x.name for x in fa}
2446
+ if not set(host).intersection(fasta_ids):
2447
+ raise RuntimeError('Annotation contig IDs do not match input FASTA identifiers')
2448
+ scorer=Scorer(model,plv_index,device,DEFAULTS['batch_size'],DEFAULTS['rc_average'])
2449
+ identification_start=time.monotonic()
2450
+ LOG.info('PLV identification started')
2451
+ predicted=scan_candidates(fa,scorer,DEFAULTS)
2452
+ if not predicted:
2453
+ finish_no_plv(out, args.genome, start_time,
2454
+ 'no candidate regions discovered')
2455
+ return 0
2456
+ adaptive_refine_candidates(fa,scorer,predicted,DEFAULTS)
2457
+ LOG.info('Gene prediction and hallmark identification started')
2458
+ annotate_candidates(fa,args.genome,predicted,args.db,args.threads,DEFAULTS,host)
2459
+ if DEFAULTS['tir_tsd']:
2460
+ LOG.info('TIR/TSD identification started')
2461
+ refine_tir_tsd(fa,args.genome,predicted,DEFAULTS,args.db,args.threads)
2462
+ validate_tir_gene_boundaries(predicted)
2463
+ for candidate in predicted:
2464
+ if candidate.tir is not None:
2465
+ candidate.boundary_status = 'TIR'
2466
+ elif candidate.boundary_unresolved:
2467
+ candidate.boundary_status = 'Unresolved'
2468
+
2469
+ if args.gff is not None:
2470
+ predicted=remove_host_overlaps(predicted,host,DEFAULTS['host_gene_max_overlap_bp'])
2471
+ predicted=deduplicate_candidates(predicted)
2472
+ marker_free_tir=[c for c in predicted if not c.families and c.tir is not None]
2473
+ refresh_final_window_support(fa,scorer,marker_free_tir,DEFAULTS)
2474
+ main,manual=classify_candidates(predicted,DEFAULTS)
2475
+ for c in main+manual:
2476
+ calculate_plv_score(c)
2477
+ nonoverlap=enforce_nonoverlap(main+manual)
2478
+ validate_retained_intervals(nonoverlap, host if args.gff is not None else None)
2479
+ main=[c for c in nonoverlap if c.category=='PLV']
2480
+ manual=[c for c in nonoverlap if c.category!='PLV']
2481
+ if not main and not manual:
2482
+ finish_no_plv(out, args.genome, start_time,
2483
+ 'no candidate regions passed evidence filtering')
2484
+ return 0
2485
+ main.sort(key=lambda c:(-c.biological_score,c.contig,c.start))
2486
+ manual.sort(key=lambda c:(-c.biological_score,c.contig,c.start))
2487
+ for i,c in enumerate(main,1):
2488
+ c.plv_id=format_plv_id(prefix, i)
2489
+ for i,c in enumerate(manual,1):
2490
+ c.plv_id=format_plv_id(prefix, i, candidate=True)
2491
+ LOG.info('PLV identification complete | PLV=%d | candidate PLV=%d | elapsed=%.1f s',
2492
+ len(main),len(manual),time.monotonic()-identification_start)
2493
+ annotation_start=time.monotonic()
2494
+ LOG.info('Functional annotation started')
2495
+ functional_annotation=annotate_pfam_main(main+manual,args.db,args.threads,DEFAULTS)
2496
+ LOG.info('Functional annotation complete | elapsed=%.1f s',time.monotonic()-annotation_start)
2497
+ write_outputs(main,manual,out,prefix,args.genome,fa,functional_annotation)
2498
+ LOG.info('DeepPLV completed successfully | total=%.1f s',time.monotonic()-start_time)
2499
+ return 0
2500
+
2501
+ if __name__=='__main__':
2502
+ try:
2503
+ sys.exit(main())
2504
+ except Exception as exc:
2505
+ LOG.exception('DeepPLV failed: %s',exc)
2506
+ sys.exit(2)