-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbioremediation_gene_miner.py
More file actions
1912 lines (1613 loc) · 61.8 KB
/
Copy pathbioremediation_gene_miner.py
File metadata and controls
1912 lines (1613 loc) · 61.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Bioremediation Gene Miner v0.3.8
Evidence-ranked bacterial WGS screening:
1) screens already-annotated CDSs using annotation_rules.tsv
2) extracts hypothetical/uncharacterized proteins
3) runs DIAMOND against the curated reference database
4) preserves the best hit PER QUERY AND PER CURATED BIOLOGICAL FAMILY
5) applies identity/query-coverage/reference-coverage safeguards
6) optionally integrates InterProScan TSV evidence
7) writes Excel and TSV reports
Important:
This software predicts candidates. It does not experimentally prove
bioremediation activity.
"""
from __future__ import annotations
import argparse
from copy import copy
import csv
import re
import subprocess
import time
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from collections import defaultdict
from pathlib import Path
import pandas as pd
try:
from Bio import SeqIO
except Exception:
SeqIO = None
VERSION = "0.3.8"
# ============================================================
# GenBank parsing
# ============================================================
def qval(q, key):
vals = q.get(key, [""])
return vals[0] if vals else ""
def parse_genbank_biopython(path):
if SeqIO is None:
raise RuntimeError("Biopython unavailable")
cds = []
for rec in SeqIO.parse(str(path), "genbank"):
for feat in rec.features:
if feat.type != "CDS":
continue
q = feat.qualifiers
cds.append({
"contig": rec.id,
"locus_tag": qval(q, "locus_tag"),
"gene": qval(q, "gene"),
"product": qval(q, "product"),
"translation": qval(q, "translation").replace(" ", ""),
"EC_number": ";".join(q.get("EC_number", [])),
"db_xref": ";".join(q.get("db_xref", [])),
})
if not cds:
raise ValueError("No CDS parsed")
return cds
def _qualifier(block, key):
m = re.search(rf'/{re.escape(key)}="([^"]*)"', block, flags=re.S)
return re.sub(r"\s+", " ", m.group(1)).strip() if m else ""
def parse_genbank_fallback(path):
"""
Tolerant parser for Prokka/GenBank files that Biopython may reject because
of nonstandard LOCUS formatting.
"""
text = Path(path).read_text(encoding="utf-8", errors="replace")
contig_starts = list(re.finditer(r"^LOCUS\s+(\S+)", text, flags=re.M))
contig_positions = [(m.start(), m.group(1)) for m in contig_starts]
cds_starts = list(re.finditer(r"^ CDS\s+(.+)$", text, flags=re.M))
cds = []
for i, m in enumerate(cds_starts):
start = m.start()
end = cds_starts[i + 1].start() if i + 1 < len(cds_starts) else len(text)
block = text[start:end]
contig = ""
for pos, name in contig_positions:
if pos <= start:
contig = name
else:
break
cds.append({
"contig": contig,
"locus_tag": _qualifier(block, "locus_tag"),
"gene": _qualifier(block, "gene"),
"product": _qualifier(block, "product"),
"translation": _qualifier(block, "translation").replace(" ", ""),
"EC_number": _qualifier(block, "EC_number"),
"db_xref": _qualifier(block, "db_xref"),
})
cds = [r for r in cds if r["locus_tag"]]
if not cds:
raise ValueError("Fallback parser found no CDS")
return cds
def parse_genbank(path):
try:
return parse_genbank_biopython(path)
except Exception as exc:
print(
f"[info] Biopython GenBank parser failed ({exc}); "
"using tolerant fallback parser."
)
return parse_genbank_fallback(path)
# ============================================================
# Existing-annotation screen
# ============================================================
def load_annotation_rules(path):
df = pd.read_csv(path, sep="\t").fillna("")
compiled = []
for _, r in df.iterrows():
policy = str(r.get("match_policy", "product_or_gene")).strip()
policy = policy or "product_or_gene"
compiled.append((r, re.compile(str(r["regex"]), re.I), policy))
return compiled
def screen_annotated(cds, rules):
"""
Product-aware annotation screening.
Rules marked product_required cannot be triggered by an ambiguous gene
symbol alone. This retains the v0.3.3 safeguard against misleading calls.
"""
hits = []
for r in cds:
product = r["product"] or ""
if re.search(
r"hypothetical protein|uncharacterized protein|unknown protein",
product,
re.I,
):
continue
# Build several matching variants of the annotated gene name.
# This makes Prokka-style copy/version suffixes transparent to the
# rule engine without altering the original gene name in the report.
#
# Examples:
# azoR2_1 -> azoR2_1, azoR2, azoR
# catA_2 -> catA_2, catA
# copA1 -> copA1, copA
gene_original = str(r["gene"] or "").strip()
gene_variants = []
if gene_original:
gene_variants.append(gene_original)
# Remove Prokka copy-number suffix: _1, _2, _3, ...
gene_no_copy = re.sub(r"_\d+$", "", gene_original)
if gene_no_copy and gene_no_copy not in gene_variants:
gene_variants.append(gene_no_copy)
# Also expose the family root when a terminal number is attached
# directly to the gene name, e.g. azoR2 -> azoR, copA1 -> copA.
gene_family_root = re.sub(r"\d+$", "", gene_no_copy)
if gene_family_root and gene_family_root not in gene_variants:
gene_variants.append(gene_family_root)
gene_text = " | ".join([r["locus_tag"]] + gene_variants)
# Preserve the original product annotation, but also create a
# punctuation-normalized variant for matching. This allows equivalent
# forms such as "catechol-2,3-dioxygenase",
# "catechol_2,3_dioxygenase", and "catechol 2,3 dioxygenase"
# to be recognized without changing the annotation shown in reports.
product_variants = [product]
product_normalized = re.sub(
r"[-_\u2010\u2011\u2012\u2013\u2014]+",
" ",
product,
)
product_normalized = re.sub(
r"\s+",
" ",
product_normalized,
).strip()
if product_normalized and product_normalized != product:
product_variants.append(product_normalized)
product_text = " | ".join(
product_variants + [r["EC_number"], r["db_xref"]]
)
for rule, rx, policy in rules:
gene_match = bool(rx.search(gene_text))
product_match = bool(rx.search(product_text))
if policy == "product_required":
if not product_match:
continue
elif not (gene_match or product_match):
continue
hits.append({
"locus_tag": r["locus_tag"],
"gene": r["gene"],
"product": product,
"contig": r["contig"],
"protein_length_aa": (
len(r["translation"]) if r["translation"] else ""
),
"family": rule["family"],
"major_category": rule["major_category"],
"evidence_class": rule["evidence_class"],
"confidence": rule["default_confidence"],
"evidence_source": "Existing annotation",
"interpretation": (
"Annotation-based candidate; product-aware matching applied. "
"Direct biological activity still requires experimental validation."
),
})
return pd.DataFrame(hits)
def extract_unmatched_annotated(cds, annotated_hits, out_faa):
"""
Export non-hypothetical proteins that were not recovered by the
annotation-rule screen.
These proteins can then be searched against the curated reference DB
using the existing DIAMOND family-classification workflow.
"""
matched_loci = set()
if annotated_hits is not None and not annotated_hits.empty:
matched_loci = set(
annotated_hits["locus_tag"].astype(str)
)
rows = []
with open(out_faa, "w", encoding="utf-8") as f:
for r in cds:
product = r["product"] or ""
if re.search(
r"hypothetical protein|uncharacterized protein|unknown protein",
product,
re.I,
):
continue
locus_tag = str(r["locus_tag"])
if locus_tag in matched_loci:
continue
seq = r["translation"]
if not seq:
continue
rows.append({
"locus_tag": locus_tag,
"gene": r["gene"],
"product": product,
"contig": r["contig"],
"protein_length_aa": len(seq),
})
f.write(
f">{locus_tag} | original_product={product} "
f"| gene={r['gene']} | contig={r['contig']}\n"
)
for i in range(0, len(seq), 80):
f.write(seq[i:i + 80] + "\n")
return pd.DataFrame(rows)
def extract_hypotheticals(cds, out_faa):
rows = []
with open(out_faa, "w", encoding="utf-8") as f:
for r in cds:
product = r["product"] or ""
if not re.search(
r"hypothetical protein|uncharacterized protein|unknown protein",
product,
re.I,
):
continue
seq = r["translation"]
if not seq:
continue
rows.append({
"locus_tag": r["locus_tag"],
"contig": r["contig"],
"product": product,
"protein_length_aa": len(seq),
})
f.write(
f">{r['locus_tag']} | original_product={product} "
f"| contig={r['contig']}\n"
)
for i in range(0, len(seq), 80):
f.write(seq[i:i + 80] + "\n")
return pd.DataFrame(rows)
# ============================================================
# DIAMOND
# ============================================================
DIAMOND_COLS = [
"query",
"subject",
"identity_pct",
"alignment_len",
"query_len",
"subject_len",
"evalue",
"bitscore",
"query_coverage_pct",
]
def run_diamond(diamond, query_faa, db, out_tsv, threads=None):
"""
v0.3.4 deliberately requests more reference hits than v0.3.3.
The curated reference DB contains related reductase/resistance families.
Keeping only the first 10 DIAMOND targets can prevent a biologically
relevant family from ever reaching the family-aware classifier.
"""
cmd = [
diamond,
"blastp",
"--query", str(query_faa),
"--db", str(db),
"--out", str(out_tsv),
"--outfmt", "6",
"qseqid", "sseqid", "pident", "length", "qlen", "slen",
"evalue", "bitscore", "qcovhsp",
"--max-target-seqs", "50",
"--evalue", "1e-5",
"--sensitive",
]
if threads:
cmd += ["--threads", str(threads)]
print("[run]", " ".join(cmd))
subprocess.run(cmd, check=True)
def load_diamond(path):
if not Path(path).exists() or Path(path).stat().st_size == 0:
return pd.DataFrame(columns=DIAMOND_COLS)
df = pd.read_csv(
path,
sep="\t",
header=None,
names=DIAMOND_COLS,
)
numeric_cols = [
"identity_pct",
"alignment_len",
"query_len",
"subject_len",
"evalue",
"bitscore",
"query_coverage_pct",
]
for c in numeric_cols:
df[c] = pd.to_numeric(df[c], errors="coerce")
df["reference_coverage_pct"] = (
df["alignment_len"] / df["subject_len"] * 100
).round(1)
df["accession"] = (
df["subject"].astype(str).str.split("|", regex=False).str[0]
)
return df
# ============================================================
# Reference metadata + evidence scoring
# ============================================================
def load_reference_metadata(path):
meta = pd.read_csv(path, sep="\t", dtype=str).fillna("")
if "Accession" not in meta.columns:
raise ValueError(
"Reference metadata must contain an 'Accession' column."
)
return meta
def base_confidence(row):
pid = float(row.get("identity_pct", 0) or 0)
qcov = float(row.get("query_coverage_pct", 0) or 0)
rcov = float(row.get("reference_coverage_pct", 0) or 0)
evalue = float(row.get("evalue", 1) or 1)
qlen = float(row.get("query_len", 0) or 0)
slen = float(row.get("subject_len", 0) or 0)
partial = (rcov < 50) or (qlen < 0.5 * slen)
if (
evalue <= 1e-30
and pid >= 30
and qcov >= 65
and rcov >= 65
and not partial
):
return "High"
if (
evalue <= 1e-10
and pid >= 25
and qcov >= 50
and rcov >= 40
):
return "Moderate"
return "Weak"
def _split_families(value):
"""
Metadata can associate one UniProt accession with several curated targets.
Exploding these targets prevents one combined metadata string from hiding
an individual family such as chrR, chrA, azoR, or azoreductase.
"""
text = str(value or "").strip()
if not text:
return ["Unresolved"]
parts = [
p.strip()
for p in re.split(r"\s*;\s*", text)
if p.strip()
]
return parts or ["Unresolved"]
def classify_hypothetical_hits(df, meta):
"""
Core v0.3.4 fix.
v0.3.3 kept ONE global best hit per hypothetical query. v0.3.4 instead:
1. joins every DIAMOND hit to curated metadata;
2. expands multi-family metadata into individual family rows;
3. keeps the best reference hit for EACH query + biological family.
Therefore a valid ChrR/AzoR/ChrA/etc. family hit is not silently removed
merely because the same query has a higher-scoring hit to another family.
"""
if df.empty:
return pd.DataFrame()
merged = df.merge(
meta,
left_on="accession",
right_on="Accession",
how="left",
)
# Do not silently turn references missing from metadata into candidates.
merged["metadata_matched"] = (
merged["Accession"].astype(str).str.strip() != ""
)
if "All_family_targets" not in merged.columns:
merged["All_family_targets"] = "Unresolved"
merged["family_target"] = merged["All_family_targets"].apply(_split_families)
merged = merged.explode("family_target", ignore_index=True)
merged["family_target"] = (
merged["family_target"].astype(str).str.strip().replace("", "Unresolved")
)
merged["confidence"] = merged.apply(base_confidence, axis=1)
# Sequence strength cannot exceed the confidence supported by the
# curated biological evidence class.
def apply_evidence_ceiling(r):
confidence = str(r.get("confidence", "Weak"))
evidence = str(r.get("Evidence_classes", "")).lower()
defaults = str(r.get("Default_confidences", "")).lower()
if (
"low" in defaults
and "moderate" not in defaults
and "high" not in defaults
):
return "Weak"
if "direct" not in evidence and confidence == "High":
return "Moderate"
return confidence
merged["confidence"] = merged.apply(apply_evidence_ceiling, axis=1)
merged["fragment_or_partial"] = (
(merged["reference_coverage_pct"] < 50)
| (merged["query_len"] < 0.5 * merged["subject_len"])
)
# Best reference within EACH biological family for EACH query.
best = (
merged.sort_values(
["query", "family_target", "bitscore", "evalue"],
ascending=[True, True, False, True],
)
.groupby(
["query", "family_target"],
as_index=False,
dropna=False,
)
.first()
)
if "Category_flag" not in best.columns:
best["Category_flag"] = "REVIEW"
if "Headline_category" not in best.columns:
best["Headline_category"] = "Unresolved"
if "Evidence_classes" not in best.columns:
best["Evidence_classes"] = ""
def decision(r):
if not bool(r.get("metadata_matched", False)):
return "Reject"
rcov = float(r.get("reference_coverage_pct", 0) or 0)
if bool(r["fragment_or_partial"]) and rcov < 20:
return "Reject"
if str(r.get("Category_flag", "")).upper() == "REVIEW":
return "Review"
if r["confidence"] == "Weak":
return "Review"
return "Candidate"
best["decision"] = best.apply(decision, axis=1)
# Keep weak evidence visible; this label is descriptive, not a filter.
best["match_strength"] = best["confidence"].astype(str) + " match"
best["evidence_source"] = "DIAMOND homology"
def interpretation(r):
if not bool(r.get("metadata_matched", False)):
return (
"DIAMOND reference was not found in the supplied metadata; "
"functional assignment rejected."
)
if r["decision"] == "Reject":
return (
"Short/partial or unsupported similarity; "
"do not assign full-length function."
)
return (
"Sequence-supported family-level candidate; conserved-domain "
"validation is recommended before a strong functional call."
)
best["interpretation"] = best.apply(interpretation, axis=1)
# Stable, useful ordering.
conf_rank = {"High": 0, "Moderate": 1, "Weak": 2}
decision_rank = {"Candidate": 0, "Review": 1, "Reject": 2}
best["_conf_rank"] = best["confidence"].map(conf_rank).fillna(9)
best["_decision_rank"] = best["decision"].map(decision_rank).fillna(9)
best = (
best.sort_values(
[
"query",
"_decision_rank",
"_conf_rank",
"family_target",
"bitscore",
],
ascending=[True, True, True, True, False],
)
.drop(columns=["_conf_rank", "_decision_rank"])
.reset_index(drop=True)
)
return best
# ============================================================
# Optional InterPro integration
# ============================================================
def load_interpro(path):
if not path:
return pd.DataFrame()
cols = [
"protein",
"md5",
"length",
"analysis",
"signature_accession",
"signature_description",
"start",
"stop",
"score",
"status",
"date",
"interpro_accession",
"interpro_description",
"go_terms",
"pathways",
]
rows = []
with open(path, encoding="utf-8") as f:
for vals in csv.reader(f, delimiter="\t"):
if len(vals) < 13:
continue
vals = vals + [""] * (15 - len(vals))
rows.append(vals[:15])
return pd.DataFrame(rows, columns=cols)
def add_interpro_support(best, ip):
"""
Attach InterPro evidence without changing Gene Miner's original
candidate, confidence, or decision logic.
Raw one-row-per-hit evidence is retained separately. Common member
databases are also summarized into dedicated columns.
"""
if best is None or best.empty:
return best
best = best.copy()
defaults = {
"interpro_support": "",
"interpro_accessions": "",
"interpro_analyses": "",
"interpro_detected": False,
"interpro_status": "NOT_SUBMITTED",
"panther_hits": "",
"pfam_hits": "",
"cdd_hits": "",
"ncbifam_hits": "",
"prints_hits": "",
"gene3d_hits": "",
"superfamily_hits": "",
"smart_hits": "",
"prosite_hits": "",
"other_interpro_member_hits": "",
"integrated_interpro_entries": "",
"interpro_go_terms": "",
"interpro_pathways": "",
"interpro_coordinates": "",
}
for col, default in defaults.items():
best[col] = default
if ip is None or ip.empty:
return best
descriptions = defaultdict(list)
accessions = defaultdict(list)
analyses = defaultdict(list)
db_hits = defaultdict(lambda: defaultdict(list))
integrated = defaultdict(list)
go_terms = defaultdict(list)
pathways = defaultdict(list)
coordinates = defaultdict(list)
def add_unique(d, key, value):
value = str(value or "").strip()
if value and value != "-" and value not in d[key]:
d[key].append(value)
def norm_db(value):
return re.sub(r"[^a-z0-9]+", "", str(value or "").lower())
db_map = {
"panther": "panther_hits",
"pfam": "pfam_hits",
"cdd": "cdd_hits",
"ncbifam": "ncbifam_hits",
"prints": "prints_hits",
"gene3d": "gene3d_hits",
"cathgene3d": "gene3d_hits",
"superfamily": "superfamily_hits",
"smart": "smart_hits",
"prosite": "prosite_hits",
"prositepatterns": "prosite_hits",
"prositeprofiles": "prosite_hits",
}
for _, r in ip.iterrows():
protein = str(r.get("protein", "") or "").strip()
if not protein:
continue
analysis = str(r.get("analysis", "") or "").strip()
sig_acc = str(r.get("signature_accession", "") or "").strip()
sig_desc = str(r.get("signature_description", "") or "").strip()
ipr_acc = str(r.get("interpro_accession", "") or "").strip()
ipr_desc = str(r.get("interpro_description", "") or "").strip()
hit_start = str(r.get("start", "") or "").strip()
hit_stop = str(r.get("stop", "") or "").strip()
go = str(r.get("go_terms", "") or "").strip()
pathway = str(r.get("pathways", "") or "").strip()
add_unique(descriptions, protein, sig_desc)
add_unique(descriptions, protein, ipr_desc)
add_unique(accessions, protein, sig_acc)
add_unique(accessions, protein, ipr_acc)
add_unique(analyses, protein, analysis)
target = db_map.get(norm_db(analysis), "other_interpro_member_hits")
member_hit = " | ".join(
x for x in (sig_acc, sig_desc, ipr_acc, ipr_desc)
if x and x != "-"
)
if member_hit and member_hit not in db_hits[protein][target]:
db_hits[protein][target].append(member_hit)
if ipr_acc and ipr_acc != "-":
add_unique(
integrated, protein,
" | ".join(x for x in (ipr_acc, ipr_desc) if x and x != "-")
)
add_unique(go_terms, protein, go)
add_unique(pathways, protein, pathway)
if hit_start and hit_stop:
add_unique(
coordinates, protein,
f"{analysis}:{sig_acc or 'NA'}:{hit_start}-{hit_stop}"
)
best["interpro_support"] = best["query"].map(
lambda q: "; ".join(descriptions.get(str(q), []))
)
best["interpro_accessions"] = best["query"].map(
lambda q: "; ".join(accessions.get(str(q), []))
)
best["interpro_analyses"] = best["query"].map(
lambda q: "; ".join(analyses.get(str(q), []))
)
best["interpro_detected"] = best["query"].map(
lambda q: bool(
descriptions.get(str(q)) or accessions.get(str(q)) or analyses.get(str(q))
)
)
best.loc[
best["interpro_detected"], "interpro_status"
] = "HITS_FOUND"
for col in [
"panther_hits", "pfam_hits", "cdd_hits", "ncbifam_hits",
"prints_hits", "gene3d_hits", "superfamily_hits", "smart_hits",
"prosite_hits", "other_interpro_member_hits",
]:
best[col] = best["query"].map(
lambda q, c=col: "; ".join(db_hits.get(str(q), {}).get(c, []))
)
best["integrated_interpro_entries"] = best["query"].map(
lambda q: "; ".join(integrated.get(str(q), []))
)
best["interpro_go_terms"] = best["query"].map(
lambda q: "; ".join(go_terms.get(str(q), []))
)
best["interpro_pathways"] = best["query"].map(
lambda q: "; ".join(pathways.get(str(q), []))
)
best["interpro_coordinates"] = best["query"].map(
lambda q: "; ".join(coordinates.get(str(q), []))
)
best.loc[
best["interpro_detected"], "evidence_source"
] = "DIAMOND + InterPro (independent evidence)"
return best
# ============================================================
# InterPro evidence relationship resolver
# ============================================================
# This resolver ONLY summarizes how independent InterPro evidence relates
# to the DIAMOND candidate. It does not assign pathways, reactions, or a
# forced final protein function.
RESOLVER_GROUPS = {
"p450": ["cytochrome p450", "cyt_p450", "pf00067", "ipr001128", "ipr002397"],
"intradiol_dioxygenase": ["intradiol", "ring-cleavage dioxygenase", "pf00775", "ipr000627", "ipr015889"],
"multicopper": ["multi-copper", "multicopper", "laccase", "pf02578", "ipr038371", "ipr011324"],
"sdr": ["short-chain dehydrogenase", "short chain dehydrogenase", "sdr family", "rossmann", "pf00106", "ipr002347", "ipr036291"],
"p_loop_atpase": ["p-loop", "partitioning atpase", "parab", "aaa domain", "soj", "ipr027417", "ipr025669"],
"fmn_reductase": ["fmn reductase", "flavin reductase", "flavoprotein-like", "pf03358", "ipr005025", "ipr029039", "pf01613", "ipr002563"],
}
FAMILY_EXPECTATIONS = {
"cytochrome p450": {"p450"}, "gcoa": {"p450"},
"cata": {"intradiol_dioxygenase"},
"laccase": {"multicopper"}, "laccase plastic-associated": {"multicopper"},
"linb": {"sdr"}, "lina": {"sdr"},
"chrr": {"fmn_reductase"}, "chromate reductase": {"fmn_reductase"},
"flavin reductase": {"fmn_reductase"},
"azoreductase": {"fmn_reductase"},
"arsa": {"p_loop_atpase"},
}
BROAD_RELATED = {"linb", "lina"}
def _resolver_norm(x):
return re.sub(r"[^a-z0-9]+", " ", str(x or "").lower()).strip()
def _resolver_groups(row):
blob = "; ".join([
str(row.get("interpro_support", "")),
str(row.get("interpro_accessions", "")),
str(row.get("panther_hits", "")),
str(row.get("pfam_hits", "")),
str(row.get("cdd_hits", "")),
str(row.get("ncbifam_hits", "")),
str(row.get("prints_hits", "")),
str(row.get("gene3d_hits", "")),
str(row.get("superfamily_hits", "")),
str(row.get("smart_hits", "")),
str(row.get("prosite_hits", "")),
]).lower()
return {g for g, terms in RESOLVER_GROUPS.items() if any(t in blob for t in terms)}
def resolve_interpro_evidence(best):
"""Evidence-relationship summary only; never changes DIAMOND confidence/decision."""
if best is None or best.empty:
return best
best = best.copy()
best["resolver_status"] = "UNINFORMATIVE"
best["resolver_note"] = ""
for i, r in best.iterrows():
if not bool(r.get("interpro_detected", False)):
best.at[i, "resolver_note"] = "No InterPro evidence was returned for this candidate."
continue
fam = _resolver_norm(r.get("family_target", ""))
groups = _resolver_groups(r)
expected = set()
for key, vals in FAMILY_EXPECTATIONS.items():
if fam == key or fam.startswith(key + " "):
expected |= vals
matched = expected & groups
support = str(r.get("interpro_support", "")).lower()
# Known strong alternative for ArsA-like weak DIAMOND hits.
if fam == "arsa" and "p_loop_atpase" in groups and any(
x in support for x in ["partitioning atpase", "parab", "sporulation initiation inhibitor soj"]
):
best.at[i, "resolver_status"] = "CONFLICTING"
best.at[i, "resolver_note"] = (
"InterPro returns a ParAB/Soj-like P-loop ATPase interpretation rather "
"than evidence specifically consistent with the DIAMOND candidate."
)
# Compatible but only broad architecture.
elif matched and fam in BROAD_RELATED:
best.at[i, "resolver_status"] = "BROAD/RELATED"
best.at[i, "resolver_note"] = (
"InterPro supports a broader protein-family/domain architecture related "
"to the DIAMOND candidate."
)
# Mixed laccase/multicopper plus YfiH/CNF1-like evidence.
elif matched and fam.startswith("laccase") and any(
x in support for x in ["yfih", "cnf1", "cysteine hydrolase", "peptidoglycan editing"]
):
best.at[i, "resolver_status"] = "BROAD/RELATED"
best.at[i, "resolver_note"] = (
"InterPro contains multicopper/laccase-related evidence together with "
"alternative YfiH/CNF1-like annotations."
)
elif matched:
best.at[i, "resolver_status"] = "SUPPORTING"
best.at[i, "resolver_note"] = (
"Independent InterPro family/domain evidence is consistent with the "
"DIAMOND candidate."
)
elif expected and groups:
best.at[i, "resolver_status"] = "CONFLICTING"
best.at[i, "resolver_note"] = (
"InterPro returns recognizable family/domain evidence that is not "
"consistent with the expected architecture of the DIAMOND candidate."
)
elif groups:
best.at[i, "resolver_status"] = "BROAD/RELATED"
best.at[i, "resolver_note"] = (
"InterPro provides related or broader family/domain information but "
"does not directly support the DIAMOND candidate."
)
else:
best.at[i, "resolver_note"] = (
"InterPro evidence was returned, but it is not informative enough for "
"a simple relationship summary."
)
return best
# ============================================================
# Automated InterProScan via EMBL-EBI Job Dispatcher
# ============================================================
INTERPRO_REST_BASE = "https://www.ebi.ac.uk/Tools/services/rest/iprscan5"
def _http_text(url, data=None, timeout=60):
req = urllib.request.Request(url, data=data, headers={
"User-Agent": "Bioremediation-Gene-Miner/0.3.8"
})
with urllib.request.urlopen(req, timeout=timeout) as response:
return response.read().decode("utf-8", errors="replace")
def _interpro_result_types(job_id):
root = ET.fromstring(_http_text(
f"{INTERPRO_REST_BASE}/resulttypes/{job_id}"
))
found = []
for elem in root.iter():
if elem.tag.split("}")[-1] == "type":
item = {c.tag.split("}")[-1]: (c.text or "").strip() for c in elem}
if item.get("identifier"):
found.append(item)
return found
def run_interpro_web(fasta_path, email, outdir, poll_seconds=5, timeout_minutes=45):
fasta_path, outdir = Path(fasta_path), Path(outdir)
status_file = outdir / "interpro_web_status.txt"
tsv_path = outdir / "interpro_web.tsv"
if not fasta_path.exists() or fasta_path.stat().st_size == 0:
status_file.write_text("NOT_RUN\tNo Weak+Review candidates.\n", encoding="utf-8")
print("[info] InterPro web: no candidates; skipped.")
return None
if not email:
status_file.write_text("NOT_RUN\t--interpro-email missing.\n", encoding="utf-8")
print("[warn] --interpro-auto requested but --interpro-email is missing.")
return None
payload = urllib.parse.urlencode({