-
Notifications
You must be signed in to change notification settings - Fork 1
/
6th-streamlit-gmxtoolbox.py
1193 lines (1030 loc) · 62.9 KB
/
6th-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 -*-
"""
Created on Fri Apr 14 16:15:48 2024
@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
# from rpy2.robjects import r
# 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
#################################################################################################################################################
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, 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, uploaded_filenames, l,r,t,b, violin, smooth):
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':
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)
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)
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)
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'
}
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
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 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', x=[-180, -120, -60, 60, 120,180], y=[-180, -120, -60, 60, 120,180])
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)
elif 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])
else:
trace = go.Scatter(x=x_data, y=y_data, line=dict(color=colour), name=str(file_name).split('.')[0])
return trace
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, violine='False', flag=0):
# 设置布局
if flag == 'pca':
legend_show = False
if violine != 'False':
x_name = ''
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=True,
showgrid=grid_show, gridwidth=1, gridcolor='rgba(235,240,248,100)', tickfont=dict(size=30)),
yaxis=dict(title=y_name, titlefont=dict(size=xy_font, color=font_color, family=font_family), zeroline=False, autorange=True,
showgrid=grid_show, gridwidth=1, gridcolor='rgba(235,240,248,100)', tickfont=dict(size=30)),
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 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):
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(file, x_name, renumber)
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(multi_files[0], x_name, renumber)
trace = self.define_trace(x_data, y_data[i], trace, 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, violine=violin)
# 绘制图形
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)
# # 调用上述方法
# for i, file in enumerate(multi_files):
# x_data, y_data, sd_data = self.read_data(file, xaxis_name, renumber)
# trace = self.define_trace(x_data, y_data, file, Plotly[i % len(Plotly)])
# 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)
# self.plot_graph(data, layout, 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):
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(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(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, flag=flag)
elif smooth == 'true':
if multi_files[0].endswith(".xvg"):
for i, file in enumerate(multi_files):
x_data, y_data, _ = self.read_data(file, "PC1", renumber) # 假设 "PC1" 和 "PC2" 是合适的轴名称
points = [list(pair) for pair in zip(x_data, y_data[i])]
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)
elif multi_files[0].endswith(".csv"):
for i, trace in enumerate(traces_name_list):
x_data, y_data, _ = self.read_data(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, xaxis_name, yaxis_name, xy_font, xaxis_size, yaxis_size, font_color, legend_show, legend_font, font_family, grid_show, l, r, t ,b, flag=flag)
# 使用 plot_graph 绘制图形
self.plot_graph(data, layout, "Scatter_" + 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(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 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)))
print(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
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:
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.metal4, i)
if dist <= distance_value:
atom_distances[i] = dist
# 对满足条件的原子按照距离 metal 的距离进行排序
sorted_atoms = sorted(atom_distances.items(), key=lambda x: x[1])
# 仅保留前 num_neighbours 个邻居
self.atom4 = [atom_index for atom_index, _ in sorted_atoms[:num_neighbours]]
if self.metal5 != 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.metal5, i)
if dist <= distance_value:
atom_distances[i] = dist
# 对满足条件的原子按照距离 metal 的距离进行排序
sorted_atoms = sorted(atom_distances.items(), key=lambda x: x[1])
# 仅保留前 num_neighbours 个邻居
self.atom5 = [atom_index for atom_index, _ in sorted_atoms[:num_neighbours]]
if self.metal6 != 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.metal6, i)
if dist <= distance_value:
atom_distances[i] = dist
# 对满足条件的原子按照距离 metal 的距离进行排序
sorted_atoms = sorted(atom_distances.items(), key=lambda x: x[1])
# 仅保留前 num_neighbours 个邻居
self.atom6 = [atom_index for atom_index, _ in sorted_atoms[:num_neighbours]]
if self.metal7 != 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.metal7, i)
if dist <= distance_value:
atom_distances[i] = dist
# 对满足条件的原子按照距离 metal 的距离进行排序
sorted_atoms = sorted(atom_distances.items(), key=lambda x: x[1])
# 仅保留前 num_neighbours 个邻居
self.atom7 = [atom_index for atom_index, _ in sorted_atoms[:num_neighbours]]
def distance(self, index1, index2):
distance = math.sqrt((self.x[index2] - self.x[index1])**2 + (self.y[index2] - self.y[index1])**2 + (self.z[index2] - self.z[index1])**2)
return distance
def calculate_distance(self, point1, point2):
x1, y1, z1 = point1
x2, y2, z2 = point2
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2 + (z2 - z1)**2)
return distance
def calculate_angle(self, point1, point2, point3):
vector_ab = np.array(point2) - np.array(point1)
vector_bc = np.array(point2) - np.array(point3)
dot_product = np.dot(vector_ab, vector_bc)
norm_ab = np.linalg.norm(vector_ab)
norm_bc = np.linalg.norm(vector_bc)
cos_angle = dot_product / (norm_ab * norm_bc)
angle_rad = np.arccos(cos_angle)
angle_deg = np.degrees(angle_rad)
return angle_deg
def bond_cal(self, metal1, atom1, metal2, atom2, metal3, atom3, metal4, atom4, metal5, atom5, metal6, atom6, bond_strength):
for i in [1,2,3,4,5,6]:
if locals()["metal" + str(i)] !=0:
metal = locals()["metal" + str(i)]+1
atom = [i + 1 for i in locals()["atom" + str(i)]]
metal_point = [self.x[metal-1],self.y[metal-1],self.z[metal-1]]
print("; please add below to topol.top's distance part")
self.output += "; please add below to topol.top's distance part\n" # for streamlit
for i in atom:
locals()["atom" + str(i)] = [self.x[i-1],self.y[i-1],self.z[i-1]]
print("%5d%6d%6d%7.2f%9d" % (metal, i, 6, self.calculate_distance(metal_point, locals()["atom" + str(i)]), bond_strength))
self.output += "%5d%6d%6d%7.2f%9d\n" % (metal, i, 6, self.calculate_distance(metal_point, locals()["atom" + str(i)]), bond_strength) # for streamlit
def pair_cal(self, metal1, atom1, metal2, atom2, metal3, atom3, metal4, atom4, metal5, atom5, metal6, atom6):
for i in [1,2,3,4,5,6]:
if locals()["metal" + str(i)] !=0:
metal = locals()["metal" + str(i)]+1
atom = [i + 1 for i in locals()["atom" + str(i)]]
target_resid = [self.resid[x-1] for x in atom]
print("; I added the pairs - so the zn will not nonbonded interact with the cyx residues")
self.output += "; add the pairs \n" # for streamlit
for i in range(len(self.atomname)):
if self.atomname[i] == 'CA' and self.resid[i] in target_resid:
print("%5d%6d%6d" % (metal,i+1,1))
self.output += "%5d%6d%6d\n" % (metal,i+1,1) # for streamlit
def angle_cal(self, metal1, atom1, metal2, atom2, metal3, atom3, metal4, atom4, metal5, atom5, metal6, atom6, angle_strength):
for i in [1,2,3,4,5,6]:
if locals()["metal" + str(i)] !=0:
metal = locals()["metal" + str(i)]+1
atom = [i + 1 for i in locals()["atom" + str(i)]]
# define how many neighbour atoms
neighbour = len(atom)
if neighbour >= 2:
metal_point = [self.x[metal-1],self.y[metal-1],self.z[metal-1]]
for i in atom:
locals()["atom" + str(i)] = [self.x[i-1],self.y[i-1],self.z[i-1]]
print("[ angle_restraints ]")
self.output += "[ angle_restraints ]\n" # for streamlit
if neighbour == 2:
print("%5d%6d%6d%6d%5d%9.2f%9d%9d" % (metal, atom[0], metal, atom[1],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[1])]),angle_strength, 1))
self.output += "%5d%6d%6d%6d%5d%9.2f%9d%9d\n" % (metal, atom[0], metal, atom[1],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[1])]),angle_strength, 1) # for streamlit
elif neighbour == 3:
print("%5d%6d%6d%6d%5d%9.2f%9d%9d" % (metal, atom[0], metal, atom[1],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[1])]),angle_strength, 1))
print("%5d%6d%6d%6d%5d%9.2f%9d%9d" % (metal, atom[0], metal, atom[2],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[2])]),angle_strength, 1))
print("%5d%6d%6d%6d%5d%9.2f%9d%9d" % (metal, atom[1], metal, atom[2],1,self.calculate_angle(locals()["atom" + str(atom[1])],metal_point, locals()["atom" + str(atom[2])]),angle_strength, 1))
self.output += "%5d%6d%6d%6d%5d%9.2f%9d%9d\n" % (metal, atom[0], metal, atom[1],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[1])]),angle_strength, 1) # for streamlit
self.output += "%5d%6d%6d%6d%5d%9.2f%9d%9d\n" % (metal, atom[0], metal, atom[2],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[2])]),angle_strength, 1) # for streamlit
self.output += "%5d%6d%6d%6d%5d%9.2f%9d%9d\n" % (metal, atom[1], metal, atom[2],1,self.calculate_angle(locals()["atom" + str(atom[1])],metal_point, locals()["atom" + str(atom[2])]),angle_strength, 1) # for streamlit
elif neighbour == 4:
print("%5d%6d%6d%6d%5d%9.2f%9d%9d" % (metal, atom[0], metal, atom[1],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[1])]),angle_strength, 1))
print("%5d%6d%6d%6d%5d%9.2f%9d%9d" % (metal, atom[1], metal, atom[2],1,self.calculate_angle(locals()["atom" + str(atom[1])],metal_point, locals()["atom" + str(atom[2])]),angle_strength, 1))
print("%5d%6d%6d%6d%5d%9.2f%9d%9d" % (metal, atom[2], metal, atom[3],1,self.calculate_angle(locals()["atom" + str(atom[2])],metal_point, locals()["atom" + str(atom[3])]),angle_strength, 1))
print("%5d%6d%6d%6d%5d%9.2f%9d%9d" % (metal, atom[0], metal, atom[3],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[3])]),angle_strength, 1))
self.output += "%5d%6d%6d%6d%5d%9.2f%9d%9d\n" % (metal, atom[0], metal, atom[1],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[1])]),angle_strength, 1) # for streamlit
self.output += "%5d%6d%6d%6d%5d%9.2f%9d%9d\n" % (metal, atom[1], metal, atom[2],1,self.calculate_angle(locals()["atom" + str(atom[1])],metal_point, locals()["atom" + str(atom[2])]),angle_strength, 1) # for streamlit
self.output += "%5d%6d%6d%6d%5d%9.2f%9d%9d\n" % (metal, atom[2], metal, atom[3],1,self.calculate_angle(locals()["atom" + str(atom[2])],metal_point, locals()["atom" + str(atom[3])]),angle_strength, 1) # for streamlit
self.output += "%5d%6d%6d%6d%5d%9.2f%9d%9d\n" % (metal, atom[0], metal, atom[3],1,self.calculate_angle(locals()["atom" + str(atom[0])],metal_point, locals()["atom" + str(atom[3])]),angle_strength, 1) # for streamlit
def GROwriter(self, gro):
print(self.head)
print("%5d" % (self.total_atom))
for i in range(len(self.resid)):
print("%5d%-3s%7s%5d%8.3f%8.3f%8.3f" % (self.resid[i], self.resname[i], self.atom[i], self.index[i], self.x[i], self.y[i], self.z[i]))
print(self.last)
##########################################################################################################################################################################################
class gromerger(): # read uploaded files
def __init__(self, receptor_gro, ligand_gro, ligand_itp, receptor_top, rec_name, lig_name, ligitp_name, rectop_name):
self.merge_gro_files(receptor_gro, ligand_gro, ligand_itp, receptor_top, rec_name, lig_name, ligitp_name, rectop_name)
def streamlit_download_file(self, download_name, content_file):
# Download topol.top file #
# 打开 content_file 文件并读取其内容
with open(content_file, 'r') as top_file:
content = top_file.read()
# 添加一个下载按钮,传递 receptor_top_content 作为文件内容
st.download_button(
label = "Download " + download_name,
data = content,
key = download_name,
file_name = download_name
)
def merge_gro_files(self, receptor_gro, ligand_gro, ligand_itp, receptor_top, rec_name, lig_name, ligitp_name, rectop_name):
# Merge the two gro files
with open(ligand_gro, 'r') as ligand_file, open(receptor_gro, 'r') as receptor_file:
ligand_lines = ligand_file.readlines()[1:-1]
receptor_lines = receptor_file.readlines()
a = int(receptor_lines[1].split()[0])
b = int(ligand_lines[0].split()[0])
c = a + b
receptor_lines[1] = f"{c}\n"
with open(ligand_gro, 'w') as complex_file:
complex_file.writelines(receptor_lines[0:-1])
complex_file.writelines(ligand_lines[1:])
complex_file.writelines(receptor_lines[-1])
# Edit the topol.top file
# with open('include.dat', 'w') as include_file:
# include_file.write("; Include ligand topology\n")
# include_file.write(f"#include \"{ligitp_name}\"\n")
# include_file.write("#ifdef POSRES_LIG\n")
# include_file.write("#include \"posre_lig.itp\"\n")
# include_file.write("#endif\n")
# adding content to the end of topol file
with open(ligand_itp, 'r') as ligand_itp_file:
# find ligand molecule name
nrexcl_line = None
lines = ligand_itp_file.readlines()
for i in range(len(lines)):
if 'nrexcl' in lines[i]:
nrexcl_line = lines[i+1].strip()
break
if nrexcl_line:
B = nrexcl_line.split()[0]
with open(receptor_top, 'r') as topol_file:
topol_lines = topol_file.readlines()
# add lig_GMX.itp record to topol.top
for i, line in enumerate(topol_lines):
if 'moleculetype' in line:
topol_lines.insert(i, f"#endif\n")
topol_lines.insert(i, f"#include \"posre_lig.itp\"\n")
topol_lines.insert(i, f"#ifdef POSRES_LIG\n")
topol_lines.insert(i, f"#include \"{ligitp_name}\"\n")
topol_lines.insert(i, f"; Include ligand topology\n")
break
# add ligand molecule type to topol.top
for i, line in enumerate(topol_lines):
if 'molecules' in line:
topol_lines.insert(-1, f"{B} 1\n")
break
with open(receptor_top, 'w') as topol_file:
topol_file.writelines(topol_lines)
# download topol.top
self.streamlit_download_file(rectop_name, receptor_top)
self.streamlit_download_file("complex.gro", ligand_gro)
##########################################################################################################################################################################################
class contact_map_detect(): # read uploaded files
protein = ''
ligand = ''
def __init__(self, topol, traj, lig, output, distance):
contact_map = self.calculate_contact(topol, traj, lig, output, distance)
self.plot(contact_map, output_name, distance)
self.csv_writer(contact_map, output_name)
def calculate_contact(self, topol, traj, lig, output, distance):
# 加载蛋白质和配体的拓扑和轨迹文件
u = mda.Universe(topol, traj)
# 选择蛋白质和配体
self.protein = u.select_atoms('protein')
self.ligand = u.select_atoms('resname ' + lig)
# 初始化接触图矩阵
contact_map = np.zeros((len(u.trajectory), len(self.protein.residues)))
# 计算每帧的接触情况
for ts in u.trajectory:
y_ticks = []
y_labels= []
frame_index = ts.frame
for i, residue in enumerate(self.protein.residues):
min_dist = np.min(contacts.distance_array(residue.atoms.positions, self.ligand.positions))
y_ticks.append(i)
y_labels.append(f'{residue.resid} {residue.resname}')
if min_dist < distance:
contact_map[frame_index, i] = 1
return contact_map
def plot(self, contact_map, output_name, distance):
resid_list = [i for i in range(self.protein.residues.resids[0], len(self.protein.residues.resids)+self.protein.residues.resids[0], 5)]
resname_list =[]
for i, residue in enumerate(self.protein.residues):
if residue.resid in resid_list:
resname_list.append(residue.resname)
i_list = range(len(resid_list))
# print(resid_list)
# print(resname_list)
plt.imshow(contact_map.T, aspect='auto', origin='lower', cmap='Greys')
plt.xlabel('Time (ns)')
plt.yticks(ticks=resid_list, labels=['' if (resid_list[i]-self.protein.residues.resids[0]) % 20 != 0 else f'{resid_list[i]} {resname_list[i]}' for i in i_list])
plt.ylabel('Residue Index')
plt.title('Protein-Ligand Contact Map')
plt.suptitle('Distance < ' + str(distance))
plt.colorbar(label='Contact', ticks=[0, 1])
# plt.show()
plt.savefig("/tmp/" + output_name)
self.streamlit_download_file_plotly(output_name, "/tmp/" + output_name)
def csv_writer(self, contact_map, output_name):
# 将contact_map数据写入CSV文件
with open('/tmp/ligand_contact.csv', 'w', newline='') as f:
writer = csv.writer(f)
# 写入标题行,假设每列代表一个残基,每行代表一个时间帧
# header = ['Frame'] + [f'Residue_{i}' for i in range(1, len(protein.residues) + 1)]
header = ['Time (ns)'] + [f'{residue.resid}_{residue.resname}' for i, residue in enumerate(self.protein.residues)]
writer.writerow(header)
# 写入每一行的数据
for frame_index, contacts_ in enumerate(contact_map):
row = [frame_index] + contacts_.tolist()
writer.writerow(row)
self.streamlit_download_file("ligand_contact.csv", '/tmp/ligand_contact.csv')
# print("Contact map data has been written to 'ligand_contact.csv'.")
def streamlit_download_file(self, download_name, content_file):
# Download topol.top file #
# 打开 content_file 文件并读取其内容
with open(content_file, 'r') as top_file:
content = top_file.read()
# 添加一个下载按钮,传递 receptor_top_content 作为文件内容
st.download_button(
label = "Download " + download_name,
data = content,
key = download_name,
file_name = download_name
)
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)
# download topol.top
##########################################################################################################################################################################################
class pep2lig():
pdb = ''
pepname = ''
chain = 'A'
resnum = 1
atomic_index = []
atomic_name = []
residue_name = []
chain_name = []
residue_index = []
X_peratom = []
Y_peratom = []
Z_peratom = []
bfactor_per_factor = []
temp_factor = []
Atomtype_per_atom = []
def __init__(self, pdb, pepname):
self.pdb = pdb
self.pepname = pepname
self.converter(pdb, pepname, self.chain, self.resnum)
self.PDBwriter("/tmp/modified_PEP.pdb")
def converter(self, pdb, pepname, chain, resnum):
with open(pdb, 'r') as infile:
for line in infile: # iterate each line in file "f"
if(line.split()[0] in["ATOM","HETATM"]): # Judgment Sentence,Used to split each row and then determine whether the first column of the row == ATOM or HETATM
self.atomic_index.append(int(line[6:11].strip())) # The second column is the atomic number
self.atomic_name.append(line[12:16].strip()) # The 3rd column is the atom name C CA CD1 CD2 and so on
# self.residue_name.append(line[17:20].strip()) # Column 4 is the residue name TYR ALA etc.
self.residue_name.append(pepname)
# self.chain_name.append(line[21].strip()) # The 5th column is the name of the chain it is on
self.chain_name.append(chain)
# self.residue_index.append(int(line[22:26].strip())) # The sixth column is the residue number
self.residue_index.append(resnum)
self.X_peratom.append(float(line[30:38].strip()))
self.Y_peratom.append(float(line[38:46].strip()))
self.Z_peratom.append(float(line[46:54].strip()))
self.bfactor_per_factor.append(float(line[54:60].strip()) if line[54:60].strip() else 0.0)
self.temp_factor.append(float(line[60:66].strip()) if line[60:66].strip() else 0.0 )
try:
self.Atomtype_per_atom.append(line[76:78].strip())
except:
self.Atomtype_per_atom.append(" ")
def PDBwriter(self,filename):
f = open(filename, "w") # e.g: f = linesplit[0]+"_PO3.pdb"
for i in range (0 ,len(self.atomic_index)): # Create a loop, i is a sequence starting from 0, and the number of atoms is the length
print("%4s%7d %-4s%1s%2s%4d %8.3f%8.3f%8.3f%6.2f%6.2f%12s" % ("ATOM" , # Formatted output, %4s, right-aligned, the output occupies 4 columns in total. If the length is less than 4 columns, the left end will be filled with spaces. If it is greater than 4 columns, the actual length will be output as a string
self.atomic_index[i], # %7d, right-aligned, the output occupies a total of 7 columns, if the length is less than 7 columns, the left end is filled with spaces, signed decimal certificate integer
self.atomic_name[i], # %-4s, left-aligned, the output occupies a total of 4 columns, if the length is less than 4 columns, the right end is filled with spaces, if it is greater than 4 columns, the actual length is output as a string
self.residue_name[i], # %1s, right-aligned, the output occupies a total of 1 column. If it is less than 1 column, it will be filled with spaces from the left end. If it is greater than 1 column, the actual length will be output as a string