-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path13th-streamlit-gmxtoolbox.py
2692 lines (2389 loc) · 143 KB
/
13th-streamlit-gmxtoolbox.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
# -*- coding: utf-8 -*-
"""
Version 1.7: Add x_scale and y_scale for plotly;continus error band added, DSSP(+percentage plot), Renumber MODELS in PDB; modified the restraints adder function
Created on Tue 16:15:48 2024-05-14
@author: dozeduck
"""
# import getopt
# import sys
import re
import os
import pandas as pd
import mimetypes
# import plotly
import plotly.graph_objs as go
import plotly.io as pio
# for PCA
import numpy as np
# import rpy2.robjects as ro
# from rpy2.robjects import pandas2ri
# from rpy2.robjects.packages import importr
# from rpy2.robjects import conversion, default_converter
# for free energy
import io
# for histogram dist plot
import plotly.figure_factory as ff
# import argparse
# for bool values
import ast
# metal restraints adding
import math
# for Streamlit usage, wide screen display
import streamlit as st
st.set_page_config(layout="wide")
from tempfile import NamedTemporaryFile
import base64
# for contact map
import MDAnalysis as mda
from MDAnalysis.analysis import contacts
import csv
import matplotlib.pyplot as plt
# for plot dssp
import json
# for RMSD per Residue
from Bio.PDB import PDBParser
import matplotlib.colors as mcolors
#################################################################################################################################################
class plotly_go():
flag = ''
sasa_flag = ''
pca_flag = ''
time1 = []
values1 = []
sd1 = []
time2 = []
values2 = []
sd2 = []
time3 = []
values3 = []
sd3 = []
max_value = []
average_value = []
multi_flag = ''
def __init__(self, multi_files, output_name, renumber, rdf_cutoff, average, ls
, nbin, size, move_average, mean_value, histogram, xaxis_name, yaxis_name, xaxis_size, yaxis_size, xy_font, title_font, legend_show, legend_font, font_family, font_color, grid_show, uploaded_filenames, l,r,t,b, violin, smooth, error_bar, replica_number, axis_show, line_width, transparency
, x_low, x_high, y_low, y_high):
if len(multi_files) >=1:
# print(multi_files)
file1 = multi_files[0]
self.flag_recognizer(file1, plot_name)
if self.pca_flag != 1 and self.flag != 'pca' and self.flag != 'free energy':
self.plotly_multy(multi_files, output_name, renumber, rdf_cutoff, average, plot_name, nbin, size, move_average, mean_value, histogram, xaxis_name, yaxis_name, xaxis_size, yaxis_size, xy_font, title_font, legend_show, legend_font, font_family, font_color, grid_show, self.flag, uploaded_filenames, l,r,t,b, violin, smooth, error_bar, replica_number, axis_show, line_width, transparency, x_low, x_high, y_low, y_high)
elif self.pca_flag == 1:
self.plotly_pca(multi_files, output_name, renumber, rdf_cutoff, average, plot_name, nbin, size, move_average, mean_value, histogram, xaxis_name, yaxis_name, xaxis_size, yaxis_size, xy_font, title_font, legend_show, legend_font, font_family, font_color, grid_show, self.flag, uploaded_filenames, l,r,t,b, smooth, axis_show, line_width, x_low, x_high, y_low, y_high)
elif self.flag == 'pca':
self.plotly_pca(multi_files, output_name, renumber, rdf_cutoff, average, plot_name, nbin, size, move_average, mean_value, histogram, xaxis_name, yaxis_name, xaxis_size, yaxis_size, xy_font, title_font, legend_show, legend_font, font_family, font_color, grid_show, self.flag, uploaded_filenames, l,r,t,b, smooth, axis_show, line_width, x_low, x_high, y_low, y_high)
elif self.flag == 'free energy':
self.plotly_free_energy(multi_files, output_name, plot_name, nbin, size, xaxis_name, yaxis_name, xaxis_size, yaxis_size, xy_font, title_font, legend_show, legend_font, font_family, font_color, grid_show, self.flag, uploaded_filenames, l,r,t,b, violin, smooth, error_bar, replica_number, axis_show, line_width, transparency, x_low, x_high, y_low, y_high)
def flag_recognizer(self,file1, plot_name): # first method to be called in __main__, used for creating object and charactors.
flags_map = {
'rms,': 'rmsd',
'rmsd' : 'rmsd',
'rmsf,': 'rmsf',
'rmsf' : 'rmsf',
'sasa,': 'sasa',
'sasa' : 'sasa',
'gyrate,': 'gyrate',
'gyrate' : 'gyrate',
'dipoles,': 'dipoles',
'dipoles' : 'dipoles',
'distance,': 'distance',
'distance' : 'distance',
'rdf,': 'rdf',
'rdf' : 'rdf',
'convergence': 'convergence',
'anaeig,': 'pca',
'pca' : 'pca',
'angle,': 'angle',
'angle' : 'angle',
'free': 'free energy'
}
if file1.endswith(".xvg"):
with open(file1, 'r') as f:
lines = f.readlines()
if len(lines) >= 3:
try:
flag = lines[2].split()[5]
self.flag = flags_map.get(flag, flag)
except IndexError:
pass
if len(lines) >= 9 and '-or' in lines[8]:
self.sasa_flag = '-or'
if 'pca' in str(file1).lower() or '2dproj' in str(file1):
self.pca_flag = 1
print("I know you are plotting " + self.flag + " figures!")
elif file1.endswith(".csv"):
found = False
for key in flags_map:
if key.strip(',') in plot_name.lower():
found = True
self.flag = flags_map[key]
break
elif file1.endswith(".dat"):
with open(file1, 'r') as f:
lines = f.readlines()
first_line = lines[0]
flag = 'free' if 'free' in first_line else None
self.flag = flags_map.get(flag, flag)
print("I know you are plotting " + self.flag + " figures!")
def consist(self,x_values):
seq1 = [x_values[0]]
seq2 = []
# seq3 = []
for i in range(1, len(x_values)):
# find the break point
if x_values[i] <= x_values[i-1]+2 and seq2 == []:
seq1.append(x_values[i])
else:
seq2.append(x_values[i])
return seq1, seq2
def read_data(self, file, x_name, renumber):
# 从文件中读取数据
x_data, y_data, sd_data = [], [], []
if file.endswith(".xvg"):
with open(file, "r") as f:
lines = f.readlines()
for line in lines:
if line.startswith("#") or line.startswith("@"):
continue
else:
# 解析数据行
split_line = line.split()
x_value = float(split_line[0])
y_value = float(split_line[1])
if x_name == 'Time (ps)': # 将时间从ps转换为ns
x_value /= 1000
if x_name == 'Residue' and renumber == 'true':
x_value = len(x_data) + 1
x_data.append(x_value)
y_data.append(y_value)
# 读取标准差(如果存在)
try:
sd_data.append(float(split_line[2]))
except IndexError:
pass
elif file.endswith(".csv"):
df = pd.read_csv(file, skiprows=0)
x_data = df[df.columns[0]].tolist() # 第一列作为X轴数据
if x_name == 'Time (ps)': # 将时间从ps转换为ns
scaled_list = [x / 1000 for x in x_data]
x_data = scaled_list
elif x_name in ['Residue', 'residue'] and renumber == 'true':
x_data = list(range(1,len(x_data)+1))
# 将除第一列外的所有列作为Y轴数据,每列一个Y数据序列
y_data = [df[col].tolist() for col in df.columns[1:]]
# CSV文件不包含标准差数据,因此sd_data保持为空
return x_data, y_data, sd_data
def read_data_xvg(self, file, x_name, renumber):
# 从文件中读取数据
x_data, y_data, sd_data = [], [], []
with open(file, "r") as f:
lines = f.readlines()
for line in lines:
if line.startswith("#") or line.startswith("@"):
continue
else:
# 解析数据行
split_line = line.split()
x_value = float(split_line[0])
y_value = float(split_line[1])
if x_name == 'Time (ps)': # 将时间从ps转换为ns
x_value /= 1000
if x_name == 'Residue' and renumber == 'true':
x_value = len(x_data) + 1
x_data.append(x_value)
y_data.append(y_value)
# 读取标准差(如果存在)
try:
sd_data.append(float(split_line[2]))
except IndexError:
pass
return x_data, y_data, sd_data
def read_data_csv(self, file, x_name, renumber):
x_data, y_data, sd_data = [], [], []
df = pd.read_csv(file, skiprows=0)
x_data = df[df.columns[0]].tolist() # 第一列作为X轴数据
if x_name == 'Time (ps)': # 将时间从ps转换为ns
scaled_list = [x / 1000 for x in x_data]
x_data = scaled_list
elif x_name in ['Residue', 'residue'] and renumber == 'true':
x_data = list(range(1,len(x_data)+1))
# 将除第一列外的所有列作为Y轴数据,每列一个Y数据序列
y_data = [df[col].tolist() for col in df.columns[1:]]
# CSV文件不包含标准差数据,因此sd_data保持为空
return x_data, y_data, sd_data
def read_data_dat(self, file_name):
with open(file_name, 'r') as file:
lines = file.readlines()
# Identifying the line with column names
columns_line = [line for line in lines if line.startswith('#! FIELDS')][0]
# Extracting column names
column_names = columns_line.strip().split()[2:] # Skip '#! FIELDS'
# 判断free_energy data 在第几列
index_of_free_energy = [index for index, name in enumerate(column_names) if 'free' in name][0]
# Extracting data lines (those not starting with '#')
data_lines = [line for line in lines if not line.startswith('#')]
# Converting data lines to a pandas DataFrame
df = pd.read_csv(io.StringIO('\n'.join(data_lines)), delim_whitespace=True, names=column_names)
if index_of_free_energy == 2:
x_data = df[df.columns[0]].tolist() # 第一列作为X轴数据
y_data = df[df.columns[1]].tolist() # 第2列作为y轴数据
z_data = df[df.columns[2]].tolist() # 第3列作为z轴数据
elif index_of_free_energy == 1:
x_data = df[df.columns[0]].tolist() # 第一列作为X轴数据
y_data = df[df.columns[1]].tolist() # 第2列作为y轴数据
z_data = []
# CSV文件不包含标准差数据,因此sd_data保持为空
return x_data, y_data, z_data, df, index_of_free_energy, column_names
def extract_plot_details(self, multi_files, plot_name, xaxis_name, yaxis_name, flag, histogram):
traces_name_list = []
## Read XVG files
if multi_files[0].endswith(".xvg"):
regex = r"\[|\]|'"
# 提取或设置图表标题
if plot_name == 'auto detect':
with open(multi_files[0], "r") as f:
plot_title = re.sub(regex, "", str(re.findall('"([^"]*)"', f.readlines()[13])))
else:
plot_title = str(plot_name)
# 提取或设置X轴名称
if xaxis_name == 'auto detect':
with open(multi_files[0], "r") as f:
x_name = re.sub(regex, "", str(re.findall('"([^"]*)"', f.readlines()[14])))
else:
x_name = xaxis_name
# 提取或设置Y轴名称
if yaxis_name == 'auto detect':
with open(multi_files[0], "r") as f:
y_name = re.sub(regex, "", str(re.findall('"([^"]*)"', f.readlines()[15])))
if plot_title in ['Solvent Accessible Surface', 'Area per residue over the trajectory']:
y_name = 'Area (nm<sup>2</sup>)'
elif flag == 'dihedral_distribution' and histogram == 'true':
y_name = 'Probability'
else:
y_name = yaxis_name
## Read CSV files
elif multi_files[0].endswith(".csv"):
df = pd.read_csv(multi_files[0])
# 提取或设置图表标题
if plot_name == 'auto detect':
base_name = os.path.basename(multi_files[0])
filename = os.path.splitext(base_name)[0]
plot_title = str(filename)
else:
plot_title = str(plot_name)
# 提取或设置X轴名称
if xaxis_name == 'auto detect':
x_name = df.columns[0]
else:
x_name = xaxis_name
# 提取或设置Y轴名称
if yaxis_name == 'auto detect':
y_name = ''
traces_name_list.extend(df.columns[1:])
else:
y_name = yaxis_name
traces_name_list.extend(df.columns[1:])
return plot_title, x_name, y_name, traces_name_list
def define_trace(self, x_data, y_data, file_name, colour, violine='False', flag=0, labels=0, smooth=0):
# 创建并返回迹线
if flag == 'pca' and smooth != 'true':
trace = go.Scatter(
x=x_data,
y=y_data,
mode='markers',
marker=dict(
color=labels, # 设置颜色为标签的数值
colorscale=colour, # 颜色映射,你可以根据需要选择不同的颜色映射
colorbar=dict(title='Label Range'), # 添加颜色条
),
)
elif flag =='pca' and smooth == 'true':
trace = go.Heatmap(z=x_data, colorscale='Viridis', showscale=True, connectgaps=True, zsmooth='best')
elif flag =='angle' and smooth == 'true':
trace = go.Heatmap(z=x_data, colorscale='Viridis', showscale=True, connectgaps=True, zsmooth='best', x=[-180, -120, -60, 60, 120,180], y=[-180, -120, -60, 60, 120,180])
elif flag not in ['pca', 'angle'] and smooth == 'true':
trace = go.Heatmap(z=x_data, colorscale='Viridis', showscale=True, connectgaps=True, zsmooth='best')
elif violine != 'False':
trace = go.Violin(x0=str(file_name).split('.')[0], y=y_data, line=dict(color='black'), fillcolor=colour, name=str(file_name).split('.')[0], box_visible=True, meanline_visible=True, opacity=0.6)
else:
trace = go.Scatter(x=x_data, y=y_data, line=dict(color=colour), name=str(file_name).split('.')[0])
return trace
def calculate_for_error_bar_or_band(self, multi_files, x_name, replica_number, uploaded_filenames):
df_data = pd.DataFrame()
df_average = pd.DataFrame()
df_sd = pd.DataFrame()
count = 1
if multi_files[0].endswith(".xvg"):
for i, file in enumerate(multi_files):
x_data, y_data, _ = self.read_data_xvg(file, x_name, renumber)
if i == 0:
x_datas = x_data
df_data[f'y_data_{i+1}'] = y_data
if i == (count * replica_number) - 1: # 检查是否达到组内文件数量
# 计算当前df_data的所有列的平均值和标准差
mean_vals = df_data.mean(axis=1)
std_vals = df_data.std(axis=1)
# 将计算得到的平均值和标准差添加到相应的DataFrame中
df_average[uploaded_filenames[(count-1)*3]] = mean_vals
df_sd[uploaded_filenames[(count-1)*3]] = std_vals
# 重置df_data以便下一组的使用,并更新计数器
df_data = pd.DataFrame()
count += 1
elif multi_files[0].endswith(".csv"):
for i, file in enumerate(multi_files):
x_data, y_data, _ = self.read_data_csv(file, x_name, renumber)
if i == 0:
x_datas = x_data
df_data[f'y_data_{i+1}'] = y_data
if i == (count * replica_number) - 1: # 检查是否达到组内文件数量
# 计算当前df_data的所有列的平均值和标准差
mean_vals = df_data.mean(axis=1)
std_vals = df_data.std(axis=1)
# 将计算得到的平均值和标准差添加到相应的DataFrame中
df_average[uploaded_filenames[(count-1)*3]] = mean_vals
df_sd[uploaded_filenames[(count-1)*3]] = std_vals
# 重置df_data以便下一组的使用,并更新计数器
df_data = pd.DataFrame()
count += 1
elif multi_files[0].endswith(".dat"):
for i, file in enumerate(multi_files):
x_data, y_data, z_data, df, index_of_free_energy, column_names = self.read_data_dat(file, x_name, renumber)
if i == 0:
x_datas = x_data
df_data[f'y_data_{i+1}'] = y_data
if i == (count * replica_number) - 1: # 检查是否达到组内文件数量
# 计算当前df_data的所有列的平均值和标准差
mean_vals = df_data.mean(axis=1)
std_vals = df_data.std(axis=1)
# 将计算得到的平均值和标准差添加到相应的DataFrame中
df_average[uploaded_filenames[(count-1)*3]] = mean_vals
df_sd[uploaded_filenames[(count-1)*3]] = std_vals
# 重置df_data以便下一组的使用,并更新计数器
df_data = pd.DataFrame()
count += 1
return df_average, df_sd, x_datas
def hex_to_rgba(self, hex_color, alpha=0.2):
# 移除可能的 "#" 符号
hex_color = hex_color.lstrip('#')
# 通过列表推导从十六进制字符串中提取并转换为RGB整数值
rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
# 将RGB整数值和透明度alpha组合成RGBA字符串
return f"rgba({rgb[0]}, {rgb[1]}, {rgb[2]}, {alpha})"
def define_trace_for_error_bands(self, error_bar, df_average, df_sd, x_data, transparency):
Plotly = ['#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3', '#FF6692', '#B6E880', '#FF97FF', '#FECB52']
colors = ['rgb(0,100,80)', 'rgb(255,0,0)'] # 不同组使用不同颜色
traces = []
if error_bar =='error band':
for idx, (col_name_avg, col_name_sd) in enumerate(zip(df_average.columns, df_sd.columns)):
y = df_average[col_name_avg]
y_std = df_sd[col_name_sd]
y_upper = y + y_std
y_lower = y - y_std
fill_color = self.hex_to_rgba(Plotly[idx], alpha=transparency)
traces.append(go.Scatter(
x=x_data,
y=y,
line=dict(color=Plotly[idx]),
mode='lines',
name=col_name_avg # 使用列名作为轨迹名称
))
traces.append(go.Scatter(
x=list(x_data) + list(x_data)[::-1],
y=list(y_upper) + list(y_lower)[::-1],
fill='toself',
fillcolor=fill_color,
line=dict(color='rgba(255,255,255,0)'),
hoverinfo="skip",
showlegend=False
))
elif error_bar == 'error bar':
for idx, (col_name_avg, col_name_sd) in enumerate(zip(df_average.columns, df_sd.columns)):
y = df_average[col_name_avg]
y_std = df_sd[col_name_sd]
traces.append(go.Scatter(
x=x_data,
y=df_average[col_name_avg],
error_y=dict(type='data', array=df_sd[col_name_sd], visible=True)
))
return traces
def setup_layout(self, plot_title, title_font, x_name, y_name, xy_font, xaxis_size, yaxis_size, font_color, legend_show, legend_font, font_family, grid_show, l,r,t,b, x_low, x_high, y_low, y_high, violine='False', flag=0, axis_shows='True', line_width=2):
# 设置布局
if flag == 'pca':
legend_show = False
if violine != 'False':
x_name = ''
if y_low == y_high == 0:
y_autorange = True
else:
y_autorange = False
if x_low == x_high == 0:
x_autorange = True
else:
x_autorange = False
layout = go.Layout(
title=plot_title, title_x=0.5, title_y=0.99, font=dict(size=title_font, color=font_color),
xaxis=dict(title=x_name, titlefont=dict(size=xy_font, color=font_color, family=font_family), zeroline=False, autorange=x_autorange, range=[x_low,x_high],
showgrid=grid_show, gridwidth=1, gridcolor='rgba(235,240,248,100)', tickfont=dict(size=30), showline=axis_shows, linewidth=line_width, linecolor=font_color),
yaxis=dict(title=y_name, titlefont=dict(size=xy_font, color=font_color, family=font_family), zeroline=False, autorange=y_autorange, range=[y_low,y_high],
showgrid=grid_show, gridwidth=1, gridcolor='rgba(235,240,248,100)', tickfont=dict(size=30), showline=axis_shows, linewidth=line_width, linecolor=font_color),
legend=dict(x=1, y=1, orientation='v', font=dict(size=legend_font, color=font_color)), showlegend=legend_show,
plot_bgcolor='rgba(255, 255, 255, 0.1)',
paper_bgcolor='rgba(255, 255, 255, 0.2)',
margin=dict(l=int(l), r=int(r), t=int(t), b=int(b)),
width=xaxis_size, height=yaxis_size
)
return layout
def pca_bins_density_define(self, nbins, data):
# 确定边界
x_min, y_min = np.min(data, axis=0)
x_max, y_max = np.max(data, axis=0)
# 创建网格
n_bins = nbins
x_bins = np.linspace(x_min, x_max, n_bins + 1)
y_bins = np.linspace(y_min, y_max, n_bins + 1)
# 计算每个格子内的点的数量(密度)
density_matrix = np.zeros((n_bins, n_bins))
for x, y in data:
x_idx = np.digitize(x, x_bins) - 1
y_idx = np.digitize(y, y_bins) - 1
# 确保索引不超出density_matrix的范围
x_idx = min(x_idx, n_bins - 1)
y_idx = min(y_idx, n_bins - 1)
density_matrix[y_idx, x_idx] += 1 # 注意矩阵的索引和坐标系的方向
return density_matrix
def plot_heatmap(self, x_points, y_points, plot_title, x_name, y_name, size, output_name):
pandas2ri.activate()
# 用Python计算高度和宽度
x_diff = np.max(x_points) - np.min(x_points)
y_diff = np.max(y_points) - np.min(y_points)
width= (x_diff / y_diff) * size
height = 1 * size
with conversion.localconverter(default_converter):
# 将Python列表转换为R向量,并创建data.frame
data = ro.DataFrame({x_name: ro.FloatVector(x_points), y_name: ro.FloatVector(y_points)})
ro.globalenv['data'] = data
# 手动定义RdYlBu颜色渐变
rdylbu_colors = [
"#d73027", # 红色
"#f46d43", # 红橙色
"#fdae61", # 橙黄色
"#fee090", # 浅黄色
"#ffffbf", # 最浅的黄色
"#e0f3f8", # 浅蓝色
"#abd9e9", # 天蓝色
"#74add1", # 亮蓝色
"#4575b4", # 蓝色
]
# 执行其他R指令
ro.globalenv['zBot'] = 1.52
ro.globalenv['zTop'] = 3.42
ro.globalenv['zW'] = 0.83
# 在R全局环境中创建颜色向量
# ro.globalenv['buylrd'] = ro.StrVector(rdylbu_colors)
# color_ramp_function = ro.r('colorRamp')(ro.globalenv['buylrd']) # 从颜色向量创建颜色渐变函数
# ro.globalenv['color_ramp'] = color_ramp_function # 将颜色渐变函数保存到全局环境中
ro.r('library(RColorBrewer)')
ro.globalenv['buylrd'] = ro.r('rev(brewer.pal(11,"RdYlBu"))')
# 设置文件名并保存为PNG
if output_name == 'output.png':
output_filename = "DensityMap_output.png" # 示例文件名,你可能需要根据multi_files调整
else:
output_filename = "DensityMap_" + output_name
# 绘制图形并保存
grDevices = importr('grDevices')
grDevices.png(file="/tmp/" + output_filename, height=height, width=width)
# ro.r('smoothScatter(data$%s ~ data$%s, colramp = color_ramp, nrpoints=Inf, pch="", cex=.7, col="black", main=%r, xlab=%r, ylab=%r, transformation = function(x) x^.45)' % (y_name, x_name, plot_title, x_name, y_name))
ro.r('smoothScatter(data$y_name ~ data$x_name, colramp=colorRampPalette(c(buylrd)), nrpoints=Inf, pch="", cex=.7, col="black", main="Title")')
# ro.r('''
# smoothScatter(data$%s ~ data$%s, colramp=color_ramp, nrpoints=Inf, pch="", cex=.7, col="black", main=%r, xlab=%r, ylab=%r, transformation=function(x) x^.45)
# ''' % (y_name, x_name, plot_title, x_name, y_name))
grDevices.dev_off()
pandas2ri.deactivate()
# Download the file
self.streamlit_download_file_plotly(output_filename, "/tmp/" + output_filename)
def streamlit_download_file_plotly(self, download_name, content_file):
# 读取文件内容
with open(content_file, "rb") as file:
file_content = file.read()
# 获取文件的 MIME 类型
mime_type, _ = mimetypes.guess_type(content_file)
# 创建下载按钮
st.download_button(
label=f"Download {download_name}",
data=file_content,
file_name=download_name,
mime=mime_type)
def plot_graph(self, data, layout, output_file_name):
# 使用数据和布局绘制图形
fig = go.Figure(data=data, layout=layout)
pio.write_image(fig, "/tmp/" + output_file_name)
self.streamlit_download_file_plotly(output_file_name, "/tmp/" + output_file_name)
def plot_histogram(self, histogram_data, group_labels, plot_title, output_file_name, colors, nbin):
# 处理直方图
fig_hist = ff.create_distplot(histogram_data, group_labels, colors=colors, bin_size=nbin, curve_type='normal')
fig_hist.update_layout(title_text=plot_title)
pio.write_image(fig_hist, "/tmp/" + output_file_name)
self.streamlit_download_file_plotly("hist_" + output_file_name, "/tmp/" + output_file_name)
def calculate_average(self, multi_files, xaxis_name, renumber):
# 计算平均值
sum_data = None
for file in multi_files:
x_data, y_data, _ = self.read_data(file, xaxis_name, renumber)
if sum_data is None:
sum_data = np.array(y_data)
else:
sum_data += np.array(y_data)
return sum_data / len(multi_files)
def output_average_file(self, output_file_name, average_value, multi_files, xaxis_name, renumber, x_data):
with open(output_file_name[:-4]+"_average.xvg", 'w') as f:
with open(multi_files[0], "r") as a:
lines = a.readlines()
for num in range(len(lines)):
if lines[num].startswith("#") or lines[num].startswith("@"):
f.write(lines[num])
else:
pass
for num in range(len(average_value)):
average_line = "{} {}\n".format(x_data[num], average_value[num])
f.write(average_line)
def moving_average(self, y_data, window_size):
# 计算移动平均
return np.convolve(y_data, np.ones(window_size) / window_size, mode='valid')
def plotly_multy(self, multi_files, output_name, renumber, rdf_cutoff, average, plot_name, nbin, size, move_average, mean_value, histogram, xaxis_name, yaxis_name, xaxis_size, yaxis_size, xy_font, title_font, legend_show, legend_font, font_family, font_color, grid_show, flag, uploaded_filenames, l,r,t,b, violin, smooth, error_bar, replica_number, axis_show, linewidth, transparency, x_low, x_high, y_low, y_high):
Plotly = ['#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3', '#FF6692', '#B6E880', '#FF97FF', '#FECB52']
data, histogram_data, group_labels = [], [], []
# 读取plot_title, x_name, y_name
plot_title, x_name, y_name, traces_name_list = self.extract_plot_details(multi_files, plot_name, xaxis_name, yaxis_name, flag, histogram)
# 读取数据并创建迹线
if multi_files[0].endswith(".xvg"):
for i, file in enumerate(multi_files):
x_data, y_data, _ = self.read_data_xvg(file, x_name, renumber)
points = [list(pair) for pair in zip(x_data, y_data)]
density_matrix = self.pca_bins_density_define(nbin, points)
# 使用 define_trace 创建迹线
if smooth == 'true':
trace = self.define_trace(density_matrix, density_matrix, file, 'rainbow', flag=flag, smooth=smooth) # 假设使用 'rainbow' 作为颜色
else:
trace = self.define_trace(x_data, y_data, uploaded_filenames[i], Plotly[i % len(Plotly)], violine=violin)
data.append(trace)
# 添加直方图数据
if histogram == 'true':
histogram_data.append(y_data)
group_labels.append(str(uploaded_filenames[i]).split('.')[0])
elif multi_files[0].endswith(".csv"):
for i, trace in enumerate(traces_name_list):
x_data, y_data, _ = self.read_data_csv(multi_files[0], x_name, renumber)
points = [list(pair) for pair in zip(x_data, y_data)]
density_matrix = self.pca_bins_density_define(nbin, points)
# 使用 define_trace 创建迹线
if smooth == 'true':
trace = self.define_trace(density_matrix, density_matrix, file, 'rainbow', flag=flag, smooth=smooth) # 假设使用 'rainbow' 作为颜色
else:
trace = self.define_trace(x_data, y_data, uploaded_filenames[i], Plotly[i % len(Plotly)], violine=violin)
data.append(trace)
# 添加直方图数据
if histogram == 'true':
histogram_data.append(y_data)
group_labels.append(str(file).split('.')[0])
# change Time (ps) to Time (ns)
if x_name == 'Time (ps)':
x_name = 'Time (ns)'
# 设置布局
layout = self.setup_layout(plot_title, title_font, x_name, y_name, xy_font, xaxis_size, yaxis_size, font_color, legend_show, legend_font, font_family, grid_show, l, r, t , b, x_low, x_high, y_low, y_high, violine=violin, axis_shows=axis_show, line_width=linewidth)
# 绘制图形
self.plot_graph(data, layout, output_name)
# 处理直方图
if histogram == 'true':
self.plot_histogram(histogram_data, group_labels, plot_title, output_name, Plotly, nbin)
# 处理平均值
if average == 'true':
average_data = self.calculate_average(multi_files, xaxis_name, renumber)
average_trace = self.define_trace(x_data, average_data, "Average", 'black')
# data.append(average_trace)
data = average_trace
self.plot_graph(data, layout, "Average_" + output_name)
self.output_average_file("/tmp/" + output_name, average_data, multi_files, xaxis_name, renumber, x_data)
# 处理移动平均
if move_average != 0:
ma_data = []
for file in multi_files:
_, y_data, _ = self.read_data(file, xaxis_name, renumber)
ma_y_data = self.moving_average(y_data, move_average)
ma_trace = self.define_trace(x_data[move_average - 1:], ma_y_data, str(file).split('.')[0], Plotly[0])
ma_data.append(ma_trace)
self.plot_graph(ma_data, layout, "MovingAverage_" + output_name)
# 处理error band or error bar
if error_bar != 'false':
plot_title, x_name, y_name, traces_name_list = self.extract_plot_details(multi_files, plot_name, xaxis_name, yaxis_name, flag, histogram)
df_average, df_sd, x_data = self.calculate_for_error_bar_or_band(multi_files, x_name, replica_number, uploaded_filenames)
error_data = self.define_trace_for_error_bands(error_bar, df_average, df_sd, x_data, transparency)
# change Time (ps) to Time (ns)
if x_name == 'Time (ps)':
x_name = 'Time (ns)'
error_layout = self.setup_layout(plot_title, title_font, x_name, y_name, xy_font, xaxis_size, yaxis_size, font_color, legend_show, legend_font, font_family, grid_show, l, r, t , b, x_low, x_high, y_low, y_high, violine=violin, axis_shows=axis_show, line_width=linewidth)
self.plot_graph(error_data, error_layout, "error_bar_" + output_name)
def plotly_pca(self, multi_files, output_name, renumber, rdf_cutoff, average, plot_name, nbin, size, move_average, mean_value, histogram, xaxis_name, yaxis_name, xaxis_size, yaxis_size, xy_font, title_font, legend_show, legend_font, font_family, font_color, grid_show, flag, uploaded_filenames, l, r, t ,b, smooth, axis_show, linewidth, x_low, x_high, y_low, y_high):
data = []
color = ['rainbow']
# labels = []
# 使用 extract_plot_details 方法获取图表标题和轴标签
plot_title, x_name, y_name, traces_name_list = self.extract_plot_details(multi_files, plot_name, xaxis_name, yaxis_name, flag, histogram)
if xaxis_name == 'auto detect':
x_name = 'PC1 (nm)'
if yaxis_name == 'auto detect':
y_name = 'PC2 (nm)'
# 处理 PCA 数据
if smooth != 'true':
if multi_files[0].endswith(".xvg"):
for i, file in enumerate(multi_files):
x_data, y_data, _ = self.read_data_xvg(file, "PC1", renumber) # 假设 "PC1" 和 "PC2" 是合适的轴名称
labels = [x for x in range(len(y_data))]
# 使用 define_trace 创建迹线
trace = self.define_trace(x_data, y_data, file, 'rainbow', flag=flag, labels=labels) # 假设使用 'rainbow' 作为颜色
data.append(trace)
elif multi_files[0].endswith(".csv"):
for i, trace in enumerate(traces_name_list):
x_data, y_data, _ = self.read_data_csv(multi_files[0], "PC1", renumber)
labels = [x for x in range(len(y_data[i]))]
trace = self.define_trace(x_data, y_data[i], multi_files[0], 'rainbow', flag=flag, labels=labels)
data.append(trace)
layout = self.setup_layout(plot_title, title_font, x_name, y_name, xy_font, xaxis_size, yaxis_size, font_color, legend_show, legend_font, font_family, grid_show, l, r, t ,b, x_low, x_high, y_low, y_high, flag=flag, axis_shows=axis_show, line_width=linewidth)
elif smooth == 'true':
if multi_files[0].endswith(".xvg"):
for i, file in enumerate(multi_files):
x_data, y_data, _ = self.read_data_xvg(file, "PC1", renumber) # 假设 "PC1" 和 "PC2" 是合适的轴名称
points = [list(pair) for pair in zip(x_data, y_data)]
density_matrix = self.pca_bins_density_define(nbin, points)
# 使用 define_trace 创建迹线
trace = self.define_trace(density_matrix, density_matrix, file, 'rainbow', flag=flag, smooth=smooth) # 假设使用 'rainbow' 作为颜色
data.append(trace)
# def plot_heatmap(self, x_points, y_points, plot_title, x_name, y_name, size, height, width, output_name):
elif multi_files[0].endswith(".csv"):
for i, trace in enumerate(traces_name_list):
x_data, y_data, _ = self.read_data_csv(multi_files[0], "PC1", renumber)
points = [list(pair) for pair in zip(x_data, y_data[0])]
density_matrix = self.pca_bins_density_define(nbin, points)
trace = self.define_trace(density_matrix, density_matrix, multi_files[0], 'rainbow', flag=flag, smooth=smooth)
data.append(trace)
# 使用 setup_layout 设置布局
layout = self.setup_layout(plot_title, title_font, x_name, y_name, xy_font, xaxis_size, yaxis_size, font_color, legend_show, legend_font, font_family, grid_show, l, r, t ,b, x_low, x_high, y_low, y_high, flag=flag, axis_shows=axis_show, line_width=linewidth)
# 使用 rpy2 绘制图形
# self.plot_heatmap(x_data, y_data, plot_title, x_name, y_name, size, output_name)
# 使用 plot_graph 绘制图形
self.plot_graph(data, layout, "Scatter_" + output_name)
def plotly_free_energy(self, multi_files, output_name, plot_name, nbin, size, xaxis_name, yaxis_name, xaxis_size, yaxis_size, xy_font, title_font, legend_show, legend_font, font_family, font_color, grid_show, flag, uploaded_filenames, l,r,t,b, violin, smooth, error_bar, replica_number, axis_show, linewidth, transparency, x_low, x_high, y_low, y_high):
Plotly = ['#636EFA', '#EF553B', '#00CC96', '#AB63FA', '#FFA15A', '#19D3F3', '#FF6692', '#B6E880', '#FF97FF', '#FECB52']
data, histogram_data, group_labels = [], [], []
plot_title = 'Free Energy Surface'
for i, file in enumerate(multi_files):
x_data, y_data, z_data, df, index_of_free_energy, column_names = self.read_data_dat(file)
# 如果有3列,则为phi psi 自由能
if index_of_free_energy == 2:
if 'phi' in column_names or 'psi' in column_names:
x_values = np.degrees(np.unique(x_data))
y_values = np.degrees(np.unique(y_data))
else:
x_values = np.unique(x_data)
y_values = np.unique(y_data)
x_grid, y_grid = np.meshgrid(x_values, y_values)
z_data_array = np.array(z_data)
free_energy_grid = z_data_array.reshape(len(y_values), len(x_values))
# Plot the FES
plt.contourf(x_grid, y_grid, free_energy_grid, levels=100)
if xaxis_name == 'auto detect' and yaxis_name == 'auto detect':
xaxis_name = column_names[0]
yaxis_name = column_names[1]
plt.xlabel(xaxis_name)
plt.ylabel(yaxis_name)
else:
plt.xlabel(xaxis_name)
plt.ylabel(yaxis_name)
plt.colorbar(label='Free energy / kJ mol^-1')
plt.title('Free Energy Surface')
plt.savefig("/tmp/" + str(i) + "_" + output_name)
self.streamlit_download_file_plotly(str(i) + "_" + output_name, "/tmp/" + str(i) + "_" + output_name)
# 3D plot
fig=plt.figure(figsize=(24,14), dpi=600)
ax = plt.axes(projection='3d')
surf = ax.plot_surface(x_grid, y_grid, free_energy_grid, cmap = 'jet', rstride=1, cstride=1, alpha=None, linewidth=0, antialiased=True)
# Set axes label
ax.set_title('Free Energy Surface')
ax.set_xlabel(xaxis_name, labelpad=5)
ax.set_ylabel(yaxis_name, labelpad=5)
ax.set_zlabel('Free energy / kJ mol^-1', labelpad=5)
fig.colorbar(surf, shrink=0.7, aspect=15)
plt.savefig("/tmp/" + str(i) + "_3D_" + output_name)
self.streamlit_download_file_plotly(str(i) + "_3D_" + output_name, "/tmp/" + str(i) + "_3D_" + output_name)
# 如果有2列,则为distance 自由能
elif index_of_free_energy == 1:
if xaxis_name == 'auto detect':
x_name = column_names[0]
else:
x_name = xaxis_name
if yaxis_name == 'auto detect':
y_name = 'Free energy / kJ mol<sup>-1</sup>'
else:
y_name = yaxis_name
# 使用 define_trace 创建迹线
trace = self.define_trace(x_data, y_data, uploaded_filenames[i], Plotly[i % len(Plotly)], violine=violin)
data.append(trace)
if data != []:
# 设置布局
layout = self.setup_layout(plot_title, title_font, x_name, y_name, xy_font, xaxis_size, yaxis_size, font_color, legend_show, legend_font, font_family, grid_show, l, r, t , b, x_low, x_high, y_low, y_high, violine=violin, axis_shows=axis_show, line_width=linewidth)
# 绘制图形
self.plot_graph(data, layout, output_name)
##########################################################################################################################################################################################
class mr(): # read content from the uploaded file directly.
head = ''
total_atom = 0
resid = []
resname= []
atomname = []
index = []
x = []
y = []
z = []
xyz = []
last = ''
metals = []
coordinators = []
metal1 = 0
metal2 = 0
metal3 = 0
metal4 = 0
metal5 = 0
metal6 = 0
metal7 = 0
atom1 = []
atom2 = []
atom3 = []
atom4 = []
atom5 = []
atom6 = []
atom7 = []
def __init__(self, gro,num_neighbours, distance_value, atom_list, metal_list, residue_list, bond_strength, angle_strength):
self.output = ""
self.GROreader(gro)
self.MetalMiner(metal_list)
self.coordinator(num_neighbours, distance_value, atom_list, metal_list, residue_list)
# self.bond_cal(atom6,bond_strength)
# self.pair_cal()
# self.angle_cal(angle_strength)
self.bond_cal( self.metal1, self.atom1, self.metal2, self.atom2, self.metal3, self.atom3, self.metal4, self.atom4, self.metal5, self.atom5, self.metal6, self.atom6, bond_strength)
self.pair_cal( self.metal1, self.atom1, self.metal2, self.atom2, self.metal3, self.atom3, self.metal4, self.atom4, self.metal5, self.atom5, self.metal6, self.atom6)
self.angle_cal( self.metal1, self.atom1, self.metal2, self.atom2, self.metal3, self.atom3, self.metal4, self.atom4, self.metal5, self.atom5, self.metal6, self.atom6, angle_strength)
def GROreader_not_good(self,gro):
lines = gro.splitlines() # for streamlit 如果 'gro' 是一个二进制文件,使用 gro.decode().splitlines()
# extra lines
self.head = lines[0].strip()
self.total_atom = int(lines[1])
self.last = lines[-1]
# 忽略前两行和最后一行
lines = lines[2:-1]
# 逐行解析内容
for line in lines:
line = line.strip() # 去除首尾空格和换行符
match = re.match(r'(\d+)([A-Za-z]{2,})', line)
if match:
self.resid.append(int(match.group(1)))
self.resname.append(str(match.group(2)))
self.atomname.append(str(line.split()[1])) # The 3rd column is the atom name C CA CD1 CD2 and so on
self.index.append(int(line.split()[2])) # Column 4 is the residue name TYR ALA etc.
self.x.append(float(line.split()[3])) # The 5th column is the name of the chain it is on
self.y.append(float(line.split()[4])) # The sixth column is the residue number
self.z.append(float(line.split()[5])) # Column 7 is the x-coordinate of the atom
self.xyz.append([float(line.split()[3]),float(line.split()[4]),float(line.split()[5])])
def GROreader(self, gro):
lines = gro.splitlines() # for streamlit 如果 'gro' 是一个二进制文件,使用 gro.decode().splitlines()
self.head = lines[0].strip()
self.total_atom = int(lines[1])
self.last = lines[-1].strip()
# 忽略前两行和最后一行
lines = lines[2:-1]
# 初始化属性列表
self.resid = []
self.resname = []
self.atomname = []
self.index = []
self.x = []
self.y = []
self.z = []
self.xyz = []
# 逐行解析内容
for line in lines:
resid = int(line[0:5].strip())
resname = line[5:10].strip()
atomname = line[10:15].strip()
atomindex = int(line[15:20].strip())
x = float(line[20:28].strip())
y = float(line[28:36].strip())
z = float(line[36:44].strip())
self.resid.append(resid)
self.resname.append(resname)
self.atomname.append(atomname)
self.index.append(atomindex)
self.x.append(x)
self.y.append(y)
self.z.append(z)
self.xyz.append([x, y, z])
def MetalMiner(self, metal_list):
print(metal_list)
for i in range(len(self.atomname)):
if self.atomname[i] in metal_list and self.resname[i] in metal_list:
self.metals.append(self.index[i])
# the index in list should -1
for i in range(len(self.metals)):
try:
setattr(self, f'metal{i+1}', self.metals[i] - 1)
except IndexError:
pass
metals_name = [self.atomname[i-1] for i in self.metals]
sentence = "The metals atom index are: {}".format(list(zip(metals_name, self.metals)))
st.text(sentence)
# print(self.metal1,self.metal2,self.metal3)
def coordinator(self, num_neighbours, distance_value, atom_list, metal_list, residue_list):
# find the atom index
# st.text(atom_list)
if self.metal1 != 0:
atom_distances = {}
for i in range(len(self.index)):
if self.resname[i] in residue_list and self.atomname[i] in atom_list:
dist = self.distance(self.metal1, i)
if dist <= distance_value:
atom_distances[i] = dist
# 对满足条件的原子按照距离 metal 的距离进行排序
sorted_atoms = sorted(atom_distances.items(), key=lambda x: x[1])
# 仅保留前 num_neighbours 个邻居
self.atom1 = [atom_index for atom_index, _ in sorted_atoms[:num_neighbours]]
if self.metal2 != 0:
atom_distances = {}
for i in range(len(self.index)):
if self.resname[i] in residue_list and self.atomname[i] in atom_list:
dist = self.distance(self.metal2, i)
if dist <= distance_value:
atom_distances[i] = dist
# 对满足条件的原子按照距离 metal 的距离进行排序
sorted_atoms = sorted(atom_distances.items(), key=lambda x: x[1])
# 仅保留前 num_neighbours 个邻居
self.atom2 = [atom_index for atom_index, _ in sorted_atoms[:num_neighbours]]
if self.metal3 != 0:
atom_distances = {}
for i in range(len(self.index)):
if self.resname[i] in residue_list and self.atomname[i] in atom_list:
dist = self.distance(self.metal3, i)
if dist <= distance_value:
atom_distances[i] = dist
# 对满足条件的原子按照距离 metal 的距离进行排序
sorted_atoms = sorted(atom_distances.items(), key=lambda x: x[1])
# 仅保留前 num_neighbours 个邻居
self.atom3 = [atom_index for atom_index, _ in sorted_atoms[:num_neighbours]]
if self.metal4 != 0: