-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_program_v2.py.txt
2466 lines (2183 loc) · 96.2 KB
/
main_program_v2.py.txt
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
# coding: utf-8
# # Description
#
# Using [MDAnalysis](https://www.mdanalysis.org), this program lets the user analize a given dynamics in AMBER. It is able to obtaing plots of distances, plots of RMSd, the number of frames with a certain distance under a given cut-off...
# # Imported packages
# In[3]:
import numpy as np
import matplotlib.pyplot as plt
import MDAnalysis as mda
import MDAnalysis.analysis.distances as distances
import MDAnalysis.lib.distances as distanceslib
import MDAnalysis.analysis.rms as mdarms
import os
import sys
import time as timer
u = 0
dir_plots = 0
time_counter = 0
# # Menu
# ### For dynamics files
# In[2]:
def menu_dyn():
print("\n******************************************************************************************")
print("\nHere you have a list with the options you can choose:")
print("\t1. Summary of the system and the dynamics.")
print("\t2. Obtain distance plots.")
print("\t3. Obtain the plot of RMSd of the protein, the backbone and the substrate.")
print("\t4. Select frames by H(subs)-protein distance.")
print("\t5. QM/MM models from frames creation. (Frames have to be saved as pdb by this program (option 4))")
print("\t6. Create the 'set act' file, where active atoms for ChemShell are specified")
print("\n******************************************************************************************")
# ### For non dynamics files
# In[ ]:
def menu_nodyn():
print("\n******************************************************************************************")
print("\nYou are in the 'nodynamics' mode. You can just do the following tasks.")
print("\nIf you want to do other jobs that require the topology and the dynamics, type 'exit' and rerun the script specifing those files (following this sintaxis:\n script.py topology_file_name dynamics_file_name).")
print("\nHere you have a list with the options you can choose:")
print("\t1. QM/MM models from frames creation. (Frames have to be saved as pdb by this program (option 4))")
print("\t2. Create the 'set act' file, where active atoms for ChemShell are specified")
print("\n******************************************************************************************")
# # Summary of the system and the dynamics
# In[3]:
def summarize():
global u
global traj
### Time counter starts
if time_counter == 1:
time_in = timer.time()
### Check if universe is loaded and load it if it's not
if u != 0:
print("Files were previously loaded, this will be faster!")
else :
print("Let's load the files!")
u = mda.Universe(topology, dinamica)
traj = u.trajectory
print("Topology and dynamics loaded!")
txt = open("MD_summary.txt", 'w+')
txt.write("The system has %s atoms, %s residues and %s segments.\n" % (len(u.atoms), len(u.residues), len(u.segments)))
txt.write("The dynamics starts at %s ns, ends at %s ns, lasts a total of %s ns, has %s frames and a timestep of %s.\n" % (round(traj[0].time/1000,1), traj[-1].time/1000, traj[-1].time/1000-round(traj[0].time/1000,1), len(traj), ((traj[-1].time/1000-round(traj[0].time/1000,1))/(traj[-1].frame-traj[0].frame +1))))
txt.write("The system has the following shape:\n")
txt.write("\tEdges length: (%s, %s, %s).\n" % (u.dimensions[0],u.dimensions[1],u.dimensions[2]))
txt.write("\tAngles: (%s, %s, %s).\n" % (u.dimensions[3],u.dimensions[4],u.dimensions[5]))
txt.close()
print("Summary saved!")
# # Dynamics analysis
# ### For 1 carbon
# In[53]:
def group1():
global u
global traj
global dir_plots
global time_counter
global dinamica
global topology
dir_now = os.getcwd()
while dir_plots != 0:
subplots = input("Do you want to save the plots in '%s' ([y]/n)? " % dir_plots)
if subplots in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
dir_plots = 'plots'
break
elif subplots in ('n', 'no', 'N', 'No', 'No', 'nO'):
break
else :
print("Sorry, I didn't understand you. Answer again, please.")
continue
while dir_plots == 0:
subplots = input("Do you want to save the plots in a subfolder ([y]/n)? ")
if subplots in ('n', 'no', 'N', 'No', 'No', 'nO'):
break
elif subplots in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
quest2 = input("Do you want to save in the \'plots\' folder (recomended) ([y]/n)? ")
if quest2 in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
if 'plots' not in list(os.listdir()):
dir_plots = 'plots'
os.mkdir(dir_plots)
elif 'plots' in list(os.listdir()):
dir_plots = 'plots'
elif quest2 in ('n', 'no', 'N', 'No', 'No', 'nO'):
dir_plots = input("In which folder do you want to save the plots? ")
if dir_plots not in list(os.listdir()):
os.mkdir(dir_plots)
os.chdir(dir_plots)
topology = '../%s' %(topology)
dinamica = '../%s' %(dinamica)
print("Plots will be saved in '%s'" % dir_plots)
break
else :
print("Sorry, I didn't understand you. Answer again, please.")
continue
### Ask for atom numbers
while True:
try :
o_prot = int(input("Number of the atom which belongs to the protein: ")) #-1 #8784
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
c9 = int(input("\nNumber of one of the carbons: ")) #-1 #8807
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h9a = int(input("Number of one of the hydrogens bonded to the previous carbon: ")) #-1 #8808
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h9b = int(input("Number of the other hydrogen bonded to the previous carbon: ")) #-1 #8809
except ValueError:
print("Enter the number again.")
continue
else :
break
### Ask if atom numbers are correct
while True:
u_top = mda.Universe(topology)
### Print selected atoms (number, name, tupe, resname an resid) and save names
print("\nYou have selected those atoms:\n")
a = str(u_top.select_atoms("bynum %s" % o_prot))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB] + "\n")
a = str(u_top.select_atoms("bynum %s" % c9))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB])
a = str(u_top.select_atoms("bynum %s" % h9a))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB])
a = str(u_top.select_atoms("bynum %s" % h9b))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB] + "\n")
a = str(list(u_top.select_atoms("bynum %s" % o_prot)))
locA = a.find(': ') +2
locB = a.find(' of')
t_o_prot = str(a[locA:locB])
a = str(list(u_top.select_atoms("bynum %s" % c9)))
locA = a.find(': ') +2
locB = a.find(' of')
t_c9 = str(a[locA:locB])
t_h9 = t_c9.replace('C','H')
quest = str(input("Are all numbers correct ([y]/n)?"))
if quest in ('n', 'no', 'N', 'No', 'No', 'nO'):
while True:
try :
o_prot = int(input("Number of the atom which belongs to the protein: ")) #-1 #8784
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
c9 = int(input("\nNumber of one of the carbons: ")) #-1 #8807
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h9a = int(input("Number of one of the hydrogens bonded to the previous carbon: ")) #-1 #8808
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h9b = int(input("Number of the other hydrogen bonded to the previous carbon: ")) #-1 #8809
except ValueError:
print("Enter the number again.")
continue
else :
break
continue
elif quest in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
break
else :
print("Sorry, answer again, please.")
continue
### Time counter
if time_counter == 1:
time_in = timer.time()
### Check if universe is loaded and load it if it's not
if u != 0:
print("Files were previously loaded, this will be faster!")
else :
print("Let's load the files!")
u = mda.Universe(topology, dinamica)
traj = u.trajectory
print("Topology and dynamics loaded!")
### Creation of the lists of distances and time
time = []
dist_c_9 = []
dist_ha_9 = []
dist_hb_9 = []
for i in u.trajectory:
pos_c = u.select_atoms("bynum %s" % c9).positions
pos_ha = u.select_atoms("bynum %s" % h9a).positions
pos_hb = u.select_atoms("bynum %s" % h9b).positions
pos_o = u.select_atoms("bynum %s" % o_prot).positions
dist_ha_9.append(distanceslib.calc_bonds(pos_o, pos_ha)[0])
dist_hb_9.append(distanceslib.calc_bonds(pos_o, pos_hb)[0])
dist_c_9.append(distanceslib.calc_bonds(pos_o, pos_c)[0])
time.append(int(traj.time)/1000)
dist_h_9 = []
for i in range(0, len(traj)):
if dist_ha_9[i] < dist_hb_9[i]:
dist_h_9.append(dist_ha_9[i])
elif dist_ha_9[i] > dist_hb_9[i]:
dist_h_9.append(dist_hb_9[i])
### Avg, min and max distances
avg_9_c = np.mean(dist_c_9)
min_9_c = np.min(dist_c_9)
max_9_c = np.max(dist_c_9)
rng_9_c = np.max(dist_c_9) - np.min(dist_c_9)
avg_9_h = np.mean(dist_h_9)
min_9_h = np.min(dist_h_9)
max_9_h = np.max(dist_h_9)
rng_9_h = np.max(dist_h_9) - np.min(dist_h_9)
avg_9_c_ar = np.array([avg_9_c for i in range(0, len(traj))])
avg_9_h_ar = np.array([avg_9_h for i in range(0, len(traj))])
print("Lists of distances created")
### Save summary of distances (avg, max and min)
txt = open('summary_of_distances_%s.txt' % t_c9, 'w+')
txt.write('Distances for %s: \n'% t_c9)
txt.write('\tAverage distance %s - %s: ' % (t_c9,t_o_prot) + str(round(avg_9_c,3)) + ' Å \n' )
txt.write('\tMinimum distance %s - %s: ' % (t_c9,t_o_prot) + str(round(min_9_c,3)) + ' Å \n')
txt.write('\tMaximum distance %s - %s: ' % (t_c9,t_o_prot) + str(round(max_9_c,3)) + ' Å \n')
txt.write('\tMax-min for distances %s - %s: ' % (t_c9,t_o_prot) + str(round(rng_9_c,3)) + ' Å \n\n')
txt.write('Distances for the nearest %s, even if it is the A or the B: \n' % t_h9)
txt.write('\tAverage distance %s - %s: ' % (t_h9,t_o_prot) + str(round(avg_9_h,3)) + ' Å \n')
txt.write('\tMinimum distance %s - %s: ' % (t_h9,t_o_prot) + str(round(min_9_h,3)) + ' Å \n')
txt.write('\tMaximum distance %s - %s: ' % (t_h9,t_o_prot) + str(round(max_9_h,3)) + ' Å \n')
txt.write('\tMax-min for distances %s - %s: ' % (t_h9,t_o_prot) + str(round(rng_9_h,3)) + ' Å \n\n\n')
txt.close()
print("Summary saved")
### Carbon distances plots
##### Histogram
plt.hist(dist_c_9, bins=20,range=(0,10), histtype='bar')
#plt.hist(dist10,bins=40,range=(0,10))
#plt.hist(dist13,bins=40,range=(0,10))
plt.xlabel('Distance (Å)')
plt.ylabel('Number of frames')
plt.xticks(range(0,11))
plt.legend(['%s-%s' % (t_c9,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
plt.title("Histogram of C-OH distances for %s" % (t_c9), y=1.08, loc='center')
plt.savefig('hist%s.png' % (t_c9), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print('Histogram of carbons saved')
##### plot w/o avg
fig, ax1 = plt.subplots()
ax1.plot(range(0,len(traj)), dist_c_9)#, label='C_9-OH')
#ax1.plot(range(0,len(traj)), dist_c_12, color='green')#, label='C_12-OH')
#ax1.plot(range(0,len(traj)), dist_c_15, color='coral', label='C_15-OH')
#ax1.plot(range(0,len(traj)), avg_9_c_ar, color='purple')
#ax1.plot(range(0,len(traj)), avg_12_c_ar, color='lime')
#ax1.plot(range(0,len(traj)), avg_15_c_ar, color='orangered')
ax1.set_xlabel('Frame')
ax1.set_ylabel('Distance (Å)')
ax1.set_xticks(range(0,len(traj) +1, round(len(traj)/10)))#, ['0','1k', '2k', '3k', '4k', '5k', '6k', '7k', '8k', '9k', '10k', '11k', '12k'])
ax1.grid(True)
ax1.legend(['%s-%s' % (t_c9,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
ax2 = ax1.twiny()
ax2.plot(time, dist_c_9)#, label='C_15-OH')
#ax2.plot(time_ar, avg_9_c_ar, color='purple')
#ax2.plot(time_ar, avg_12_c_ar, color='lime')
#ax2.plot(time_ar, avg_15_c_ar, color='orangered')
#ax2.set_xticks(time)
ax2.set_xlabel('Time (ns)')
plt.title("Plot of C-OH distances for %s" % (t_c9), y=1.15, loc='center')
plt.savefig('plot_%s.png' % (t_c9), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
##### plot w/ avg
fig, ax1 = plt.subplots()
ax1.plot(range(0,len(traj)), dist_c_9)#, label='C_9-OH')
#ax1.plot(range(0,len(traj)), dist_c_12, color='green', label='C_12-OH')
#ax1.plot(range(0,len(traj)), dist_c_15, color='coral', label='C_15-OH')
ax1.plot(range(0,len(traj)), avg_9_c_ar, color='blue')
#ax1.plot(range(0,len(traj)), avg_12_c_ar, color='lime')
#ax1.plot(range(0,len(traj)), avg_15_c_ar, color='orangered')
ax1.set_xlabel('Frame')
ax1.set_ylabel('Distance (Å)')
ax1.set_xticks(range(0,len(traj) +1, round(len(traj)/10)))#, ['0','1k', '2k', '3k', '4k', '5k', '6k', '7k', '8k', '9k', '10k', '11k', '12k'])
ax1.grid(True)
ax1.legend(['%s-%s' % (t_c9,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
ax2 = ax1.twiny()
#ax2.plot(time, dist_c_, color='coral', label='C_15-OH')
ax2.plot(time, avg_9_c_ar, color='blue')
#ax2.plot(time, avg_12_c_ar, color='lime')
#ax2.plot(time, avg_15_c_ar, color='orangered')
#ax2.set_xticks(time_ar)
ax2.set_xlabel('Time (ps)')
plt.title("Plot of C-OH distances for %s vs. time and frames with average distances" % (t_c9), y=1.15, loc='center')
plt.savefig('plot_%s_avg.png' % (t_c9), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print("Plots of carbons saved")
### Hydrogen plots
##### Histogram
plt.hist([dist_h_9], bins=20,range=(0,10), histtype='bar')
#plt.hist(dist10,bins=40,range=(0,10))
#plt.hist(dist13,bins=40,range=(0,10))
plt.xlabel('Distance (Å)')
plt.ylabel('Number of frames')
plt.xticks(range(0,11))
plt.legend(['%s-%s' % (t_h9,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
plt.title("Histogram of H-OH distances for %s" % (t_h9), y=1.08, loc='center')
plt.savefig('hist_%s.png' % (t_h9), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print('Histogram of hydrogen saved')
##### Plot w/o average
fig, ax1 = plt.subplots()
ax1.plot(range(0,len(traj)), dist_h_9)#, label='H_9-OH')
#ax1.plot(range(0,len(traj)), dist_h_12, color='green', label='H_12-OH')
#ax1.plot(range(0,len(traj)), dist_h_15, color='coral', label='H_15-OH')
#ax1.plot(range(0,len(traj)), avg_9_h_ar, color='purple')
#ax1.plot(range(0,len(traj)), avg_12_h_ar, color='lime')
#ax1.plot(range(0,len(traj)), avg_15_h_ar, color='orangered')
ax1.set_xlabel('Frame')
ax1.set_ylabel('Distance (Å)')
ax1.set_xticks(range(0,len(traj) +1, round(len(traj)/10)))
ax1.grid(True)
ax1.legend(['%s-%s' % (t_h9,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
ax2 = ax1.twiny()
ax2.plot(time, dist_h_9, label='H_15-OH')
#ax2.plot(time_ar, avg_9_h_ar, color='purple')
#ax2.plot(time_ar, avg_12_h_ar, color='lime')
#ax2.plot(time_ar, avg_15_h_ar, color='orangered')
#ax2.set_xticks(time_ar)
ax2.set_xlabel('Time (ps)')
plt.title("Plot of H-OH distances for %s vs. time and frames" % (t_h9), y=1.15, loc='center')
plt.savefig('plot_%s.png' % (t_h9), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
##### plot w/ avg
fig, ax1 = plt.subplots()
ax1.plot(range(0,len(traj)), dist_h_9)#, label='H_9-OH')
#ax1.plot(range(0,len(traj)), dist_h_12, color='green', label='H_12-OH')
#ax1.plot(range(0,len(traj)), dist_h_15, color='coral', label='H_15-OH')
ax1.plot(range(0,len(traj)), avg_9_h_ar)
#ax1.plot(range(0,len(traj)), avg_12_h_ar, color='lime')
#ax1.plot(range(0,len(traj)), avg_15_h_ar, color='orangered')
ax1.set_xlabel('Frame')
ax1.set_ylabel('Distance (Å)')
ax1.set_xticks(range(0,len(traj) +1, round(len(traj)/10)))
ax1.grid(True)
ax1.legend(['%s-%s' % (t_h9,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
ax2 = ax1.twiny()
#ax2.plot(time, dist_h_15, color='coral', label='C_15-OH')
ax2.plot(time, avg_9_h_ar, color='blue')
#ax2.plot(time, avg_12_h_ar, color='lime')
#ax2.plot(time, avg_15_h_ar, color='orangered')
#ax2.set_xticks(time_ar)
ax2.set_xlabel('Time (ns)')
plt.title("Plot of H-OH distances for %s vs. time and frames" % (t_h9), y=1.15, loc='center')
plt.savefig('plot_%s_avg.png' % (t_h9), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print("Plots of carbons saved")
### Scattering plot
plt.scatter(dist_h_9,dist_c_9)
#plt.scatter(dist_h_12,dist_c_12, color='green')
#plt.scatter(dist_h_15,dist_c_15, color='coral')
plt.legend(['%s-%s' % (t_c9,t_h9)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
plt.grid(True)
plt.xlabel('O-C distance (Å)')
plt.ylabel('O-H distance (Å)')
plt.savefig('scatter_%s.png' %(t_c9), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print("Scatter of carbon vs hydrogen distances saved")
if subplots in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
os.chdir(dir_now)
### Time counter ends
if time_counter == 1:
time_fin = timer.time()
print("I spent " + str(round((time_fin-time_in)/60,1)) + " min")
#####################################################################
# ### For 2 carbons
# In[5]:
def group2():
global u
global traj
global dir_plots
global time_counter
global dinamica
global topology
dir_now = os.getcwd()
while dir_plots != 0:
subplots = input("Do you want to save the plots in '%s' ([y]/n)? " % dir_plots)
if subplots in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
dir_plots = 'plots'
break
elif subplots in ('n', 'no', 'N', 'No', 'No', 'nO'):
break
else :
print("Sorry, I didn't understand you. Answer again, please.")
continue
while dir_plots == 0:
subplots = input("Do you want to save the plots in a subfolder ([y]/n)? ")
if subplots in ('n', 'no', 'N', 'No', 'No', 'nO'):
break
elif subplots in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
quest2 = input("Do you want to save in the \'plots\' folder (recomended) ([y]/n)? ")
if quest2 in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
if 'plots' not in list(os.listdir()):
dir_plots = 'plots'
os.mkdir(dir_plots)
elif 'plots' in list(os.listdir()):
dir_plots = 'plots'
elif quest2 in ('n', 'no', 'N', 'No', 'No', 'nO'):
dir_plots = input("In which folder do you want to save the plots? ")
if dir_plots not in list(os.listdir()):
os.mkdir(dir_plots)
os.chdir(dir_plots)
topology = '../%s' %(topology)
dinamica = '../%s' %(dinamica)
print("Plots will be saved in '%s'" % dir_plots)
break
else :
print("Sorry, I didn't understand you. Answer again, please.")
continue
### Ask for atom numbers
while True:
try :
o_prot = int(input("Number of the atom which belongs to the protein: ")) #-1 #8784
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
c9 = int(input("\nNumber of one of the carbons: ")) #-1 #8807
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h9a = int(input("Number of one of the hydrogens bonded to the previous carbon: ")) #-1 #8808
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h9b = int(input("Number of the other hydrogen bonded to the previous carbon: ")) #-1 #8809
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
c12 = int(input("\nNumber of one of the carbons: ")) #-1 #8814
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h12a = int(input("Number of one of the hydrogens bonded to the previous carbon: ")) #-1 #8815
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h12b = int(input("Number of the other hydrogen bonded to the previous carbon: ")) #-1 #8816
except ValueError:
print("Enter the number again.")
continue
else :
break
### Ask if atom numbers are correct
while True:
u_top = mda.Universe(topology)
### Print selected atoms (number, name, tupe, resname an resid) and save names
print("\nYou have selected those atoms:\n")
a = str(u_top.select_atoms("bynum %s" % o_prot))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB] + "\n")
a = str(u_top.select_atoms("bynum %s" % c9))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB])
a = str(u_top.select_atoms("bynum %s" % h9a))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB])
a = str(u_top.select_atoms("bynum %s" % h9b))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB] + "\n")
a = str(list(u_top.select_atoms("bynum %s" % o_prot)))
locA = a.find(': ') +2
locB = a.find(' of')
t_o_prot = str(a[locA:locB])
a = str(list(u_top.select_atoms("bynum %s" % c9)))
locA = a.find(': ') +2
locB = a.find(' of')
t_c9 = str(a[locA:locB])
t_h9 = t_c9.replace('C','H')
a = str(u_top.select_atoms("bynum %s" % c12))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB])
a = str(u_top.select_atoms("bynum %s" % h12a))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB])
a = str(u_top.select_atoms("bynum %s" % h12b))
locA = a.find('[<') +2
locB = a.find(' and')
print("\t" + a[locA:locB] + "\n")
a = str(list(u_top.select_atoms("bynum %s" % c12)))
locA = a.find(': ') +2
locB = a.find(' of')
t_c12 = str(a[locA:locB])
t_h12 = str(t_c12.replace('C','H'))
quest = str(input("Are all numbers correct ([y]/n)?"))
if quest in ('n', 'no', 'N', 'No', 'No', 'nO'):
while True:
try :
o_prot = int(input("Number of the atom which belongs to the protein: ")) #-1 #8784
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
c9 = int(input("\nNumber of one of the carbons: ")) #-1 #8807
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h9a = int(input("Number of one of the hydrogens bonded to the previous carbon: ")) #-1 #8808
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h9b = int(input("Number of the other hydrogen bonded to the previous carbon: ")) #-1 #8809
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
c12 = int(input("\nNumber of one of the carbons: ")) #-1 #8814
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h12a = int(input("Number of one of the hydrogens bonded to the previous carbon: ")) #-1 #8815
except ValueError:
print("Enter the number again.")
continue
else :
break
while True:
try :
h12b = int(input("Number of the other hydrogen bonded to the previous carbon: ")) #-1 #8816
except ValueError:
print("Enter the number again.")
continue
else :
break
elif quest in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
break
else :
print("Sorry, answer again, please.")
continue
### Time counter starts
if time_counter == 1:
time_in = timer.time()
### Check if universe is loaded and load it if it's not
global u
global traj
if u != 0:
print("Files were previously loaded, this will be faster!")
else :
print("Let's load the files!")
u = mda.Universe(topology, dinamica)
traj = u.trajectory
print("Topology and dynamics loaded!")
### Creation of the lists of distances
###### For carbon 9
dist_c_9 = []
dist_ha_9 = []
dist_hb_9 = []
for i in u.trajectory:
pos_c = u.select_atoms("bynum %s" % c9).positions
pos_ha = u.select_atoms("bynum %s" % h9a).positions
pos_hb = u.select_atoms("bynum %s" % h9b).positions
pos_o = u.select_atoms("bynum %s" % o_prot).positions
dist_ha_9.append(distanceslib.calc_bonds(pos_o, pos_ha)[0])
dist_hb_9.append(distanceslib.calc_bonds(pos_o, pos_hb)[0])
dist_c_9.append(distanceslib.calc_bonds(pos_o, pos_c)[0])
dist_h_9 = []
for i in range(0, len(traj)):
if dist_ha_9[i] < dist_hb_9[i]:
dist_h_9.append(dist_ha_9[i])
elif dist_ha_9[i] > dist_hb_9[i]:
dist_h_9.append(dist_hb_9[i])
avg_9_c = np.mean(dist_c_9)
min_9_c = np.min(dist_c_9)
max_9_c = np.max(dist_c_9)
rng_9_c = np.max(dist_c_9) - np.min(dist_c_9)
avg_9_h = np.mean(dist_h_9)
min_9_h = np.min(dist_h_9)
max_9_h = np.max(dist_h_9)
rng_9_h = np.max(dist_h_9) - np.min(dist_h_9)
avg_9_c_ar = np.array([avg_9_c for i in range(0, len(traj))])#needed for plots, it is just an array of the same value (the average) repeated as many times as frames the dynamics has
avg_9_h_ar = np.array([avg_9_h for i in range(0, len(traj))])
##### For carbon 12
time = []
dist_c_12 = []
dist_ha_12 = []
dist_hb_12 = []
for i in u.trajectory:
pos_c = u.select_atoms("bynum %s" % c12).positions
pos_ha = u.select_atoms("bynum %s" % h12a).positions
pos_hb = u.select_atoms("bynum %s" % h12b).positions
pos_o = u.select_atoms("bynum %s" % o_prot).positions
dist_ha_12.append(distanceslib.calc_bonds(pos_o, pos_ha)[0])
dist_hb_12.append(distanceslib.calc_bonds(pos_o, pos_hb)[0])
dist_c_12.append(distanceslib.calc_bonds(pos_o, pos_c)[0])
time.append(traj.time/1000)
dist_h_12 = []
for i in range(0, len(traj)):
if dist_ha_12[i] < dist_hb_12[i]:
dist_h_12.append(dist_ha_12[i])
elif dist_ha_12[i] > dist_hb_12[i]:
dist_h_12.append(dist_hb_12[i])
avg_12_c = np.mean(dist_c_12)
min_12_c = np.min(dist_c_12)
max_12_c = np.max(dist_c_12)
rng_12_c = np.max(dist_c_12) - np.min(dist_c_12)
avg_12_h = np.mean(dist_h_12)
min_12_h = np.min(dist_h_12)
max_12_h = np.max(dist_h_12)
rng_12_h = np.max(dist_h_12) - np.min(dist_h_12)
avg_12_c_ar = np.array([avg_12_c for i in range(0, len(traj))])
avg_12_h_ar = np.array([avg_12_h for i in range(0, len(traj))])
print("Lists of distances created")
### Summary of distances
txt = open('summary_of_distances_%s_%s.txt' % (t_c9, t_c12), 'w+')
txt.write('Distances for %s: \n'% t_c9)
txt.write('\tAverage distance %s - %s: ' % (t_c9,t_o_prot) + str(round(avg_9_c,3)) + ' Å \n' )
txt.write('\tMinimum distance %s - %s: ' % (t_c9,t_o_prot) + str(round(min_9_c,3)) + ' Å \n')
txt.write('\tMaximum distance %s - %s: ' % (t_c9,t_o_prot) + str(round(max_9_c,3)) + ' Å \n')
txt.write('\tMax-min for distances %s - %s: ' % (t_c9,t_o_prot) + str(round(rng_9_c,3)) + ' Å \n\n')
txt.write('Distances for the nearest %s, even if it is the A or the B: \n' % t_h9)
txt.write('\tAverage distance %s - %s: ' % (t_h9,t_o_prot) + str(round(avg_9_h,3)) + ' Å \n')
txt.write('\tMinimum distance %s - %s: ' % (t_h9,t_o_prot) + str(round(min_9_h,3)) + ' Å \n')
txt.write('\tMaximum distance %s - %s: ' % (t_h9,t_o_prot) + str(round(max_9_h,3)) + ' Å \n')
txt.write('\tMax-min for distances %s - %s: ' % (t_h9,t_o_prot) + str(round(rng_9_h,3)) + ' Å \n\n\n')
txt.write('Distances for %s: \n' % t_c12)
txt.write('\tAverage distance %s - %s: ' % (t_c12,t_o_prot) + str(round(avg_12_c,3)) + ' Å \n')
txt.write('\tMinimum distance %s - %s: ' % (t_c12,t_o_prot) + str(round(min_12_c,3)) + ' Å \n')
txt.write('\tMaximum distance %s - %s: ' % (t_c12,t_o_prot) + str(round(max_12_c,3)) + ' Å \n')
txt.write('\tMax-min for distances %s - %s: ' % (t_c12,t_o_prot) + str(round(rng_12_c,3)) + ' Å \n\n')
txt.write('Distances for the nearest %s, even if it is the A or the B: \n'% t_h12 )
txt.write('\tAverage distance %s - %s: ' % (t_h12,t_o_prot) + str(round(avg_12_h,3)) + ' Å \n')
txt.write('\tMinimum distance %s - %s: ' % (t_h12,t_o_prot) + str(round(min_12_h,3)) + ' Å \n')
txt.write('\tMaximum distance %s - %s: ' % (t_h12,t_o_prot) + str(round(max_12_h,3)) + ' Å \n')
txt.write('\tMax-min for distances %s - %s: ' % (t_h12,t_o_prot) + str(round(rng_12_h,3)) + ' Å \n\n\n')
txt.close()
print("Summary saved")
### Carbon plots
##### Histogram
plt.hist([dist_c_9, dist_c_12], bins=20,range=(0,10), histtype='bar', color = ['indigo', 'green'])
plt.xlabel('Distance (Å)')
plt.ylabel('Number of frames')
plt.xticks(range(0,11))
plt.legend(['%s-%s' % (t_c9,t_o_prot), '%s-%s' % (t_c12,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
plt.title("Histogram of C-OH distances for %s and %s" % (t_c9,t_c12), y=1.08, loc='center')
plt.savefig('hist_%s_%s.png' % (t_c9,t_c12), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print('Histogram of carbons saved')
##### Distances w/o avg
fig, ax1 = plt.subplots()
ax1.plot(range(0,len(traj)), dist_c_9, color='indigo')#, label='C_9-OH')
ax1.plot(range(0,len(traj)), dist_c_12, color='green')#, label='C_12-OH')
ax1.set_xlabel('Frame')
ax1.set_ylabel('Distance (Å)')
ax1.set_xticks(range(0,len(traj) +1, round(len(traj)/10)))#, ['0','1k', '2k', '3k', '4k', '5k', '6k', '7k', '8k', '9k', '10k', '11k', '12k'])
ax1.grid(True)
ax1.legend(['%s-%s' % (t_c9,t_o_prot), '%s-%s' % (t_c12,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
ax2 = ax1.twiny()
ax2.plot(time, dist_c_12, color='green')#, label='C_15-OH')
#ax2.plot(time_ar, avg_9_c_ar, color='purple')
#ax2.plot(time_ar, avg_12_c_ar, color='lime')
#ax2.plot(time_ar, avg_15_c_ar, color='orangered')
#ax2.set_xticks(time)
ax2.set_xlabel('Time (ns)')
plt.title("Plot of C-OH distances for %s and %s vs. time and frames" % (t_c9,t_c12), y=1.15, loc='center')
plt.savefig('plot_%s_%s.png' % (t_c9,t_c12), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
### Distances w/ avg
fig, ax1 = plt.subplots()
ax1.plot(range(0,len(traj)), dist_c_9, color='indigo')#, label='C_9-OH')
ax1.plot(range(0,len(traj)), dist_c_12, color='green', label='C_12-OH')
ax1.set_xlabel('Frame')
ax1.set_ylabel('Distance (Å)')
ax1.set_xticks(range(0,len(traj) +1, round(len(traj)/10)))#, ['0','1k', '2k', '3k', '4k', '5k', '6k', '7k', '8k', '9k', '10k', '11k', '12k'])
ax1.grid(True)
ax1.legend(['%s-%s' % (t_c9,t_o_prot), '%s-%s' % (t_c12,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
ax2 = ax1.twiny()
ax2.plot(time, avg_9_c_ar, color='purple')
ax2.plot(time, avg_12_c_ar, color='lime')
#ax2.set_xticks(time_ar)
ax2.set_xlabel('Time (ps)')
plt.title("Plot of C-OH distances for %s and %s vs. time and frames with average distances" % (t_c9,t_c12), y=1.15, loc='center')
plt.savefig('plot_%s_%s_avg.png' % (t_c9,t_c12), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print("Plots of carbons saved")
### Hydrogen plots
##### Histogram
plt.hist([dist_h_9, dist_h_12], bins=20,range=(0,10), histtype='bar', color = ['indigo', 'green'])
plt.xlabel('Distance (Å)')
plt.ylabel('Number of frames')
plt.xticks(range(0,11))
plt.legend(['%s-%s' % (t_h9,t_o_prot), '%s-%s' % (t_h12,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
plt.title("Histogram of H-OH distances for %s and %s" % (t_h9,t_h12), y=1.08, loc='center')
plt.savefig('hist_%s_%s.png' % (t_h9,t_h12), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print('Histogram of hydrogen saved')
##### Distance w/o avg
fig, ax1 = plt.subplots()
ax1.plot(range(0,len(traj)), dist_h_9, color='indigo')#, label='H_9-OH')
ax1.set_xlabel('Frame')
ax1.set_ylabel('Distance (Å)')
ax1.set_xticks(range(0,len(traj) +1, round(len(traj)/10)))
ax1.grid(True)
ax1.legend(['%s-%s' % (t_h9,t_o_prot), '%s-%s' % (t_h12,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
ax2 = ax1.twiny()
ax2.plot(range(0,len(traj)), dist_h_12, color='green', label='H_12-OH')
#ax2.plot(time_ar, avg_9_h_ar, color='purple')
#ax2.plot(time_ar, avg_12_h_ar, color='lime')
#ax2.plot(time_ar, avg_15_h_ar, color='orangered')
#ax2.set_xticks(time_ar)
ax2.set_xlabel('Time (ps)')
plt.title("Plot of H-OH distances for %s and %s vs. time and frames" % (t_h9,t_h12), y=1.15, loc='center')
plt.savefig('plot_%s_%s.png' % (t_h9,t_h12), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
##### Distance w/ avg
fig, ax1 = plt.subplots()
ax1.plot(range(0,len(traj)), dist_h_9, color='indigo')#, label='H_9-OH')
ax1.set_xlabel('Frame')
ax1.set_ylabel('Distance (Å)')
ax1.set_xticks(range(0,len(traj) +1, round(len(traj)/10)))#, ['0','1k', '2k', '3k', '4k', '5k', '6k', '7k', '8k', '9k', '10k', '11k', '12k'])
ax1.grid(True)
ax1.legend(['%s-%s' % (t_h9,t_o_prot), '%s-%s' % (t_h12,t_o_prot)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
ax2 = ax1.twiny()
ax2.plot(range(0,len(traj)), dist_h_12, color='green', label='H_12-OH')
ax2.plot(time, avg_9_h_ar, color='purple')
ax2.plot(time, avg_12_h_ar, color='lime')
#ax2.set_xticks(time_ar)
ax2.set_xlabel('Time (ps)')
plt.title("Plot of H-OH distances for %s and %s vs. time and frames with averages" % (t_h9,t_h12), y=1.15, loc='center')
plt.savefig('plot_%s_%s.png' % (t_h9,t_h12), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print("Plots of carbons saved")
##### Scatter
plt.scatter(dist_h_9,dist_c_9, color='indigo')
plt.scatter(dist_h_12,dist_c_12, color='green')
plt.legend(['%s-%s' % (t_c9,t_h9), '%s-%s' % (t_c12,t_h12)], bbox_to_anchor=(1.02,1), loc=2, borderaxespad=0.)
plt.grid(True)
plt.xlabel('O-C distance (Å)')
plt.ylabel('O-H distance (Å)')
plt.title("Scatter of distances for %s vs. %s and %s vs %s" % (t_c9, t_h9, t_c12, t_h12))
plt.savefig('scatter_%s_%s.png' %(t_c9,t_c12), transparent=False, dpi=300, bbox_inches='tight')
#plt.show()
plt.close()
print("Scatter of carbon vs hydrogen distances saved")
if subplots in ('', 'y', 'yes', 'Y', 'YES', 'Yes', 'yES', 'YeS', 'yEs', 'YEs'):
os.chdir(dir_now)
### Time counter ends
if time_counter == 1:
time_fin = timer.time()
print("I spent " + str(round((time_fin-time_in)/60,1)) + " min")
#####################################################################
# ### For 3 carbons
# In[6]:
def group3():
global u
global traj