-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdna.py
More file actions
2816 lines (2367 loc) · 107 KB
/
dna.py
File metadata and controls
2816 lines (2367 loc) · 107 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
import datetime
import os
import re
import torch
from transformers import AutoTokenizer, AutoModelForMaskedLM
from dotenv import load_dotenv
import numpy as np
import requests
from Bio.Blast import NCBIWWW, NCBIXML
from collections import Counter
from Bio import (
Entrez, SeqIO, motifs, Phylo, AlignIO,
pairwise2
)
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from Bio.pairwise2 import format_alignment
from Bio.PDB import *
from Bio.SeqUtils.ProtParam import ProteinAnalysis
from io import StringIO
from colorama import Fore, Style
from prettytable import PrettyTable
import matplotlib.pyplot as plt
import pandas as pd
import random
import functools
import signal
from concurrent.futures import ThreadPoolExecutor, TimeoutError
import textwrap
import RNA
import json
import time
from typing import Dict, List, Union, Optional
from colorama import init
from Bio.SeqUtils import molecular_weight
from Bio.SeqUtils import gc_fraction # For GC content calculation
import warnings
import logging
from ratelimit import limits, sleep_and_retry
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
import sys
# Load environment variables
load_dotenv()
Entrez.email = os.getenv('NCBI_EMAIL')
# Add try-except for model loading
try:
tokenizer = AutoTokenizer.from_pretrained("InstaDeepAI/nucleotide-transformer-v2-500m-multi-species", trust_remote_code=True)
model = AutoModelForMaskedLM.from_pretrained("InstaDeepAI/nucleotide-transformer-v2-500m-multi-species", trust_remote_code=True)
except Exception as e:
print(f"Warning: Genetic Due Diligence Micro-Agent Failed to load: {str(e)}")
tokenizer = None
model = None
# Add new constants for protein analysis
aa_weights = {
'A': 89.1, 'R': 174.2, 'N': 132.1, 'D': 133.1, 'C': 121.2, 'E': 147.1,
'Q': 146.2, 'G': 75.1, 'H': 155.2, 'I': 131.2, 'L': 131.2, 'K': 146.2,
'M': 149.2, 'F': 165.2, 'P': 115.1, 'S': 105.1, 'T': 119.1, 'W': 204.2,
'Y': 181.2, 'V': 117.1
}
# Add this near the top of the file with other constants
# Kyte & Doolittle hydrophobicity scale
kd = {
'A': 1.8, # Alanine
'R': -4.5, # Arginine
'N': -3.5, # Asparagine
'D': -3.5, # Aspartic acid
'C': 2.5, # Cysteine
'Q': -3.5, # Glutamine
'E': -3.5, # Glutamic acid
'G': -0.4, # Glycine
'H': -3.2, # Histidine
'I': 4.5, # Isoleucine
'L': 3.8, # Leucine
'K': -3.9, # Lysine
'M': 1.9, # Methionine
'F': 2.8, # Phenylalanine
'P': -1.6, # Proline
'S': -0.8, # Serine
'T': -0.7, # Threonine
'W': -0.9, # Tryptophan
'Y': -1.3, # Tyrosine
'V': 4.2 # Valine
}
def is_dna(sequence):
"""Check if the sequence is DNA."""
return all(base in {'A', 'T', 'C', 'G'} for base in sequence.upper())
def is_rna(sequence):
"""Check if the sequence is RNA."""
return all(base in {'A', 'U', 'C', 'G'} for base in sequence.upper())
def is_protein(sequence):
"""Check if the sequence is a protein."""
return all(base in {'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V'} for base in sequence.upper())
def is_mrna(sequence):
"""Check if the sequence is mRNA."""
return is_rna(sequence) # mRNA is a type of RNA
def is_trna(sequence):
"""Check if the sequence is tRNA."""
return is_rna(sequence) # tRNA is also a type of RNA
def is_rrna(sequence):
"""Check if the sequence is rRNA."""
return is_rna(sequence) # rRNA is also a type of RNA
def is_noncoding_rna(sequence):
"""Check if the sequence is non-coding RNA."""
return is_rna(sequence) # Non-coding RNA is also a type of RNA
def is_genomic_dna(sequence):
"""Check if the sequence is genomic DNA."""
return is_dna(sequence) # Genomic DNA is a type of DNA
def is_plasmid_dna(sequence):
"""Check if the sequence is plasmid DNA."""
return is_dna(sequence) # Plasmid DNA is also a type of DNA
def is_viral_sequence(sequence):
"""Check if the sequence is viral RNA or DNA."""
return is_dna(sequence) or is_rna(sequence) # Viral sequences can be DNA or RNA
def is_synthetic_sequence(sequence):
"""Determine if sequence shows synthetic characteristics."""
gc = calculate_gc_content(sequence)
complexity = sequence_complexity(sequence)
return {
'gc_content': gc,
'optimal_gc': abs(gc - 50) < 10, # Within 10% of optimal 50%
'complexity': complexity,
'high_complexity': complexity > 0.6
}
def analyze_codon_bias(sequence):
"""Analyze codon usage bias in the sequence."""
if len(sequence) < 3:
return 0.0
# Get all codons
codons = [sequence[i:i+3] for i in range(0, len(sequence)-2, 3)]
# Count codon frequencies
codon_freq = Counter(codons)
# Calculate bias score (simplified version)
total_codons = len(codons)
max_freq = max(codon_freq.values())
bias_score = max_freq / total_codons
return bias_score
def sequence_complexity(sequence):
"""Calculate sequence complexity score."""
if not sequence:
return 0
k = 3 # Use trinucleotide frequency
kmers = {}
for i in range(len(sequence) - k + 1):
kmer = sequence[i:i+k]
kmers[kmer] = kmers.get(kmer, 0) + 1
total_kmers = len(sequence) - k + 1
complexity = len(kmers) / (4**k) # Normalize by possible kmers
return round(complexity, 3)
def is_repetitive_sequence(sequence):
"""Check if the sequence contains repetitive elements."""
repeat_pattern = r'(A{2,}|T{2,}|C{2,}|G{2,})'
return bool(re.search(repeat_pattern, sequence))
def is_chimeric_sequence(sequence):
"""Detect chimeric sequences by analyzing sequence composition."""
window_size = 100
if len(sequence) < window_size * 2:
return False
# Analyze GC content in windows
gc_windows = []
for i in range(0, len(sequence) - window_size, window_size):
window = sequence[i:i+window_size]
gc_windows.append(gc_content(window))
# Calculate standard deviation of GC content
gc_std = np.std(gc_windows)
# Check for sudden composition changes
composition_shifts = []
for i in range(1, len(gc_windows)):
diff = abs(gc_windows[i] - gc_windows[i-1])
composition_shifts.append(diff)
# Criteria for chimeric sequence
max_shift = max(composition_shifts) if composition_shifts else 0
return gc_std > 10 and max_shift > 20 # Significant composition changes
def determine_sequence_type(sequence):
"""Determine the type of the sequence."""
sequence_types = []
if is_dna(sequence):
sequence_types.append("DNA")
if is_synthetic_sequence(sequence): # Now returns list of indicators
sequence_types.append("Synthetic")
elif is_rna(sequence):
sequence_types.append("RNA")
elif is_protein(sequence):
sequence_types.append("Protein")
return " + ".join(sequence_types) if sequence_types else "Unknown"
def determine_sequence_type_detailed(sequence):
"""Enhanced sequence type detection."""
sequence = sequence.upper()
if is_dna(sequence):
return "DNA"
elif is_rna(sequence):
return "RNA"
elif is_protein(sequence):
return "Protein"
else:
return "Unknown"
def get_embeddings(sequence):
"""Generate embeddings for a sequence."""
if tokenizer is None or model is None:
raise ValueError("GDDA not available - embeddings cannot be generated")
tokens = tokenizer(sequence, return_tensors="pt", padding=True, truncation=True)
with torch.no_grad():
outputs = model(**tokens, output_hidden_states=True)
embeddings = outputs['hidden_states'][-1].detach().numpy()
return embeddings
def reverse_complement(sequence):
"""Return the reverse complement of a DNA sequence."""
if not is_dna(sequence):
raise ValueError("Input sequence must be DNA.")
complement = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}
sequence = sequence.upper()
return ''.join(complement[base] for base in reversed(sequence))
def gc_content(sequence):
if not is_dna(sequence):
raise ValueError("Input sequence must be DNA.")
g_count = sequence.count('G')
c_count = sequence.count('C')
return (g_count + c_count) / len(sequence) * 100
def transcribe(sequence):
if not is_dna(sequence):
raise ValueError("Input sequence must be DNA.")
return sequence.replace('T', 'U')
def translate(rna_sequence):
"""Translate an RNA sequence into a protein sequence."""
if not is_rna(rna_sequence):
return "Error: The sequence must be RNA."
if len(rna_sequence) % 3 != 0:
return "Error: The length of the RNA sequence must be a multiple of three."
codon_table = {
'AUG': 'M', 'UUU': 'F', 'UUC': 'F', 'UUA': 'L', 'UUG': 'L',
'UCU': 'S', 'UCC': 'S', 'UCA': 'S', 'UCG': 'S', 'UAU': 'Y',
'UAC': 'Y', 'UGU': 'C', 'UGC': 'C', 'UGG': 'W', 'UAA': '',
'UAG': '', 'UGA': '', 'CUU': 'L', 'CUC': 'L', 'CUA': 'L',
'CUG': 'L', 'CCU': 'P', 'CCC': 'P', 'CCA': 'P', 'CCG': 'P',
'CAU': 'H', 'CAC': 'H', 'CAA': 'Q', 'CAG': 'Q', 'CGU': 'R',
'CGC': 'R', 'CGA': 'R', 'CGG': 'R', 'AUU': 'I', 'AUC': 'I',
'AUA': 'I', 'AUG': 'M', 'ACU': 'T', 'ACC': 'T', 'ACA': 'T',
'ACG': 'T', 'AAU': 'N', 'AAC': 'N', 'AAA': 'K', 'AAG': 'K',
'AGU': 'S', 'AGC': 'S', 'AGA': 'R', 'AGG': 'R', 'GUU': 'V',
'GUC': 'V', 'GUA': 'V', 'GUG': 'V', 'GCU': 'A', 'GCC': 'A',
'GCA': 'A', 'GCG': 'A', 'GAU': 'D', 'GAC': 'D', 'GAA': 'E',
'GAG': 'E', 'GGU': 'G', 'GGC': 'G', 'GGA': 'G', 'GGG': 'G'
}
protein = []
for i in range(0, len(rna_sequence), 3): # Process complete codons
codon = rna_sequence[i:i+3]
protein.append(codon_table.get(codon, '')) # Append empty string for invalid codons
return ''.join(protein)
def compare_sequences(seq1, seq2):
"""Compare two DNA sequences and return similarity percentage."""
if not is_dna(seq1) or not is_dna(seq2):
raise ValueError("Both sequences must be DNA.")
matches = sum(1 for a, b in zip(seq1, seq2) if a == b)
return (matches / max(len(seq1), len(seq2))) * 100
def detect_mutations(reference, test):
"""Identify mutations in a test sequence compared to a reference."""
if not is_dna(reference) or not is_dna(test):
raise ValueError("Both sequences must be DNA.")
mutations = []
mutation_types = {
'substitutions': [],
'insertions': [],
'deletions': [],
'inversions': []
}
# Align sequences using local alignment
alignments = pairwise2.align.localxx(reference, test)
if not alignments:
return mutations
for alignment in alignments:
ref_aligned, test_aligned, score, start, end = alignment
for i, (ref_base, test_base) in enumerate(zip(ref_aligned, test_aligned)):
if ref_base != test_base:
if ref_base == '-':
mutation_types['insertions'].append((i, test_base))
elif test_base == '-':
mutation_types['deletions'].append((i, ref_base))
else:
mutation_types['substitutions'].append((i, ref_base, test_base))
# Detect inversions
for i in range(len(reference)):
for j in range(i + 4, len(reference)): # Min 4 bases for inversion
ref_segment = reference[i:j]
test_segment = test[i:j]
if ref_segment == reverse_complement(test_segment):
mutation_types['inversions'].append((i, j, ref_segment))
return mutation_types
def timeout(seconds):
"""Decorator to add timeout to a function"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(func, *args, **kwargs)
try:
return future.result(timeout=seconds)
except TimeoutError:
raise TimeoutError(f"Operation timed out after {seconds} seconds")
return wrapper
return decorator
@timeout(90)
def find_homologous_sequences(sequence, e_value_thresh=10.0):
"""Find homologous sequences using NCBI BLAST with timeout."""
if not is_dna(sequence):
raise ValueError("Input sequence must be DNA.")
try:
ncbi_email = os.getenv('NCBI_EMAIL')
if not ncbi_email:
raise ValueError("NCBI_EMAIL not found in environment variables")
Entrez.email = ncbi_email
# First convert sequence to FASTA format
fasta_sequence = f">query\n{sequence}"
result_handle = NCBIWWW.qblast(
"blastn",
"nt",
fasta_sequence,
expect=e_value_thresh,
hitlist_size=5 # Reduced for faster response
)
blast_records = NCBIXML.parse(result_handle)
homologous_sequences = []
for blast_record in blast_records:
for alignment in blast_record.alignments[:5]: # Limit to top 5 matches
for hsp in alignment.hsps:
homologous_sequences.append({
'title': alignment.title,
'length': alignment.length,
'e_value': hsp.expect,
'identity_percent': (hsp.identities / hsp.align_length) * 100,
'score': hsp.score # This is the bit score
})
break # Only take first HSP per alignment
return homologous_sequences
except Exception as e:
print(f"BLAST search error: {str(e)}")
return []
def kmer_analysis(sequence, k):
"""Analyze the frequency of k-mers in a DNA sequence."""
if not is_dna(sequence):
raise ValueError("Input sequence must be DNA.")
kmer_counts = {}
for i in range(len(sequence) - k + 1):
kmer = sequence[i:i+k]
kmer_counts[kmer] = kmer_counts.get(kmer, 0) + 1
return kmer_counts
@timeout(90)
def check_patents_and_papers(sequence):
"""Check patents and papers with timeout."""
try:
results = {
'patents': [],
'papers': [],
'databases': []
}
# Use correct database names
Entrez.email = os.getenv('NCBI_EMAIL')
# 1. Check Nucleotide Database for Patents
try:
handle = Entrez.esearch(
db="nuccore",
term=f"{sequence} AND patent[PROP]",
retmax=5
)
record = Entrez.read(handle)
if record["Count"] != "0":
results['patents'].append({
'message': f"Found {record['Count']} potential patent matches",
'ids': record['IdList']
})
except Exception as e:
print(f"Warning: Patent search in nuccore failed: {str(e)}")
# 2. Check PubMed for Research Papers
try:
handle = Entrez.esearch(
db="pubmed",
term=sequence,
retmax=5
)
record = Entrez.read(handle)
if record["Count"] != "0":
results['papers'].append({
'message': f"Found {record['Count']} related papers",
'ids': record['IdList']
})
except Exception as e:
print(f"Warning: Paper search failed: {str(e)}")
# 3. Check GenBank Database
try:
handle = Entrez.esearch(
db="nucleotide",
term=sequence,
retmax=5
)
record = Entrez.read(handle)
if record["Count"] != "0":
results['databases'].append({
'message': f"Found {record['Count']} database entries",
'ids': record['IdList']
})
except Exception as e:
print(f"Warning: Database search failed: {str(e)}")
return results
except Exception as e:
return {
'error': f"Search failed: {str(e)}",
'patents': [],
'papers': [],
'databases': []
}
def detect_anomalies(sequence, reference_sequence=None):
"""Detect anomalies in a DNA sequence."""
if not is_dna(sequence):
raise ValueError("Input sequence must be DNA.")
# Check for unusual base composition
base_counts = Counter(sequence)
total_bases = len(sequence)
# Calculate percentages of each base
base_percentages = {base: (count / total_bases) * 100 for base, count in base_counts.items()}
# Define thresholds for unusual base composition
unusual_threshold = 10 # Example threshold for base composition
anomalies = []
for base, percentage in base_percentages.items():
if percentage < unusual_threshold or percentage > (100 - unusual_threshold):
anomalies.append(f"Unusual base composition: {base} at {percentage:.2f}%")
# Check for repetitive sequences
repeat_pattern = r'(A{2,}|T{2,}|C{2,}|G{2,})' # Adjust the pattern for different repeats
repeats = re.findall(repeat_pattern, sequence)
if repeats:
anomalies.append(f"Repetitive sequences detected: {', '.join(set(repeats))}")
# Check for mutations against a reference sequence if provided
if reference_sequence:
mutations = detect_mutations(reference_sequence, sequence)
if mutations:
anomalies.append(f"Mutations detected: {mutations}")
if not anomalies:
return "No anomalies detected."
return "\n".join(anomalies)
def phylogenetic_analysis(sequences):
"""Perform phylogenetic analysis on a list of DNA sequences."""
# Create a Multiple Sequence Alignment
alignment = MultipleSeqAlignment([SeqIO.SeqRecord(Seq(seq), id=f"Seq{i+1}") for i, seq in enumerate(sequences)])
# Use a simple distance matrix method (e.g., UPGMA) to create a phylogenetic tree
distance_matrix = Phylo.distance.pdist(alignment, metric='identity')
tree = Phylo.upgma(distance_matrix)
# Print the tree in Newick format
newick_format = Phylo.write(tree, StringIO(), format='newick')
return f"Phylogenetic analysis complete. Tree in Newick format:\n{newick_format}"
def generate_report(sequence, results, homologous_sequences, patent_paper_check):
"""Generate comprehensive DNA analysis report."""
import textwrap
# Helper function for consistent section headers
def section_header(title, width=80):
return f"\n{Fore.CYAN}╔{'═' * (width-2)}╗\n║ {Fore.GREEN}{title:<{width-4}}{Fore.CYAN}║\n╚{'═' * (width-2)}╝{Style.RESET_ALL}\n"
# Helper function for subsection headers
def subsection_header(title, width=80):
return f"\n{Fore.BLUE}▓▓▓ {Fore.LIGHTMAGENTA_EX}{title} {Fore.BLUE}{'▓' * (width - len(title) - 5)}{Style.RESET_ALL}\n"
# Helper function for data display
def data_row(label, value, width=80):
return f"{Fore.CYAN}│ {Fore.LIGHTWHITE_EX}{label}: {Fore.YELLOW}{value}{Style.RESET_ALL}"
# Helper function for wrapping text
def wrap_text(text, width=80, indent=4):
wrapped = textwrap.fill(text, width=width-indent)
return textwrap.indent(wrapped, ' ' * indent)
# Helper function for info messages
def print_info(text):
return f"{Fore.LIGHTBLUE_EX}ℹ {text}{Style.RESET_ALL}"
# Helper function for warning messages
def print_warning(text):
return f"{Fore.YELLOW}⚠ {text}{Style.RESET_ALL}"
# Start building the report
report = [
f"\n{Fore.CYAN}",
f"{Fore.LIGHTMAGENTA_EX}█▀ █ █ █▄▄ ▄▀█ ▀█▀ █▀█ █▀▄▀█ █ █▀▀",
f"{Fore.LIGHTMAGENTA_EX}▄█ █▄█ █▄█ █▀█ █ █▄█ █ ▀ █ █ █▄▄",
f"{Fore.CYAN}",
f"{Fore.LIGHTMAGENTA_EX}█ █▄ █ █ █ █▀▀ █▀ ▀█▀ █ █▀▀ ▄▀█ ▀█▀ █ █▀█ █▄ █",
f"{Fore.MAGENTA}█ █ ▀█ ▀▄▀ ██▄ ▄█ █ █ █▄█ █▀█ █ █ █▄█ █ ▀█",
f"{Fore.CYAN}",
f"{Fore.MAGENTA}█▀▀ █▄ █ █▀▀ █ █▄ █ █▀▀",
f"{Fore.LIGHTMAGENTA_EX}██▄ █ ▀█ ██ █ █ ▀█ ██▄",
f"{Fore.CYAN}{'═' * 100}{Style.RESET_ALL}",
f"{Fore.LIGHTCYAN_EX}GDDA v0.21 XP - Genetic Due Diligence Micro-Agent, by MicroNOW, an ARPA Corporation subsidiary.{Style.RESET_ALL}\n",
]
# Add comprehensive analysis results
if results.get('basic_analysis'):
report.append(section_header("SEQUENCE ANALYSIS"))
basic = results['basic_analysis']
report.append(data_row("Sequence Type", basic.get('sequence_type', 'Unknown')))
report.append(data_row("Length", basic.get('length', 0)))
report.append(data_row("GC Content", f"{basic.get('gc_content', 0):.2f}%"))
# Add structure analysis if available
if results.get('structure_analysis'):
report.append(section_header("STRUCTURAL FEATURES"))
struct = results['structure_analysis']
report.append(data_row("Melting Temperature", f"{struct.get('melting_temp', 0)}°C"))
# Add motifs
if struct.get('motifs'):
report.append(subsection_header("DNA MOTIFS"))
for motif in struct['motifs']:
report.append(f"{Fore.CYAN}■ {motif['description']} at position(s): {', '.join(map(str, motif['positions']))}{Style.RESET_ALL}")
# Sequence Display (with wrapping)
report.append(subsection_header("RAW SEQUENCE"))
report.append(wrap_text(sequence))
# Transformations Section
report.append(section_header("SEQUENCE TRANSFORMATIONS"))
report.append(data_row("Reverse Complement", results['reverse_complement']))
report.append(data_row("Transcription", results['transcription']))
report.append(data_row("Translation", results['translation']))
# Anomaly Analysis
report.append(section_header("ANOMALY ANALYSIS"))
if isinstance(results['anomalies'], str):
report.append(wrap_text(results['anomalies']))
else:
for anomaly in results['anomalies']:
report.append(f"{Fore.RED}■ {Fore.LIGHTWHITE_EX}{anomaly}{Style.RESET_ALL}")
# K-mer Analysis
report.append(section_header("K-MER FREQUENCY ANALYSIS"))
kmer_data = results.get('kmer_analysis', {})
if kmer_data:
# Sort k-mers by frequency (descending) and alphabetically for same frequency
sorted_kmers = sorted(kmer_data.items(), key=lambda x: (-x[1], x[0]))
for kmer, count in sorted_kmers:
report.append(f"{Fore.CYAN}{kmer}: {Fore.YELLOW}{'█' * count} {Fore.CYAN}({count}){Style.RESET_ALL}")
# Enhanced Homology Section
report.append(section_header("HOMOLOGY ANALYSIS"))
if homologous_sequences:
report.append(f"{Fore.YELLOW}Found {len(homologous_sequences)} significant matches:{Style.RESET_ALL}\n")
# Add our new cyberpunk visualization
report.append(display_homology_results(sequence, homologous_sequences))
else:
report.append(print_info("No significant homologous sequences found"))
# Patents and Papers Section
report.append(section_header("INTELLECTUAL PROPERTY & LITERATURE SEARCH"))
if patent_paper_check.get('error'):
report.append(print_warning(patent_paper_check['error']))
else:
# Patents
if patent_paper_check['patents']:
report.append(subsection_header("PATENT MATCHES"))
for patent in patent_paper_check['patents']:
report.append(f"{Fore.CYAN}{patent['message']}")
if 'ids' in patent:
report.append(f"{Fore.YELLOW}IDs: {', '.join(patent['ids'])}\n")
else:
report.append(print_info("No patent matches found"))
# Research Papers
if patent_paper_check['papers']:
report.append(subsection_header("RESEARCH PAPERS"))
for paper in patent_paper_check['papers']:
report.append(f"{Fore.CYAN}{paper['message']}")
if 'ids' in paper:
report.append(f"{Fore.YELLOW}IDs: {', '.join(paper['ids'])}\n")
else:
report.append(print_info("No research papers found"))
# Database Entries
if patent_paper_check['databases']:
report.append(subsection_header("DATABASE ENTRIES"))
for entry in patent_paper_check['databases']:
report.append(f"{Fore.CYAN}{entry['message']}")
if 'ids' in entry:
report.append(f"{Fore.YELLOW}IDs: {', '.join(entry['ids'])}\n")
else:
report.append(print_info("No database entries found"))
# Report Footer
report.append(f"\n{Fore.CYAN}{'═' * 80}")
report.append(f"{Fore.LIGHTGREEN_EX}Analysis Complete! {Fore.BLUE}Generated: {Fore.LIGHTWHITE_EX}{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report.append(f"{Fore.CYAN}{'═' * 80}{Style.RESET_ALL}\n")
return '\n'.join(report)
def generate_random_dna(length=33):
"""Generate a random DNA sequence of specified length."""
bases = ['A', 'T', 'C', 'G']
return ''.join(random.choice(bases) for _ in range(length))
def generate_random_rna(length=33):
"""Generate a random RNA sequence of specified length."""
bases = ['A', 'U', 'C', 'G']
return ''.join(random.choice(bases) for _ in range(length))
def generate_random_protein(length=20):
"""Generate a random protein sequence of specified length."""
amino_acids = ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y']
return ''.join(random.choice(amino_acids) for _ in range(length))
def handle_dna_command(command):
"""
Enhanced handler for DNA/RNA/Protein analysis commands with improved error handling.
"""
from datetime import datetime
from colorama import Fore, Style, init
init() # Initialize colorama
def print_error(message):
return f"{Fore.RED}ERROR: {message}{Style.RESET_ALL}"
def print_warning(message):
return f"{Fore.YELLOW}WARNING: {message}{Style.RESET_ALL}"
def print_info(message):
return f"{Fore.CYAN}INFO: {message}{Style.RESET_ALL}"
# Parse command
parts = command.split()
# Basic command validation
if len(parts) < 2:
return print_error("Invalid command format. Usage: /dna <sequence> or /dna <subcommand> <sequence>")
# Extract sequence and subcommand
if parts[0].lower() != "/dna":
return print_error("Command must start with '/dna'")
# Handle different command formats
if len(parts) == 2:
sequence = parts[1].strip()
subcommand = "report" # Default to report
else:
subcommand = parts[1].lower()
sequence = ' '.join(parts[2:]).strip()
# Validate sequence
if not sequence:
return print_error("No sequence provided")
# Basic sequence validation
sequence = sequence.upper() # Convert to uppercase for consistency
try:
# Command processing with error handling
if subcommand == "report":
# Determine sequence type
seq_type = determine_sequence_type_detailed(sequence)
if seq_type == "DNA":
try:
print_info("Analyzing DNA sequence...")
results = {
'type': determine_sequence_type(sequence),
'gc_content': calculate_gc_content(sequence),
'reverse_complement': reverse_complement(sequence),
'transcription': transcribe(sequence),
'translation': translate(transcribe(sequence)),
'anomalies': detect_anomalies(sequence),
'kmer_analysis': kmer_analysis(sequence, 3),
'complexity': sequence_complexity(sequence),
'synthetic_indicators': is_synthetic_sequence(sequence)
}
try:
homologous_sequences = find_homologous_sequences(sequence)
except Exception as e:
print_warning(f"Homology search failed: {str(e)}")
homologous_sequences = []
try:
patent_check = check_patents_and_papers(sequence)
except Exception as e:
print_warning(f"Patent check failed: {str(e)}")
patent_check = "Patent check unavailable"
return generate_report(sequence, results, homologous_sequences, patent_check)
except Exception as e:
return print_error(f"DNA analysis failed: {str(e)}")
elif seq_type == "RNA":
try:
print_info("Analyzing RNA sequence...")
results = {
'type': 'RNA',
'basic_properties': {
'length': len(sequence),
'gc_content': (sequence.count('G') + sequence.count('C')) / len(sequence) * 100,
'base_composition': dict(Counter(sequence))
},
'targeting_analysis': analyze_rna_targeting_potential(sequence),
'structure_prediction': predict_rna_secondary_structure(sequence),
'regulatory_elements': analyze_regulatory_elements(sequence),
'motifs': find_rna_motifs(sequence)
}
return generate_rna_report(sequence, results)
except Exception as e:
return print_error(f"RNA analysis failed: {str(e)}")
elif seq_type == "Protein":
try:
print_info("Analyzing protein sequence...")
results = analyze_protein_sequence(sequence)
return generate_protein_report(sequence, results)
except Exception as e:
return print_error(f"Protein analysis failed: {str(e)}")
else:
return print_error("Invalid sequence. Must be DNA, RNA, or protein sequence.")
# Handle existing DNA-specific commands
elif subcommand in ["revcom", "gc_content", "transcribe", "compare", "kmer", "anomalies"]:
if not is_dna(sequence):
return print_error(f"Invalid DNA sequence for {subcommand}")
# Execute existing DNA command handlers
if subcommand == "revcom":
return print_info(f"Reverse complement: {reverse_complement(sequence)}")
elif subcommand == "gc_content":
return print_info(f"GC Content: {calculate_gc_content(sequence):.2f}%")
elif subcommand == "transcribe":
return print_info(f"RNA sequence: {transcribe(sequence)}")
elif subcommand == "compare":
if len(parts) < 4:
return print_error("Missing second sequence for comparison")
seq2 = parts[3].upper()
if not is_dna(seq2):
return print_error("Both sequences must be valid DNA")
similarity = compare_sequences(sequence, seq2)
return print_info(f"Sequence similarity: {similarity:.2f}%")
elif subcommand == "kmer":
k = 3 # Default k value
if len(parts) > 3 and parts[3].isdigit():
k = int(parts[3])
if k < 1 or k > len(sequence):
return print_error(f"Invalid k value: {k}")
kmer_counts = kmer_analysis(sequence, k)
result = [f"{Fore.CYAN}K-mer Analysis (k={k}){Style.RESET_ALL}"]
for kmer, count in sorted(kmer_counts.items(), key=lambda x: (-x[1], x[0])):
result.append(f"{Fore.LIGHTWHITE_EX}{kmer}: {Fore.YELLOW}{count}{Style.RESET_ALL}")
return "\n".join(result)
elif subcommand == "anomalies":
anomalies = detect_anomalies(sequence)
return print_info(f"Anomalies detected:\n{anomalies}")
# Handle embeddings command (works for all sequence types)
elif subcommand == "embeddings":
try:
embeddings = get_embeddings(sequence)
return print_info(f"Embeddings shape: {embeddings.shape}\nFirst few values: {embeddings[0][:5]}")
except Exception as e:
return print_error(f"Embedding generation failed: {str(e)}")
# Handle translate command (works for both DNA and RNA)
elif subcommand == "translate":
if not is_rna(sequence):
if is_dna(sequence):
sequence = transcribe(sequence)
else:
return print_error("Invalid sequence for translation. Must be RNA or DNA.")
result = translate(sequence)
return print_info(f"Protein sequence: {result}")
# Handle random sequence generation
elif subcommand == "random":
try:
parts = command.split()[2:] # Get parts after "/dna random"
length = 33 # Default length
seq_type = "dna" # Default type
if not parts: # Just "/dna random"
random_seq = generate_random_dna(length)
return f"{Fore.CYAN}Random DNA Sequence ({length} bp):{Style.RESET_ALL}\n{Fore.YELLOW}{random_seq}{Style.RESET_ALL}"
if parts[0].lower() in ["dna", "rna", "protein"]:
seq_type = parts[0].lower()
if len(parts) > 1 and parts[1].isdigit():
length = int(parts[1])
elif parts[0].isdigit():
length = int(parts[0])
seq_type = "dna" # Explicit DNA for number-only case
if length < 1:
return print_error("Length must be positive")
if length > 10000:
return print_error("Length too large. Maximum is 10000 bases")
if seq_type == "dna":
random_seq = generate_random_dna(length)
type_str = "DNA"
unit = "bp"
elif seq_type == "rna":
random_seq = generate_random_rna(length)
type_str = "RNA"
unit = "bp"
else: # protein
random_seq = generate_random_protein(length)
type_str = "Protein"
unit = "aa"
return f"{Fore.CYAN}Random {type_str} Sequence ({length} {unit}):{Style.RESET_ALL}\n{Fore.YELLOW}{random_seq}{Style.RESET_ALL}"
except Exception as e:
return print_error(f"Failed to generate random sequence: {str(e)}")
# Handle help command
elif subcommand == "help":
help_msg = f"""
{Fore.CYAN}Sequence Analysis Tool Commands:{Style.RESET_ALL}
{Fore.YELLOW}/dna <sequence>{Style.RESET_ALL} - Generate full analysis report (DNA/RNA/Protein)
{Fore.YELLOW}/dna revcom <sequence>{Style.RESET_ALL} - Get reverse complement (DNA only)
{Fore.YELLOW}/dna gc <sequence>{Style.RESET_ALL} - Calculate GC content (DNA only)
{Fore.YELLOW}/dna transcribe <sequence>{Style.RESET_ALL} - Transcribe DNA to RNA
{Fore.YELLOW}/dna translate <sequence>{Style.RESET_ALL} - Translate RNA/DNA to protein
{Fore.YELLOW}/dna compare <seq1> <seq2>{Style.RESET_ALL} - Compare two sequences (DNA only)
{Fore.YELLOW}/dna kmer <sequence> [k]{Style.RESET_ALL} - Perform k-mer analysis (DNA only)
{Fore.YELLOW}/dna anomalies <sequence>{Style.RESET_ALL} - Detect sequence anomalies (DNA only)
{Fore.YELLOW}/dna embeddings <sequence>{Style.RESET_ALL} - Generate sequence embeddings
{Fore.YELLOW}/dna random dna [length]{Style.RESET_ALL} - Generate random DNA sequence
{Fore.YELLOW}/dna random rna [length]{Style.RESET_ALL} - Generate random RNA sequence
{Fore.YELLOW}/dna random protein [length]{Style.RESET_ALL} - Generate random protein sequence
"""
return help_msg
else:
return print_error(f"Unknown subcommand: {subcommand}. Use '/dna help' for available commands.")
except Exception as e:
return print_error(f"An unexpected error occurred: {str(e)}")
def determine_sequence_type_detailed(sequence):
"""Enhanced sequence type detection."""
sequence = sequence.upper()
if is_dna(sequence):
return "DNA"
elif is_rna(sequence):
return "RNA"
elif is_protein(sequence):
return "Protein"
else:
return "Unknown"
def calculate_mirna_score(target_region, seed_sequence):
"""
Calculate miRNA targeting score based on multiple factors:
1. Seed match type
2. Site accessibility
3. AU content in surrounding region
4. Position in 3' UTR (if applicable)
5. Base pairing stability
"""
score = 0.0
# Perfect seed match (positions 2-7)
if complementary_match(target_region[1:7], seed_sequence[1:7]):
score += 3.0
# Extended seed match (position 8)
if len(target_region) >= 8 and len(seed_sequence) >= 8:
if complementary_match(target_region[7], seed_sequence[7]):
score += 0.5
# Check for A at position 1
if target_region[0] == 'A':
score += 0.3
# Calculate AU content in surrounding region (30 nt window)
au_content = (target_region.count('A') + target_region.count('U')) / len(target_region)
score += au_content * 0.5
# Calculate base pairing stability using RNA.fold
try:
hybrid = RNA.duplexfold(target_region, seed_sequence)
mfe = abs(hybrid.energy)
# Normalize MFE contribution (typical range -5 to -15 kcal/mol)
score += min(mfe / 15.0, 1.0)
except Exception:
# Fallback if ViennaRNA fails
gc_content = (target_region.count('G') + target_region.count('C')) / len(target_region)
score += (1 - gc_content) * 0.5
# Normalize final score to 0-1 range
return min(score / 5.0, 1.0)
def analyze_rna_targeting_potential(sequence):
"""Analyze RNA targeting potential using real miRNA data and RNA folding."""
targeting_results = {
'mirna_sites': [],
'sirna_regions': [],
'accessibility_scores': [],
'targeting_score': 0.0
}
try:
# siRNA analysis
for i in range(len(sequence)-18):
region = sequence[i:i+19]
fold = RNA.fold_compound(region)
(mfe_struct, mfe) = fold.mfe()
if is_good_sirna_candidate(region): # Only pass sequence
targeting_results['sirna_regions'].append({
'position': i,