-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3201 lines (2759 loc) · 201 KB
/
app.py
File metadata and controls
3201 lines (2759 loc) · 201 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 streamlit as st
import google.generativeai as genai
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import random
import string
import re
import time
from datetime import datetime
import hashlib
import json
import io
import base64
# Imports for practical CONF tab tools
from scipy.stats import entropy
from statsmodels.tsa.stattools import acf
# Configure page
st.set_page_config(
layout="wide",
page_title="AlphaFold - Protein Structure Prediction Suite",
page_icon="🧬",
initial_sidebar_state="expanded"
)
# Custom CSS for professional styling
st.markdown("""
<style>
.main-header {
background: linear-gradient(90deg, #1e3c72 0%, #2a5298 100%);
padding: 2rem;
border-radius: 10px;
margin-bottom: 2rem;
color: white;
text-align: center;
}
.metric-card { /* Changed background to a darker shade */
background: #2c3e50; /* Dark blue-gray */
padding: 1rem;
border-radius: 8px;
border-left: 4px solid #2a5298;
margin: 0.5rem 0;
}
.prediction-status {
padding: 0.5rem 1rem;
border-radius: 20px;
font-weight: bold;
text-align: center;
margin: 1rem 0;
}
.status-running { /* Darker yellow/orange */
background: #4A3B00; /* Dark yellow */
color: #FFD700; /* Brighter yellow text */
}
.status-complete { /* Darker green */
background: #1A3A1F; /* Dark green */
color: #A8D5BA; /* Lighter green text */
}
.status-error { /* Darker red */
background: #4C1C24; /* Dark red */
color: #F5C6CB; /* Lighter red text */
}
.metric-card h4, .metric-card h2 { /* Ensure text in metric cards is light */
color: #ecf0f1;
}
.confidence-high { color: #28a745; font-weight: bold; }
.confidence-medium { color: #ffc107; font-weight: bold; }
.confidence-low { color: #dc3545; font-weight: bold; }
</style>
""", unsafe_allow_html=True)
# Constants
AMINO_ACIDS = "ACDEFGHIKLMNPQRSTVWY"
SECONDARY_STRUCTURES = ["Helix", "Sheet", "Coil", "Turn"]
CONFIDENCE_LEVELS = ["Very High (>90)", "High (70-90)", "Medium (50-70)", "Low (<50)"]
# Initialize session state
if 'prediction_history' not in st.session_state:
st.session_state.prediction_history = []
if 'current_prediction' not in st.session_state:
st.session_state.current_prediction = None
if 'analysis_cache' not in st.session_state:
st.session_state.analysis_cache = {}
def generate_protein_sequence(length=None, complexity="medium"):
"""Generate realistic protein sequences based on complexity."""
if length is None:
length = random.randint(50, 300) if complexity == "medium" else random.randint(300, 800)
# Realistic amino acid frequency distribution
aa_weights = {
'A': 8.25, 'R': 5.53, 'N': 4.06, 'D': 5.45, 'C': 1.37,
'Q': 3.93, 'E': 6.75, 'G': 7.07, 'H': 2.27, 'I': 5.96,
'L': 9.66, 'K': 5.84, 'M': 2.42, 'F': 3.86, 'P': 4.70,
'S': 6.56, 'T': 5.34, 'W': 1.08, 'Y': 2.92, 'V': 6.87
}
amino_acids = list(aa_weights.keys())
weights = list(aa_weights.values())
sequence = ''.join(np.random.choice(amino_acids, size=length, p=np.array(weights)/sum(weights)))
protein_id = f"PROT_{random.randint(10000, 99999)}"
return f">{protein_id}\n{sequence}"
def validate_protein_sequence(sequence):
"""Validate protein sequence format and content."""
lines = sequence.strip().split('\n')
if not sequence.strip():
return False, "Empty sequence"
# Check FASTA format
if sequence.startswith('>'):
if len(lines) < 2:
return False, "Invalid FASTA format: missing sequence"
seq_lines = lines[1:]
else:
seq_lines = lines
# Combine sequence lines
seq = ''.join(seq_lines).upper().replace(' ', '').replace('\t', '')
# Validate amino acids
invalid_chars = set(seq) - set(AMINO_ACIDS)
if invalid_chars:
return False, f"Invalid amino acids found: {', '.join(invalid_chars)}"
if len(seq) < 10:
return False, "Sequence too short (minimum 10 residues)"
if len(seq) > 2000:
return False, "Sequence too long (maximum 2000 residues)"
return True, seq
def generate_mock_predictions(sequence, model_name):
"""Generate comprehensive mock predictions."""
seq_len = len(sequence)
# Secondary structure prediction
ss_pred = np.random.choice(SECONDARY_STRUCTURES, size=seq_len,
p=[0.35, 0.25, 0.30, 0.10])
# Confidence scores
confidence = np.random.beta(3, 1, seq_len) * 100
# Disorder prediction
disorder_pred = np.random.random(seq_len) < 0.15
# pLDDT scores (AlphaFold confidence)
plddt = np.random.normal(75, 15, seq_len)
plddt = np.clip(plddt, 0, 100)
# Domain predictions
domains = []
if seq_len > 50:
n_domains = max(1, seq_len // 150)
for i in range(n_domains):
start = random.randint(i * (seq_len // n_domains),
min((i + 1) * (seq_len // n_domains), seq_len - 20))
end = min(start + random.randint(50, 100), seq_len)
domains.append({
'name': f'Domain_{i+1}',
'start': start,
'end': end,
'type': random.choice(['Enzymatic', 'Binding', 'Structural', 'Regulatory'])
})
return {
'sequence': sequence,
'length': seq_len,
'secondary_structure': ss_pred,
'confidence': confidence,
'disorder': disorder_pred,
'plddt': plddt,
'domains': domains,
'model_used': model_name,
'timestamp': datetime.now(),
'overall_confidence': np.mean(plddt)
}
def generate_mock_interaction_data(protein_id, num_interactions=5):
interactions = []
for i in range(num_interactions):
partner_type = random.choice(["Protein", "Ligand"])
if partner_type == "Protein":
partner_id = f"PROT_{random.randint(1000,9999)}"
interaction_detail = {"type": "PPI", "confidence": round(random.uniform(0.5, 0.99), 2)}
else:
partner_id = f"LIG_{''.join(random.choices(string.ascii_uppercase + string.digits, k=3))}"
interaction_detail = {"type": "Protein-Ligand", "affinity_nM": round(random.uniform(10, 5000), 1)}
interactions.append({
"partner_id": partner_id,
"details": interaction_detail
})
return interactions
def generate_mock_mutational_data(sequence_length, num_mutations=10):
mutations = []
for _ in range(num_mutations):
pos = random.randint(1, sequence_length)
original_aa = random.choice(AMINO_ACIDS)
mutated_aa = random.choice([aa for aa in AMINO_ACIDS if aa != original_aa])
ddg = round(random.uniform(-3.0, 3.0), 2)
effect = "Neutral"
if ddg > 1.0: effect = "Destabilizing"
elif ddg < -1.0: effect = "Stabilizing"
mutations.append({
"Mutation": f"{original_aa}{pos}{mutated_aa}",
"Predicted_ddG_kcal_mol": ddg,
"Predicted_Effect": effect,
"Tool": random.choice(["MockFoldX", "MockRosetta"])
})
return pd.DataFrame(mutations)
def generate_mock_protein_symmetry_data():
symmetry_type = random.choice(["None", "C2", "C3", "C4", "D2", "D3", "Icosahedral (mock)"])
if symmetry_type == "None":
return {"type": "None", "axis": "N/A", "confidence": 0.0}
return {
"type": symmetry_type,
"axis": random.choice(["X-axis", "Y-axis", "Z-axis", "Diagonal"]),
"confidence": round(random.uniform(0.6, 0.98), 2)
}
def generate_mock_coevolution_contacts(sequence_length, num_contacts_factor=0.02):
num_contacts = int(sequence_length * num_contacts_factor * random.uniform(0.5, 1.5))
contacts = []
if sequence_length < 5: return pd.DataFrame()
for _ in range(num_contacts):
res1, res2 = sorted(random.sample(range(1, sequence_length + 1), 2))
contacts.append({
"Residue_1": res1,
"Residue_2": res2,
"Coevolution_Score": round(random.uniform(0.3, 0.95), 3),
"Distance_Prediction_Mock_Angstrom": round(random.uniform(4.0, 15.0), 1)
})
return pd.DataFrame(contacts).sort_values(by="Coevolution_Score", ascending=False)
def generate_mock_structural_waters(num_waters_factor=0.1):
num_waters = int(random.uniform(5, 20) * num_waters_factor) # Simplified
waters = []
for i in range(num_waters):
waters.append({
"Water_ID": f"HOH_{i+1}",
"X_Coord_Mock": round(random.uniform(-20, 20), 2),
"Y_Coord_Mock": round(random.uniform(-20, 20), 2),
"Z_Coord_Mock": round(random.uniform(-20, 20), 2),
"B_Factor_Mock": round(random.uniform(10, 60), 1),
"Occupancy_Mock": round(random.uniform(0.8, 1.0), 2),
"Bridging_Residues_Mock": f"R{random.randint(1,50)}-D{random.randint(51,100)}" if random.random() > 0.5 else "None"
})
return pd.DataFrame(waters)
def generate_mock_ligand_pockets(sequence_length, num_pockets=3):
pockets = []
for i in range(num_pockets):
start_res = random.randint(1, sequence_length - 20)
pocket_residues = sorted(random.sample(range(start_res, min(start_res + 30, sequence_length)), random.randint(5,15)))
pockets.append({
"pocket_id": f"Pocket_{i+1}",
"residues": ", ".join(map(str, pocket_residues)),
"volume_A3": round(random.uniform(100, 1000), 1),
"druggability_score": round(random.uniform(0.1, 0.95), 2),
"target_ligand_type": random.choice(["Inhibitor", "Activator", "Cofactor", "Substrate"])
})
return pockets
def generate_mock_surface_properties(sequence_length):
properties = []
for i in range(sequence_length):
properties.append({
"residue_index": i + 1,
"hydrophobicity_kyte_doolittle": round(random.uniform(-4.5, 4.5), 2), # Kyte-Doolittle scale
"electrostatic_potential_mock": round(random.uniform(-5, 5), 2), # Mock potential
"solvent_accessibility_mock_percent": round(random.uniform(0, 100), 1)
})
return pd.DataFrame(properties)
def generate_mock_structural_comparison(num_hits=5):
hits = []
for i in range(num_hits):
hits.append({
"PDB_ID": f"{random.choice(string.digits)}{random.choice(string.ascii_uppercase)}{random.choice(string.ascii_uppercase)}{random.choice(string.ascii_uppercase)}",
"Chain": random.choice(["A", "B", ""]),
"RMSD_Angstrom": round(random.uniform(0.5, 5.0), 2),
"Sequence_Identity_Percent": round(random.uniform(20, 99), 1),
"Alignment_Score": random.randint(50, 500),
"Description": random.choice(["Kinase domain", "Receptor binding domain", "Hypothetical protein", "Enzyme active site"])
})
return pd.DataFrame(hits).sort_values(by="RMSD_Angstrom")
def generate_mock_quality_assessment(sequence_length):
ramachandran_favored = round(random.uniform(85, 98), 1)
ramachandran_allowed = round(random.uniform(1, 15 - (ramachandran_favored-85)), 1)
ramachandran_outlier = round(100 - ramachandran_favored - ramachandran_allowed, 1)
return {
"ramachandran_favored_percent": ramachandran_favored,
"ramachandran_allowed_percent": ramachandran_allowed,
"ramachandran_outliers_percent": ramachandran_outlier,
"clashscore": round(random.uniform(0, 20), 2), # Lower is better
"avg_bond_length_deviation_percent": round(random.uniform(0.1, 2.0), 2),
"avg_bond_angle_deviation_degrees": round(random.uniform(0.5, 5.0), 1),
"overall_gdt_ts_mock": round(random.uniform(50, 95), 1) # Global Distance Test
}
def generate_mock_allosteric_sites(sequence_length, num_sites=2):
sites = []
possible_site_types = ["Activator Binding", "Inhibitor Binding", "Modulatory Interface", "Cryptic Pocket"]
for i in range(num_sites):
start_res = random.randint(1, sequence_length - 15)
site_residues_indices = sorted(random.sample(range(start_res, min(start_res + 25, sequence_length)), random.randint(4,10)))
sites.append({
"site_id": f"AlloSite_{i+1}",
"residues": ", ".join(map(str, site_residues_indices)),
"prediction_score": round(random.uniform(0.3, 0.9), 2), # Higher is more likely
"pocket_volume_A3_mock": round(random.uniform(50, 500), 1),
"site_type_mock": random.choice(possible_site_types),
"avg_conservation_mock": round(random.uniform(0.2, 0.95), 2) # Mock conservation score for the site
})
return sites
def generate_mock_pore_profile(channel_length_residues=50):
# Simulate a pore along Z-axis, length in Angstroms
z_coords = np.linspace(0, channel_length_residues * 1.5, 50) # Approx 1.5A per residue length in helix
# Simulate a narrowing and widening pore
radius = 5 * np.sin(z_coords / (channel_length_residues*1.5/np.pi) * 2) + \
2 * np.cos(z_coords / (channel_length_residues*1.5/np.pi) * 5) + \
random.uniform(1.5, 4) # Base radius
radius = np.clip(radius, 0.5, 10) # Min/max radius
return pd.DataFrame({"Position_Angstrom": np.round(z_coords,1), "Radius_Angstrom": np.round(radius,1)})
def generate_mock_protein_symmetry_data():
symmetry_type = random.choice(["None", "C2", "C3", "C4", "D2", "D3", "Icosahedral (mock)"])
if symmetry_type == "None":
return {"type": "None", "axis": "N/A", "confidence": 0.0}
return {
"type": symmetry_type,
"axis": random.choice(["X-axis", "Y-axis", "Z-axis", "Diagonal"]),
"confidence": round(random.uniform(0.6, 0.98), 2)
}
def generate_mock_coevolution_contacts(sequence_length, num_contacts_factor=0.02):
num_contacts = int(sequence_length * num_contacts_factor * random.uniform(0.5, 1.5))
contacts = []
if sequence_length < 5: return pd.DataFrame()
for _ in range(num_contacts):
res1, res2 = sorted(random.sample(range(1, sequence_length + 1), 2))
contacts.append({
"Residue_1": res1,
"Residue_2": res2,
"Coevolution_Score": round(random.uniform(0.3, 0.95), 3),
"Distance_Prediction_Mock_Angstrom": round(random.uniform(4.0, 15.0), 1)
})
return pd.DataFrame(contacts).sort_values(by="Coevolution_Score", ascending=False)
def generate_mock_structural_waters(num_waters_factor=0.1):
num_waters = int(random.uniform(5, 20) * num_waters_factor) # Simplified
waters = []
for i in range(num_waters):
waters.append({
"Water_ID": f"HOH_{i+1}",
"X_Coord_Mock": round(random.uniform(-20, 20), 2),
"Y_Coord_Mock": round(random.uniform(-20, 20), 2),
"Z_Coord_Mock": round(random.uniform(-20, 20), 2),
"B_Factor_Mock": round(random.uniform(10, 60), 1),
"Occupancy_Mock": round(random.uniform(0.8, 1.0), 2),
"Bridging_Residues_Mock": f"R{random.randint(1,50)}-D{random.randint(51,100)}" if random.random() > 0.5 else "None"
})
return pd.DataFrame(waters)
def generate_mock_pore_profile(channel_length_residues=50):
# Simulate a pore along Z-axis, length in Angstroms
z_coords = np.linspace(0, channel_length_residues * 1.5, 50) # Approx 1.5A per residue length in helix
# Simulate a narrowing and widening pore
radius = 5 * np.sin(z_coords / (channel_length_residues*1.5/np.pi) * 2) + \
2 * np.cos(z_coords / (channel_length_residues*1.5/np.pi) * 5) + \
random.uniform(1.5, 4) # Base radius
radius = np.clip(radius, 0.5, 10) # Min/max radius
return pd.DataFrame({"Position_Angstrom": np.round(z_coords,1), "Radius_Angstrom": np.round(radius,1)})
def generate_mock_surface_curvature(sequence_length):
# Simplified: assign curvature type per residue
curvature_types = ["Convex", "Concave", "Saddle", "Flat"]
curvatures = random.choices(curvature_types, weights=[0.4, 0.3, 0.15, 0.15], k=sequence_length)
return pd.DataFrame({"Residue_Index": range(1, sequence_length + 1), "Curvature_Type_Pred": curvatures})
def generate_mock_packing_geometry(num_elements=5): # e.g., 5 helices/sheets
packing = []
elements = [f"{random.choice(['Helix', 'Sheet'])}_{i+1}" for i in range(num_elements)]
if num_elements < 2: return pd.DataFrame()
for i in range(num_elements):
for j in range(i + 1, num_elements):
packing.append({
"Element_1": elements[i],
"Element_2": elements[j],
"Packing_Angle_Degrees_Mock": round(random.uniform(-90, 90), 1),
"Closest_Distance_Angstrom_Mock": round(random.uniform(5, 15), 1)
})
return pd.DataFrame(packing)
def generate_mock_fold_recognition(num_hits=3):
folds = ["Rossmann fold", "TIM barrel", "Beta-propeller", "Jelly roll", "Globin fold", "Alpha-alpha superhelix"]
hits = []
for i in range(num_hits):
hits.append({
"Fold_Database_ID_Mock": f"{random.choice(['CATH', 'SCOP'])}_{random.randint(1000,9999)}",
"Fold_Name": random.choice(folds),
"Z_Score_Mock": round(random.uniform(3.0, 15.0), 2),
"Sequence_Identity_to_Exemplar_Percent_Mock": round(random.uniform(10, 40),1)
})
return pd.DataFrame(hits).sort_values(by="Z_Score_Mock", ascending=False)
def generate_mock_cryoem_fit():
return {
"Resolution_Angstrom_Mock": round(random.uniform(2.5, 6.0), 1),
"Cross_Correlation_Score_Mock": round(random.uniform(0.5, 0.85), 3),
"Map_Segmentation_Quality_Mock": random.choice(["Good", "Moderate", "Poor"])
}
def generate_mock_saxs_profile():
q_values = np.logspace(-2, 0, 100) # q range for SAXS
rg_mock = random.uniform(15, 50) # Mock Radius of Gyration
i_q = np.exp(-(q_values**2 * rg_mock**2) / 3) * random.uniform(1e3, 1e5) + np.random.normal(0, 0.05 * 1e4, 100) # Guinier approximation + noise
i_q = np.maximum(i_q, 1) # Ensure positive intensity
return pd.DataFrame({"q_Angstrom_inv": q_values, "Intensity_I_q_arbitrary_units": i_q}), rg_mock
def generate_mock_crystallization_propensity():
# Based on Surface Entropy Reduction concepts, etc.
return {
"Overall_Propensity_Score_Mock": round(random.uniform(0.1, 0.9), 2), # Higher is better
"Number_of_Low_Entropy_Patches_Mock": random.randint(0, 5),
"Largest_Hydrophobic_Patch_Area_A2_Mock": round(random.uniform(100, 800),1)
}
def generate_mock_rotamer_analysis(sequence_length):
favored = random.uniform(0.85, 0.98)
allowed = random.uniform(0.01, 0.15 - (favored - 0.85))
outlier = 1.0 - favored - allowed
return {
"Favored_Rotamers_Percent": round(favored * 100, 1),
"Allowed_Rotamers_Percent": round(allowed * 100, 1),
"Outlier_Rotamers_Percent": round(outlier * 100, 1)
}
def generate_mock_membrane_topology(sequence_length):
is_membrane_protein = random.random() < 0.3 # 30% chance of being a membrane protein
if not is_membrane_protein or sequence_length < 60:
return {"is_membrane_protein": False, "helices": [], "topology_summary": "Predicted as globular protein."}
num_helices = random.randint(1, min(7, sequence_length // 25))
helices = []
current_pos = 1
for i in range(num_helices):
if current_pos + 40 > sequence_length: break # Not enough space for more helices
start = random.randint(current_pos, current_pos + 15)
length = random.randint(18, 25)
end = min(start + length -1, sequence_length)
if end > sequence_length: break
helices.append({"id": f"TMH{i+1}", "start": start, "end": end, "length": end - start + 1})
current_pos = end + random.randint(5, 20)
if not helices:
return {"is_membrane_protein": False, "helices": [], "num_helices": 0, "n_terminus_location": "Unknown", "c_terminus_location": "Unknown", "topology_summary": "Predicted as globular protein (no clear TMHs found)."}
n_term_location = random.choice(["Inside", "Outside"])
c_term_location = n_term_location if num_helices % 2 == 0 else ("Outside" if n_term_location == "Inside" else "Inside")
return {
"is_membrane_protein": True,
"helices": helices,
"num_helices": len(helices),
"n_terminus_location": n_term_location,
"c_terminus_location": c_term_location,
"topology_summary": f"Predicted membrane protein with {len(helices)} TMHs. N-terminus: {n_term_location}, C-terminus: {c_term_location}."
}
def generate_mock_folding_pathway_insights(sequence_length):
insights = [
f"An early folding nucleus is predicted around residues {random.randint(10, sequence_length//3)}-{random.randint(sequence_length//3 + 1, sequence_length//2)}.",
"Long-range interactions between N-terminal and C-terminal domains appear crucial for final fold acquisition.",
f"A potential misfolding trap involving residues in the loop region {random.randint(sequence_length//2, sequence_length - 30)}-{random.randint(sequence_length//2+10, sequence_length-10)} might slow down folding.",
"The formation of secondary structures (helices and sheets) is likely rapid, followed by slower tertiary packing.",
"Chaperone assistance might be beneficial for efficient folding of larger domains.",
"Overall folding is predicted to be cooperative with few stable intermediates."
]
return random.sample(insights, k=random.randint(2,4))
def generate_mock_ppi_interface_data(sequence_length, partner_protein_id="PartnerX"):
num_interface_residues = random.randint(5, 20)
interface_residues = sorted(random.sample(range(1, sequence_length + 1), num_interface_residues))
return {
"partner_protein_id": partner_protein_id,
"interface_residues": ", ".join(map(str, interface_residues)),
"buried_surface_area_A2_mock": round(random.uniform(600, 2000), 1),
"interface_hydrophobicity_score_mock": round(random.uniform(-1.5, 1.5), 2),
"predicted_binding_energy_kcal_mol_mock": round(random.uniform(-5, -15), 1)
}
def generate_mock_ramachandran_data(sequence_length):
# Simulate phi and psi angles
# Favoring allowed regions: alpha-helix, beta-sheet
phi_psi_pairs = []
for _ in range(sequence_length):
region = random.choices(["alpha_L", "beta", "alpha_R", "disallowed"], weights=[0.4, 0.3, 0.1, 0.2])[0]
if region == "alpha_L": # Left-handed alpha helix (less common but for variety)
phi = random.uniform(40, 90)
psi = random.uniform(0, 90)
elif region == "beta": # Beta sheet
phi = random.uniform(-180, -40)
psi = random.uniform(90, 180) if random.random() > 0.5 else random.uniform(-180, -150)
elif region == "alpha_R": # Right-handed alpha helix
phi = random.uniform(-150, -40)
psi = random.uniform(-70, 0)
else: # Disallowed / generously allowed
phi = random.uniform(-180, 180)
psi = random.uniform(-180, 180)
phi_psi_pairs.append({"phi": round(phi,1), "psi": round(psi,1)})
return pd.DataFrame(phi_psi_pairs)
def generate_mock_nmr_spectra_data(sequence_length):
# Simplified mock 1D Proton NMR-like spectrum
ppm_range = np.linspace(0, 10, 500)
intensity = np.zeros_like(ppm_range)
num_peaks = sequence_length // 10 + random.randint(-5, 5)
num_peaks = max(5, num_peaks) # Ensure at least a few peaks
for _ in range(num_peaks):
peak_pos = random.uniform(0.5, 9.5)
intensity += np.exp(-((ppm_range - peak_pos)**2) / (2 * (random.uniform(0.01, 0.05))**2)) * random.uniform(0.1, 1)
return pd.DataFrame({"Chemical_Shift_ppm": ppm_range, "Intensity_Arbitrary": intensity * 100})
def generate_mock_chemical_shift_deviations(sequence_length):
# Simulate deviations from random coil or expected values
deviations = np.random.normal(loc=0, scale=0.5, size=sequence_length) + \
5 * np.sin(np.arange(sequence_length) / (sequence_length/15)) # Add some structural influence
return pd.DataFrame({
"Residue_Index": range(1, sequence_length + 1),
"Calpha_Deviation_ppm_Mock": np.round(deviations, 2),
"Halpha_Deviation_ppm_Mock": np.round(deviations * random.uniform(0.3, 0.6), 2)
})
def generate_mock_peak_integration_data(sequence_length):
# Simplified: just count AA types and present as "integrated peaks"
aa_counts = pd.Series(list("".join(random.choices(AMINO_ACIDS, k=sequence_length)))).value_counts().reset_index()
aa_counts.columns = ['Amino_Acid', 'Integrated_Intensity_Mock']
return aa_counts
def generate_mock_functional_prediction_data(sequence_length, domains_data):
go_terms = {
"Molecular Function": [f"GO:000{random.randint(1000,9999)} - {random.choice(['ATP binding', 'DNA binding', 'protein kinase activity', 'receptor activity', 'catalytic activity', 'transporter activity'])} (Score: {random.uniform(0.6,0.95):.2f})"],
"Biological Process": [f"GO:000{random.randint(1000,9999)} - {random.choice(['metabolic process', 'signal transduction', 'cell cycle', 'transcription', 'translation', 'immune response'])} (Score: {random.uniform(0.5,0.9):.2f})"],
"Cellular Component": [f"GO:000{random.randint(1000,9999)} - {random.choice(['nucleus', 'cytoplasm', 'mitochondrion', 'plasma membrane', 'ribosome', 'endoplasmic reticulum'])} (Score: {random.uniform(0.4,0.85):.2f})"]
}
if random.random() > 0.3: # Add a second term sometimes
go_terms["Molecular Function"].append(f"GO:000{random.randint(1000,9999)} - {random.choice(['ion binding', 'structural molecule activity', 'enzyme regulator activity'])} (Score: {random.uniform(0.5,0.8):.2f})")
ec_number = "N/A"
if any(d['type'] == 'Enzymatic' for d in domains_data) or random.random() < 0.2: # If enzymatic domain or 20% chance
ec_number = f"{random.randint(1,6)}.{random.randint(1,20)}.{random.randint(1,20)}.{random.randint(1,100)}"
return {"go_terms": go_terms, "ec_number": ec_number, "predicted_pathways_mock": [random.choice(["Glycolysis", "Citric Acid Cycle", "MAPK signaling", "Apoptosis", "DNA Repair"]) for _ in range(random.randint(0,2))]}
def generate_mock_protein_family_prediction():
families = ["Kinase", "GPCR", "Ion Channel", "Transcription Factor", "Enzyme (Hydrolase)", "Structural Protein"]
superfamilies = ["Protein Kinase Superfamily", "G Protein-Coupled Receptor Family", "Ligand-Gated Ion Channel Family", "Helix-Turn-Helix Transcription Factors", "Hydrolase Superfamily", "Cytoskeletal Proteins"]
return {
"Family_Mock": random.choice(families),
"Superfamily_Mock": random.choice(superfamilies),
"Confidence_Score_Mock": round(random.uniform(0.7, 0.99), 2),
"Method_Mock": random.choice(["Sequence Homology", "Structural Similarity", "Domain Content"])
}
def generate_mock_subcellular_localization():
locations = ["Cytoplasm", "Nucleus", "Mitochondrion", "Endoplasmic Reticulum", "Golgi Apparatus", "Plasma Membrane", "Extracellular"]
return {
"Predicted_Location_Mock": random.choice(locations),
"Confidence_Score_Mock": round(random.uniform(0.6, 0.95), 2),
"Top_Locations_Mock": random.sample(locations, k=random.randint(1,3)),
"Method_Mock": random.choice(["Sequence Features", "Domain Content", "Signal Peptides"])
}
def generate_mock_contact_map_data(sequence_length):
contacts = np.random.rand(sequence_length, sequence_length) < 0.05 # 5% chance of contact
# Make it symmetric and remove self-contacts
contacts = np.triu(contacts, k=1)
contacts = contacts + contacts.T
# Add some local contacts (common in helices/sheets)
for i in range(sequence_length - 4):
if random.random() < 0.3: contacts[i, i+3] = contacts[i+3, i] = 1 # i, i+3
if random.random() < 0.2: contacts[i, i+4] = contacts[i+4, i] = 1 # i, i+4
return contacts
def generate_mock_sasa_data(sequence_length):
# Simulate SASA values, often higher for loops/turns, lower for core residues
sasa = np.random.normal(loc=60, scale=40, size=sequence_length)
# Add some periodic variation (e.g. exposed every few residues in a helix)
sasa += 20 * np.sin(np.arange(sequence_length) * np.pi / 3.5)
sasa = np.clip(sasa, 5, 200) # Realistic SASA range in Å^2
return sasa
AA_HYDROPHOBICITY_KD = { # Kyte-Doolittle
'A': 1.8, 'R': -4.5, 'N': -3.5, 'D': -3.5, 'C': 2.5,
'Q': -3.5, 'E': -3.5, 'G': -0.4, 'H': -3.2, 'I': 4.5,
'L': 3.8, 'K': -3.9, 'M': 1.9, 'F': 2.8, 'P': -1.6,
'S': -0.8, 'T': -0.7, 'W': -0.9, 'Y': -1.3, 'V': 4.2,
'X': 0.0 # Placeholder for unknown/gap
}
def generate_mock_b_factors_data(sequence_length):
# Simulate B-factors, often higher for loops/flexible regions
b_factors = np.abs(np.random.normal(loc=30, scale=15, size=sequence_length))
# Add some higher values for potential loop regions
for _ in range(sequence_length // 20): # Add a few flexible regions
start = random.randint(0, sequence_length - 5)
b_factors[start:start+random.randint(3,10)] *= random.uniform(1.5, 2.5)
return np.clip(b_factors, 5, 150)
def generate_mock_aggregation_propensity_data(sequence_length):
# Simulate aggregation propensity (e.g., on a 0-1 scale)
propensity = np.random.beta(a=2, b=8, size=sequence_length) # Mostly low propensity
# Add a few high propensity patches
for _ in range(random.randint(0, sequence_length // 50)):
start = random.randint(0, sequence_length - 10)
propensity[start:start+random.randint(5,10)] = np.random.beta(a=8, b=2, size=len(propensity[start:start+random.randint(5,10)]))
return np.clip(propensity, 0, 1)
def create_structure_plot(prediction_data):
"""Create interactive structure visualization."""
seq_len = prediction_data['length']
positions = list(range(1, seq_len + 1))
# Create subplots
fig = make_subplots(
rows=4, cols=1,
subplot_titles=['Secondary Structure', 'Confidence (pLDDT)', 'Disorder Prediction', 'Domain Architecture'],
vertical_spacing=0.08,
row_heights=[0.3, 0.25, 0.2, 0.25]
)
# Secondary structure plot
ss_colors = {'Helix': '#FF6B6B', 'Sheet': '#4ECDC4', 'Coil': '#45B7D1', 'Turn': '#FFA07A'}
for ss_type in SECONDARY_STRUCTURES:
mask = prediction_data['secondary_structure'] == ss_type
if np.any(mask):
fig.add_trace(
go.Scatter(
x=np.array(positions)[mask],
y=[ss_type] * np.sum(mask),
mode='markers',
marker=dict(color=ss_colors[ss_type], size=8),
name=ss_type,
showlegend=True
),
row=1, col=1
)
# Confidence plot
fig.add_trace(
go.Scatter(
x=positions,
y=prediction_data['plddt'],
mode='lines',
line=dict(color='#2E86AB', width=2),
name='pLDDT Score',
showlegend=False
),
row=2, col=1
)
# Add confidence threshold lines
fig.add_hline(y=90, line_dash="dash", line_color="green", row=2, col=1)
fig.add_hline(y=70, line_dash="dash", line_color="orange", row=2, col=1)
fig.add_hline(y=50, line_dash="dash", line_color="red", row=2, col=1)
# Disorder prediction
disorder_y = prediction_data['disorder'].astype(int)
fig.add_trace(
go.Scatter(
x=positions,
y=disorder_y,
mode='lines',
line=dict(color='#E74C3C', width=2),
fill='tonexty',
name='Disorder',
showlegend=False
),
row=3, col=1
)
# Domain architecture
domain_colors = ['#3498DB', '#E67E22', '#2ECC71', '#9B59B6', '#F39C12']
for i, domain in enumerate(prediction_data['domains']):
fig.add_trace(
go.Scatter(
x=[domain['start'], domain['end']],
y=[1, 1],
mode='lines',
line=dict(color=domain_colors[i % len(domain_colors)], width=15),
name=domain['name'],
showlegend=False
),
row=4, col=1
)
# Update layout
fig.update_layout(
height=800,
title="Protein Structure Analysis",
showlegend=True,
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1)
)
# Update axes
fig.update_xaxes(title_text="Residue Position", row=4, col=1)
fig.update_yaxes(title_text="Structure", row=1, col=1)
fig.update_yaxes(title_text="Confidence", range=[0, 100], row=2, col=1)
fig.update_yaxes(title_text="Disorder", range=[0, 1.2], row=3, col=1)
fig.update_yaxes(title_text="Domains", range=[0, 2], row=4, col=1)
return fig
def create_confidence_distribution(prediction_data):
"""Create confidence distribution chart."""
plddt_scores = prediction_data['plddt']
fig = go.Figure()
fig.add_trace(go.Histogram(
x=plddt_scores,
nbinsx=20,
marker_color='#3498DB',
opacity=0.7,
name='pLDDT Distribution'
))
fig.update_layout(
title="Confidence Score Distribution",
xaxis_title="pLDDT Score",
yaxis_title="Number of Residues",
bargap=0.1
)
return fig
def export_results(prediction_data, format_type):
"""Export prediction results in various formats."""
if format_type == "JSON":
# Convert numpy arrays to lists for JSON serialization
export_data = prediction_data.copy()
export_data['secondary_structure'] = export_data['secondary_structure'].tolist()
export_data['confidence'] = export_data['confidence'].tolist()
export_data['disorder'] = export_data['disorder'].tolist()
export_data['plddt'] = export_data['plddt'].tolist()
export_data['timestamp'] = export_data['timestamp'].isoformat()
return json.dumps(export_data, indent=2)
elif format_type == "CSV":
df = pd.DataFrame({
'Position': range(1, len(prediction_data['sequence']) + 1),
'Residue': list(prediction_data['sequence']),
'Secondary_Structure': prediction_data['secondary_structure'],
'Confidence': prediction_data['confidence'],
'pLDDT': prediction_data['plddt'],
'Disorder': prediction_data['disorder']
})
return df.to_csv(index=False)
elif format_type == "PDB":
# Mock PDB format (simplified)
pdb_lines = [
"HEADER PROTEIN STRUCTURE PREDICTION",
f"TITLE ALPHAFOLD PREDICTION",
"REMARK THIS IS A MOCK PDB FILE FOR DEMONSTRATION"
]
for i, aa in enumerate(prediction_data['sequence']):
line = f"ATOM {i+1:5d} CA {aa} A{i+1:4d} {i*3.8:8.3f}{0.0:8.3f}{0.0:8.3f} 1.00{prediction_data['plddt'][i]:6.2f} C"
pdb_lines.append(line)
pdb_lines.append("END")
return '\n'.join(pdb_lines)
# Main UI
st.markdown("""
<div class="main-header">
<h1>🧬 AlphaFold </h1>
<p>Advanced Protein Structure Prediction Suite</p>
<p style="font-size: 0.9em; opacity: 0.8;">Powered by Google Gemini AI | Professional-Grade Analysis</p>
</div>
""", unsafe_allow_html=True)
# Sidebar
with st.sidebar:
st.header("🔬 Analysis Configuration")
# Model selection
st.subheader("AI Model Selection")
AVAILABLE_MODELS = {
"Gemini 2.0 Flash": "gemini-2.0-flash",
}
selected_model = st.selectbox(
"Choose AI Model:",
options=list(AVAILABLE_MODELS.keys()),
help="Select the AI model for structure analysis"
)
# API Configuration
st.subheader("API Configuration")
api_key = st.text_input(
"Gemini API Key:",
type="password",
help="Enter your Google AI Studio API key"
)
# Sequence Input
st.subheader("Sequence Input")
col1, col2 = st.columns(2)
with col1:
if st.button("🎲 Random Protein", help="Generate random sequence"):
st.session_state.sequence_input = generate_protein_sequence()
with col2:
if st.button("🧪 Complex Protein", help="Generate complex sequence"):
st.session_state.sequence_input = generate_protein_sequence(complexity="high")
sequence_input = st.text_area(
"Protein Sequence (FASTA or raw):",
height=200,
placeholder=">MyProtein\nMQIFVKTLTGKTITLEVEPSDTIENVKAKIQDKEGIPPDQQRLIFAGKQLEDGRTLSDYNIQKESTLHLVLRLRGG",
key="sequence_input"
)
# Analysis Options
st.subheader("Analysis Options")
include_disorder = st.checkbox("Disorder Prediction", value=True)
include_domains = st.checkbox("Domain Analysis", value=True)
confidence_threshold = st.slider("Confidence Threshold", 0, 100, 70)
# Prediction Button
predict_button = st.button(
"🚀 Predict Structure",
type="primary",
help="Start structure prediction analysis"
)
st.divider()
# Export Options
if st.session_state.current_prediction:
st.subheader("📊 Export Results")
export_format = st.selectbox(
"Export Format:",
["JSON", "CSV", "PDB"],
help="Choose export format"
)
if st.button("💾 Download Results"):
result = export_results(st.session_state.current_prediction, export_format)
st.download_button(
f"Download {export_format}",
result,
file_name=f"prediction_results.{export_format.lower()}",
mime="text/plain"
)
# Main content area
if predict_button:
if not sequence_input.strip():
st.error("❌ Please enter a protein sequence")
elif not api_key:
st.error("❌ Please enter your API key")
else:
# Validate sequence
is_valid, result = validate_protein_sequence(sequence_input)
if not is_valid:
st.error(f"❌ Sequence validation failed: {result}")
else:
sequence = result
# Create prediction hash for caching
seq_hash = hashlib.md5(sequence.encode()).hexdigest()
# Show progress
progress_container = st.container()
with progress_container:
st.markdown('<div class="prediction-status status-running">🔄 Running Structure Prediction...</div>',
unsafe_allow_html=True)
progress_bar = st.progress(0)
status_text = st.empty()
# Simulate realistic prediction process
steps = [
"Preprocessing sequence...",
"Running MSA search...",
"Generating structural features...",
"Predicting secondary structure...",
"Calculating confidence scores...",
"Analyzing domains...",
"Finalizing predictions..."
]
for i, step in enumerate(steps):
status_text.text(step)
progress_bar.progress((i + 1) / len(steps))
time.sleep(0.5)
# Generate predictions
mock_data = generate_mock_predictions(sequence, selected_model)
# AI Analysis
try:
genai.configure(api_key=api_key)
model = genai.GenerativeModel(AVAILABLE_MODELS[selected_model])
prompt = f"""
As an expert structural biologist, analyze this protein sequence and provide a comprehensive analysis:
Sequence Length: {len(sequence)} residues
Sequence: {sequence[:100]}{'...' if len(sequence) > 100 else ''}
Please provide:
1. **Structural Classification**: Predict the overall fold class and architecture
2. **Secondary Structure Analysis**: Detailed prediction of helices, sheets, and loops
3. **Functional Domains**: Identify potential functional regions and motifs
4. **Stability Assessment**: Comment on predicted structural stability
5. **Functional Predictions**: Potential biological function based on structure
6. **Key Structural Features**: Notable characteristics and critical residues
7. **Confidence Assessment**: Areas of high/low prediction confidence
Format as a detailed scientific report with specific residue ranges where applicable.
"""
response = model.generate_content(prompt)
ai_analysis = response.text
mock_data['ai_analysis'] = ai_analysis
except Exception as e:
mock_data['ai_analysis'] = f"AI Analysis Error: {str(e)}"
st.session_state.current_prediction = mock_data
st.session_state.prediction_history.append(mock_data)
progress_container.empty()
# Display Results
if st.session_state.current_prediction:
data = st.session_state.current_prediction
st.markdown('<div class="prediction-status status-complete">✅ Structure Prediction Complete!</div>',
unsafe_allow_html=True)
# Summary metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.markdown(f"""
<div class="metric-card">
<h4>Sequence Length</h4>
<h2>{data['length']} AA</h2>
</div>
""", unsafe_allow_html=True)
with col2:
confidence_class = "high" if data['overall_confidence'] > 70 else "medium" if data['overall_confidence'] > 50 else "low"
st.markdown(f"""
<div class="metric-card">
<h4>Overall Confidence</h4>
<h2 class="confidence-{confidence_class}">{data['overall_confidence']:.1f}</h2>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown(f"""
<div class="metric-card">
<h4>Domains Found</h4>
<h2>{len(data['domains'])}</h2>
</div>
""", unsafe_allow_html=True)
with col4:
disorder_pct = np.mean(data['disorder']) * 100
st.markdown(f"""
<div class="metric-card">
<h4>Disorder Regions</h4>
<h2>{disorder_pct:.1f}%</h2>
</div>
""", unsafe_allow_html=True)
# Tabs for different analyses