-
Notifications
You must be signed in to change notification settings - Fork 13
/
conan.py
executable file
·2091 lines (1984 loc) · 92.1 KB
/
conan.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
# Import a bunch of stuff
import time
import sys
import os
import math
import gc
import numpy as np
import matplotlib.pyplot as plt
import itertools
from scipy.stats import pearsonr
from scipy.stats import sem
from scipy.stats import linregress
from scipy.spatial.distance import pdist
from scipy import var
from scipy.sparse.linalg import eigsh
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
def weight_contacts(r, trunc):
# this function is used for the "weighted number of contacts" for the cross-correlation.
return ((trunc - r) / trunc)
# 0.0 when r>rcut...
def update_interaction(r, trunc_inter, trunc_inter_high, status, inter_mode):
# This function is used for the update of the status of an interaction
# Two modes are implemented at the moment:
# 0 = "history" - status can only be 0 or 1. when the distance is in the buffer, keep the last status.
# 1 = "linear" - status can be fractional, switching between 0 and 1 linearly when in the buffer.
if (trunc_inter == trunc_inter_high):
new_status = int(r < trunc_inter) # If the buffer doesn't exist, the old status is ignored.
elif (inter_mode == 0):
if (r < trunc_inter):
new_status = 1
elif (r > trunc_inter_high):
new_status = 0
else:
new_status = status
elif (inter_mode == 1):
if (r < trunc_inter):
new_status = 1
elif (r > trunc_inter_high):
new_status = 0
else:
new_status = (r - trunc_inter)/(trunc_inter_high - trunc_inter)
return new_status
# new_status can be an integer (1 or 0) but also a real number between (0, 1).
# Add new modes if needed.
# At the moment, inter_mode = 0 is the only one accessible
# ("# of encounters" and "avg encounters" would be needlessly complicated).
def read_in_observables(inputf, time_vec):
# this function will read in the observables from the given file. It gets as input the (open) file
# as well as the available time frames. It returns the time vector (of frames that have both time information
# and observables) and several vectors of observables.
time_vec_out = []
frame_indices = []
obs_vec = []
titles = []
units = []
ntitles = -1
for line in inputf:
if ( not line.startswith("#") and (len(line.split()) > 0) ):
if (ntitles == -1):
ntitles = int(line.split()[0])
elif (len(titles)<ntitles):
title = line[:-1]
titles.append(title)
else:
t = int(float(line.split()[0]))
if (t in time_vec):
ind = time_vec.index(t)
time_vec_out.append(t)
frame_indices.append(ind)
if (not obs_vec):
obs_vec = [ [] for val in range(ntitles)]
for n in range (0, ntitles):
obs_vec[n].append(float(line.split()[n+1]))
return frame_indices, time_vec_out, titles, obs_vec
def cond_index(i, j, n):
# the index in the condensed distance matrix of an element (i,j) from the upper triangle (i<j).
return int(n*(n-1)/2 - (n-i)*(n-i-1)/2 + j - i - 1)
def remove_shadows(dict_frame, nterm, nres, tol):
# assuming a dictionary of a frame, we remove any contact between residue pair (i,j) where there is a
# "shortcut" through a third residue k; this is defined as r_ij > tol* (r_ik + r_jk)
dict_copy = dict(dict_frame)
for pair in dict_frame:
i = pair[0]
j = pair[1]
d0 = dict_frame[pair]
for k in range(nterm, nterm+nres):
pair1 = tuple(sorted((i,k)))
pair2 = tuple(sorted((j,k)))
if (pair1 in dict_frame and pair2 in dict_frame):
if ((dict_frame[pair1] + dict_frame[pair2])*tol < d0 ):
dict_copy.pop((i, j))
break
return dict_copy
def read_in_observables_blind(inputf):
# this function ignores the time column from the observable file and just returns the vectors.
obs_vec = []
titles = []
units = []
ntitles = -1
for line in inputf:
if ( not line.startswith("#") and (len(line.split()) > 0) ):
if (ntitles == -1):
ntitles = int(line.split()[0])
elif (len(titles)<ntitles):
title = line[:-1]
titles.append(title)
else:
if (not obs_vec):
obs_vec = [ [] for val in range(ntitles)]
for n in range (0, ntitles):
obs_vec[n].append(float(line.split()[n+1]))
return titles, obs_vec
def which(program):
# This function checks for the existence of an executable
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return ''
# This function will generate the necessary gnuplot preamble that will label the domains in the axes.
def change_bf_in_pdb (inputpdb, outputpdb, bf_dict):
for line in inputpdb:
lineoutput = line
if (len(line.split()) > 5):
if (line.split()[0]=='ATOM'):
resid = int(line[22:26])
bf = bf_dict.get(resid,0.0)
lineoutput = line[:60] + "%6.2f"%bf + line[66:]
outputpdb.write(lineoutput)
def interaction(str):
# This function identifies a possible interaction between two resiudes, assuming this happens
# through the side chains (but will ignore hydrophobic packing of lysine and other exotic effects).
negative = ['E', 'D']
positive = ['R', 'K']
charged = negative + positive
hydrophobic = ['A', 'F', 'I', 'L', 'M', 'P', 'V', 'W', 'Y']
donor = ['C', 'H', 'N', 'Q', 'S', 'T', 'Y', 'R', 'K']
acceptor = ['D', 'E', 'N', 'Q', 'S', 'T', 'Y']
r1 = str[0]
r2 = str[1]
if (r1 in hydrophobic and r2 in hydrophobic):
return 1 #hydrophobic
elif (r1 in negative and r2 in positive) or (r1 in positive and r2 in negative):
return 3 #salt bridge
elif ((r1 in donor and r2 in acceptor) or (r1 in acceptor and r2 in donor)):
return 2 # hydrogen bond
else:
return 0 #nothing...
def read_zoom_list(zoomfile):
# This function reads in the "zoom list" with particularly interesting residue pairs.
zoom_list = []
for line in zoomfile:
if ( not line.startswith("#") and (len(line.split()) > 0) ):
i1 = int(line.split()[0])
i2 = int(line.split()[1])
pair = tuple(sorted( (i1, i2)))
zoom_list.append(pair)
return zoom_list
def zoom_on_pair(pair, rvec, time_vec, trunc, inter_low, inter_high, pairs_list, pairs_legend, vectors):
# This function executes the "zooming in" on one of the residue pairs on the list.
inter = 0
dfile = open("zoom/dist_%i_%i.dat"%pair, "w")
pearson2dfile = open("zoom/2d_correlate_%i_%i.dat"%pair, "w")
dfile.write("# t (ps) r (nm) interact?\n")
for i in range(len(rvec)):
r = rvec[i]
if (r < inter_low):
inter = 1
elif (r > inter_high):
inter = 0
dfile.write("%9d %12.6f %3i\n"%(time_vec[i], rvec[i], inter))
dfile.close()
pearson2d_dict = dict()
for i in range(len(pairs_list)):
pair2 = pairs_list[i]
rvec2 = vectors[i]
if (len(set(rvec)) > 1 and len(set(rvec2)) > 1):
rvalue, pvalue = pearsonr(rvec, rvec2)
else:
rvalue = 0.0
pearson2d_dict[pair2] = rvalue
pearson2d_dict[pair2[::-1]] = rvalue
for i in range(xterm, xterm+xres):
for j in range(yterm, yterm+yres):
pair2 = (i,j)
x = pearson2d_dict.get(pair2, 0.0)
pearson2dfile.write("%5i %5i %12.6f\n"%(i, j, x))
pearson2dfile.write("\n")
pearson2dfile.close()
if (gnus_path): os.system("""gnuplot -e "maxz=1;domains=%i;inputfile='zoom/2d_correlate_%i_%i.dat' ; outputfile='zoom/2d_correlate_%i_%i.png'; title_time = 'Correlation with the contact distance between residues (%i, %i)'" %s/script_corr.gnu """%
((domains,) + 3*pair + (gnus_path,) ))
dfile.close()
if (gnus_path): os.system("""gnuplot -e "inter_high=%f;inter_low=%f;inputfile='zoom/dist_%i_%i.dat'; outputfile='zoom/dist_%i_%i.png'; title_plot='Time dependence of distance between residues (%i,%i)'" %s/1d_zoom.gnu """%((inter_high,inter_low)+3*pair + (gnus_path,)))
def aggregate(rvec, trunc, inter_low, inter_high):
# This function "aggregates" the vector of inter-residue distance of one particular pair.
dwells = []
n = 0
first = -1
last = -1
i = 0
for r in rvec:
if (n==0 and r<inter_low):
n = 1
if (len(dwells) == 0):
first = i
elif (n > 0):
if (r > inter_high):
dwells.append(n)
n = 0
last = i
else:
n += 1
last = i
i = i + 1
if (n > 0):
dwells.append(n)
last = i-1
if (len(dwells) == 0):
last = 0
first = i - 1
n_tot = sum(dwells)
avg = np.mean(rvec)
std = np.std(rvec)
return avg, std, first, last, n_tot, len(dwells)
def read_sequence(inputpdb):
#This is a function reading in all the residues from a PDB file (assuming the name is the fourth column).
residue_dict = {'ALA':'A','CYS':'C','ASP':'D','GLU':'E','GLH':'E','PHE':'F','GLY':'G','HIS':'H','HIE':'H','HID':'H','HIP':'H','ILE':'I','LYS':'K','LYN':'K','LEU':'L','MET':'M','ASN':'N','PRO':'P','GLN':'Q','ARG':'R','SER':'S','THR':'T','VAL':'V','TRP':'W','TYR':'Y'}
list = []
for line in inputpdb:
if (len(line.split()) > 5):
if (line.split()[0]=='ATOM' and line.split()[2] in ['CA', 'BB']):
resid = int(line[22:26])
resname = residue_dict.get(line.split()[3],'X')
list.append((resid,resname))
interact_pair_dict = dict()
i = 0
for r1 in list:
for r2 in list:
i = i+1
s = r1[1]+r2[1]
pair = (r1[0], r2[0])
if (r1[0] != r2[0]):
inter = interaction(s)
else:
inter = 0
if (inter>0):
interact_pair_dict[pair] = inter
return interact_pair_dict
def read_sequence_asymm(inputpdb_x, inputpdb_y, xterm, xres, yterm, yres):
#This is an analogue to the function above but using two PDBs and identifying those interactions.
residue_dict = {'ALA':'A','CYS':'C','ASP':'D','GLU':'E','PHE':'F','GLY':'G','HIS':'H','ILE':'I','LYS':'K','LEU':'L','MET':'M','ASN':'N','PRO':'P','GLN':'Q','ARG':'R','SER':'S','THR':'T','VAL':'V','TRP':'W','TYR':'Y'}
list_x = []
for line in inputpdb_x:
if (len(line.split()) > 5):
if (line.split()[0]=='ATOM' and line.split()[2] in ['CA', 'BB']):
resid = int(line[22:26])
resname = residue_dict.get(line.split()[3],'X')
list_x.append((resid,resname))
list_y = []
for line in inputpdb_y:
if (len(line.split()) > 5):
if (line.split()[0]=='ATOM' and line.split()[2] in ['CA', 'BB']):
resid = int(line[22:26])
resname = residue_dict.get(line.split()[3],'X')
list_y.append((resid,resname))
interact_pair_dict = dict()
i = 0
for r1 in list_x:
for r2 in list_y:
if (r1[0] in range(xterm, xterm+xres) and r2[0] in range(yterm, yterm+yres)):
i = i+1
s = r1[1]+r2[1]
pair = (r1[0], r2[0])
inter = interaction(s)
if (inter>0):
interact_pair_dict[pair] = inter
return interact_pair_dict
def read_stages(stagef):
#This is a function reading in the stage file...
stages_list = []
for line in stagef:
if ( not line.startswith("#") and (len(line.split()) > 0) ):
t1 = int(line.split()[0])
t2 = int(line.split()[1])
if (len(line.split()) > 2):
stage_name = line[line.find('"')+1:line.rfind('"')]
stages_list.append((t1, t2, stage_name))
else:
stages_list.append( (t1, t2, "Stage %d"%(len(stages_list)+1) ) )
return stages_list
def create_tics(domainf, nterm, nres, name_2d = "domains.gnu", name_1d = "domains_1d.gnu"):
#This function creates the tics for the domains file for gnuplot.
gnuf_1d = open(name_1d,"w")
gnuf_2d = open(name_2d,"w")
rmin = nterm
rmax = nterm + nres - 1
mtics = []
tics = []
for line in domainf:
if ( not line.startswith("#") and (len(line.split()) > 0) ):
i1 = int(line.split()[0])
i2 = int(line.split()[1])
domain_name = line[line.find('"')+1:line.rfind('"')]
tics.append((domain_name, 0.5 * (i1 + i2)))
mtics = mtics + [i1 - 0.5, i2 + 0.5]
mtics_copy = set(mtics)
mtics = set(mtics)
for i in mtics_copy:
if (i < rmin or i > rmax):
mtics.remove(i)
tics_str = ", ".join(['"%s" %.1f'%i for i in tics])
xtics_str = "set xtics (" + tics_str + ")\n"
ytics_str = "set ytics (" + tics_str + ")\n"
gnuf_2d.write(xtics_str)
gnuf_2d.write(ytics_str)
gnuf_1d.write(xtics_str)
for i in mtics:
gnuf_2d.write("set xtics add (%.1f 1) \n"%(i))
gnuf_2d.write("set ytics add (%.1f 1) \n"%(i))
gnuf_1d.write("set xtics add (%.1f 1) \n"%(i))
gnuf_2d.close()
gnuf_1d.close()
def create_tics_asymm(domainf_x, domainf_y, xterm, xres, yterm, yres):
gnuf_2d = open("domains.gnu","w")
rminx = xterm
rmaxx = xterm+xres-1
rminy = yterm
rmaxy = yterm+yres-1
mxtics = []
xtics = []
mytics = []
ytics = []
for line in domainf_x:
if ( not line.startswith("#") and (len(line.split()) > 0) ):
i1 = int(line.split()[0])
i2 = int(line.split()[1])
domain_name = line[line.find('"')+1:line.rfind('"')]
xtics.append((domain_name, 0.5 * (i1 + i2)))
mxtics = mxtics + [i1 - 0.5, i2 + 0.5]
for line in domainf_y:
if ( not line.startswith("#") and (len(line.split()) > 0) ):
i1 = int(line.split()[0])
i2 = int(line.split()[1])
domain_name = line[line.find('"')+1:line.rfind('"')]
ytics.append((domain_name, 0.5 * (i1 + i2)))
mytics = mytics + [i1 - 0.5, i2 + 0.5]
mxtics_copy = set(mxtics)
mxtics = set(mxtics)
for i in mxtics_copy:
if (i < rminx or i > rmaxx):
mxtics.remove(i)
mytics_copy = set(mytics)
mytics = set(mytics)
for i in mytics_copy:
if (i < rminy or i > rmaxy):
mytics.remove(i)
xtics_str = ", ".join(['"%s" %.1f'%i for i in xtics])
ytics_str = ", ".join(['"%s" %.1f'%i for i in ytics])
xtics_str = "set xtics (" + xtics_str + ")\n"
ytics_str2d = "set ytics (" + ytics_str + ")\n"
gnuf_2d.write(xtics_str)
gnuf_2d.write(ytics_str2d)
for i in mxtics:
gnuf_2d.write("set xtics add (%.1f 1) \n"%(i))
for i in mytics:
gnuf_2d.write("set ytics add (%.1f 1) \n"%(i))
gnuf_2d.close()
def plot_pc (xterm, xres, yterm, yres, ii, vec, pairs, pairs_dict, gnus_path, domains):
pc_file = open("pca/pc.%i.dat"%(ii+1), "w+")
maxz = max(-min(vec), max(vec))
pc_dict = dict()
for pair in pairs:
pc_dict[pair] = vec[pairs_legend[pair]]
if (not asymm):
pc_dict[pair[::-1]] = vec[pairs_legend[pair]]
for i in range(xterm, xterm+xres):
for j in range(yterm, yterm+yres):
pair = i, j
x = pc_dict.get(pair, 0.0)
pc_file.write("%5i %5i %12.6f\n"%(i, j, x))
pc_file.write("\n")
pc_file.close()
if (gnus_path): os.system("""gnuplot -e "domains=%i;i=%i;maxz=%f;input_file='pca/pc.%i.dat'" %s/script_pca.gnu """%(domains, ii+1, maxz, ii+1, gnus_path))
def project_pc(v, time_vec, vectors, pairs_list, change_sign = True):
file_projections = open("pca/pca_projections.dat", "w+")
nframes = len(time_vec)
n = np.shape(v)[1]
projections = np.zeros((nframes, n))
ordered_v = np.array(v)
print("Projecting principal components...")
for i in range(nframes):
time = time_vec[i]
dist_frame = [vec[i] for vec in vectors]
projections[i] = np.array([ np.dot(v[:, j ], dist_frame) for j in range(n)])
if (change_sign):
for i in range(n):
slope, intercept, r, p, std_err = linregress(projections[:, i], time_vec)
if (r < 0):
ordered_v[:, i] = -v[:, i]
projections[:, i] *= -1
for i in range(nframes):
dist_frame = [vec[i] for vec in vectors]
file_projections.write("%12i"%time_vec[i])
file_projections.write((n*" %12.6f")%tuple(projections[i])+"\n")
file_projections.close()
return ordered_v
# This function reads the index from the first frame of the dmf.xpm file
def read_index(inputf):
dict_legend = dict()
line = inputf.readline()
while (line.split()[0]!="static"):
line = inputf.readline()
line = inputf.readline()[1:-3]
nres = int(line.split()[0])
nlevels = int(line.split()[2])
nchar = int(line.split()[3])
value = 0.0
chars = []
for i in range(nlevels):
line = inputf.readline()
char = line[1:].split()[0]
chars.append(char)
if (len(char) != nchar):
print('warning! this character is of the wrong length:',char)
print('carrying on but it is a good idea to check.')
trunc = float(line.split()[-2][1:-1])
dx = trunc/(nlevels-1)
value = 0.0
for i in range(nlevels-1):
dict_legend[chars[i]]=value
value = value + dx
dict_legend[chars[nlevels-1]] = trunc #make sure the truncation threshold is the same as the highest value.
return nres, nlevels, nchar, dict_legend, trunc
# Function to read the values and the title (time) of a frame
def read_next_time(inputf):
line = inputf.readline()
if not line:
return float('-Inf')
get_out = False
while (not get_out):
line = inputf.readline()
if (not line):
return float('-Inf')
break
get_out = len(line.split()) > 1
if (get_out):
get_out = get_out and (line.split()[1] == 'title:')
title = line[line.find('"')+1:line.rfind('"')]
time = float(title[2:].split()[0])
return time
def read_frame(inputf, nres, nlevels, nchar, dict_legend, nterm, trunc, asymm_data, dimer):
line = inputf.readline()
dict_frame = dict()
if (asymm_data):
xdict, ydict, xres, yres, xterm, yterm = asymm_data
#skip all the stuff with /* comments...
while (line.split()[0]!="static"):
line = inputf.readline()
#skip the legend - we know already...
for i in range(nlevels+1):
line = inputf.readline()
#skip the axes...
line = inputf.readline()
while (not line.split()[0].startswith('"')):
line = inputf.readline()
n = nres-1
if (not asymm_data):
for i in range(nres):
if (i < nres-1):
linestr = line[1:-3]
else:
linestr = line[1:-2]
z = [dict_legend[linestr[k:k+nchar]] for k in range(0, n * nchar, nchar)]
for m in range(n):
if (z[m] < trunc):
dict_frame[(m + nterm, n + nterm)] = z[m]
line = inputf.readline()
n=n-1
else:
for i in range(nres):
if (i < nres-1):
linestr = line[1:-3]
else:
linestr = line[1:-2]
z = [dict_legend[linestr[k:k+nchar]] for k in range(0, nres * nchar, nchar)]
for m in range(nres):
if (z[m] < trunc and ( m+1 in xdict ) and ( n+1 in ydict) ):
dict_frame[(xdict[m+1], ydict[n+1])] = z[m]
line = inputf.readline()
n=n-1
if (dimer):
contacts_above = 0.0
contacts_below = 0.0
for i, j in dict_frame:
if (i < j):
contacts_above += weight_contacts(dict_frame[(i, j)], trunc)
elif (i > j):
contacts_below += weight_contacts(dict_frame[(i, j)], trunc)
if (contacts_above < contacts_below):
dict_frame_transpose = {(j, i): dict_frame[(i, j)] for i, j in dict_frame}
return dict_frame_transpose
else:
return dict_frame
else:
return dict_frame
def write_matrix(outputf, time, xterm, xres, yterm, yres, trunc, dict_frame, dr, asymm):
#This function prints out one matrix.
# dr is a boolean variable showing whether the "frame" is really a difference of frames.
if (not dr):
outputf.write ("# i j r_ij\n")
outputf.write ("# r_ij is the shortest distance between any atom of residues i, j.\n")
defaultr = trunc
else:
outputf.write ("# i j dr_ij\n")
outputf.write ("# dr_ij is the change (compared to the previous frame)\n")
outputf.write ("# in shortest distance between any atom of residues i, j.\n")
defaultr = 0.0
for i in range(xterm, xterm+xres):
for j in range(yterm, yterm+yres):
if (not asymm):
if (i == j):
r = 0
else:
if (i < j):
pair = (i, j)
else:
pair = (j, i)
r = dict_frame.get(pair, defaultr)
else:
r = dict_frame.get((i, j), defaultr)
outputf.write("%4d %4d %9.4f\n"%(i, j, r) )
outputf.write("\n")
def update_aggregate(r, time, trunc, trunc_inter, trunc_inter_high, agg, inter_mode = 0):
first, last, n_int, n_enc, status, sumr, sumr2 = tuple(agg)
sumr += r
sumr2 += r*r
new_status = update_interaction(r, trunc_inter, trunc_inter_high, status, inter_mode) # at the moment, "history" is the only one accessible.
if (new_status):
n_int += 1
last = time
if (not status): #switch from OFF to ON
if (first == -1):
first = time
n_enc += 1
return np.array([first, last, n_int, n_enc, new_status, sumr, sumr2])
def prepare_dimer_transpose(pairs_list, pairs_legend):
npad = 0
n_len = len(pairs_list)
new_legend = pairs_legend
map = []
pad_map = []
for i, pair in enumerate(pairs_list):
pair_transpose = pair[::-1]
if pair_transpose in pairs_list:
j = pairs_legend[pair_transpose]
else:
j = n_len + npad
pad_map.append(i)
npad += 1
map.append(j)
map = map + pad_map
return npad, map
def plot_frames(dict_frame, first_frame, prev_frame, pairs_list, dr_mode, xterm, xres, yterm, yres, trunc, matrices, clean_matrices, n, time, rmsd_perframe_file, asymm, dimer):
if (matrices):
outputf = open("matrices/%05d.dat"%n,"w")
write_matrix(outputf, time, xterm, xres, yterm, yres, trunc, dict_frame, False, asymm)
outputf.close()
if (clean_matrices):
if (gnus_path): os.system("""gnuplot -e "domains=%d;maxz=%f;label_str='Residue index';inputfile='matrices/%05d.dat';outputfile='frames/%05d.png';"""%(domains,trunc,n,n)+
"""title_str='t = %7.3f (ns)';cblabel_str = 'Distance (nm)" %s/script_single.gnu"""%(time * 0.001, gnus_path))
os.system("""rm matrices/%05d.dat"""%n)
if (first_frame):
diff_dict_0 = {pair: dict_frame.get(pair, trunc) - first_frame.get(pair, trunc) for pair in (set(dict_frame.keys()) | set(first_frame.keys()))}
diff_dict_p = {pair: dict_frame.get(pair, trunc) - prev_frame.get(pair, trunc) for pair in (set(dict_frame.keys()) | set( prev_frame.keys()))}
rmsd_perframe_0 = rmsd_frame(dict_frame, first_frame, trunc, xres, yres, asymm, dimer)
rmsd_perframe_p = rmsd_frame(dict_frame, prev_frame, trunc, xres, yres, asymm, dimer)
rmsd_perframe_file.write("%9.4f %9.4f %9.4f\n"%(0.001*time, rmsd_perframe_p, rmsd_perframe_0))
if (matrices):
if (dr_mode in [1, 3]):
outputf_dr = open("matrices/%05d_dr.init.dat"%n,"w")
write_matrix(outputf_dr, time, xterm, xres, yterm, yres, trunc, diff_dict_0, True, asymm)
outputf_dr.close()
if (clean_matrices):
if (gnus_path):
os.system('gnuplot -e "domains=0;maxz=%f;inputfile='%(trunc_dr)+"'matrices/%05d_dr.init.dat'"%n+";outputfile='frames/%05d_dr.init.png';title_time='Change up to t = %7.3f (ns)'"%(n,time)+'" %s/script_dr.gnu'%(gnus_path))
if (domains):
os.system('gnuplot -e "domains=1;maxz=%f;inputfile='%(trunc_dr)+"'matrices/%05d_dr.init.dat'"%n+";outputfile='frames/%05d_dr.init.domains.png';title_time='Change up to t = %7.3f (ns)'"%(n,time)+'" %s/script_dr.gnu'%(gnus_path))
os.system("rm matrices/%05d_dr.init.dat"%n)
if (dr_mode in [2, 3]):
outputf_dr = open("matrices/%05d_dr.prev.dat"%n,"w")
write_matrix(outputf_dr, time, xterm, xres, yterm, yres, trunc, diff_dict_p, True, asymm)
outputf_dr.close()
if (clean_matrices):
if (gnus_path):
os.system('gnuplot -e "domains=0;maxz=%f;inputfile='%(trunc_dr)+"'matrices/%05d_dr.prev.dat'"%n+";outputfile='frames/%05d_dr.prev.png';title_time='Change at t = %7.3f (ns)'"%(n,time)+'" %s/script_dr.gnu'%(gnus_path))
if (domains):
os.system('gnuplot -e "domains=1;maxz=%f;inputfile='%(trunc_dr)+"'matrices/%05d_dr.prev.dat'"%n+";outputfile='frames/%05d_dr.prev.domains.png';title_time='Change at t = %7.3f (ns)'"%(n,time)+'" %s/script_dr.gnu'%(gnus_path))
os.system("rm matrices/%05d_dr.prev.dat"%n)
print("done with frame corresponding to ",time,"ps",end="\r")
def get_inter(residue_vectors, nterm, nres, pearson_2d_density_file):
#this is the computation and output of inter-residue Pearson correlation (either symmetric or asymmetric).
results_inter = []
density_r2_metric = dict()
for i in range(nres):
for j in range(i+1, nres):
if (len(set(residue_vectors[i])) > 1 and len(set(residue_vectors[j])) > 1):
slope, intercept, r, pvalue, std_err = linregress(residue_vectors[i], residue_vectors[j])
else:
r = 0.0
results_inter.append(r)
density_r2_metric[(i, j)] = 1 - r**2
density_r2_metric[(j, i)] = 1 - r**2
for i in range(nres):
for j in range(nres):
if (i == j):
if (len(set(residue_vectors[i])) > 1):
r = 1.0
else:
r = 0.0
elif (i < j):
r = results_inter[cond_index(i, j, nres)]
else:
r = results_inter[cond_index(j, i, nres)]
pearson_2d_density_file.write("%5i %5i %15.6f\n"%(nterm + i, nterm + j, r))
pearson_2d_density_file.write("\n")
return density_r2_metric
def read_process_frames(inputf, nres, nlevels, nchar, dict_legend, asymm_data, trunc, trunc_inter, trunc_inter_high, begin, end, dt, patch_time, gnus_path,
dr_mode, domains, pearson_inter, economy, dimer, reread, stages_list, interact_pair_dict, trunc_lifetime):
outputf_timeline = open("aggregate/timeline.dat", "w")
outputf_timeline.write ("# i j t_first t_last t_total (# encounters)\n")
outputf_timeline.write ("# first/last time residues i and j are within the interaction distance.\n")
outputf_timeline.write ("# total: fraction of frames in which residues i and j are within interaction distance (maximum = 1.0).\n")
outputf_avg_rmsf = open("aggregate/mdmat_average_rmsf.dat", "w")
outputf_avg_rmsf.write ("# i j r_ij^avg sigma_(rij)\n")
outputf_avg_rmsf.write ("# average of the distance between residues i and j and the standard deviation (computed across frames.\n")
native_file = open("aggregate/native_contacts.dat", "w")
native_file.write("# time (ns) #native #non-native\n")
rmsd_perframe_file = open("aggregate/time_mdmat_rmsd.dat","w")
rmsd_perframe_file.write("# time (ns) RMSD_mdmat_previous RMSD_mdmat_total\n")
if (stages_list):
frames_stages = [ stage + (None, None) for stage in stages_list]
asymm = bool(asymm_data)
if (asymm):
xdict, ydict, xres, yres, xterm, yterm = asymm_data
interaction_map_x = [[] for x in range(xres)]
interaction_map_y = [[] for x in range(yres)]
total_interact_dict_x = dict()
total_interact_dict_y = dict()
else:
xdict, ydict, xres, yres, xterm, yterm = (None, None, nres, nres, nterm, nterm)
interaction_map = [[] for x in range(nres)]
local_interact_dict = dict()
if (inputf):
inputline = inputf.readline()
prev_frame = None
first_frame = None
pairs_list = []
time_vec = []
native_list = []
vectors = np.zeros((0, 0), dtype = np.float16) # the main data structure. rows = pairs. columns = frames.
emptiness = np.zeros((1, 0), dtype = np.float16) # the row that "newcomer pairs" will inherit.
pairs_legend = dict()
if (interact_pair_dict):
interact_file = open("aggregate/interaction_types.dat", 'w')
if (pearson_inter):
if (asymm):
residue_vectors_x = np.zeros([xres,0])
residue_vectors_y = np.zeros([yres,0])
else:
residue_vectors = np.zeros([nres,0])
aggregates = np.zeros([0, 7]) # aggregate values for all pairs
empty_aggregate = np.array([-1, 0, 0, 0, 0, 0, 0]) #first, last, lifetime, N_encounter, status, sumr, sumr2
n = 0
if (reread):
matrixfiles = []
for i in (range(100000)):
filename = "%s/%05i.dat"%(reread, i)
if (os.path.exists(filename)):
matrixfiles.append(filename)
if (not begin):
begin = 0
if (not dt):
dt = 1000
if (matrixfiles == []):
print("Reread folder is empty, will quit now.")
sys.exit()
else:
print("Found %i matrices to reread from."%len(matrixfiles))
time = begin
end = float('Inf')
else:
time = read_next_time(inputf)
if (not dt):
time_next = read_next_time(inputf)
dt = time_next - time
inputf.seek(0)
inputline = inputf.readline()
time = read_next_time(inputf)
if (dt > float('-inf')):
print("Detected dt = %i ps"%dt)
time0= time
if (not end):
end = float('Inf')
if (not begin):
begin = time0
if (asymm):
total_interactionf_x = open("aggregate/total_interactions.x.dat","w")
total_interactionf_y = open("aggregate/total_interactions.y.dat","w")
else:
local_interactionf = open("aggregate/local_interactions.dat","w")
while (time > float('-Inf') and time <=end):
if (time >= begin and ((time-begin) % dt == 0)):
npairs = vectors.shape[0]
frame_column = np.zeros([npairs, 1], dtype = np.float16)
if (pearson_inter):
if (asymm):
residue_column_x = np.zeros([xres, 1])
residue_column_y = np.zeros([yres, 1])
else:
residue_column = np.zeros([nres, 1])
if (reread):
inputf = open(matrixfiles[n])
dict_frame = read_matrix(inputf, xterm, xres, yterm, yres, asymm, trunc)
inputf.close()
else:
dict_frame = read_frame(inputf, nres, nlevels, nchar, dict_legend, nterm, trunc, asymm_data, dimer)
if (stages_list):
for i in range(len(frames_stages)):
stage = frames_stages[i]
if (not stage[3] and time >= stage[0]):
stage = stage[:3] + (dict_frame,) + (stage[4],)
if (not stage[4] and time >= stage[1]):
stage = stage[:4] + (dict_frame,)
frames_stages[i] = stage
for i, pair in enumerate(pairs_list):
if (not economy):
r = dict_frame.get(pair, trunc)
frame_column[i] = r
for pair in (set(dict_frame.keys()) - set(pairs_list)):
pairs_legend[pair] = len(pairs_list)
i, j = pair
if (asymm):
interaction_map_x[i-xterm].append(len(pairs_list))
interaction_map_y[j-yterm].append(len(pairs_list))
else:
if (i < j-3): # exclude "trivial interactions"
interaction_map[i-nterm].append(len(pairs_list))
interaction_map[j-nterm].append(len(pairs_list))
pairs_legend[pair[::-1]] = len(pairs_list)
aggregates = np.vstack([aggregates, empty_aggregate])
pairs_list.append(pair)
if (not economy):
vectors = np.vstack([vectors, emptiness])
frame_column = np.vstack( [ frame_column, np.array([np.float16(dict_frame[pair])]) ] )
vectors = np.hstack([vectors, frame_column])
plot_frames(dict_frame, first_frame, prev_frame, pairs_list, dr_mode, xterm, xres, yterm, yres, trunc, matrices, clean_matrices, n, time, rmsd_perframe_file, asymm, dimer)
if (dt == float('-inf')):
print("Detected a single frame. Not very dynamic, but we will plot the distances and finish.")
if (gnus_path): os.system("""gnuplot -e "domains=%d;maxz=%f;label_str='Residue index';inputfile='matrices/00000.dat';outputfile='frames/00000.png';"""%(domains,trunc)+
"""title_str='Inter-residue distance';cblabel_str = 'Distance (nm)" %s/script_single.gnu"""%(gnus_path))
sys.exit()
if (not first_frame):
first_frame = dict_frame
prev_frame = dict_frame
time_vec.append(time)
for i, pair in enumerate(pairs_list):
r = dict_frame.get(pair, trunc)
agg = aggregates[i]
aggregates[i] = update_aggregate(r, time, trunc, trunc_inter, trunc_inter_high, agg)
if (len(time_vec) == 1 and aggregates[i][4] > 0 ):
native_list.append(i)
if (pearson_inter):
weight = weight_contacts(r, trunc)
if (asymm):
residue_column_x[pair[0] - xterm] += weight
residue_column_y[pair[1] - yterm] += weight
else:
residue_column[pair[0] - nterm] += weight
residue_column[pair[1] - nterm] += weight
total_contacts = sum(aggregates[:, 4])
native = sum(aggregates[native_list, 4])
non_native = total_contacts - native
native_file.write("%9.4f %12.4f %12.4f\n"%(0.001*time, native, non_native))
n += 1
emptiness = trunc * np.ones([1, n], dtype = np.float16)
if (pearson_inter):
if (asymm):
residue_vectors_x = np.hstack([residue_vectors_x, residue_column_x])
residue_vectors_y = np.hstack([residue_vectors_y, residue_column_y])
else:
residue_vectors = np.hstack([residue_vectors, residue_column])
empty_aggregate = np.array([-1, 0., 0., 0., 0., n*trunc, n*trunc**2])
if (reread):
if (n == len(matrixfiles)):
time = float('-Inf')
else:
time = time + dt
else:
time_tmp = read_next_time(inputf)
if (patch_time and time_tmp > float('-Inf')):
time = time + dt
else:
time = time_tmp
density_r2_metric = dict()
if (pearson_inter):
if (asymm):
filex = open("aggregate/pearson_map_density.x.dat", "w")
get_inter(residue_vectors_x, xterm, xres, filex)
filex.close()
filey = open("aggregate/pearson_map_density.y.dat", "w")
get_inter(residue_vectors_y, yterm, yres, filey)
filey.close()
else:
filesymm = open("aggregate/pearson_map_density.dat", "w")
density_r2_metric = get_inter(residue_vectors, nterm, nres, filesymm)
filesymm.close()
print("")
t0 = time_vec[0]
tmax = time_vec[-1]
tn = len(time_vec)
avg_metric_dict0 = dict()
life_metric_dict0 = dict()
for i in range(xres):
local_interactions = 0
local_lifetime = 0.0
for j in range(yres):
if (i==j and not asymm):
outputf_timeline.write("%4d %4d %12i %12i %12.6f %12.6f %5i\n"%(i+nterm, j+nterm, t0, tmax, 1.0, tmax-t0, 1))
outputf_avg_rmsf.write("%4d %4d %9.4f %9.4f\n"%(i+nterm, j+nterm, 0.0, 0.0))
continue
pair = (i+xterm, j+yterm)
if (pair in pairs_legend):
agg = tuple(aggregates[pairs_legend[pair]])
else:
agg = empty_aggregate
first, last, n_int, n_enc, status, sumr, sumr2 = agg
if (first == -1):
first = tmax
avg = sumr/tn
if (sumr2/tn - avg**2 > 0):
std = np.sqrt(sumr2/tn - avg**2)
else:
std = 0.0
outputf_timeline.write("%4d %4d %12i %12i %12.6f %12.6f %5i\n"%(i+xterm, j+yterm, first, last, n_int/tn, tmax-t0, n_enc))
if (interact_pair_dict):
if (pair in interact_pair_dict and n_int/tn >= trunc_lifetime):
interact_file.write("%4d %4d %i\n"%(i+xterm, j+yterm, interact_pair_dict[pair]))
else:
interact_file.write("%4d %4d %i\n"%(i+xterm, j+yterm, 0))
if (n_int/tn > 0 and abs(i-j) > 3):
local_interactions += 1
local_lifetime += n_int/tn
outputf_avg_rmsf.write("%4d %4d %9.4f %9.4f\n"%(i + xterm, j + yterm, avg, std))
avg_metric_dict0[(i, j)] = avg
life_metric_dict0[(i, j)] = 1 - n_int/tn
outputf_timeline.write("\n")
outputf_avg_rmsf.write("\n")
if (interact_pair_dict):
interact_file.write("\n")
if (local_interactions > 0):
avg_lifetime = 1.0*local_lifetime/local_interactions
else:
avg_lifetime = 0
if (asymm):
for i in range(xres):
int_i = sum( x[2] for x in aggregates[interaction_map_x[i]])
total_interactionf_x.write("%5i%12.6f\n"%(xterm + i, int_i/tn))
total_interact_dict_x[xterm + i] = int_i/tn
for j in range(yres):
int_j = sum( x[2] for x in aggregates[interaction_map_y[j]])
total_interactionf_y.write("%5i%12.6f\n"%(yterm + j, int_j/tn))
total_interact_dict_y[yterm + j] = int_j/tn
total_interactionf_x.close()
total_interactionf_y.close()
else:
for i in range(nres):
vec_i = np.array([x[2] for x in aggregates[interaction_map[i]]])
int_i = sum(vec_i)/tn
if (int_i > 0):
int_i /= len([x for x in vec_i if x > 0])
local_interactionf.write("%5i%12.6f\n"%(i + nterm, int_i))
local_interact_dict[nterm + i] = int_i
local_interactionf.close()
outputf_timeline.close()
outputf_avg_rmsf.close()
native_file.close()
if (stages_list):
for n, stage in enumerate(frames_stages):
if (stage[3]!=None and stage[4]!=None):
print("Found stage:", stage[2])
else:
print("Did NOT find stage:", stage[2])
continue
stage_outf = open("matrices/stage_%04d_dr.dat"%(n+1), "w")
title = stage[2]
frame_1 = stage[3]
frame_2 = stage[4]
for i in range(xterm, xterm+xres):
for j in range(yterm, yterm+yres):
if (not asymm):
if (i < j):
pair = (i, j)
else:
pair = (j, i)
else:
pair = (i, j)
r0 = frame_1.get(pair, trunc)
r = frame_2.get(pair, trunc)
dr = r-r0
stage_outf.write("%4d %4d %9.4f\n"%(i, j, dr))
stage_outf.write("\n")
stage_outf.close()
if (gnus_path):
os.system('gnuplot -e "domains=0;maxz=%f;inputfile='%(trunc_dr)+"'matrices/stage_%04d_dr.dat'"%(n+1)+";outputfile='frames/stage_%04d_dr.png';title_time='%s'"%(n+1,title)+'" %s/script_dr.gnu'%(gnus_path))
if (domains):
os.system('gnuplot -e "domains=1;maxz=%f;inputfile='%(trunc_dr)+"'matrices/stage_%04d_dr.dat'"%(n+1)+";outputfile='frames/stage_%04d_dr.domains.png';title_time='%s'"%(n+1,title)+'" %s/script_dr.gnu'%(gnus_path))
if (interact_pair_dict):
interact_file.close()
if (gnus_path): os.system('gnuplot -e "domains=%d" %s/interaction_types.gnu'%(domains,gnus_path))
if (gnus_path): os.system('gnuplot -e "domains=%i" %s/aggregate.gnu'%(domains, gnus_path))
rmsd_perframe_file.close()
if (gnus_path): os.system('gnuplot -e "domains=%d" %s/1d_plots.gnu'%(domains,gnus_path))
if (make_movie and matrices and not clean_matrices and gnus_path):
print("Calling gnuplot for all frames... This may take a minute or two. (Aggregate plots are finished already - check them out.)")
os.system('gnuplot -e "dr_mode=%d;domains=%d;maxz=%f;maxdr=%f;nframes=%d;begin=%d;dt=%d"'%(dr_mode,domains,trunc,trunc_dr,tn,begin,dt)
+' %s/script_all.gnu'%(gnus_path))