-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsnp2sim.py
More file actions
executable file
·2340 lines (2044 loc) · 94.3 KB
/
snp2sim.py
File metadata and controls
executable file
·2340 lines (2044 loc) · 94.3 KB
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 python
import os
import sys
import argparse
import copy
import random
import multiprocessing
import yaml
import shutil
import subprocess
import csv
import time
import logging
import glob
import re
#Class that parses the command line and Yaml Config arguments
class argParse():
#reads command line args, then config args
#Config args supercede in case of conflict
#Args are added to argParse parameters
def __init__(self):
self.requiredArgs = ['protein', 'mode']
self.commandargs = _parseCommandLine()
self.__dict__.update(self.commandargs.__dict__)
if (self.config):
self.args = yaml.safe_load(open(self.config))
self.args = {k: v for k, v in self.args.items() if v is not None}
self.__dict__.update(self.args)
if self.verbose:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s [%(name)-s] %(levelname)-s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
else:
logging.basicConfig(level=logging.INFO,
format='%(asctime)s [%(name)-s] %(levelname)-s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
self.logger = logging.getLogger('BASE')
#Verifies all required general and module-specific args are provided
#Throws assertionError if required parameter is not provided
def checkRequiredArgs(self):
for arg in self.requiredArgs:
if not (hasattr(self, arg) and getattr(self, arg)):
self.logger.error(arg + " not specified! " + arg + " is required.")
sys.exit(1)
if self.mode == "varMDsim":
if not self.simID:
self.simID = str(random.randint(1,1000))
self.logger.debug("varMDsim ID: %s", self.simID)
if not self.newStruct:
self.logger.error("Template PDB not specified for simulation.")
# sys.exit(1)
if not self.simLength:
self.logger.error("Simulation length not specified.")
sys.exit(1)
if self.mode == "varScaffold":
if not (hasattr(self, "scaffID") and getattr(self, "scaffID")):
self.logger.error("scaffID not specified.")
sys.exit(1)
if not (hasattr(self, "alignmentResidues") and getattr(self, "alignmentResidues")):
self.logger.error("Alignment Residues not specified.")
sys.exit(1)
if not (hasattr(self, "clusterResidues") and getattr(self, "clusterResidues")):
self.logger.error("Cluster Residues not specified.")
sys.exit(1)
if self.mode == "varAnalysis":
if not (hasattr(self, "analysisVariants") and self.analysisVariants):
parameters.logger.error("Variants for analysis not specified.")
sys.exit(1)
#Sets the defaults for all other parameters, and initializes any other variables needed for the workflow.
def setDefault(self):
#programDir is the path for the main script and analysis scripts
#as well as topology files and other supllemental files
self.programDIR = os.path.abspath(__file__)
self.programDIR = os.path.dirname(self.programDIR)
#runDir is the path to save all results, and reference previous results or modules
if not self.runDIR:
self.runDIR = "/opt/snp2sim_results"
if not os.path.isdir(self.runDIR):
os.makedirs(self.runDIR)
self.logger.debug("Run Directory: %s", self.runDIR)
self.logger.debug("Installation Directory: %s", self.programDIR)
if "." in self.protein:
self.protein = self.protein.replace(".", "_")
self.logger.info("Protein system: %s", self.protein)
#set paths for tools
if not self.VMDpath:
self.VMDpath = "vmd"
if not self.NAMDpath:
self.NAMDpath = "namd2"
if not self.PYTHONSHpath:
#make sure pythonsh (from AutoDockTools) has been added to path
self.PYTHONSHpath = "/opt/mgltools_x86_64Linux2_1.5.6/bin/pythonsh"
if not self.ADTpath:
#must have path for "prepare_xxx.py" scripts from autodock tools
self.ADTpath = "/opt/mgltools_x86_64Linux2_1.5.6/MGLToolsPckgs/AutoDockTools/Utilities24/"
if not self.VINApath:
self.VINApath = "/opt/vina/autodock_vina_1_1_2_linux_x86/bin/vina"
#Creates the variant parameter, a string that contains a unique ID for the variants used in the run
#Covers the cases of the variants being provided as a list of AA and residue numbers
#Defaults to WT if not variant provided
if self.variant != "wt":
if isinstance(self.varAA,list) and isinstance(self.varResID,list):
if len(self.varAA) == len(self.varResID):
self.variant = [str(self.varResID[x]) + self.varAA[x] for x in range(len(self.varAA))]
self.logger.info("Variant: %s", ", ".join(self.variant))
self.variant = "_".join(self.variant)
else:
self.logger.warning("Number of ResIDs does not match number of variant AAs.")
self.logger.warning("Using WT structure for simulation")
self.variant = "wt"
elif self.varResID and self.varAA:
self.variant = str(self.varResID) + self.varAA
self.logger.info("Variant: %s", self.variant)
else:
self.logger.warning("varResID and varAA not specified")
self.logger.warning("Using WT structure for simulation")
self.variant = "wt"
else:
self.logger.info("Using WT structure for simulation")
#Points to the supplemental files needed to create the starter files for the MD sim.
self.simTopology = ("%s/simParameters/top_all36_prot.rtf" % self.programDIR,
"%s/simParameters/top_all36_na.rtf" % self.programDIR,
"%s/simParameters/toppar_all36_prot_na_combined.str" % self.programDIR,
"%s/simParameters/toppar_water_ions_namd.str" % self.programDIR)
self.simParameters = ("%s/simParameters/par_all36_prot.prm" % self.programDIR,
"%s/simParameters/par_all36_na.prm" % self.programDIR,
"%s/simParameters/toppar_all36_prot_na_combined.str" % self.programDIR,
"%s/simParameters/toppar_water_ions_namd.str" %self.programDIR)
#by default uses all cores
if not self.simProc:
self.simProc = multiprocessing.cpu_count()
self.logger.debug("Using %d cores", self.simProc)
self.inputDIR = self.runDIR
self.varsDIR = os.path.join(self.runDIR, "variantSimulations", self.protein) + "/"
self.analysisDIR = os.path.join(self.runDIR, "variantSimulations", self.protein, "analysis/")
self.runDIR = os.path.join(self.runDIR, "variantSimulations", self.protein, self.variant) + "/"
self.structDIR = os.path.join(self.runDIR, "structures/")
self.binDIR = os.path.join(self.runDIR, "bin/")
self.configDIR = os.path.join(self.runDIR, "config/")
self.resultsDIR = os.path.join(self.runDIR, "results/")
self.drugBindingDIR = os.path.join(self.resultsDIR, "drugBinding/")
self.trajDIR = os.path.join(self.resultsDIR, "trajectory/")
self.scaffoldDIR = os.path.join(self.resultsDIR, "scaffold/")
if not os.path.isdir(self.configDIR):
os.makedirs(self.configDIR)
if not os.path.isdir(self.binDIR):
os.makedirs(self.binDIR)
shutil.copy(self.config, self.configDIR)
#creates paths to all the structures used in the prep for MD sim
self.simPDB = self.structDIR + "%s.%s.pdb" \
% (self.protein,self.variant)
self.simPSF = self.structDIR + "%s.%s.psf" \
% (self.protein,self.variant)
self.templatePDB = self.structDIR + "%s.template.pdb" \
% (self.protein)
self.wtPDB = self.structDIR + "%s.wt.UNSOLVATED.pdb" \
% (self.protein)
self.wtPSF = self.structDIR + "%s.wt.UNSOLVATED.psf" \
% (self.protein)
self.varPrefix = self.structDIR + "%s.%s.UNSOLVATED" \
% (self.protein,self.variant)
self.varPDB = self.structDIR + "%s.%s.UNSOLVATED.pdb" \
% (self.protein,self.variant)
self.varPSF = self.structDIR + "%s.%s.UNSOLVATED.psf" \
% (self.protein,self.variant)
#paths to the TCL scripts used to generate the starter structures
self.wtStructTCL = self.binDIR + "%s.wt.genStructFiles.tcl" \
% (self.protein)
self.varStructTCL = self.binDIR + "%s.%s.genStructFiles.tcl" \
% (self.protein,self.variant)
self.singleRunTCL = self.binDIR + "%s.%s.genSingleRunPDB.tcl" \
% (self.protein,self.variant)
self.solvTCL = self.binDIR + "%s.%s.genSolvStruct.tcl" \
% (self.protein,self.variant)
self.solvBoundary = self.configDIR + "%s.%s.solvBoundary.txt" \
% (self.protein,self.variant)
self.structPrefix = self.structDIR + "%s.%s" \
% (self.protein,self.variant)
#path to NAMD parameters
self.NAMDconfig = self.configDIR + "%s.%s.%s.NAMD" \
% (self.protein, self.variant, self.simID)
self.NAMDout = self.trajDIR + "%s.%s.%s" \
% (self.protein, self.variant, self.simID)
#path to the drug libraries in the program directory
self.drugLibPath = "%s/drugLibraries/%s/" % \
(self.programDIR, self.drugLibrary)
#hardcoding bindingID as drugLibrary
#TODO - refactor to remove "bindingID"
self.bindingID = self.drugLibrary
if not self.vinaExh or not isinstance(self.vinaExh, int):
self.vinaExh = 50
#Autodock config
if self.bindingID:
self.drugBindConfig = self.configDIR + "%s.autodock" \
% (self.bindingID)
#allows user to input trajectories in PDB format from external source
if self.loadPDBtraj:
variantDIR = self.trajDIR
if not os.path.exists(variantDIR):
os.makedirs(variantDIR)
for pdbFile in self.loadPDBtraj:
pdbNewLoc = self.trajDIR + os.path.basename(pdbFile)
os.system("cp %s %s" % (pdbFile,pdbNewLoc))
def _parseCommandLine():
parser = argparse.ArgumentParser(
#version="0.1",
description="snp2sim - Molecular Simulation of Somatic Variation",
epilog="written by Matthew McCoy, mdm299@georgetown.edu"
)
#general parameters
parser.add_argument("--mode",
help="varMDsim, varScaffold, drugSearch, or varAnalysis",
action="store",
type=str,
)
parser.add_argument("--protein",
help="name of protein system",
action="store",
type=str,
)
parser.add_argument("--variant",
help="variant as \"wt\" or \"x###x\"",
action="store",
type=str,
)
parser.add_argument("--runDIR",
help="path to directory to store results",
action="store",
type=str,
)
parser.add_argument("--clean",
help="remove all files from previous run with same protein name",
action="store_true",
)
parser.add_argument("--cgcRun",
help="if Run is on CGC platform, move pdb and log to snp2sim root for processing",
action="store_true",
)
#VarMDsim options
parser.add_argument("--newStruct",
help="path to cleaned PDB file (protein structure w/ cannonical aa)",
action="store",
type=str,
)
parser.add_argument("--cofactorStruct",
help="path to PDB file of cofactor (ion or protein)",
action="store",
type=str,
)
parser.add_argument("--bindingTemplate",
help="path to PDB file used to create search space to align scaffold",
action="store",
type=str,
)
parser.add_argument("--simLength",
help="varTraj simulation length in ns",
action="store",
type=float,
)
parser.add_argument("--varResID",
help="variant residue ID from PDB template",
action="store",
type=str,
)
parser.add_argument("--varAA",
help="amino acid to change",
action="store",
type=str,
)
parser.add_argument("--simID",
help="ID number for the MD sim run",
action="store",
type=str,
)
parser.add_argument("--VMDpath",
help="path to VMD executable",
action="store",
type=str,
)
parser.add_argument("--NAMDpath",
help="path to NAMD executable",
action="store",
type=str,
)
parser.add_argument("--simProc",
help="number of processors to run simulation",
action="store",
type=int,
)
parser.add_argument("--singleRun",
help="output summary PDB trajectory only",
action="store_true",
)
parser.add_argument("--genStructures",
help="only generate initial structures",
action="store_true",
)
parser.add_argument("--noMinimize",
help="skip minimization",
action="store_true",
)
parser.add_argument("--implicitSolvent",
help="use implicit solvent instead of water",
action="store_true",
)
parser.add_argument("--margin",
help="value of margin to use in NAMD simulation ",
action="store",
default="1.0",
type=str,
)
#varScaff options
parser.add_argument("--scaffID",
help="ID for the Scaffolding run",
action="store",
type=str,
)
parser.add_argument("--clustPDBtraj",
help="cluster results from multiple varScafold singleRun",
action="store_true",
)
parser.add_argument("--loadPDBtraj", nargs='+',
help="pdb trajectory files to import, list one after another",
action="store",
)
parser.add_argument("--alignmentResidues",
help="residue numbers used to align trajectory for clustering",
action="store",
type=str,
)
parser.add_argument("--clusterResidues",
help="residue numbers to consider when clustering",
action="store",
type=str,
)
parser.add_argument("--featureTableMethod",
help="use the feature table method, otherwise RMSD method is used",
action="store_true",
)
parser.add_argument("--PairwiseRMSD",
help="if RMSD method is used, pass in already created PairwiseRMSD matrix",
action="store",
type=str,
)
parser.add_argument("--colorTrajectory",
help="create a full trajectory PDB file where each frame is colored by cluster",
action="store_true",
)
#drugBinding options
parser.add_argument("--vinaExh",
help="exhaustiveness parameter of autodock vina",
action="store",
default="8",
type=str,
)
parser.add_argument("--VINApath",
help="path to AutoDock Vina executable",
action="store",
type=str,
)
parser.add_argument("--PYTHONSHpath",
help="path to autodock tools python executable",
action="store",
type=str,
)
parser.add_argument("--ADTpath",
help="path to autodock utilities directory",
action="store",
type=str,
)
parser.add_argument("--newBindingConfig",
help="path to new binding config file",
action="store",
type=str,
)
parser.add_argument("--flexBinding",
help="path to file with flex residue numbers",
action="store",
type=str,
)
parser.add_argument("--drugLibrary",
help="name of snp2sim drug library",
action="store",
type=str,
)
parser.add_argument("--singleDrug",
help="path to single drug PDBQT",
action="store",
type=str,
)
parser.add_argument("--inputScaff", nargs='+',
help="pdb scaffold files to import, list one after another",
action="store",
)
parser.add_argument("--bindSingleVar",
help="only bind single variant scaffolds",
action="store_true",
)
parser.add_argument("--ligandPDB",
help="path to dir with ligand PDBs",
action="store",
type=str,
)
parser.add_argument("--config",
help="use parameters from config.yaml. OVERWRITES command line parameters",
action="store",
)
parser.add_argument("--verbose",
help="show debugging logs",
action="store_true",
)
#parses command line args
cmdlineparameters, unknownparams = parser.parse_known_args()
parameters = copy.copy(cmdlineparameters)
return parameters
#creates unsolvated PDB and PSF files
#solvates the struct files
def genNAMDstructFiles(parameters):
if not os.path.exists(parameters.binDIR):
os.makedirs(parameters.binDIR)
if os.path.isfile(parameters.templatePDB):
parameters.logger.debug("Generating solvated/ionized PDB and PSF from %s", parameters.templatePDB)
#creates the unsolvated PDB and PSF files if not already present
#also mutates if necessary
if os.path.isfile(parameters.varPDB) and os.path.isfile(parameters.varPSF):
parameters.logger.debug("Unsolvated PDB and PSF exist")
parameters.logger.debug("Using previously created unsolvated PDB and PSF")
else:
genStructTCL(parameters)
genStructCommand = "%s -e %s" % (parameters.VMDpath, parameters.varStructTCL)
parameters.logger.debug("Running unsolvated structure generation TCL in VMD")
parameters.logger.debug("VMD Command: %s", genStructCommand)
try:
out = subprocess.check_output(genStructCommand, shell = True)
parameters.logger.debug("VMD Output: \n\n%s\n\n", out.decode('ascii'))
except subprocess.CalledProcessError as e:
parameters.logger.error("VMD output: \n%s", e.output.decode('ascii'))
sys.exit(1)
if parameters.implicitSolvent:
parameters.logger.debug("Implicit Solvent selected, using unsolvated PDB and PSF")
return
#Solvates the structure files with a water box for simulation
genSolvTCL(parameters)
genSolvCommand = "%s -e %s" % (parameters.VMDpath, parameters.solvTCL)
if not os.path.exists(parameters.configDIR):
os.makedirs(parameters.configDIR)
parameters.logger.debug("Running structure solvation/ionization TCL in VMD")
parameters.logger.debug("VMD Command: %s", genSolvCommand)
try:
out = subprocess.check_output(genSolvCommand, shell = True)
parameters.logger.debug("VMD Output: \n\n%s\n\n", out.decode('ascii'))
except subprocess.CalledProcessError as e:
parameters.logger.error("VMD output: \n%s", e.output.decode('ascii'))
sys.exit(1)
else:
parameters.logger.error("No template exists")
parameters.logger.error("Use --newStruct to specify clean PDB (only cannonical aa) ")
sys.exit(1)
#Creates a TCL script for VMD
#uses Topology files with template PDB to make PDB and PSF files
#mutates with all variants
def genStructTCL(parameters):
parameters.logger.debug("Creating unsolvated struct files")
structFile = open(parameters.varStructTCL,"w+")
parameters.logger.debug("Writing unsolvated structure generation TCL: %s", parameters.varStructTCL)
structFile.write("package require psfgen\n")
for tFile in parameters.simTopology:
structFile.write("topology %s\n" % tFile)
structFile.write("pdbalias residue HIS HSE\n")
structFile.write("pdbalias residue PTR TYR\n")
structFile.write("pdbalias residue CA CAL\n")
structFile.write("pdbalias atom CAL CA CAL\n")
structFile.write("segment PROT {pdb %s}\n" % parameters.templatePDB)
structFile.write("coordpdb %s PROT\n" % parameters.templatePDB)
if parameters.cofactorStruct:
structFile.write("segment COF {pdb %s}\n" % parameters.cofactorStruct)
structFile.write("coordpdb %s COF\n" % parameters.cofactorStruct)
structFile.write("guesscoord\n")
structFile.write("writepdb %s\n" % parameters.wtPDB)
structFile.write("writepsf %s\n" % parameters.wtPSF)
if not parameters.variant == "wt":
longAA = { "G":"GLY","A":"ALA","L":"LEU","M":"MET","F":"PHE",
"W":"TRP","K":"LYS","Q":"GLN","E":"GLU","S":"SER",
"P":"PRO","V":"VAL","I":"ILE","C":"CYS","Y":"TYR",
"H":"HSE","R":"ARG","N":"ASN","D":"ASP","T":"THR"}
structFile.write("package require mutator\n")
if (isinstance(parameters.varAA, list) and isinstance(parameters.varResID, list)):
for x in range(len(parameters.varAA)):
structFile.write("mutator -psf %s -pdb %s -o %s -ressegname PROT -resid %s -mut %s\n" \
% (parameters.wtPSF, parameters.wtPDB, \
parameters.varPrefix, parameters.varResID[x], longAA.get(parameters.varAA[x])))
else:
structFile.write("mutator -psf %s -pdb %s -o %s -ressegname PROT -resid %s -mut %s\n" \
% (parameters.wtPSF, parameters.wtPDB, \
parameters.varPrefix, parameters.varResID, longAA.get(parameters.varAA)))
structFile.write("mol new %s\n" %parameters.varPDB)
structFile.write("set box [atomselect top all]\n")
structFile.write("set output [open %s w]\n" % parameters.solvBoundary)
structFile.write("puts $output [measure center $box]\n")
structFile.write("puts $output [measure minmax $box]\n")
structFile.write("close $output\n")
structFile.write("quit\n")
#Solvates and ionizes the structure with water box
#measures center and dimensions of structure
def genSolvTCL(parameters):
#todo - adjustable solvation/ionization parameters
solvFile = open(parameters.solvTCL,"w+")
parameters.logger.debug("Writing solvation/ionization TCL: %s", parameters.solvTCL)
solvFile.write("package require solvate\n")
solvFile.write("solvate %s %s -t 10 -o %s.wb\n" % \
(parameters.varPSF, parameters.varPDB, parameters.structPrefix))
solvFile.write("package require autoionize\n")
solvFile.write("autoionize -psf %s.wb.psf -pdb %s.wb.pdb -neutralize -o %s\n" % \
(parameters.structPrefix, parameters.structPrefix, parameters.structPrefix))
solvFile.write("set box [atomselect top all]\n")
solvFile.write("set output [open %s w]\n" % parameters.solvBoundary)
solvFile.write("puts $output [measure center $box]\n")
solvFile.write("puts $output [measure minmax $box]\n")
solvFile.write("close $output\n")
solvFile.write("quit")
#Runs NAMD for MD simulation using structures and options
def runNAMD(parameters):
if not os.path.exists(parameters.configDIR):
os.makedirs(parameters.configDIR)
#parses the dimensions of the solvated structure
if os.path.isfile(parameters.solvBoundary):
boundaryFile = open(parameters.solvBoundary,"r")
bLines = boundaryFile.readlines()
center = bLines[0]
center = center.rstrip()
center = center.split(" ")
center = [float(i) for i in center]
minmax = bLines[1]
minmax = minmax.rstrip()
minmax = minmax.replace("{","")
minmax = minmax.replace("}","")
minmax = minmax.split(" ")
minmax = [float(i) for i in minmax]
parameters.dimX = minmax[3] - minmax[0] + 0.1
parameters.dimY = minmax[4] - minmax[1] + 0.1
parameters.dimZ = minmax[5] - minmax[2] + 0.1
else:
parameters.logger.error("Boundary file does not exist")
parameters.logger.error("Remove solvated/ionized PDB and PSF and resubmit")
sys.exit(1)
#creates the NAMD config file and populates it with default options
configFile = open(parameters.NAMDconfig,"w+")
parameters.logger.debug("Writing NAMD config: %s", parameters.NAMDconfig)
if parameters.implicitSolvent:
configFile.write("structure %s\n" % parameters.varPSF)
configFile.write("coordinates %s\n" % parameters.varPDB)
else:
configFile.write("structure %s\n" % parameters.simPSF)
configFile.write("coordinates %s\n" % parameters.simPDB)
configFile.write("set outputname %s\n" % parameters.NAMDout)
configFile.write("paraTypeCharmm on\n")
for pFile in parameters.simParameters:
configFile.write("parameters %s\n" % pFile)
configFile.write("mergeCrossterms yes\n")
configFile.write("set temperature 310\n")
configFile.write("firsttimestep 0\n")
configFile.write("\n")
configFile.write("temperature $temperature\n")
configFile.write("\n")
configFile.write("\n")
if parameters.implicitSolvent:
configFile.write("# Implicit Solvant Parameters\n")
configFile.write("gbis on\n")
configFile.write("alphaCutoff 12.0\n")
configFile.write("ionConcentration 0.3\n")
configFile.write("\n")
configFile.write("\n")
configFile.write("# Force-Field Parameters\n")
configFile.write("exclude scaled1-4\n")
configFile.write("1-4scaling 1.0\n")
if parameters.implicitSolvent:
configFile.write("cutoff 16.0\n")
configFile.write("pairlistdist 16.0\n")
else:
configFile.write("cutoff 12.0\n")
configFile.write("pairlistdist 14.0\n")
configFile.write("switching on\n")
configFile.write("switchdist 10.0\n")
configFile.write("\n")
configFile.write("# Integrator Parameters\n")
configFile.write("timestep 2.0 ;# 2fs/step\n")
configFile.write("rigidBonds all ;# needed for 2fs steps\n")
configFile.write("nonbondedFreq 1\n")
configFile.write("fullElectFrequency 2\n")
configFile.write("stepspercycle 10\n")
configFile.write("\n")
configFile.write("# Constant Temperature Control\n")
configFile.write("langevin on ;# do langevin dynamics\n")
configFile.write("langevinDamping 1 ;# damping coefficient (gamma) of 1/ps\n")
configFile.write("langevinTemp $temperature\n")
configFile.write("langevinHydrogen off ;# don't couple langevin bath to hydrogens\n\n")
if not parameters.implicitSolvent:
configFile.write("#Periodic Boundary Conditions\n")
configFile.write("cellBasisVector1 %.1f 0.0 0.0\n" % parameters.dimX)
configFile.write("cellBasisVector2 0.0 %.1f 0.0\n" % parameters.dimY)
configFile.write("cellBasisVector3 0.0 0.0 %.1f\n" % parameters.dimZ)
configFile.write("cellOrigin %.1f %.1f %.1f\n" % \
(center[0], center[1], center[2]))
configFile.write("margin %s\n\n" % parameters.margin)
if not parameters.implicitSolvent:
configFile.write("# PME (for full-system periodic electrostatics)\n")
configFile.write("PME yes\n")
configFile.write("PMEGridSpacing 1.0\n")
configFile.write("wrapAll on\n\n")
configFile.write("# Constant Pressure Control (variable volume)\n")
configFile.write("useGroupPressure yes ;# needed for rigidBonds\n")
configFile.write("useFlexibleCell no\n")
configFile.write("useConstantArea no\n")
configFile.write("langevinPiston on\n")
configFile.write("langevinPistonTarget 1.01325 ;# in bar -> 1 atm\n")
configFile.write("langevinPistonPeriod 100.0\n")
configFile.write("langevinPistonDecay 50.0\n")
configFile.write("langevinPistonTemp $temperature\n")
configFile.write("# Output\n")
configFile.write("outputName $outputname\n")
#todo - configure output options i.e. freq of output)
configFile.write("restartfreq 10000 ;# 500steps = every 1ps\n")
configFile.write("dcdfreq 5000\n")
configFile.write("xstFreq 5000\n")
configFile.write("outputEnergies 5000\n")
configFile.write("outputPressure 5000\n")
if not parameters.noMinimize:
configFile.write("# Minimization\n")
configFile.write("minimize 1000\n")
configFile.write("reinitvels $temperature\n\n")
configFile.write("run %i\n" % (parameters.simLength*500000)) # using 2 fs step size
if not os.path.isdir(parameters.trajDIR):
os.makedirs(parameters.trajDIR)
#Runs NAMD for MD simulation using structures and options
def runNAMD_replicaExchange(parameters):
if not os.path.exists(parameters.configDIR):
os.makedirs(parameters.configDIR)
#parses the dimensions of the solvated structure
if os.path.isfile(parameters.solvBoundary):
boundaryFile = open(parameters.solvBoundary,"r")
bLines = boundaryFile.readlines()
center = bLines[0]
center = center.rstrip()
center = center.split(" ")
center = [float(i) for i in center]
minmax = bLines[1]
minmax = minmax.rstrip()
minmax = minmax.translate(None,"{}")
minmax = minmax.split(" ")
minmax = [float(i) for i in minmax]
parameters.dimX = minmax[3] - minmax[0] + 0.1
parameters.dimY = minmax[4] - minmax[1] + 0.1
parameters.dimZ = minmax[5] - minmax[2] + 0.1
else:
parameters.logger.error("Boundary file does not exist")
parameters.logger.error("Remove solvated/ionized PDB and PSF and resubmit")
sys.exit(1)
parameters.repConfig = parameters.configDIR + "replica_s%s.%s.%s.conf" \
% (parameters.protein, parameters.variant, parameters.simID)
repConfig = open(parameters.repConfig, "w+")
parameters.logger.debug("Writing replica exchange config: %s", parameters.repConfig)
repConfig.write("set num_replicas 8\n")
repConfig.write("set min_temp 300\n")
repConfig.write("set max_temp 600\n")
repConfig.write("set steps_per_run 1000\n")
repConfig.write("set num_runs %s\n" %(int(parameters.simLength*500)))
repConfig.write("set runs_per_frame 5\n")
repConfig.write("set frames_per_restart 2\n")
repConfig.write("set namd_config_file \"%s\"\n" %parameters.NAMDconfig)
repConfig.write("set output_root \"%s\"\n" %parameters.NAMDout)
repConfig.write("set psf_file \"%s\"\n" %parameters.simPSF)
repConfig.write("set initial_pdb_file \"%s\"\n" %parameters.simPDB)
repConfig.write("set fit_pdb_file \"%s\"\n" %parameters.templatePDB)
parameters.jobConfig = parameters.configDIR + "job_s%s.%s.%s.conf" \
% (parameters.protein, parameters.variant, parameters.simID)
jobConfig = open(parameters.jobConfig, "w+")
jobConfig.write("source %s\n" %parameters.repConfig)
if parameters.NAMDpath:
jobConfig.write("if { ! [catch numPes] } { cd $(echo $(dirname %s)\"/lib/replica\") \nsource replica.namd }\n")
else:
jobConfig.write("if { ! [catch numPes] } { cd $(echo $(dirname $(which namd2))\"/lib/replica\") \nsource replica.namd }\n")
#creates the NAMD config file and populates it with default options
configFile = open(parameters.NAMDconfig,"w+")
parameters.logger.debug("Writing NAMD config: %s", parameters.NAMDconfig)
configFile.write("structure %s\n" % parameters.simPSF)
configFile.write("coordinates %s\n" % parameters.simPDB)
#configFile.write("set outputname %s\n" % parameters.NAMDout)
configFile.write("paraTypeCharmm on\n")
for pFile in parameters.simParameters:
configFile.write("parameters %s\n" % pFile)
configFile.write("mergeCrossterms yes\n")
#configFile.write("set temperature 310\n")
configFile.write("firsttimestep 0\n")
configFile.write("\n")
#configFile.write("temperature $temperature\n")
configFile.write("\n")
configFile.write("\n")
configFile.write("# Force-Field Parameters\n")
configFile.write("exclude scaled1-4\n")
configFile.write("1-4scaling 1.0\n")
configFile.write("cutoff 12.0\n")
configFile.write("switching on\n")
configFile.write("switchdist 10.0\n")
configFile.write("pairlistdist 14.0\n")
configFile.write("\n")
configFile.write("# Integrator Parameters\n")
configFile.write("timestep 2.0 ;# 2fs/step\n")
configFile.write("rigidBonds all ;# needed for 2fs steps\n")
configFile.write("nonbondedFreq 1\n")
configFile.write("fullElectFrequency 2\n")
configFile.write("stepspercycle 10\n")
configFile.write("\n")
configFile.write("# Constant Temperature Control\n")
#configFile.write("langevin on ;# do langevin dynamics\n")
# configFile.write("langevinDamping 1 ;# damping coefficient (gamma) of 1/ps\n")
#configFile.write("langevinTemp $temperature\n")
# configFile.write("langevinHydrogen off ;# don't couple langevin bath to hydrogens\n\n")
configFile.write("#Periodic Boundary Conditions\n")
configFile.write("cellBasisVector1 %.1f 0.0 0.0\n" % parameters.dimX)
configFile.write("cellBasisVector2 0.0 %.1f 0.0\n" % parameters.dimY)
configFile.write("cellBasisVector3 0.0 0.0 %.1f\n" % parameters.dimZ)
configFile.write("cellOrigin %.1f %.1f %.1f\n" % \
(center[0], center[1], center[0]))
configFile.write("margin 1.0\n\n")
configFile.write("wrapAll on\n\n")
configFile.write("# PME (for full-system periodic electrostatics)\n")
configFile.write("PME yes\n")
configFile.write("PMEGridSpacing 1.0\n")
configFile.write("# Constant Pressure Control (variable volume)\n")
configFile.write("useGroupPressure yes ;# needed for rigidBonds\n")
configFile.write("useFlexibleCell no\n")
configFile.write("useConstantArea no\n")
# configFile.write("langevinPiston on\n")
# configFile.write("langevinPistonTarget 1.01325 ;# in bar -> 1 atm\n")
# configFile.write("langevinPistonPeriod 100.0\n")
# configFile.write("langevinPistonDecay 50.0\n")
# configFile.write("langevinPistonTemp $temperature\n")
configFile.write("# Output\n")
#configFile.write("outputName $outputname\n")
#todo - configure output options i.e. freq of output)
configFile.write("restartfreq 10000 ;# 500steps = every 1ps\n")
#configFile.write("dcdfreq 5000\n")
configFile.write("xstFreq 5000\n")
#configFile.write("outputEnergies 5000\n")
configFile.write("outputPressure 5000\n")
configFile.write("# Minimization\n")
configFile.write("minimize 1000\n")
#configFile.write("reinitvels $temperature\n\n")
configFile.write("run %i\n" % (parameters.simLength*500000)) # using 2 fs step size
if not os.path.isdir(parameters.trajDIR):
os.makedirs(parameters.trajDIR)
#if running in CGC, prepares the results of MD sim as PDB file to export
def genSingleRunTCL(parameters):
parameters.logger.debug("Writing PDB converter TCL: %s", parameters.singleRunTCL)
pdbTCL = open(parameters.singleRunTCL,"w+")
pdbTCL.write("mol new %s waitfor all\n" % parameters.simPSF)
variantDIR = parameters.trajDIR
#loads DCD files from the results into VMD
parameters.logger.debug("using DCD files in %s", variantDIR)
for tFile in os.listdir(variantDIR):
if tFile.endswith(".dcd"):
dcdFile = variantDIR + tFile
pdbTCL.write("mol addfile %s waitfor all\n" % dcdFile)
pdbTCL.write("package require pbctools\n")
pdbTCL.write("pbc wrap -center com -centersel \"protein\" -compound residue -all\n")
#writes the trajectory as a PDB file instead of DCD for CGC runs
allPDBoutput = "%s/%s.%s.%s.pdb" % (variantDIR, parameters.protein,
parameters.variant, parameters.simID)
pdbTCL.write("animate write pdb %s beg 0 end -1 sel [atomselect top \"protein\"]\n" \
% allPDBoutput)
pdbTCL.write("quit")
genPDBcommand = "%s -e %s" % (parameters.VMDpath, parameters.singleRunTCL)
parameters.logger.debug("Running PDB converter TCL in VMD")
parameters.logger.debug("VMD Command: %s", genPDBCommand)
try:
out = subprocess.check_output(genPDBCommand, shell = True)
parameters.logger.debug("VMD Output: \n\n%s\n\n", out.decode('ascii'))
except subprocess.CalledProcessError as e:
parameters.logger.error("VMD output: \n%s", e.output.decode('ascii'))
sys.exit(1)
#Creates a pairwise RMSD matrix of the trajectory frames for use in multidimensional scaling method
def calcPairwiseRMSD(parameters):
#only calculated RMSD based on clusterResidues and aligns frames by alignmentResidues
alignmentRes = parameters.alignmentResidues
clusterRes = parameters.clusterResidues
if not os.path.exists(parameters.scaffoldDIR):
os.makedirs(parameters.scaffoldDIR)
#will not generate new TCL if previous scaffID log exists
scaffLOG = parameters.scaffBASE + ".log"
if os.path.isfile(scaffLOG):
parameters.logger.warning("Scaffold log already exists. Remove to recalculate Scaffolds")
parameters.logger.warning("Creating scaffold PDBs using previous log")
return
#loads in the DCD files of the trajectory
parameters.logger.debug("Writing RMSD matrix TCL: %s", parameters.scaffoldTCL)
clustTCL = open(parameters.scaffoldTCL,"w+")
clustTCL.write("package require csv\n")
if parameters.implicitSolvent:
clustTCL.write("mol new %s waitfor all\n" % parameters.varPSF)
else:
clustTCL.write("mol new %s waitfor all\n" % parameters.simPSF)
variantDIR = parameters.trajDIR
parameters.logger.debug("Using DCD files in %s", variantDIR)
for tFile in sorted(os.listdir(variantDIR)):
if tFile.endswith(".dcd"):
dcdFile = variantDIR + tFile
clustTCL.write("mol addfile %s waitfor all\n" % dcdFile)
#aligns the frames to the first frame
clustTCL.write("set nf [molinfo top get numframes]\n")
clustTCL.write("set refRes [atomselect top \""+alignmentRes+"\" frame 0]\n")
clustTCL.write("set refStruct [atomselect top all frame 0]\n")
clustTCL.write("for {set i 0} {$i < $nf} {incr i} {\n")
clustTCL.write(" set curStruct [atomselect top all frame $i]\n")
clustTCL.write(" set curRes [atomselect top \""+alignmentRes+"\" frame $i]\n")
clustTCL.write(" set M [measure fit $curRes $refRes]\n")
clustTCL.write(" $curStruct move $M\n")
clustTCL.write("}\n")
clustTCL.write("set output [open %s w]\n" % parameters.featureTable)
clustTCL.write("set back [atomselect top \""+clusterRes+"\"]\n")
clustTCL.write("set refclustRes [atomselect top \""+clusterRes+"\" frame 0]\n")
#Makes the matrix square by padding with 0s to avoid calculating RMSD between pairs twice
clustTCL.write("for {set i 0} {$i < $nf} {incr i} {\n")
clustTCL.write("set row {}\n")
clustTCL.write("for {set pad 0} {$pad <= $i} {incr pad} {\n")
clustTCL.write("lappend row 0}\n")
#calculates RMSD and writes to a file
clustTCL.write("for {set j [expr $i + 1]} {$j < $nf} {incr j} {\n")
clustTCL.write("$refclustRes frame $i \n")
clustTCL.write("$back frame $j \n")
clustTCL.write("set M [measure rmsd $back $refclustRes] \n")
clustTCL.write("lappend row $M}\n")
clustTCL.write("puts $output [::csv::join $row]}\n")
clustTCL.write("close $output\n")
clustTCL.write("quit")
clustTCL.close()
makeTableCommand = "%s -e %s" % (parameters.VMDpath, parameters.scaffoldTCL)
parameters.logger.debug("Running RMSD matrix generation TCL in VMD")
parameters.logger.debug("VMD Command: %s", makeTableCommand)
try:
out = subprocess.check_output(makeTableCommand, shell = True)
parameters.logger.debug("VMD Output: \n\n%s\n\n", out.decode('ascii'))
except subprocess.CalledProcessError as e:
parameters.logger.error("VMD output: \n%s", e.output.decode('ascii'))
sys.exit(1)
#Same function as calcPairwaiseRMSD(), but used a PDB format as input trajectory
def calcPairwiseRMSD_PDB(parameters):
alignmentRes = parameters.alignmentResidues
clusterRes = parameters.clusterResidues
if not os.path.exists(parameters.scaffoldDIR):
os.makedirs(parameters.scaffoldDIR)
#will not generate new TCL if previous scaffID log exists
scaffLOG = parameters.scaffBASE + ".log"
if os.path.isfile(scaffLOG):
parameters.logger.warning("Scaffold log already exists. Remove to recalculate Scaffolds")
parameters.logger.warning("Creating scaffold PDBs using previous log")
return
parameters.logger.debug("Writing RMSD matrix TCL: %s", parameters.scaffoldTCL)
clustTCL = open(parameters.scaffoldTCL,"w+")
clustTCL.write("package require csv\n")
variantDIR = parameters.trajDIR
parameters.logger.debug("Using DCD files in %s", variantDIR)
for trajFile in sorted(os.listdir(variantDIR)):
if trajFile.endswith(".pdb"):
pdbFile = variantDIR + trajFile
clustTCL.write("mol addfile %s waitfor all\n" % pdbFile)
clustTCL.write("set nf [molinfo top get numframes]\n")
clustTCL.write("set refRes [atomselect top \""+alignmentRes+"\" frame 0]\n")
clustTCL.write("set refStruct [atomselect top all frame 0]\n")
clustTCL.write("for {set i 0} {$i < $nf} {incr i} {\n")
clustTCL.write(" set curStruct [atomselect top all frame $i]\n")
clustTCL.write(" set curRes [atomselect top \""+alignmentRes+"\" frame $i]\n")
clustTCL.write(" set M [measure fit $curRes $refRes]\n")
clustTCL.write(" $curStruct move $M\n")
clustTCL.write("}\n")
clustTCL.write("set output [open %s w]\n" % parameters.featureTable)
clustTCL.write("set back [atomselect top \""+clusterRes+"\"]\n")
clustTCL.write("set refclustRes [atomselect top \""+clusterRes+"\" frame 0]\n")
clustTCL.write("for {set i 0} {$i < $nf} {incr i} {\n")
clustTCL.write("set row {}\n")
clustTCL.write("for {set pad 0} {$pad <= $i} {incr pad} {\n")
clustTCL.write("lappend row 0}\n")
clustTCL.write("for {set j [expr $i + 1]} {$j < $nf} {incr j} {\n")
clustTCL.write("$refclustRes frame $i \n")
clustTCL.write("$back frame $j \n")
clustTCL.write("set M [measure rmsd $back $refclustRes] \n")
clustTCL.write("lappend row $M}\n")
clustTCL.write("puts $output [::csv::join $row]}\n")
clustTCL.write("close $output\n")
clustTCL.write("quit")
clustTCL.close()
makeTableCommand = "%s -e %s" % (parameters.VMDpath, parameters.scaffoldTCL)
parameters.logger.debug("Running RMSD matrix generation TCL in VMD")
parameters.logger.debug("VMD Command: %s", makeTableCommand)
try: