-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresult_page_generator.py
executable file
·1442 lines (1217 loc) · 56.1 KB
/
result_page_generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Result Page Generator Module
This module generates individual HTML pages with results for each input protein.
It provides functions to create plots and other outputs based on the prediction results.
"""
import os
import pickle
import numpy as np
import pandas as pd
import json
import plotly.graph_objects as go
from datetime import datetime
import plotly.graph_objects as go
from Bio import SeqIO
# Mapping dictionaries for amino acid codes
AA_1TO3 = {
'A': 'ALA', 'C': 'CYS', 'D': 'ASP', 'E': 'GLU',
'F': 'PHE', 'G': 'GLY', 'H': 'HIS', 'I': 'ILE',
'K': 'LYS', 'L': 'LEU', 'M': 'MET', 'N': 'ASN',
'P': 'PRO', 'Q': 'GLN', 'R': 'ARG', 'S': 'SER',
'T': 'THR', 'V': 'VAL', 'W': 'TRP', 'Y': 'TYR'
}
AA_1TOFULL = {
'A': 'Alanine', 'C': 'Cysteine', 'D': 'Aspartic Acid', 'E': 'Glutamic Acid',
'F': 'Phenylalanine', 'G': 'Glycine', 'H': 'Histidine', 'I': 'Isoleucine',
'K': 'Lysine', 'L': 'Leucine', 'M': 'Methionine', 'N': 'Asparagine',
'P': 'Proline', 'Q': 'Glutamine', 'R': 'Arginine', 'S': 'Serine',
'T': 'Threonine', 'V': 'Valine', 'W': 'Tryptophan', 'Y': 'Tyrosine'
}
def load_tsv(protein_id, predictions_dir='predictions'):
"""
Load TSV file with per-embedding predictions for a given protein.
Args:
protein_id (str): The protein identifier.
predictions_dir (str): The directory where prediction files are stored.
Returns:
list: A list of numpy arrays, each containing per-embedding predictions for a metric.
"""
filepath = os.path.join(predictions_dir, f'{protein_id}_raw.tsv')
df = pd.read_csv(filepath, sep='\t')
# Check if DataFrame has at least 2 columns
if df.shape[1] < 2:
raise ValueError(f"TSV file {filepath} must have at least two columns.")
# Extract metrics (excluding first column, assuming it's an index or position)
all_metrics = df.iloc[:, 1:].values
# Determine number of metrics
num_metrics = 4 # Assuming 4 metrics
num_embeddings = all_metrics.shape[1]
if num_embeddings % num_metrics != 0:
raise ValueError("Number of embeddings is not divisible by the number of metrics.")
# Split metrics into list
results_by_metric = np.array_split(all_metrics, num_metrics, axis=1)
return results_by_metric
def draw_interactive_plot(result_dict, protein_id, output_dir, results_by_metric):
"""
Draw interactive Plotly plots for each predicted metric and save as HTML files.
Args:
result_dict (dict): Dictionary containing results with proteins as keys.
protein_id (str): Protein identifier.
output_dir (str): Directory to save HTML output files.
results_by_metric (list): List of numpy arrays with individual embedding predictions.
Returns:
None
"""
COLORS = ['firebrick', 'steelblue', 'forestgreen', 'gold']
METRICS = ['RMSF', 'PHI', 'PSI', 'LDDT']
UNITS = ['Å', '°', '°', '']
#RMSF
metric = "RMSF"
matrix = results_by_metric[0]
# Get the mean result for the metric
result = result_dict[protein_id][metric]
#Convert RMSF from nm to Angstrom
result = result * 10
result = np.around(result, 3)
x = np.arange(1, len(result)+1)
# Calculate standard deviation across embeddings
metric_std = np.std(matrix, axis=1)
#Convert RMSF from nm to Angstrom
metric_std = metric_std * 10
metric_std = np.around(metric_std, 3)
# Create figure
fig = go.Figure()
# Create main metric trace
fig.add_trace(go.Scatter(
x=x, y=result,
line=dict(color='rgba(221, 97, 74, 1)'),
mode="lines", name="RMSF"
))
fig.update_traces(customdata=metric_std)
fig["data"][0]["hovertemplate"] = "%{x}<br>RMSF = %{y} ± %{customdata} Å<extra></extra>"
fig.update_layout(hoverlabel=dict(bgcolor="white"),
hoverlabel_font_color="black")
# Add confidence interval (mean ± std)
fig.add_traces([
go.Scatter(
x=x, y=result+metric_std,
mode='lines', line_color='rgba(0,0,0,0)',
showlegend=False, hoverinfo='none'
),
go.Scatter(
x=x, y=result-metric_std,
mode='lines', line_color='rgba(0,0,0,0)',
name='SD',
fill='tonexty', fillcolor='rgba(221, 97, 74, 0.2)',
hoverinfo='none'
)
])
# Update layout parameters
fig.update_layout(
xaxis_title="<b>Position</b>",
yaxis_title="<b>Pred. RMSF (Å)</b>",
yaxis=dict(range=[0, np.nanmax(result+metric_std) * 1.05]),
showlegend=False,
margin=dict(l=10, r=10, b=30, t=30, pad=4),
hoverlabel=dict(bgcolor="white", font_color="black"),
template="plotly_white",
hovermode="x unified"
)
# Save plot to HTML file
output_filepath = os.path.join(output_dir, f"{protein_id}_{metric}_pred.html")
fig.write_html(
output_filepath,
full_html=False, auto_play=False,
include_plotlyjs=False, config={"responsive": True},
default_width="100%", default_height="100%"
)
#Phi
metric = "PHI"
matrix = results_by_metric[1]
# Get the mean result for the metric
result = result_dict[protein_id][metric]
result = np.around(result, 3)
x = np.arange(1, len(result)+1)
# Calculate standard deviation across embeddings
metric_std = np.std(matrix, axis=1)
metric_std = np.around(metric_std, 3)
# Create figure
fig = go.Figure()
# Create main metric trace
fig.add_trace(go.Scatter(
x=x, y=result,
line=dict(color='rgba(115, 165, 128, 1)'),
mode="lines", name=f"Std. Phi"
))
fig.update_traces(customdata=metric_std)
fig["data"][0]["hovertemplate"] = "%{x}<br>Std. Phi = %{y} ± %{customdata} °<extra></extra>"
fig.update_layout(hoverlabel=dict(bgcolor="white"),
hoverlabel_font_color="black")
# Add confidence interval (mean ± std)
fig.add_traces([
go.Scatter(
x=x, y=result+metric_std,
mode='lines', line_color='rgba(0,0,0,0)',
showlegend=False, hoverinfo='none'
),
go.Scatter(
x=x, y=result-metric_std,
mode='lines', line_color='rgba(0,0,0,0)',
name='SD',
fill='tonexty', fillcolor='rgba(115, 165, 128, 0.2)',
hoverinfo='none'
)
])
# Update layout parameters
fig.update_layout(
xaxis_title="<b>Position</b>",
yaxis_title="<b>Pred. Std. Phi (°)</b>",
yaxis=dict(range=[0, np.nanmax(result+metric_std) * 1.05]),
showlegend=False,
margin=dict(l=10, r=10, b=30, t=30, pad=4),
hoverlabel=dict(bgcolor="white", font_color="black"),
template="plotly_white",
hovermode="x unified"
)
# Save plot to HTML file
output_filepath = os.path.join(output_dir, f"{protein_id}_{metric}_pred.html")
fig.write_html(
output_filepath,
full_html=False, auto_play=False,
include_plotlyjs=False, config={"responsive": True},
default_width="100%", default_height="100%"
)
#Psi
metric = "PSI"
matrix = results_by_metric[2]
# Get the mean result for the metric
result = result_dict[protein_id][metric]
result = np.around(result, 3)
x = np.arange(1, len(result)+1)
# Calculate standard deviation across embeddings
metric_std = np.std(matrix, axis=1)
metric_std = np.around(metric_std, 3)
# Create figure
fig = go.Figure()
# Create main metric trace
fig.add_trace(go.Scatter(
x=x, y=result,
line=dict(color='rgba(127, 106, 147, 1)'),
mode="lines", name=f"Std. Psi"
))
fig.update_traces(customdata=metric_std)
fig["data"][0]["hovertemplate"] = "%{x}<br>Std. Psi = %{y} ± %{customdata} °<extra></extra>"
fig.update_layout(hoverlabel=dict(bgcolor="white"),
hoverlabel_font_color="black")
# Add confidence interval (mean ± std)
fig.add_traces([
go.Scatter(
x=x, y=result+metric_std,
mode='lines', line_color='rgba(0,0,0,0)',
showlegend=False, hoverinfo='none'
),
go.Scatter(
x=x, y=result-metric_std,
mode='lines', line_color='rgba(0,0,0,0)',
name='SD',
fill='tonexty', fillcolor='rgba(127, 106, 147, 0.2)',
hoverinfo='none'
)
])
# Update layout parameters
fig.update_layout(
xaxis_title="<b>Position</b>",
yaxis_title="<b>Pred. Std. Psi (°)</b>",
yaxis=dict(range=[0, np.nanmax(result+metric_std) * 1.05]),
showlegend=False,
margin=dict(l=10, r=10, b=30, t=30, pad=4),
hoverlabel=dict(bgcolor="white", font_color="black"),
template="plotly_white",
hovermode="x unified"
)
# Save plot to HTML file
output_filepath = os.path.join(output_dir, f"{protein_id}_{metric}_pred.html")
fig.write_html(
output_filepath,
full_html=False, auto_play=False,
include_plotlyjs=False, config={"responsive": True},
default_width="100%", default_height="100%"
)
#Mean LDDT
metric = "LDDT"
matrix = results_by_metric[3]
# Get the mean result for the metric
result = result_dict[protein_id][metric]
result = np.around(result, 3)
x = np.arange(1, len(result)+1)
# Calculate standard deviation across embeddings
metric_std = np.std(matrix, axis=1)
metric_std = np.around(metric_std, 3)
# Create figure
fig = go.Figure()
# Create main metric trace
fig.add_trace(go.Scatter(
x=x, y=result,
line=dict(color='rgba(213, 160, 33, 1)'),
mode="lines", name=f"Mean LDDT"
))
fig.update_traces(customdata=metric_std)
fig["data"][0]["hovertemplate"] = "%{x}<br>Mean LDDT = %{y} ± %{customdata}<extra></extra>"
fig.update_layout(hoverlabel=dict(bgcolor="white"),
hoverlabel_font_color="black")
# Add confidence interval (mean ± std)
fig.add_traces([
go.Scatter(
x=x, y=result+metric_std,
mode='lines', line_color='rgba(0,0,0,0)',
showlegend=False, hoverinfo='none'
),
go.Scatter(
x=x, y=result-metric_std,
mode='lines', line_color='rgba(0,0,0,0)',
name='SD',
fill='tonexty', fillcolor='rgba(213, 160, 33, 0.2)',
hoverinfo='none'
)
])
# Update layout parameters
fig.update_layout(
xaxis_title="<b>Position</b>",
yaxis_title="<b>Pred. Mean LDDT</b>",
yaxis=dict(range=[0, np.nanmax(result+metric_std) * 1.05]),
showlegend=False,
margin=dict(l=10, r=10, b=30, t=30, pad=4),
hoverlabel=dict(bgcolor="white", font_color="black"),
template="plotly_white",
hovermode="x unified"
)
# Save plot to HTML file
output_filepath = os.path.join(output_dir, f"{protein_id}_{metric}_pred.html")
fig.write_html(
output_filepath,
full_html=False, auto_play=False,
include_plotlyjs=False, config={"responsive": True},
default_width="100%", default_height="100%"
)
def draw_interactive_plot_all(result_dict, protein_id, output_dir):
"""
Draw interactive Plotly plot with all normalized predicted metrics and save as an HTML file.
Args:
result_dict (dict): Dictionary containing results with proteins as keys.
protein_id (str): Protein identifier.
output_dir (str): Directory to save HTML output file.
Returns:
None
"""
METRICS = ['RMSF', 'PHI', 'PSI', 'LDDT']
# Retrieve and normalize metrics
normalized_metrics = {}
for metric in METRICS:
values = result_dict[protein_id][metric]
normalized_values = np.interp(values, (values.min(), values.max()), (0, 1))
normalized_metrics[metric] = np.around(normalized_values, 3)
# Prepare x-axis values
x = np.arange(1, len(next(iter(normalized_metrics.values()))) + 1)
# Create figure
fig = go.Figure()
# Add traces for each metric
fig.add_trace(go.Scatter(
x=x, y=normalized_metrics['RMSF'],
line=dict(color='rgba(221, 97, 74, 1)'),
mode="lines", name=f"RMSF (Å)"
))
fig.add_trace(go.Scatter(
x=x, y=normalized_metrics['PHI'],
line=dict(color='rgba(115, 165, 128, 1)'),
mode="lines", name=f"Std. Phi (°)"
))
fig.add_trace(go.Scatter(
x=x, y=normalized_metrics['PSI'],
line=dict(color='rgba(127, 106, 147, 1)'),
mode="lines", name=f"Std. Psi (°)"
))
fig.add_trace(go.Scatter(
x=x, y=normalized_metrics['LDDT'],
line=dict(color='rgba(213, 160, 33, 1)'),
mode="lines", name=f"Mean LDDT"
))
# Update layout parameters
fig.update_layout(
xaxis_title="<b>Position</b>",
yaxis_title="<b>Normalised metrics</b>",
yaxis=dict(range=[0, 1.05]),
showlegend=True,
margin=dict(l=10, r=10, b=30, t=30, pad=4),
hoverlabel=dict(bgcolor="white", font_color="black"),
template="plotly_white",
hovermode="x unified"
)
# Save plot to HTML file
output_filepath = os.path.join(output_dir, f"{protein_id}_ALL_pred.html")
fig.write_html(
output_filepath,
full_html=False, auto_play=False,
include_plotlyjs=False, config={"responsive": True},
default_width="100%", default_height="100%"
)
def write_result_page(result_dict, protein_realname, protein_id, output_dir, sequence):
"""
Write the full results page for the PEGASUS model as an HTML file.
Args:
result_dict (dict): Dictionary containing results with proteins as keys.
protein_realname (str): The real name or header of the protein.
protein_id (str): Protein identifier.
output_dir (str): Directory to save the HTML output file.
sequence (str): Amino acid sequence of the protein.
Returns:
None
"""
# Normalize and round metric values for display
metrics = ['RMSF', 'PHI', 'PSI', 'LDDT']
normalized_metrics = {}
rounded_metrics = {}
for metric in metrics:
values = result_dict[protein_id][metric]
normalized_values = np.interp(values, (values.min(), values.max()), (0, 1))
normalized_metrics[metric] = np.around(normalized_values, 3)
rounded_metrics[metric] = np.around(values, 3)
# Generate the sequenceTrack content
sequence_track_displays = []
for idx, res in enumerate(sequence, start=1):
display = f"""{{displayType:"sequence", displayId:"cs{idx}", displayData:[{{begin:{idx}, value:"{res}", featureId:"[{AA_1TO3.get(res, '')} : {AA_1TOFULL.get(res, '')}]"}}]}},\n"""
sequence_track_displays.append(display)
sequence_track_config = ''.join(sequence_track_displays)
# Generate the area tracks for each metric
area_tracks = ''
colors = ['#DD614A', '#73A580', '#7F6A93', '#D5A021']
#RMSF
metric = metrics[0]
color = colors[0]
track_data_entries = ''
for idx, (norm_value, value) in enumerate(zip(normalized_metrics[metric], rounded_metrics[metric]*10), start=1):
track_data_entries += f"{{begin:{idx}, value:{norm_value}, featureId:\"value: {value:.2f} Å\"}},\n"
area_track = f"""
const {metric.lower()}Track = {{
trackId: "{metric.lower()}Track",
trackHeight: 100,
trackColor: "#F9F9F9",
displayType: "area",
nonEmptyDisplay: true,
interpolationType: "cardinal",
displayColor: "{color}",
rowTitle: "RMSF (Å)",
fitTitleWidth: true,
trackData: [
{track_data_entries}
]
}};
"""
area_tracks += area_track
#Phi
metric = metrics[1]
color = colors[1]
track_data_entries = ''
for idx, (norm_value, value) in enumerate(zip(normalized_metrics[metric], rounded_metrics[metric]), start=1):
track_data_entries += f"{{begin:{idx}, value:{norm_value}, featureId:\"value: {value:.2f} °\"}},\n"
area_track = f"""
const {metric.lower()}Track = {{
trackId: "{metric.lower()}Track",
trackHeight: 100,
trackColor: "#F9F9F9",
displayType: "area",
nonEmptyDisplay: true,
interpolationType: "cardinal",
displayColor: "{color}",
rowTitle: "Std. Phi (°)",
fitTitleWidth: true,
trackData: [
{track_data_entries}
]
}};
"""
area_tracks += area_track
#Psi
metric = metrics[2]
color = colors[2]
track_data_entries = ''
for idx, (norm_value, value) in enumerate(zip(normalized_metrics[metric], rounded_metrics[metric]), start=1):
track_data_entries += f"{{begin:{idx}, value:{norm_value}, featureId:\"value: {value:.2f} °\"}},\n"
area_track = f"""
const {metric.lower()}Track = {{
trackId: "{metric.lower()}Track",
trackHeight: 100,
trackColor: "#F9F9F9",
displayType: "area",
nonEmptyDisplay: true,
interpolationType: "cardinal",
displayColor: "{color}",
rowTitle: "Std. Psi (°)",
fitTitleWidth: true,
trackData: [
{track_data_entries}
]
}};
"""
area_tracks += area_track
#LDDT
metric = metrics[3]
color = colors[3]
track_data_entries = ''
for idx, (norm_value, value) in enumerate(zip(normalized_metrics[metric], rounded_metrics[metric]), start=1):
track_data_entries += f"{{begin:{idx}, value:{norm_value}, featureId:\"value: {value:.2f}\"}},\n"
area_track = f"""
const {metric.lower()}Track = {{
trackId: "{metric.lower()}Track",
trackHeight: 100,
trackColor: "#F9F9F9",
displayType: "area",
nonEmptyDisplay: true,
interpolationType: "cardinal",
displayColor: "{color}",
rowTitle: "Mean LDDT",
fitTitleWidth: true,
trackData: [
{track_data_entries}
]
}};
"""
area_tracks += area_track
# Define the HTML template
html_template = '''<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta tags and page title -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>PEGASUS | {protein_realname}</title>
<link id="favicon" rel="icon" href="https://dsimb.inserm.fr/PEGASUS/images/favicon.png" type="image/png" sizes="16x16">
<!-- CSS and JS includes -->
<!-- Bootstrap -->
<link href="https://dsimb.inserm.fr/PEGASUS/css/bootstrap.min.css" rel="stylesheet">
<!-- Load Chart.js -->
<script src="https://dsimb.inserm.fr/PEGASUS/js/d3.v4.js"></script>
<script src="https://dsimb.inserm.fr/PEGASUS/js/Chart.bundle.min.js"></script>
<script src="https://dsimb.inserm.fr/PEGASUS/js/chartjs-plugin-labels.js"></script>
<!-- jQuery -->
<script src="https://dsimb.inserm.fr/PEGASUS/js/jquery.min.js"></script>
<link rel="stylesheet" href="https://dsimb.inserm.fr/PEGASUS/css/jquery-ui.min.css"/>
<script src="https://dsimb.inserm.fr/PEGASUS/js/jquery-ui.min.js"></script>
<!-- Features viewer -->
<script src="https://dsimb.inserm.fr/PEGASUS/js/custom_rcsb_saguaro_mini.js"></script>
<!-- Plotly -->
<script src="https://dsimb.inserm.fr/PEGASUS/js/plotly-2.12.1.min.js"></script>
<!-- Custom Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600;1,700&display=swap" rel="stylesheet">
<!-- Custom styles -->
<link href="https://dsimb.inserm.fr/PEGASUS/css/custom_features.css" rel="stylesheet" />
</head>
<body class="d-flex flex-column min-vh-100">
<!-- Header -->
<nav class="navbar navbar-expand-lg navbar-light bg-white fixed-top">
<div class="container pb-2" id="nav-container">
<a class="navbar-brand" href="/PEGASUS/index.html">
<img src="https://dsimb.inserm.fr/PEGASUS/images/PEGASUS_logo.png" alt="Website logo" id="logo" style="transition: 0.4s;height:70px;">
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarResponsive"
aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation"
style="margin-top: 3px;margin-bottom: 2px">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive" style="margin-top: auto">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link" href="https://dsimb.inserm.fr/PEGASUS/index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://dsimb.inserm.fr/PEGASUS/about.html">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://dsimb.inserm.fr/PEGASUS/example.html">Example</a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://dsimb.inserm.fr/PEGASUS/contact.html">Contact</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container mt-7">
<div class="alert alert-success mt-5 mb-0" role="alert">
<h1 class="alert-heading"> Results </h1>
<p class="fw-bold mb-0">Query: <span class="fw-normal text-break font-monospace">{protein_realname}</span></p>
<p class="fw-bold mb-0">Sequence: <span class="fw-normal text-break font-monospace">{sequence}</span></p>
<p class="fw-bold mb-0">Length: <span class="fw-normal text-break font-monospace">{seq_length}</span></p>
</div>
<!-- Summary -->
<div class="card mt-2 pt-4">
<h2> Flexibility Profiles </h2>
<hr class="mt-2">
<div class="card-body px-0 mt-3 w-100 mb-2">
<div id="summary" style="height: 445px">
<!-- Sequence viewer -->
<div id="pfv" class="mb-2"></div>
</div>
</div>
</div>
<!-- Metric by Metric Predictions -->
<div class="card mt-2 pt-4">
<h2> Metric by Metric Predictions </h2>
<hr class="mt-2">
<div class="card-body px-0 mt-3 w-100 mb-2">
<div class="container" id="results-overview">
<div class="row">
<div class="col-12">
<div class="card mt-0" id="flex_rep">
<h5 class="card-header"> Flexibility profile </h5>
<div class="d-flex justify-content-center">
<div class="ratio" style="--bs-aspect-ratio: 30%;position:relative;" id="plot_rep"></div>
</div>
<div class="btn-toolbar d-flex justify-content-center pt-2 pb-4" role="toolbar" aria-label="toolbar_rep">
<div>
<input type="radio" class="btn-check" name="btnradio_rep" id="btnradio_rep2" autocomplete="off" checked>
<label class="btn btn-outline-primary me-2" for="btnradio_rep2" onclick="display_rep_rmsf();">RMSF</label>
<input type="radio" class="btn-check" name="btnradio_rep" id="btnradio_rep1" autocomplete="off">
<label class="btn btn-outline-primary me-2" for="btnradio_rep1" onclick="display_rep_phi();">Std. Phi</label>
<input type="radio" class="btn-check" name="btnradio_rep" id="btnradio_rep3" autocomplete="off">
<label class="btn btn-outline-primary me-2" for="btnradio_rep3" onclick="display_rep_psi();">Std. Psi</label>
<input type="radio" class="btn-check" name="btnradio_rep" id="btnradio_rep4" autocomplete="off">
<label class="btn btn-outline-primary me-2" for="btnradio_rep4" onclick="display_rep_lddt();">Mean LDDT</label>
<input type="radio" class="btn-check" name="btnradio_rep" id="btnradio_rep5" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio_rep5" onclick="display_all();">Comparison</label>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Metric by Metric Scripts -->
<script>
const spinner = `<div class="d-flex justify-content-center h-100 w-100">
<div class="spinner-border text-primary my-auto" role="status" style="color: #146698 !important;">
<span class="visually-hidden">Loading...</span>
</div>
</div>`;
function display_rep_phi() {{
$('#plot_rep').children().css("position", "absolute").css("z-index", "-1").addClass("blur");
$('#plot_rep').append(spinner);
$("#plot_rep").load("{protein_id}_PHI_pred.html");
}};
function display_rep_rmsf() {{
$('#plot_rep').children().css("position", "absolute").css("z-index", "-1").addClass("blur");
$('#plot_rep').append(spinner);
$("#plot_rep").load("{protein_id}_RMSF_pred.html");
}};
function display_rep_psi() {{
$('#plot_rep').children().css("position", "absolute").css("z-index", "-1").addClass("blur");
$('#plot_rep').append(spinner);
$("#plot_rep").load("{protein_id}_PSI_pred.html");
}};
function display_rep_lddt() {{
$('#plot_rep').children().css("position", "absolute").css("z-index", "-1").addClass("blur");
$('#plot_rep').append(spinner);
$("#plot_rep").load("{protein_id}_LDDT_pred.html");
}};
function display_all() {{
$('#plot_rep').children().css("position", "absolute").css("z-index", "-1").addClass("blur");
$('#plot_rep').append(spinner);
$("#plot_rep").load("{protein_id}_ALL_pred.html");
}};
</script>
<!-- Sequence Viewer Script -->
<script>
const sequence = "{sequence}";
// Adjust track width based on window size
let trackWidth_start = 1117;
if (window.matchMedia("(max-width: 1400px)").matches) {{
trackWidth_start = 1007;
}}
if (window.matchMedia("(max-width: 1200px)").matches) {{
trackWidth_start = 827;
}}
if (window.matchMedia("(max-width: 992px)").matches) {{
trackWidth_start = 587;
}}
if (window.matchMedia("(max-width: 768px)").matches) {{
trackWidth_start = 407;
}}
const boardConfigData = {{
length: sequence.length,
trackWidth: trackWidth_start,
rowTitleWidth: 129,
includeAxis: true,
includeTooltip: true,
disableMenu: false,
range: {{min: 2, max: sequence.length - 1}}
}};
// Sequence track configuration
const sequenceTrack = {{
trackId: "sequenceTrack",
trackHeight: 25,
trackColor: "#F9F9F9",
displayType: "composite",
nonEmptyDisplay: true,
rowTitle: "Sequence",
displayConfig: [
{sequence_track_config}
]
}};
{area_tracks}
// Initialize the feature viewer
const pfv = new RcsbFv.Create({{
boardConfigData: boardConfigData,
rowConfigData: [sequenceTrack, rmsfTrack, phiTrack, psiTrack, lddtTrack],
elementId: "pfv"
}});
// Resize feature viewer on window resize
let trackWidth_current = trackWidth_start;
function resizeFeatureViewer() {{
let newTrackWidth;
if (window.matchMedia("(min-width: 1400px)").matches) {{
newTrackWidth = 1117;
}} else if (window.matchMedia("(min-width: 1200px)").matches) {{
newTrackWidth = 1007;
}} else if (window.matchMedia("(min-width: 992px)").matches) {{
newTrackWidth = 827;
}} else if (window.matchMedia("(min-width: 768px)").matches) {{
newTrackWidth = 587;
}} else {{
newTrackWidth = 407;
}}
if (newTrackWidth !== trackWidth_current) {{
trackWidth_current = newTrackWidth;
pfv.updateBoardConfig({{boardConfigData: {{trackWidth: trackWidth_current}}}});
}}
}};
window.addEventListener('resize', resizeFeatureViewer, false);
</script>
<!-- Footer -->
<div id="footer" class="mt-auto"></div>
</div>
<!-- Load external scripts -->
<script>
$(function() {{
$("#footer").load("https://dsimb.inserm.fr/PEGASUS/footer.html");
$("#plot_rep").load("{protein_id}_RMSF_pred.html");
}});
</script>
</body>
</html>
'''
# Format the HTML content with the variables
html_content = html_template.format(
protein_realname=protein_realname,
protein_id=protein_id,
sequence=sequence,
seq_length=len(sequence),
sequence_track_config=sequence_track_config,
area_tracks=area_tracks
)
# Write the HTML content to the file
output_filepath = os.path.join(output_dir, f"{protein_id}.html")
with open(output_filepath, 'w') as f_out:
f_out.write(html_content)
def generate_result_pages(result_dict, fasta_file, id_mapping, output_dir='result_pages', predictions_dir='predictions'):
"""
Generate result pages for all proteins in the given FASTA file.
Args:
result_dict (dict): Dictionary containing results with proteins as keys.
fasta_file (str): Path to the input FASTA file.
id_mapping (dict): Dictionary mapping the original protein ids with the unique P{i} generated by Pegasus
output_dir (str): Directory to save HTML output files.
predictions_dir (str): Directory where prediction TSV files are stored.
Returns:
None
"""
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Read sequences from FASTA file
headers = []
sequences = []
protein_ids = []
for record in SeqIO.parse(fasta_file, "fasta"):
sequence = str(record.seq).upper()
protein_id = record.id.strip()
header = id_mapping[protein_id]
sequences.append(sequence)
headers.append(header)
protein_ids.append(protein_id)
# Process each protein
for protein_realname, sequence, protein_id in zip(headers, sequences, protein_ids):
# Load TSV data
all_results = load_tsv(protein_id, predictions_dir)
# Generate plots and result page
draw_interactive_plot(result_dict, protein_id, output_dir, all_results)
draw_interactive_plot_all(result_dict, protein_id, output_dir)
write_result_page(result_dict, protein_realname, protein_id, output_dir, sequence)
def write_results_overview_page(job_id, job_duration, date, headers, sequences, protein_ids, results_dict, results_dict_aligned, output_dir, aligned_fasta):
"""
Generate the results overview HTML page with comparison functionality.
Args:
job_id (str): Job identifier.
job_duration (str): Duration of the job.
date (str): Date of the job.
headers (list): List of protein headers.
sequences (list): List of protein sequences.
protein_ids (list): List of protein IDs.
results_dict (dict): Dictionary containing results.
results_dict_aligned (dict or None): Dictionary containing aligned results with None for gaps.
output_dir (str): Directory to save the overview page.
aligned_fasta (bool): Flag indicating if sequences are aligned.
"""
import json
# Prepare the output file path
output_filepath = os.path.join(output_dir, "results_overview.html")
# Generate table rows for each protein
table_rows = ''
for i, prot_id in enumerate(protein_ids):
header = headers[i]
sequence = sequences[i]
seq_length = len(sequence)
table_rows += f'''
<tr>
<td style="width: 2%; cursor:pointer;"></td><!-- Checkbox column; leave empty -->
<td class="details-control" style="width: 2%; cursor:pointer;">
<span class="me-2">
<!-- Arrow icon -->
<svg class="collapse-icon bi bi-caret-right-fill" width="1em" height="1em" fill="currentColor" xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16">
<path d="M12 8L6 12V4l6 4z"/>
</svg>
</span>
</td>
<td class="td-ellipsis"><strong>{prot_id}</strong> - {header}</td>
<td class="text-center" style="width: 8%;">{seq_length}</td>
<td>{sequence}</td> <!-- Hidden column -->
<td class="text-center" style="width: 3%;">
<a class="btn" role="button" href="../predictions/{prot_id}_predictions.tsv" download="{prot_id}_predictions.tsv">
<!-- Download icon -->
<svg width="1.2em" xmlns="http://www.w3.org/2000/svg" fill="none"
viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="align-text-top">
<path stroke-linecap="round" stroke-linejoin="round"
d="M9 8.25H7.5a2.25 2.25 0 0 0-2.25 2.25v9a2.25 2.25 0 0 0 2.25 2.25h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25H15M9 12l3 3m0 0 3-3m-3 3V2.25" />
</svg>
</a>
</td>
<td class="text-center" style="width: 10%;">
<a class="btn" href="{prot_id}.html" role="button" target="_blank">
<!-- View icon -->
<svg width="1.2em" xmlns="http://www.w3.org/2000/svg" fill="none"
viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="align-text-top">
<path stroke-linecap="round" stroke-linejoin="round"
d="M13.5 6H5.25A2.25 2.25 0 0 0 3 8.25v10.5A2.25 2.25 0 0 0 5.25 21h10.5A2.25 2.25 0 0 0 18 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
</svg>
</a>
</td>
</tr>
'''
# Construct the full HTML content
html_content = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Website title -->
<title>PEGASUS Results Overview</title>
<link id="favicon" rel="icon" href="https://dsimb.inserm.fr/PEGASUS/images/favicon.png" type="image/png" sizes="16x16">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="https://cdn.datatables.net/v/bs5/dt-2.1.8/b-3.1.2/b-colvis-3.1.2/b-html5-3.1.2/r-3.0.3/sl-2.1.0/datatables.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/v/bs5/dt-2.1.8/b-3.1.2/b-colvis-3.1.2/b-html5-3.1.2/r-3.0.3/sl-2.1.0/datatables.min.js"></script>
<!-- Plotly -->
<script src="https://cdn.plot.ly/plotly-2.12.1.min.js"></script>
<!-- Custom styles for this template -->