Repository navigation
Expand file tree
/
Copy pathmain_tp53_analysis.py
More file actions
1216 lines (984 loc) · 41.4 KB
/
Copy pathmain_tp53_analysis.py
File metadata and controls
1216 lines (984 loc) · 41.4 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
"""
TP53 Gene Bioinformatics Analysis Pipeline
============================================
Author: [Dr. Samuel Mbote]
Description:
A bioinformatics pipeline for fetching, analyzing, and visualizing
DNA sequences from NCBI. Covers: sequence translation, GC content
analysis, pairwise alignment, mutation detection, ORF discovery,
codon usage bias, amino acid frequency profiling, multi-species
sequence comparison with phylogenetic tree building, and protein
domain annotation via the EMBL-EBI InterProScan REST API.
Usage:
Set your ENTREZ_EMAIL environment variable before running:
export ENTREZ_EMAIL="your@email.com"
Then run:
python tp53_analysis.py --accession NM_000546
Requirements:
- biopython >= 1.79
- matplotlib >= 3.3.0
"""
import os
import sys
import argparse
import csv
import json
import time
import logging
import urllib.request
import urllib.parse
import urllib.error
import re
from collections import Counter
from typing import Optional, Dict, List, Tuple
from Bio import Entrez, SeqIO, Phylo
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.SeqUtils import gc_fraction
from Bio import Align
from Bio.Align import MultipleSeqAlignment
from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor
import matplotlib
matplotlib.use("Agg") # non-interactive backend — safe for servers / CI
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
# ---------------------------------------------------------------------------
# LOGGING CONFIGURATION
# ---------------------------------------------------------------------------
def setup_logging(log_file: str = "results/tp53_analysis.log") -> logging.Logger:
"""
Configure logging to both file and console.
Args:
log_file (str): Path to log file.
Returns:
logging.Logger: Configured logger instance.
"""
os.makedirs(os.path.dirname(log_file) or ".", exist_ok=True)
logger = logging.getLogger("TP53Pipeline")
logger.setLevel(logging.DEBUG)
# Console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
console_format = logging.Formatter(
'[%(levelname)s] %(message)s'
)
console_handler.setFormatter(console_format)
# File handler
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.DEBUG)
file_format = logging.Formatter(
'%(asctime)s - [%(levelname)s] - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
file_handler.setFormatter(file_format)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
return logger
logger = None # Will be initialized in main
# ---------------------------------------------------------------------------
# INPUT VALIDATION
# ---------------------------------------------------------------------------
def validate_email(email: str) -> bool:
"""
Validate email format.
Args:
email (str): Email address to validate.
Returns:
bool: True if valid email format, False otherwise.
"""
email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(email_pattern, email))
def validate_accession(accession: str) -> bool:
"""
Validate NCBI accession format (basic check).
Args:
accession (str): Accession ID to validate.
Returns:
bool: True if accession format looks valid.
"""
# NCBI accessions are typically 2+ letters followed by digits
return bool(re.match(r'^[A-Z]{1,6}_?\d+(\.\d+)?$', accession))
def validate_sequence(seq: Seq, seq_type: str = "DNA") -> bool:
"""
Validate that sequence contains only valid nucleotides.
Args:
seq (Seq): Sequence to validate.
seq_type (str): Either "DNA" or "PROTEIN".
Returns:
bool: True if sequence is valid.
"""
seq_str = str(seq).upper()
# Empty sequence is never valid
if not seq_str:
return False
if seq_type == "DNA":
valid_chars = set("ACGTNRYSWKMBDHV-") # Full IUPAC ambiguity alphabet
elif seq_type == "PROTEIN":
valid_chars = set("ACDEFGHIKLMNPQRSTVWY*-")
else:
return False
return all(c in valid_chars for c in seq_str)
def validate_positive_int(value: int, min_val: int = 1) -> bool:
"""
Validate that a value is a positive integer.
Args:
value (int): Value to validate.
min_val (int): Minimum allowed value.
Returns:
bool: True if valid.
"""
return isinstance(value, int) and value >= min_val
def check_results_directory_writable() -> bool:
"""
Check if results directory is writable.
Returns:
bool: True if writable, False otherwise.
"""
try:
os.makedirs("results", exist_ok=True)
test_file = "results/.write_test"
with open(test_file, 'w') as f:
f.write("")
os.remove(test_file)
return True
except OSError as e:
logger.error(f"Cannot write to results/: {e}")
return False
# ---------------------------------------------------------------------------
# 1. SEQUENCE FETCHING
# ---------------------------------------------------------------------------
def fetch_sequence(accession_id: str, email: str, max_retries: int = 3) -> Optional[SeqRecord]:
"""
Fetch a nucleotide sequence from NCBI by accession ID with retry logic.
Args:
accession_id (str): NCBI accession number (e.g. 'NM_000546').
email (str): Email address required by NCBI Entrez API.
max_retries (int): Maximum number of retry attempts.
Returns:
SeqRecord: BioPython SeqRecord object containing the sequence.
None: If fetch fails after all retries.
"""
accession_id = accession_id.strip()
if not validate_accession(accession_id):
logger.warning(f"Accession '{accession_id}' has unusual format, attempting fetch anyway.")
Entrez.email = email.strip()
# Only assign api_key when a real value exists — empty string causes HTTP 400
_api_key = os.environ.get("NCBI_API_KEY", "").strip()
if _api_key:
Entrez.api_key = _api_key
for attempt in range(max_retries):
try:
with Entrez.efetch(
db="nucleotide",
id=accession_id,
rettype="fasta",
retmode="text"
) as handle:
record = SeqIO.read(handle, "fasta")
if not record:
logger.error(f"No sequence returned for accession '{accession_id}'.")
return None
if not validate_sequence(record.seq, "DNA"):
logger.warning(f"Sequence contains non-standard nucleotides.")
logger.info(f"Fetched: {record.id} | Length: {len(record.seq)} bp")
return record
except urllib.error.HTTPError as e:
logger.warning(f"Attempt {attempt + 1}/{max_retries}: HTTP Error {e.code}. Retrying...")
if attempt < max_retries - 1:
time.sleep(2 ** attempt) # Exponential backoff
else:
logger.error(f"Failed to fetch accession '{accession_id}' after {max_retries} attempts: {e}")
return None
except Exception as e:
logger.error(f"Failed to fetch accession '{accession_id}': {e}")
return None
# ---------------------------------------------------------------------------
# 2. TRANSLATION
# ---------------------------------------------------------------------------
def analyze_protein(dna_sequence: Seq) -> Optional[Seq]:
"""
Translate a DNA sequence to a protein, stopping at the first stop codon.
Args:
dna_sequence (Seq): BioPython Seq object of the DNA sequence.
Returns:
Seq: Translated protein sequence.
None: If translation fails.
"""
if not dna_sequence or len(dna_sequence) == 0:
logger.error("Empty DNA sequence provided for translation.")
return None
if not validate_sequence(dna_sequence, "DNA"):
logger.error("Invalid DNA sequence (contains invalid nucleotides).")
return None
try:
protein = dna_sequence.translate(to_stop=True)
if len(protein) == 0:
logger.warning("Translation produced empty protein — possible missing start codon.")
return protein # empty Seq is valid — not an error
logger.info(f"Protein translated: {len(protein)} amino acids")
return protein
except Exception as e:
logger.error(f"Translation failed: {e}")
return None
# ---------------------------------------------------------------------------
# 3. PAIRWISE ALIGNMENT
# ---------------------------------------------------------------------------
def run_alignment(seq1: Seq, seq2: Seq) -> Optional[float]:
"""
Perform global pairwise alignment between two sequences.
Args:
seq1 (Seq): First sequence (original).
seq2 (Seq): Second sequence (mutant or homolog).
Returns:
float: Best alignment score.
None: If alignment fails.
"""
if not seq1 or not seq2:
logger.error("Empty sequence provided for alignment.")
return None
if len(seq1) == 0 or len(seq2) == 0:
logger.error("Sequence length is zero.")
return None
try:
aligner = Align.PairwiseAligner()
aligner.mode = "global"
alignments = aligner.align(seq1, seq2)
if len(alignments) == 0:
logger.warning("No alignments found.")
return None
score = alignments.score
logger.info(f"Alignment score: {score:.2f}")
return score
except Exception as e:
logger.error(f"Alignment failed: {e}")
return None
# ---------------------------------------------------------------------------
# 4. MUTATION DETECTION
# ---------------------------------------------------------------------------
def find_mutation_positions(original: str, mutant: str) -> List[Dict]:
"""
Find and report every position where the mutant differs from the original.
Args:
original (str): Original DNA string.
mutant (str): Mutant DNA string.
Returns:
list[dict]: List of dicts with keys 'position', 'original', 'mutant'.
"""
if not original or not mutant:
logger.error("Empty sequences provided for mutation detection.")
return []
if len(original) != len(mutant):
logger.warning(
f"Sequences differ in length ({len(original)} vs {len(mutant)}). "
"Comparing overlapping region only."
)
mutations = []
min_len = min(len(original), len(mutant))
for i in range(min_len):
orig_base = original[i].upper()
mut_base = mutant[i].upper()
if orig_base != mut_base:
mutations.append({
"position": i + 1,
"original": orig_base,
"mutant": mut_base
})
logger.debug(f"Mutation @ position {i + 1}: {orig_base} -> {mut_base}")
logger.info(f"Total mutations found: {len(mutations)}")
return mutations
# ---------------------------------------------------------------------------
# 5. ORF FINDER — all 6 reading frames
# ---------------------------------------------------------------------------
def find_orfs(dna_sequence: Seq, min_length: int = 100) -> List[Dict]:
"""
Scan all 6 reading frames and report ORFs above a minimum length.
Args:
dna_sequence (Seq): Full DNA sequence to scan.
min_length (int): Minimum ORF length in nucleotides (default 100).
Returns:
list[dict]: Each dict contains 'frame', 'start', 'end', 'length', 'protein'.
"""
if not dna_sequence or len(dna_sequence) < 3:
logger.error("Sequence too short for ORF discovery (minimum 3 bp).")
return []
if not validate_positive_int(min_length):
logger.error(f"Invalid min_length: {min_length}. Must be positive integer.")
return []
orfs = []
seq_len = len(dna_sequence)
for strand, nuc in [(+1, dna_sequence), (-1, dna_sequence.reverse_complement())]:
for frame in range(3):
try:
trans = nuc[frame:].translate()
trans_str = str(trans)
aa_start = 0
while True:
met = trans_str.find("M", aa_start)
if met == -1:
break
stop = trans_str.find("*", met)
if stop == -1:
break
orf_len_aa = stop - met
orf_len_nt = orf_len_aa * 3
if orf_len_nt >= min_length:
nt_start = frame + met * 3
nt_end = frame + (stop + 1) * 3
if strand == -1:
nt_start = seq_len - (frame + (stop + 1) * 3)
nt_end = seq_len - (frame + met * 3)
# Ensure start <= end
if nt_start > nt_end:
nt_start, nt_end = nt_end, nt_start
orfs.append({
"frame": ("+" if strand == 1 else "-") + str(frame + 1),
"start": nt_start,
"end": nt_end,
"length": orf_len_nt,
"protein": str(trans_str[met:stop])
})
aa_start = stop + 1
except Exception as e:
logger.warning(f"Error processing frame {frame} on strand {strand}: {e}")
continue
orfs.sort(key=lambda x: x["length"], reverse=True)
logger.info(f"ORFs found (>={min_length} nt): {len(orfs)}")
if orfs:
logger.info(f" Longest ORF: Frame {orfs[0]['frame']} | "
f"{orfs[0]['start']}-{orfs[0]['end']} | {orfs[0]['length']} nt")
return orfs
# ---------------------------------------------------------------------------
# 6. CODON USAGE BIAS
# ---------------------------------------------------------------------------
def codon_usage(dna_sequence: Seq) -> Dict[str, float]:
"""
Calculate codon usage frequency across the coding sequence.
Args:
dna_sequence (Seq): DNA sequence (should be in-frame CDS).
Returns:
dict: {codon (str): frequency (float)} -- frequencies sum to 1.0.
Empty dict if sequence too short.
"""
if not dna_sequence or len(dna_sequence) < 3:
logger.warning("Sequence too short for codon analysis (minimum 3 bp).")
return {}
try:
seq_str = str(dna_sequence).upper()
codons = [seq_str[i:i+3] for i in range(0, len(seq_str) - 2, 3)
if len(seq_str[i:i+3]) == 3]
if len(codons) == 0:
logger.warning("No complete codons found in sequence.")
return {}
total = len(codons)
counts = Counter(codons)
freq = {codon: round(count / total, 4) for codon, count in counts.items()}
logger.info(f"Codon usage calculated over {total} codons ({len(freq)} unique).")
return freq
except Exception as e:
logger.error(f"Codon usage analysis failed: {e}")
return {}
# ---------------------------------------------------------------------------
# 7. AMINO ACID FREQUENCY
# ---------------------------------------------------------------------------
def amino_acid_frequency(protein_sequence: Seq) -> Dict[str, int]:
"""
Count and return the frequency of each amino acid in a protein sequence.
Args:
protein_sequence (Seq): Translated protein sequence.
Returns:
dict: {amino_acid (str): count (int)}, sorted by count descending.
"""
if not protein_sequence or len(protein_sequence) == 0:
logger.warning("Empty protein sequence provided.")
return {}
try:
counts = Counter(str(protein_sequence).upper())
sorted_counts = dict(sorted(counts.items(), key=lambda x: x[1], reverse=True))
logger.debug(f"Amino acid frequency calculated for {len(protein_sequence)} residues.")
return sorted_counts
except Exception as e:
logger.error(f"Amino acid frequency analysis failed: {e}")
return {}
# ---------------------------------------------------------------------------
# 8. MULTI-SPECIES COMPARISON & PHYLOGENETIC TREE
# ---------------------------------------------------------------------------
# TP53 orthologs across species. Add/swap accessions here to study any gene family.
TP53_HOMOLOGS = {
"NM_000546": "Human",
"NM_011640": "Mouse",
"NM_001271820": "Zebrafish",
"NM_009895": "Rat",
"NM_001123020": "Chimpanzee",
}
def fetch_multiple_sequences(accession_map: Dict[str, str], email: str) -> List[SeqRecord]:
"""
Fetch multiple nucleotide sequences from NCBI with detailed error reporting.
Args:
accession_map (dict): {accession_id (str): species_label (str)}.
email (str): Email for NCBI Entrez API.
Returns:
list[SeqRecord]: Records with species name as .id and .name.
"""
if not accession_map:
logger.error("Empty accession map provided.")
return []
records = []
failed = []
for accession, species in accession_map.items():
try:
rec = fetch_sequence(accession, email)
if rec:
label = species.replace(" ", "_")
rec.id = label
rec.name = label
rec.description = ""
records.append(rec)
else:
failed.append(f"{species} ({accession})")
time.sleep(0.4) # respect NCBI rate limit (~3 req/s)
except Exception as e:
logger.warning(f"Failed to fetch {species} ({accession}): {e}")
failed.append(f"{species} ({accession})")
logger.info(f"Fetched {len(records)}/{len(accession_map)} homolog sequences.")
if failed:
logger.warning(f"Failed accessions: {', '.join(failed)}")
return records
def build_multiple_alignment(records: List[SeqRecord]) -> Optional[MultipleSeqAlignment]:
"""
Build a multiple sequence alignment by trimming all records to the
length of the shortest sequence.
Args:
records (list[SeqRecord]): Fetched sequence records.
Returns:
MultipleSeqAlignment: Trimmed alignment object.
None: If insufficient sequences.
"""
if not records or len(records) < 2:
logger.error("At least 2 sequences required for multiple alignment.")
return None
try:
min_len = min(len(r.seq) for r in records)
if min_len < 100:
logger.warning(f"Alignment length very short ({min_len} bp). Results may be unreliable.")
trimmed = [
SeqRecord(r.seq[:min_len], id=r.id, name=r.name, description="")
for r in records
]
alignment = MultipleSeqAlignment(trimmed)
logger.info(f"Multiple alignment ready | {len(records)} species x {min_len} bp")
return alignment
except Exception as e:
logger.error(f"Multiple alignment failed: {e}")
return None
def build_phylogenetic_tree(alignment: MultipleSeqAlignment):
"""
Build a Neighbour-Joining phylogenetic tree from a multiple alignment.
Args:
alignment (MultipleSeqAlignment): Aligned sequences.
Returns:
Bio.Phylo.BaseTree.Tree: The NJ tree.
None: If tree building fails.
"""
if not alignment or len(alignment) < 2:
logger.error("At least 2 sequences required for phylogenetic tree.")
return None
try:
calculator = DistanceCalculator("identity")
dist_matrix = calculator.get_distance(alignment)
constructor = DistanceTreeConstructor(calculator, method="nj")
tree = constructor.build_tree(alignment)
logger.info("Neighbour-Joining phylogenetic tree built successfully.")
return tree
except Exception as e:
logger.error(f"Phylogenetic tree construction failed: {e}")
return None
def save_phylogenetic_tree(tree,
txt_path: str = "results/phylo_tree.txt",
png_path: str = "results/phylo_tree.png") -> bool:
"""
Save the phylogenetic tree as a Newick text file and a PNG figure.
Args:
tree: BioPython Tree object from build_phylogenetic_tree().
txt_path (str): Output path for Newick-format text.
png_path (str): Output path for the PNG figure.
Returns:
bool: True if successful, False otherwise.
"""
if not tree:
logger.error("No tree provided for saving.")
return False
try:
os.makedirs(os.path.dirname(txt_path) or ".", exist_ok=True)
# Newick text
Phylo.write(tree, txt_path, "newick")
logger.info(f"Newick tree saved -> {txt_path}")
# PNG figure
fig, ax = plt.subplots(figsize=(10, 6))
Phylo.draw(tree, axes=ax, do_show=False)
ax.set_title(
"TP53 Orthologs -- Neighbour-Joining Phylogenetic Tree",
fontsize=13, fontweight="bold"
)
plt.tight_layout()
plt.savefig(png_path, dpi=150, bbox_inches="tight")
plt.close()
logger.info(f"Phylogenetic tree plot saved -> {png_path}")
return True
except Exception as e:
logger.error(f"Failed to save phylogenetic tree: {e}")
return False
def export_distance_matrix_csv(alignment: MultipleSeqAlignment,
filepath: str = "results/distance_matrix.csv") -> bool:
"""
Export the pairwise identity distance matrix between all species to CSV.
Args:
alignment (MultipleSeqAlignment): Aligned sequences.
filepath (str): Destination CSV path.
Returns:
bool: True if successful, False otherwise.
"""
if not alignment:
logger.error("No alignment provided for distance matrix export.")
return False
try:
calculator = DistanceCalculator("identity")
dist_matrix = calculator.get_distance(alignment)
names = dist_matrix.names
os.makedirs(os.path.dirname(filepath) or ".", exist_ok=True)
with open(filepath, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Species"] + names)
for i, name in enumerate(names):
row = [name] + [
f"{dist_matrix[i][j]:.4f}" for j in range(len(names))
]
writer.writerow(row)
logger.info(f"Distance matrix exported -> {filepath}")
return True
except Exception as e:
logger.error(f"Failed to export distance matrix: {e}")
return False
# ---------------------------------------------------------------------------
# 9. PROTEIN DOMAIN ANNOTATION -- EMBL-EBI InterProScan REST API
# ---------------------------------------------------------------------------
# NOTE: The EBI InterProScan REST API (iprscan5) was retired in 2024.
# The replacement is the InterPro API: https://www.ebi.ac.uk/interpro/api/
# Domain annotation now queries InterPro directly by protein sequence hash,
# or can be run manually at https://www.ebi.ac.uk/interpro/search/sequence/
_INTERPRO_API = "https://www.ebi.ac.uk/interpro/api/protein/UniProt/entry/interpro/?format=json"
def annotate_protein_domains(protein_seq: Seq, email: str,
max_wait: int = 180) -> List[Dict]:
"""
Annotate protein domains using the EMBL-EBI InterPro REST API.
Queries InterPro for known domains matching the TP53 protein.
The legacy iprscan5 REST endpoint was retired in 2024 — this
function uses the current InterPro API instead.
For custom sequence submission, use the web interface at:
https://www.ebi.ac.uk/interpro/search/sequence/
Args:
protein_seq (Seq): Translated protein sequence.
email (str): Contact email (kept for API compatibility).
max_wait (int): Timeout in seconds (default 180).
Returns:
list[dict]: Each dict has keys 'database', 'accession', 'name',
'start', 'end', 'score'. Empty list on failure.
"""
if not protein_seq or len(protein_seq) == 0:
logger.error("Empty protein sequence provided for domain annotation.")
return []
if len(protein_seq) < 10:
logger.warning(
f"Very short protein sequence ({len(protein_seq)} aa). "
"Domain annotation may be unreliable."
)
# Query InterPro for TP53 human protein (P04637) — the canonical
# UniProt entry for human p53. This returns all known domain annotations
# for the exact protein this pipeline analyses.
TP53_UNIPROT_ID = "P04637"
url = f"https://www.ebi.ac.uk/interpro/api/entry/all/protein/UniProt/{TP53_UNIPROT_ID}/?format=json"
try:
req = urllib.request.Request(
url,
headers={
"Accept": "application/json",
"User-Agent": f"TP53-Pipeline/1.0 ({email})"
}
)
logger.info("Querying InterPro API for TP53 domain annotations...")
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
logger.warning(f"InterPro API returned HTTP {e.code}. Skipping domain annotation.")
return []
except Exception as e:
logger.warning(f"Domain annotation failed: {e}. Skipping.")
return []
# --- Parse InterPro API response ---
domains = []
try:
results = data.get("results", [])
if not results:
logger.warning("No domain results returned from InterPro.")
return []
for entry in results:
metadata = entry.get("metadata", {})
acc = metadata.get("accession", "?")
name = metadata.get("name", "?")
db = metadata.get("source_database", "?").upper()
# Extract location from protein structure
proteins = entry.get("proteins", [])
for protein in proteins:
for location in protein.get("entry_protein_locations", []):
for fragment in location.get("fragments", []):
domains.append({
"database": db,
"accession": acc,
"name": name,
"start": fragment.get("start", "?"),
"end": fragment.get("end", "?"),
"score": "N/A",
})
except (KeyError, IndexError, TypeError) as e:
logger.error(f"Could not parse InterPro domain results: {e}")
return []
logger.info(f"Protein domains annotated: {len(domains)} hits")
for d in domains[:10]:
logger.info(
f" [{d['database']}] {d['accession']} | "
f"{d['name']} | aa {d['start']}-{d['end']}"
)
return domains
def export_domains_csv(domains: List[Dict],
filepath: str = "results/protein_domains.csv") -> bool:
"""
Export protein domain annotations to a CSV file.
Args:
domains (list[dict]): Output from annotate_protein_domains().
filepath (str): Destination CSV path.
Returns:
bool: True if successful, False otherwise.
"""
if not domains:
logger.warning("No domain data to export.")
return False
try:
os.makedirs(os.path.dirname(filepath) or ".", exist_ok=True)
with open(filepath, "w", newline="") as f:
writer = csv.DictWriter(
f, fieldnames=["database", "accession", "name", "start", "end", "score"]
)
writer.writeheader()
writer.writerows(domains)
logger.info(f"Protein domains exported -> {filepath}")
return True
except Exception as e:
logger.error(f"Failed to export domains: {e}")
return False
# ---------------------------------------------------------------------------
# 10. CSV EXPORTS -- mutations & ORFs
# ---------------------------------------------------------------------------
def export_mutations_csv(mutations: List[Dict],
filepath: str = "results/mutations.csv") -> bool:
"""
Export detected mutations to a CSV file.
Args:
mutations (list[dict]): Output from find_mutation_positions().
filepath (str): Destination CSV path.
Returns:
bool: True if successful, False otherwise.
"""
if not mutations:
logger.warning("No mutations to export.")
return False
try:
os.makedirs(os.path.dirname(filepath) or ".", exist_ok=True)
with open(filepath, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["position", "original", "mutant"])
writer.writeheader()
writer.writerows(mutations)
logger.info(f"Mutations exported -> {filepath}")
return True
except Exception as e:
logger.error(f"Failed to export mutations: {e}")
return False
def export_orfs_csv(orfs: List[Dict], filepath: str = "results/orfs.csv") -> bool:
"""
Export discovered ORFs to a CSV file with full protein sequences.
Args:
orfs (list[dict]): Output from find_orfs().
filepath (str): Destination CSV path.
Returns:
bool: True if successful, False otherwise.
"""
if not orfs:
logger.warning("No ORFs to export.")
return False
try:
os.makedirs(os.path.dirname(filepath) or ".", exist_ok=True)
with open(filepath, "w", newline="") as f:
writer = csv.DictWriter(
f, fieldnames=["frame", "start", "end", "length", "protein"]
)
writer.writeheader()
writer.writerows(orfs)
logger.info(f"ORFs exported -> {filepath} ({len(orfs)} ORFs)")
return True
except Exception as e:
logger.error(f"Failed to export ORFs: {e}")
return False
# ---------------------------------------------------------------------------
# 11. PLOTTING -- GC content + amino acid frequency
# ---------------------------------------------------------------------------
def plot_all(dna_seq: Seq, protein_seq: Seq, gc_window: int = 100) -> bool:
"""
Generate a two-panel figure:
Panel 1 -- GC content sliding window across the full gene.
Panel 2 -- Amino acid frequency bar chart of the translated protein.
Args:
dna_seq (Seq): Full DNA sequence.
protein_seq (Seq): Translated protein sequence.
gc_window (int): Sliding window size in bp (default 100).
Returns:
bool: True if successful, False otherwise.
"""
if not dna_seq or len(dna_seq) == 0:
logger.error("Empty DNA sequence for plotting.")
return False
if not protein_seq or len(protein_seq) == 0:
logger.error("Empty protein sequence for plotting.")
return False
if not validate_positive_int(gc_window):
logger.error(f"Invalid gc_window: {gc_window}. Must be positive integer.")
return False
try:
os.makedirs("results", exist_ok=True)
fig = plt.figure(figsize=(14, 10))
fig.suptitle(
"TP53 Gene -- Bioinformatics Analysis",
fontsize=16, fontweight="bold", y=0.98
)
gs = gridspec.GridSpec(2, 1, hspace=0.45)
# Panel 1 -- GC Content
ax1 = fig.add_subplot(gs[0])
gc_values = []
x_pos = []
for i in range(0, len(dna_seq), gc_window):
window = dna_seq[i:i + gc_window]
if len(window) > 0:
gc_values.append(gc_fraction(window) * 100)
x_pos.append(i)
if len(gc_values) == 0:
logger.warning("Unable to calculate GC content.")
return False
mean_gc = sum(gc_values) / len(gc_values) if gc_values else 0
ax1.plot(x_pos, gc_values, color="#2196F3", linewidth=1.5)
ax1.axhline(y=mean_gc, color="red", linestyle="--", linewidth=1,
label=f"Mean GC: {mean_gc:.1f}%")
ax1.fill_between(x_pos, gc_values, alpha=0.15, color="#2196F3")
ax1.set_title(f"GC Content (Sliding Window = {gc_window} bp)", fontsize=13)
ax1.set_xlabel("Position (bp)")
ax1.set_ylabel("GC Content (%)")
ax1.set_ylim([0, 100])
ax1.legend()
ax1.grid(True, alpha=0.3)
# Panel 2 -- Amino Acid Frequency
ax2 = fig.add_subplot(gs[1])
aa_freq = amino_acid_frequency(protein_seq)
if not aa_freq:
logger.warning("Unable to calculate amino acid frequency.")
return False
aa_labels = list(aa_freq.keys())
aa_counts = list(aa_freq.values())
colors = plt.cm.viridis([i / len(aa_labels) for i in range(len(aa_labels))])
bars = ax2.bar(aa_labels, aa_counts, color=colors,
edgecolor="white", linewidth=0.5)
ax2.set_title("Amino Acid Frequency in Translated TP53 Protein", fontsize=13)
ax2.set_xlabel("Amino Acid")
ax2.set_ylabel("Count")
ax2.grid(True, axis="y", alpha=0.3)
for bar, count in zip(bars[:min(5, len(bars))], aa_counts[:5]):
ax2.text(
bar.get_x() + bar.get_width() / 2,
bar.get_height() + max(aa_counts) * 0.01,
str(count), ha="center", va="bottom", fontsize=8, fontweight="bold"
)
outpath = "results/tp53_analysis.png"