-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyLFDA_cli.py
2449 lines (2310 loc) · 153 KB
/
pyLFDA_cli.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
import argparse
import sys
import os
import decimal
import math
import time
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
from numpy.core.fromnumeric import mean
import MDAnalysis as mda
import MDAnalysis.analysis.msd as msd
from membrane_curvature.base import MembraneCurvature
import subprocess
from scipy.stats import linregress
import traceback
import textwrap
import errno
import copy
import re
import warnings
import logging
import faulthandler
import pickle
import string
import secrets
warnings.filterwarnings('ignore')
class Point():
'''
Class to store the coordinates and perform the required
operations on a given atom in 3D space
'''
def __init__(self, x, y, z):
self.x = decimal.Decimal(str(x))
self.y = decimal.Decimal(str(y))
self.z = decimal.Decimal(str(z))
def mod(self):
'''
Returns magnitude of the Point
'''
modulus_value = math.sqrt(( self.x * self.x ) + ( self.y * self.y ) + ( self.z * self.z ))
return modulus_value
def __add__(self, point):
'''
Adds the points
'''
added_points = Point( self.x + point.x, self.y + point.y, self.z + point.z )
return added_points
def __sub__(self, point):
'''
Subtracts the points
'''
subtracted_points = Point( self.x - point.x, self.y - point.y, self.z - point.z )
return subtracted_points
def dot(self, point):
'''
Multiplies the points
'''
multiplied_points = Point( self.x * point.x, self.y * point.y, self.z * point.z )
return multiplied_points
def negate(self):
'''
Creates a new Point object with the components such that the
given fore vector reverses direction but remains the same in magnitude
and returns it
'''
new_point = Point( -self.x, -self.y, -self.z)
return new_point
def print(self):
'''
Returns magnitude of the Point
'''
print("X : ", self.x, " Y : ", self.y, " Z : ", self.z, "", flush = True)
class Atom():
'''
Class to Represent an Atom in 3D sapce
'''
def __init__(self, name, x, y, z):
self.name = name
self.Coords = Point(x, y, z)
def print(self):
print(self.name," ",self.point.x," ",self.point.y," ",self.point.z, flush=True)
def dot(self, point):
dot_pdt = self.x*point.x + self.y*point.y + self.z*point.z
return dot_pdt
def print(self):
print("X : ", self.x, " Y : ", self.y, " Z : ", self.z, "", flush = True)
class AtomForced():
'''
Class to store forces on an atom
'''
def __init__(self, ResNum, ResName, AtomName, AtomNumber, X, Y, Z, Fx, Fy, Fz):
self.ResNum = ResNum
self.ResName = ResName
self.AtomName = AtomName
self.AtomNumber = AtomNumber
self.Coords = Point(X, Y, Z)
self.Force = Point(Fx, Fy, Fz)
class LFDA():
'''
Class to manage path, variables and functions related to LFDA analysis
'''
def __init__(self, experiment_name=None, pdb_filename=None, gro_filename=None, trr_filename=None, tpr_filename=None, ndx_filename=None, gfda_version="v2019.3-fda2.9.1"):
'''
Initialising the experiment
Arguments :
- experiment_name : Name of the experiment. Uses this to create a directory to store outputs in. If not specified time-stamp of experiment will be used.
- pdb_filename : Path of the PDB file to be used.
- gro_filename : Path of the GRO file to be used.
- trr_filename : Path of the TRR file to be used.
- tpr_filename : Path of the TPR file to be used.
- ndx_filename : Path of the NDX file to be used.
- gfda_version : Version of Gromacs FDA to be used. Creates a directory with the name to store it and uses it for further experiments.
'''
logging.getLogger('MDAnalysis.MDAKit.membrane_curvature').setLevel(logging.CRITICAL + 1)
logging.getLogger('MDAnalysis').setLevel(logging.INFO)
global logger
logging.basicConfig(format='%(name)s : %(levelname)s :\t%(message)s')
logger = logging.getLogger('pyLFDA')
logger.addHandler(logging.NullHandler())
logging.getLogger('pyLFDA').setLevel(logging.INFO)
#faulthandler.enable() #for debugging purposes
try:
sys.tracebacklimit = -1
#Set Experiment Name
self.timestamp = time.strftime('%b-%d-%Y_%H%M', time.localtime())
if experiment_name!=None:
if os.path.exists(experiment_name):
self.experiment_name = os.path.abspath(os.path.expanduser(os.path.expandvars(experiment_name)))
else:
subprocess.run(["mkdir", experiment_name])
self.experiment_name = os.path.abspath(os.path.expanduser(os.path.expandvars(experiment_name)))
else:
subprocess.run(["mkdir", self.timestamp])
self.experiment_name = os.path.abspath(os.path.expanduser(os.path.expandvars(self.timestamp)))
if not os.path.exists(self.experiment_name):
subprocess.run(["mkdir", self.experiment_name])
#Set PDB File
if pdb_filename!=None:
self.pdb_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(pdb_filename)))
if ".pdb" not in self.pdb_filename:
raise ValueError('Enter valid PDB file')
if not os.path.exists(self.pdb_filename):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), self.pdb_filename)
#Set GRO File
if gro_filename!=None:
self.gro_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(gro_filename)))
if ".gro" not in self.gro_filename:
raise ValueError('Enter valid GRO file')
if not os.path.exists(self.gro_filename):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), self.gro_filename)
#Set TRR File
if trr_filename!=None:
self.trr_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(trr_filename)))
if ".trr" not in self.trr_filename:
raise ValueError('Enter valid TRR file')
if not os.path.exists(self.trr_filename):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), self.trr_filename)
#Set TPR File
if tpr_filename!=None:
self.tpr_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(tpr_filename)))
if ".tpr" not in self.tpr_filename:
raise ValueError('Enter valid TPR file')
if not os.path.exists(self.tpr_filename):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), self.tpr_filename)
#Set NDX File
if ndx_filename!=None:
self.ndx_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(ndx_filename)))
if ".ndx" not in self.ndx_filename:
raise ValueError('Enter valid NDX file')
if not os.path.exists(self.ndx_filename):
raise FileNotFoundError(errno.ENOENT, os.strerror(errno.ENOENT), self.ndx_filename)
#1: Install Gromacs FDA if it not inilialized
if not os.path.isdir(gfda_version):
logger.info(f"Checking GROMACS FDA installation - {gfda_version}")
version_control(gfda_version)
self.fda_bin_path = os.path.abspath(os.path.expanduser(os.path.expandvars(gfda_version+"/bin")))
#Initialise MDA Universe
self.create_mda_universe()
self.group1 = None
self.group2 = None
self.force = None
self.residue_list = None
self.pfi_filename = None
self.pfa_filename = None
self.parallel_theads = 1
self.MEMBRANE_PARTITION_THRESHOLD_FRACTION = 0.01
self.framewise = True
self.summed_pfa_filename_framewise = None
self.atom_dict_framewise = None
self.summed_pfa_filename = None
self.atom_dict = None
logger.info("Parsing GRO file to calculate numbers of atoms, atoms information and box vectors")
self.num_atoms, self.atom_info_list, self.box_vectors = parse_gro(self.gro_filename)
except:
logger.error(traceback.format_exc())
sys.exit(0)
def run_fda(self, group1=None, group2=None, force="all", residue_list=None, pfi_filename=None, pfa_filename=None):
'''
Function to create PFI file and then generating a PFA file using GROMACS FDA.
Arguments :
- group1 : 1st group selected
- group2 : 2nd group selected
- residue_list : [group1, group2]
- pfi_filename : Name of the PFI file to be generated. It is inferred from the experiment class if None.
- pfa_filename : Name of the PFA file to be generated. It is inferred from the experiment class if None.
'''
try:
self.group1 = group1
self.group2 = group2
self.force = force
self.residue_list = residue_list
if pfi_filename==None:
self.pfi_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/pfi_"+self.timestamp+".pfi")))
else:
self.pfi_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/"+pfi_filename)))
if pfa_filename==None:
self.pfa_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/pfa_"+self.timestamp+".pfa")))
else:
self.pfa_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/"+pfa_filename)))
#2: Create pfi file
logger.info("Creating PFI file")
create_pfi(path=self.pfi_filename,
group_1=self.group1,
group_2=self.group2,
force_type=self.force,
onepair="summed",
atombased="pairwise_forces_vector",
residuebased="no",
ignore_missing_potentials="yes")
#3: Running gmx fda
logger.info("Running Gromacs FDA")
run_gmx_fda(fda_install_path=self.fda_bin_path,
trr_filename=self.trr_filename,
tpr_filename=self.tpr_filename,
pfi_filename=self.pfi_filename,
pfa_filename=self.pfa_filename,
index_file=self.ndx_filename,
threads=self.parallel_theads)
logger.info("{} PFA file is generated in {}".format(self.pfa_filename, self.experiment_name))
return
except:
logger.error(traceback.format_exc())
sys.exit(0)
return
def load_pfa(self, pfa_filename=None, group1=None, group2=None, residue_list=None,):
'''
Function to load PFA file generated. Removes need to re-run experiments.
Arguments :
- pfa_filename : Path of PFA file generated by Gromacs FDA.
- group1 : 1st group selected
- group2 : 2nd group selected
- residue_list : [group1, group2]
'''
try:
logger.info("Loading PFA file generated by Gromacs FDA")
self.pfa_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(pfa_filename)))
self.group1 = group1
self.group2 = group2
self.residue_list = residue_list
except:
logger.error(traceback.format_exc())
sys.exit(0)
def create_mda_universe(self,):
'''
Function to extract relevant information using MDAnalysis.
'''
try:
logger.info("Making MDA Universe from PDB and TRR file")
self.mda_universe = mda.Universe(self.pdb_filename, self.trr_filename)
self.mda_timestamp = [int(i.time) for i in self.mda_universe.trajectory]
self.mda_residue_name = list(set(self.mda_universe.residues.resnames))
except:
logger.error(traceback.format_exc())
sys.exit(0)
def parse_pfa(self, file_name=None):
'''
Function to parse PFA generated by Gromacs FDA.
Arguments :
- file_name : Name with which parsed PFA file is to be saved.
'''
try:
if self.framewise==True:
if file_name==None:
self.summed_pfa_filename_framewise = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/pfa_framewise_"+self.timestamp+".pfa")))
else:
self.summed_pfa_filename_framewise = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/"+file_name)))
logger.info("Parsing PFA file as framewise")
create_summed_pfa(pfa_filename=self.pfa_filename,
num_atoms=self.num_atoms,
summed_pfa_filename=self.summed_pfa_filename_framewise,
framewise=True)
self.atom_dict_framewise = parse_summed_pfa(summed_pfa_file=self.summed_pfa_filename_framewise,
atom_info=self.atom_info_list,
residue_list=self.residue_list)
#self.save_atom_dict(mode="framewise")
else:
if file_name==None:
self.summed_pfa_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/pfa_averaged_"+self.timestamp+".pfa")))
else:
self.summed_pfa_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/"+file_name)))
logger.info("Parsing PFA file as average")
create_summed_pfa(pfa_filename=self.pfa_filename,
num_atoms=self.num_atoms,
summed_pfa_filename=self.summed_pfa_filename,
framewise=False)
self.atom_dict = parse_summed_pfa(summed_pfa_file=self.summed_pfa_filename,
atom_info=self.atom_info_list,
residue_list=self.residue_list)
#self.save_atom_dict(mode="average")
except:
logger.error(traceback.format_exc())
sys.exit(0)
def parse_parsed_pfa(self, file_name=None, mode=None, group1=None, group2=None, residue_list=None,):
'''
Function to parse PFA generated by pyLFDA.
Arguments :
- file_name : Name with which parsed PFA file is to be saved.
- mode : "average" - parse file as averaged. "framewise" - parse file per frame.
'''
try:
self.group1 = group1
self.group2 = group2
self.residue_list = residue_list
if mode == "average":
logger.info("Loading Average parsed PFA file")
self.framewise = False
self.summed_pfa_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(file_name)))
self.atom_dict = parse_summed_pfa(summed_pfa_file=self.summed_pfa_filename,
atom_info=self.atom_info_list,
residue_list=self.residue_list)
#self.save_atom_dict(mode="average")
elif mode == "framewise":
logger.info("Loading Framewise parsed PFA file")
self.framewise = True
self.summed_pfa_filename_framewise = os.path.abspath(os.path.expanduser(os.path.expandvars(file_name)))
self.atom_dict_framewise = parse_summed_pfa(summed_pfa_file=self.summed_pfa_filename_framewise,
atom_info=self.atom_info_list,
residue_list=self.residue_list)
#self.save_atom_dict(mode="framewise")
else:
raise ValueError("Mode not specified or Incorrect")
except:
logger.error(traceback.format_exc())
sys.exit(0)
def save_atom_dict(self, mode):
if mode == "average":
with open(f'{self.summed_pfa_filename.split(".")[0]}.pkl', 'wb') as fl:
pickle.dump(self.atom_dict, fl, protocol=pickle.HIGHEST_PROTOCOL)
logger.info(f'Database file saved at {self.summed_pfa_filename.split(".")[0]}.pkl')
elif mode == "framewise":
with open(f'{self.summed_pfa_filename_framewise.split(".")[0]}.pkl', 'wb') as fl:
pickle.dump(self.atom_dict_framewise, fl, protocol=pickle.HIGHEST_PROTOCOL)
logger.info(f'Database file saved at {self.summed_pfa_filename_framewise.split(".")[0]}.pkl')
def load_database(self, database_file, mode):
if mode == "average":
with open(database_file, 'rb') as fl:
self.atom_dict = pickle.load(fl)
logger.info(f'Loaded database file')
elif mode == "framewise":
with open(database_file, 'rb') as fl:
self.atom_dict_framewise = pickle.load(fl)
logger.info(f'Loaded database file')
def bfactor_pdb(self, bfactor_pdb_filename=None, mode="atomistic"):
'''
Function to load bfactor to a new PDB file.
Arguments :
- mode : "atomistic" loads value per atom. "groupwise" loads value averaged for the entire group.
'''
try:
if self.atom_dict==None and self.atom_dict_framewise==None:
raise ValueError("Force property of atoms are not calculated yet, please run make_summed_pfa(framewise=False) function before running this function")
else:
#if self.framewise:
# raise ValueError("Cannot create BFactor value with framewise option as true")
#else:
if bfactor_pdb_filename==None:
self.bfactor_pdb_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/bfactor_"+self.timestamp+os.path.basename(self.pdb_filename)[:-4]+".pdb")))
else:
self.bfactor_pdb_filename = os.path.abspath(os.path.expanduser(os.path.expandvars(self.experiment_name+"/"+bfactor_pdb_filename+".pdb")))
logger.info("Loading a new PDB file with bFactor")
bfactor_pdb(atom_dict=self.atom_dict if self.atom_dict!=None else self.atom_dict_framewise,
pdb_filename=self.pdb_filename,
bfactor_pdb_filename=self.bfactor_pdb_filename,
mode=mode)
except:
logger.error(traceback.format_exc())
sys.exit(0)
def force_graph(self, specific_frame=None, window=None):
'''
Function to plot force graph for a pair of groups.
Arguments :
- No arguments : Average Force over all frames.
- specific_frame : Forces for a specific frame.
- window : Forces for a moving window of the specified size.
'''
try:
if self.framewise==True:
if self.atom_dict_framewise==None:
raise ValueError("Force of atoms are not calculated yet, please run parse_pfa() function before running this function")
logger.info("Creating framewise average force plot")
if specific_frame==None and window==None:
create_average_residue_graph(atom_dict=self.atom_dict_framewise,
plot_name=self.experiment_name+"/force_averaged")
elif specific_frame:
create_specific_frame_graph(atom_dict=self.atom_dict_framewise,
specific_frame=specific_frame,
plot_name=self.experiment_name+"/force_specific_frame")
elif window:
create_moving_window_graph(atom_dict=self.atom_dict_framewise,
moving_window=window,
plot_name=self.experiment_name+"/force_moving_window")
else:
if self.atom_dict==None:
raise ValueError("Force property of atoms are not calculated yet, please run parse_pfa() function before running this function")
logger.info("Creating average force plot")
create_average_residue_graph(atom_dict=self.atom_dict,
plot_name=self.experiment_name+"/force_averaged")
except:
logger.error(traceback.format_exc())
sys.exit(0)
def curvature(self, specific_frame=None, window=None, selection="", num_x_bins=None, num_y_bins=None, split=False):
'''
Function to create a .pfi file
Arguments :
curvature_type=(Available optons : None, framewise, window)
window_size=(Default : None)
selection=(Default : "")
num_x_bins=(Default : 10)
num_y_bins=(Default : 10)
plot_type=(Default : "box")
split=(Default : False)
Returns :
None
Outputs :
Cuvature plots of type selected by the user
'''
if num_x_bins == None:
num_x_bins = 10
else:
num_x_bins = int(num_x_bins)
if num_y_bins == None:
num_y_bins = 10
else:
num_y_bins = int(num_y_bins)
try:
if not specific_frame and not window:
angle = gangle(self.trr_filename, self.tpr_filename, self.ndx_filename, self.pdb_filename, self.mda_universe, self.group1, self.group2, mode="average", split = split)
logger.info("Creating curvature plot")
plot_curvature( universe=self.mda_universe,
atom_dict=self.atom_dict if self.atom_dict!=None else self.atom_dict_framewise,
num_x_bins=num_x_bins,
num_y_bins=num_y_bins,
split=split,
gangle = angle,
plot_name=self.experiment_name+"/curvature_averaged")
elif specific_frame:
if self.atom_dict_framewise==None:
raise ValueError("Force property of atoms are not calculated yet, please run make_summed_pfa() function before running this function")
else:
logger.info(f"Creating curvature plot for frame {specific_frame}")
angle = gangle(self.trr_filename, self.tpr_filename, self.ndx_filename, self.pdb_filename, self.mda_universe, self.group1, self.group2, mode="framewise", split = split)
plot_curvature_framewise( universe=self.mda_universe,
atom_dict=self.atom_dict_framewise,
specific_frame=specific_frame,
num_x_bins = num_x_bins,
num_y_bins = num_y_bins,
split = split,
gangle = angle,
plot_name=self.experiment_name+"/curvature_framewise")
elif window:
if self.atom_dict_framewise==None:
raise ValueError("Force property of atoms are not calculated yet, please run make_summed_pfa() function before running this function")
else:
logger.info(f"Creating {window} window size curvature plots")
angle = gangle(self.trr_filename, self.tpr_filename, self.ndx_filename, self.pdb_filename, self.mda_universe, self.group1, self.group2, mode="window", split = split)
plot_curvature_window( universe=self.mda_universe,
atom_dict=self.atom_dict_framewise,
window_size = window,
num_x_bins = num_x_bins,
num_y_bins = num_y_bins,
split = split,
gangle = angle,
plot_name=self.experiment_name+"/curvature_moving_window")
except:
logger.error(traceback.print_exc(), "at line", format(sys.exc_info()[-1].tb_lineno))
sys.exit(0)
return
def cluster(self, lipids_to_cluster=None, attached_ligands=None, protein_residue_names=None, mode="pair", box_side_length = 6):
try:
logger.info("Making clutering plots")
lipids_to_cluster=self.group1 if lipids_to_cluster == None else lipids_to_cluster
attached_ligands=[None] if attached_ligands == None else [attached_ligands]
protein_residue_names = [x for x in self.mda_residue_name if x not in [attached_ligands, lipids_to_cluster]] if mode == "pair" else [x for x in self.mda_residue_name if x not in [lipids_to_cluster]]
clustering_plots(pdb_file=self.pdb_filename,
top_bottom='top',
box_side_length=box_side_length,
protein_residue_names=protein_residue_names,
attached_ligands=attached_ligands,
lipids_to_cluster=lipids_to_cluster,
mode=mode,
plot_name=self.experiment_name+"/cluster")
except:
logger.error(traceback.format_exc(), "at line", format(sys.exc_info()[-1].tb_lineno))
sys.exit(0)
return
def msd(self, select='all', msd_type='xyz', fft=True, timestep=1, start_index=None, end_index=None):
'''
Function to plot MSD values for all frames and calculates the diffusion coefficient
Arguments :
- select : MDUniverse Atom selection
- msd_type : MSD Type
'''
try:
logger.info("Calculating diffusion coefficient")
plot_msd(universe=self.mda_universe,
select=select,
msd_type=msd_type,
fft=fft,
timestep=timestep,
start_index=start_index,
end_index=end_index,
plot_name=self.experiment_name+"/MSD")
except:
logger.error(traceback.format_exc())
sys.exit(0)
return
def angles(self, selection, grouping, c_atom_name, split = False):
'''
Function to plot the averaged angle with the z-axis for the selected lipids over all frames.
Arguments :
- select : MDUniverse Atom selection
- msd_type : MSD Type
'''
try:
logger.info(f"Calculating lipid angles with vector as P -> {c_atom_name}")
angle = gangle(self.trr_filename, self.tpr_filename, self.ndx_filename, self.pdb_filename, self.mda_universe, selection = selection, grouping = grouping, c_atom_name = c_atom_name, split = split, angles = True)
if grouping != 'combine':
if split == False:
color = iter(plt.cm.cmap_d['rainbow'](np.linspace(0, 1, len(selection))))
for n, group in enumerate(selection):
plt.plot(list(range(len(angle[group]))), angle[group], linewidth=1, color=next(color), label=group, alpha=0.6)
plt.xlabel("Frame")
plt.ylabel("Angle")
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
plt.title(f'Lipid Angles P to {c_atom_name} {"_".join(selection)}', fontdict={'fontsize':10})
plt.savefig(f'{self.experiment_name}/angles_framewise_P_to_{c_atom_name}_{"_".join(selection)}.svg', dpi = 1000, bbox_inches="tight")
plt.close()
else:
for split in ["Upper", "Lower"]:
color = iter(plt.cm.cmap_d['rainbow'](np.linspace(0, 1, len(selection))))
for n, group in enumerate(selection):
plt.plot(range(len(angle[split][group])), angle[split][group], linewidth=1, color=next(color), label=group, alpha=0.6)
plt.xlabel("Frame")
plt.ylabel("Angle")
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)
plt.title(f'Lipid Angles P to {c_atom_name} {"_".join(selection)} {split} Membrane', fontdict={'fontsize':10})
plt.savefig(f'{self.experiment_name}/angles_framewise_P_to_{c_atom_name}_{"_".join(selection)}_{split}.svg', dpi = 1000, bbox_inches="tight")
plt.close()
else:
if split == False:
plt.plot(range(len(angle["Combined"])), angle["Combined"], linewidth=1, color='crimson', label="Combined")
plt.xlabel("Frame")
plt.ylabel("Angle")
plt.title(f'Lipid Angles P to {c_atom_name} combined', fontdict={'fontsize':10})
plt.savefig(f'{self.experiment_name}/angles_framewise_combined_P_to_{c_atom_name}.svg', dpi = 1000, bbox_inches="tight")
plt.close()
else:
for split in ["Upper", "Lower"]:
plt.plot(range(len(angle[split]["Combined"])), angle[split]["Combined"], linewidth=1, color='crimson', label="Combined")
plt.xlabel("Frame")
plt.ylabel("Angle")
plt.title(f'Lipid Angles P to {c_atom_name} combined {split} Membrane', fontdict={'fontsize':10})
plt.savefig(f'{self.experiment_name}/angles_framewise_combined_P_to_{c_atom_name}_{split}.svg', dpi = 1000, bbox_inches="tight")
plt.close()
except:
logger.error(traceback.format_exc(), "at line", format(sys.exc_info()[-1].tb_lineno))
sys.exit(0)
return
def version_control(version):
try:
if version not in ['v2020.4-fda2.10.2', 'v2020.3-fda2.10.1', 'v2020.3-fda2.10', 'v2020-fda2.10', 'v2019.3-fda2.9.1', 'v2018.7-fda2.9.1']:
raise ValueError("Please enter valid gromac version from list ['v2020.4-fda2.10.2', 'v2020.3-fda2.10.1', 'v2020.3-fda2.10', 'v2020-fda2.10', 'v2019.3-fda2.9.1', 'v2018.7-fda2.9.1']")
if not os.path.isdir(version):
logger.info(f"Installing GROMACS FDA version {version}")
subprocess.call(["sudo", "apt-get", "install", "libboost-all-dev", "libfftw3-3", "libfftw3-dev"])
subprocess.run(["mkdir", "-p", f"{version}/"])
subprocess.run(["git", "clone", f"https://github.com/HITS-MBM/gromacs-fda.git", "-b", f"{version}"])
subprocess.run(["mkdir", "-p", f"gromacs-fda/build"])
Installation_directory = os.getcwd()+f"/{version}"
os.chdir(f"gromacs-fda/build")
subprocess.check_call(["cmake", f"-DCMAKE_INSTALL_PREFIX={Installation_directory}", "-DGMX_BUILD_FDA=ON", "-DGMX_DEFAULT_SUFFIX=OFF", "-DGMX_BINARY_SUFFIX=_fda", "-DGMX_SIMD=NONE", "-DGMX_BUILD_UNITTESTS=ON", "-DGMX_GPU=OFF", ".."])
subprocess.check_call(["make", "-j", "1"])
subprocess.check_call(["make", "check"])
subprocess.check_call(["make", "install"])
os.chdir("../../")
subprocess.run(["rm", "-rf", "gromacs-fda"])
logger.info(f"Installed GROMACS FDA version {version}")
except:
logger.error("Please ensure that you have the prerequisites for installing GROMACS-FDA. Please open a GItHub issue if you cannot get it to work")
logger.error(traceback.format_exc())
subprocess.run(["rm", "-rf", f"{version}/"])
subprocess.run(["rm", "-rf", "gromacs-fda/"])
sys.exit(0)
return
def create_pfi(path, group_1, group_2, force_type="all", onepair="summed", atombased="pairwise_forces_vector", residuebased="no", ignore_missing_potentials="yes"):
'''
Function to create a .pfi file
Arguments :
path : Path where to create the .pfi file
group_1 : Residue Group 1
group_2 : Residue Group 2
force_type : Force type to be calculated (default : all)
onepair : Forces summation (default : summed)
atombased : Force type (default : pairwise_forces_vector)
residuebased : Are foreces are residue based (default : no)
ignore_missing_potentials : Missing potential from files (default : yes)
Returns :
None
Outputs :
Creates a .pfi file with parameters to be used my gromacs-fda
'''
try:
start_time = time.time()
if group_1==None or group_2==None:
raise ValueError('Enter enter names for group1 or group2')
with open(path, 'w') as fp:
fp.write("onepair = " +onepair+"\n")
fp.write("group1 = " +group_1+"\n")
fp.write("group2 = " +group_2+"\n")
fp.write("atombased = " +atombased+"\n")
fp.write("residuebased = " +residuebased+"\n")
fp.write("type = " +force_type+"\n")
fp.write("ignore_missing_potentials=" +ignore_missing_potentials+"\n")
end_time = time.time()
logger.info("{} file created in {} seconds ".format(path, (end_time-start_time)))
except:
logger.error(traceback.format_exc())
sys.exit(0)
return
def run_gmx_fda(fda_install_path, trr_filename, tpr_filename, pfi_filename, pfa_filename, index_file, threads=1):
try:
gromacs_start = time.time()
subprocess.check_call([f"{fda_install_path}/./gmx_fda", "mdrun", "-rerun", trr_filename, "-s", tpr_filename, "-pfi", pfi_filename, "-nt", str(threads), "-pfa", pfa_filename, "-pfn", index_file])
gromacs_end = time.time()
logger.info("GMX RUN completed in {} seconds".format((gromacs_end-gromacs_start)))
return
except:
logger.error("Please ensure that your files are compatible with the GROMACS FDA version and are entered correctly!!")
sys.exit(0)
return
def parse_gro(filename):
'''
Function to parse a .gro file to numbers of atoms, atoms details and box vector values list.
Arguments :
filename : Path to the .gro file
Returns :
num_atoms : int : Number of atoms
atom_info_list : list of dictionary : A list of dictionaries containing the properties of each atom
for example one element of atom_info_list:-
{'Residue_Number': 1,
'Residue_Name': 'CHL1',
'Atom_Name': 'C3',
'Atom_Number': 1,
'X_Coordinate': 6.332,
'Y_Coordinate': 5.87,
'Z_Coordinate': 4.784,
'X_Velocity': 0.4755,
'Y_Velocity': 0.637,
'Z_Velocity': 0.1449}
box_vectors : list of int : A list of the box vector values
'''
try:
gro_parse_start = time.time()
with open(filename, 'r') as fp:
title = fp.readline()
num_atoms = int(fp.readline())
atom_info_list = []
gro_current_line = ''
while True:
previous_line = copy.deepcopy(gro_current_line)
gro_current_line = fp.readline()
if len(gro_current_line) == 0:
break
atom_info = {"Residue_Number" : None, "Residue_Name" : None, "Atom_Name" : None, "Atom_Number" : None, "X_Coordinate" : None, "Y_Coordinate" : None, "Z_Coordinate" : None, "X_Velocity" : None, "Y_Velocity" : None, "Z_Velocity" : None}
try:
gro_current_line = gro_current_line.split()
if len(gro_current_line) == 9:
Residue_Name = re.search(r"[a-zA-Z]", gro_current_line[0])
Residue_Name = Residue_Name.start()
atom_info["Residue_Number"] = int(gro_current_line[0][:Residue_Name])
atom_info["Residue_Name"] = str(gro_current_line[0][Residue_Name:])
atom_info["Atom_Name"] = str(gro_current_line[1])
atom_info["Atom_Number"] = int(gro_current_line[2])
current_len = len(gro_current_line[2])
atom_info["X_Coordinate"] = float(gro_current_line[3])
atom_info["Y_Coordinate"] = float(gro_current_line[4])
atom_info["Z_Coordinate"] = float(gro_current_line[5])
atom_info["X_Velocity"] = float(gro_current_line[6])
atom_info["Y_Velocity"] = float(gro_current_line[7])
atom_info["Z_Velocity"] = float(gro_current_line[8])
atom_info_list.append(atom_info)
else:
Residue_Name = re.search(r"[a-zA-Z]", gro_current_line[0])
Residue_Name = Residue_Name.start()
atom_info["Residue_Number"] = int(gro_current_line[0][:Residue_Name])
atom_info["Residue_Name"] = str(gro_current_line[0][Residue_Name:])
atom_info["Atom_Name"] = str(gro_current_line[1][:current_len])
atom_info["Atom_Number"] = int(gro_current_line[1][current_len:])
current_len = len(gro_current_line[:current_len])
atom_info["X_Coordinate"] = float(gro_current_line[2])
atom_info["Y_Coordinate"] = float(gro_current_line[3])
atom_info["Z_Coordinate"] = float(gro_current_line[4])
atom_info["X_Velocity"] = float(gro_current_line[5])
atom_info["Y_Velocity"] = float(gro_current_line[6])
atom_info["Z_Velocity"] = float(gro_current_line[7])
atom_info_list.append(atom_info)
except:
break
box_vectors = list(map(float,previous_line[-1].split()))
gro_parse_end = time.time()
logger.info("{} file parsed. with {} atoms in {} seconds".format(filename, num_atoms, (gro_parse_end-gro_parse_start)))
return num_atoms, atom_info_list, box_vectors
except:
logger.error(traceback.format_exc())
sys.exit(0)
return
def create_summed_pfa(pfa_filename, num_atoms, summed_pfa_filename=None, framewise=False):
'''
Function to parse a .pfa file according to framewise or all frame at once.
Arguments :
pfa_filename : Path to the .pfa file
num_atoms : Numbers of atoms
summed_pfa_filename : Path to new summned pfa that will be generated from this function (default : summed_pfa.pfa if framewise = false otherwise framewised_summed_pfa.pfa)
framewise : how to sum all the force (default : false)
Returns :
None
Outputs :
Creates a file with summed up pairwise force values either framewise or combined
'''
try:
start_time=time.time()
if summed_pfa_filename==None:
raise ValueError("Pleae enter name for new PFA file !!!")
#If framewise force summation is not selected
if not framewise:
#Intitialise forces on atom with 0
Forces_on_Atoms = []
for i in range(0, num_atoms+1):
Forces_on_Atoms.append(Point(0, 0, 0))
num_frames = 0
with open(pfa_filename, "r") as fp:
pfa_current_line = fp.readline()
while True:
pfa_current_line = fp.readline()
#if blank line then end of file and end the read operation
if len(pfa_current_line) == 0:
break
#if new frame is detected then increment frame number
elif pfa_current_line[:5] == "frame" or pfa_current_line[:5] == "force":
num_frames += 1
continue
#summation of forces from all frames are done if
# force is applied by atom then forces are subtracted
# otherwise added to previous force sum
else:
pfa_current_line = pfa_current_line.split()
force_applied_by = int(pfa_current_line[1])
force_recieved_by = int(pfa_current_line[0])
force_magnitude = Point(pfa_current_line[2], pfa_current_line[3], pfa_current_line[4])
Forces_on_Atoms[force_recieved_by] += force_magnitude
Forces_on_Atoms[force_applied_by] += force_magnitude.negate()
#all forces will be written in new pfa file
with open(summed_pfa_filename, "w") as fp:
fp.write("frame " + str(num_frames) + "\n")
for i in range(0, len(Forces_on_Atoms)):
fp.write(str(i+1) + "\t" + str(Forces_on_Atoms[i].x) + "\t" + str(Forces_on_Atoms[i].y) + "\t" + str(Forces_on_Atoms[i].z) + "\n")
#If framewise force summation is selected
else:
open(summed_pfa_filename, "w").close()
#Intitialise forces on atom with 0
Forces_on_Atoms_Holder = []
for i in range(0, num_atoms+1):
Forces_on_Atoms_Holder.append(Point(0, 0, 0))
Forces_on_Atoms = Forces_on_Atoms_Holder
with open(pfa_filename, "r") as fp:
pfa_current_line = fp.readline()
while True:
pfa_current_line = fp.readline()
#if blank line then end of file and end the read operation
if len(pfa_current_line) == 0:
break
#if new frame is detected then summation of forces from previous frame is written in file
elif pfa_current_line[:5] == "frame" or pfa_current_line[:5] == "force":
frame_number = int(pfa_current_line[6:])
if frame_number >= 0:
with open(summed_pfa_filename, "a") as fp_temp:
fp_temp.write("frame " + str(frame_number) + "\n")
for i in range(0, len(Forces_on_Atoms)):
fp_temp.write(str(i+1) + "\t" + str(Forces_on_Atoms[i].x) + "\t" + str(Forces_on_Atoms[i].y) + "\t" + str(Forces_on_Atoms[i].z) + "\n")
Forces_on_Atoms = []
for i in range(0, num_atoms+1):
Forces_on_Atoms.append(Point(0, 0, 0))
#summation of forces from one frames are done if
# force is applied by atom then forces are subtracted
# otherwise added to previous force sum
else:
pfa_current_line = pfa_current_line.split()
force_applied_by = int(pfa_current_line[1])
force_recieved_by = int(pfa_current_line[0])
force_magnitude = Point(pfa_current_line[2], pfa_current_line[3], pfa_current_line[4])
Forces_on_Atoms[force_recieved_by] += force_magnitude
Forces_on_Atoms[force_applied_by] += force_magnitude.negate()
end_time=time.time()
logger.info("Parsed PFA file {} created with {} atoms in {} seconds".format(summed_pfa_filename, num_atoms, (end_time-start_time)))
except:
logger.error(traceback.format_exc())
sys.exit(0)
return
def parse_summed_pfa(summed_pfa_file, atom_info, residue_list):
'''
Function to parse the summed .pfa file
Arguments :
summed_pfa_file : Path to the summed .pfa file
atom_info : vector of class 'AtomForced'
residue_list : List of residues to be calculated (example : ["POPS","POPC"])
Returns :
Dictionary of input residues containing a list of their atoms
for example if the framewise summation pfa is selected :-
if ["POPS","POPC"] are selected
[1]['POPS'][AtomForced class object, .... ]
['POPC'][AtomForced class object, .... ]
[2]['POPS'][AtomForced class object, .... ]
['POPC'][AtomForced class object, .... ]
:
:
[100]['POPS'][AtomForced class object, .... ]
['POPC'][AtomForced class object, .... ]
if framewise is selected :-
last frame will content all the details if the last frame is 100 then,
[100]['POPS'][AtomForced class object, .... ]
['POPC'][AtomForced class object, .... ]
'''
try:
start_time=time.time()
current_frame = 0
AllResidueGroupsFramewise = {}
with open(summed_pfa_file, 'r') as fp:
restart = True
while restart:
for i in atom_info:
# read lines from summation generated pfa file
summed_pfa_current_line = fp.readline().split()
#if blank line then end of file and end the read operation
if len(summed_pfa_current_line) == 0:
restart = False
break
#if new frame is detected then summation of forces from previous frame is written in file
elif summed_pfa_current_line[0] == "frame":
current_frame = int(summed_pfa_current_line[1])
AllResidueGroupsFramewise[current_frame] = {}
for residueName in residue_list:
AllResidueGroupsFramewise[current_frame][str(residueName)] = []
break
#summation of forces from one frames are done if
# force is applied by atom then forces are subtracted
# otherwise added to previous force sum
else:
if i["Residue_Name"] in residue_list:
if int(summed_pfa_current_line[0]) == i["Atom_Number"]:
f_x = summed_pfa_current_line[1]
f_y = summed_pfa_current_line[2]
f_z = summed_pfa_current_line[3]
forceAtom = AtomForced(
i["Residue_Number"],
i["Residue_Name"],
i["Atom_Name"],
i["Atom_Number"],
i["X_Coordinate"],
i["Y_Coordinate"],
i["Z_Coordinate"],
f_x,
f_y,
f_z
)
AllResidueGroupsFramewise[current_frame][i["Residue_Name"]].append(forceAtom)
end_time = time.time()
logger.info("Summed PFA file parsed in {} seconds".format((end_time-start_time)))
return AllResidueGroupsFramewise
except:
logger.error(traceback.format_exc())
sys.exit(0)
return
def bfactor_pdb(atom_dict, pdb_filename, bfactor_pdb_filename, mode = "combined"):
'''
Create a .pdb file with the same atoms as the .gro file but with the bfactor
Arguments :
summed_pfa_file : Path to the summed .pfa file
gro_file : Path to the .gro file
residue_list : List of residues to be calculated (example : ["POPS","POPC"])
mode : "combined" (atomistic or combined)
Returns :
None
Outputs :
.pdb file with bfactor values loaded
'''
try:
start_time = time.time()
bfactor = {}
atom_numbers = {}
min_force = np.finfo(float).max
max_force = np.finfo(float).min
num_frames = len(atom_dict)
num_frames_orignal = list(atom_dict.keys())[0] if num_frames == 1 else num_frames
numKeys = len(atom_dict[list(atom_dict.keys())[0]])
allKeys = [key for key in atom_dict[list(atom_dict.keys())[0]]]
if mode == "combined":
for i in range(numKeys):
if num_frames == num_frames_orignal:
forced_atomGroup = [atom_dict[window][allKeys[i]] for window in range(0, num_frames)]
else: