forked from luancarvalhomartins/PyAutoFEP
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprepare_dual_topology.py
4503 lines (3943 loc) · 267 KB
/
prepare_dual_topology.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
#
# prepare_dual_topology.py
#
# Copyright 2019 Luan Carvalho Martins <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
import argparse
import os
import shutil
import rdkit.Chem
import rdkit.Chem.rdMolAlign
import rdkit.Chem.PropertyMol
import subprocess
import tempfile
import time
import re
import tarfile
import configparser
import itertools
import multiprocessing
from collections import OrderedDict
from align_utils import align_protein
try:
from openbabel import pybel
except ImportError:
import pybel
import all_classes
import process_user_input
import savestate_util
import mol_util
import merge_topologies
import os_util
SPECIAL_SUBSTITUTIONS = '_LENGTH', '_TEMPERATURE', '_PRESSURE'
def guess_water_box(solvent_box, pdb2gmx_topology='', verbosity=0):
""" Guess solvent box to be used in gmx solvate from pdb2gmx topology or from number of points of water model
:param [int, str] solvent_box: use this solvate box in gmx solvate; if int, will use a box with a model with
solvent_box points, if str, will pass to gmx solvate -cp, if None, will try to guess
from pdb2gmx output (Default: None, guess).
:param str pdb2gmx_topology: guess water model from this topology (required ir solvent_box is None)
:param int verbosity: set verbosity
:rtype: str
"""
water_box_data = {'spc216.gro': ['spc.itp', 'tip3p.itp', 'scpe.itp', 'tips3p.itp'], 'tip4p.gro': ['tip4p.itp'],
'tip5p.grp': ['tip5p.itp', 'tip5pe.itp']}
water_box_data_numeric = {3: 'spc216.gro', 4: 'tip4p.itp', 5: 'tip5p.itp'}
build_base_dir = os.path.dirname(pdb2gmx_topology)
if not pdb2gmx_topology:
ValueError('pdb2gmx_topology required if solvent_box is None')
if solvent_box is None:
# 4.1 User wants automatic detection of water type. Get water topology from pdb2gmx topology file
pdb2gmx_topology_data = os_util.read_file_to_buffer(pdb2gmx_topology, die_on_error=True,
error_message='Failed to read topology from pdb2gmx. '
'Cannot continue. Verify the system '
'builder intermediate files in {}'
''.format(build_base_dir),
return_as_list=True, verbosity=verbosity)
try:
water_topology = pdb2gmx_topology_data[pdb2gmx_topology_data.index('; Include water topology\n') + 1]
except ValueError:
os_util.local_print('Failed to find a water topology in file {}. Cannot guess the correct water box to '
'use. Cannot continue. Please, check build system files in {} or set solvent_box.'
''.format(pdb2gmx_topology, build_base_dir),
current_verbosity=verbosity, msg_verbosity=os_util.verbosity_level.error)
raise SystemExit(-1)
# 4.2 Try to detect to which box this model corresponds
for water_box, water_models in water_box_data.items():
for each_model in water_models:
if water_topology.find(each_model) != -1:
solvent_box = water_box
os_util.local_print('Using water box {} because the water line "{}" in topology file {} is '
'importing water model {}. If this is wrong, please, set solvent_box '
'explicitly.'
''.format(water_box, water_topology.replace('\n', '\\n'), pdb2gmx_topology,
each_model),
current_verbosity=verbosity, msg_verbosity=os_util.verbosity_level.info)
break
else:
continue
break
if solvent_box is None:
os_util.local_print('Failed to parse water topology line ({}) from file {}. Cannot guess the correct water '
'box to use. Cannot continue. Please, check build system files in {} or set '
'solvent_box.'.format(water_topology.replace('\n', '\\n'),
pdb2gmx_topology, build_base_dir),
current_verbosity=verbosity, msg_verbosity=os_util.verbosity_level.error)
raise SystemExit(-1)
elif isinstance(solvent_box, int):
# User wants a box with a solvent_box-points water
try:
solvent_box = water_box_data_numeric[solvent_box]
except KeyError:
os_util.local_print('You asked me to use a water box for water molecules with "{}" points, but I cannot do '
'so. I can only use the following boxes: "{}". Cannot continue. If this is what your '
'really want, you will need a pre-solvated system.'
''.format(solvent_box, ', '.join(['{} ({} points)'.format(j, i)
for i, j in water_box_data_numeric.items()])),
current_verbosity=verbosity, msg_verbosity=os_util.verbosity_level.error)
raise SystemExit(-1)
return solvent_box
def set_default_solvate_data(solvate_data):
if not solvate_data:
solvate_data = {}
# This will use default water for the FF
solvate_data.setdefault('box_type', 'dodecahedron')
solvate_data.setdefault('water_model', None)
solvate_data.setdefault('water_shell', 10.0)
solvate_data.setdefault('nname', 'CL')
solvate_data.setdefault('pname', 'NA')
solvate_data.setdefault('ion_concentration', 0.15)
return solvate_data
def fix_chain_restraint(restraint_file, first_atom=1, verbosity=0):
"""Edits a restraint file setting the atom indexes to i -= first_atom + 1, therefore converting a restraint that was
generated for a molecule in the complex to a valid restraint file.
Parameters
----------
restraint_file : str
Input GROMACS-compatible restraint file. Will be editted in place.
first_atom : int
The index first atom of this group in the complex input that was used to prepare the restraint
verbosity : int
Sets the verbosity level
"""
directive_match = re.compile(r'\s*\[\s+position_restraints\s+]', flags=re.IGNORECASE)
restraint_data = os_util.read_file_to_buffer(restraint_file, die_on_error=True, return_as_list=True)
restraint_data_mod = []
found_directive_line = False
for each_line in restraint_data:
if each_line.lstrip().startswith(';') or each_line.lstrip() == '\n':
# This a comment or empty line, append as is
pass
elif directive_match.match(each_line):
found_directive_line = True
elif found_directive_line:
try:
atom_num, fn, f_x, f_y, f_z = each_line.split()
atom_num = int(atom_num)
except ValueError as error:
os_util.local_print(f'Could not parse restraints data from file {restraint_file}. The following '
f'line could not be understood: {each_line}',
current_verbosity=verbosity, msg_verbosity=os_util.verbosity_level.error)
raise error
else:
each_line = f'{atom_num - first_atom + 1:>7} {fn:<5} {f_x:<5} {f_y:<5} {f_z:<5}\n'
restraint_data_mod.append(each_line)
with open(restraint_file, 'w') as fh:
fh.writelines(restraint_data_mod)
@os_util.trace
def prepare_complex_system(structure_file, base_dir, ligand_dualmol, topology='FullSystem.top',
index_file='index.ndx', forcefield=1, index_groups=None,
selection_method='internal', gmx_bin='gmx', extradirs=None, extrafiles=None,
solvate_data=None, ligand_name='LIG', water_mol_name=None, gmx_maxwarn=1, no_checks=False,
verbosity=0, **kwargs):
"""Builds a system complex using gmx tools
Parameters
----------
structure_file : str
Receptor file (PDB)
base_dir : str
Build system to this directory
ligand_dualmol : all_classes.MergedTopologies or all_classes.MolecularTopologies
Merged (all_classes.MergedTopologies) or single (all_classes.MolecularTopologies) molecule to be added to the
system. Method to_pdb_block will be called to obtain the small molecule pdb.
topology : str
GROMACS-compatible topology file will be saved to this file
index_file : str
GROMACS-compatible index file will be saved to this file
forcefield : str or int
Force field to be passed to pdb2gmx
index_groups : dict or None
Groups to be added to index file and their selection string
selection_method : str
Use gmx make_ndx (internal, default) or mdanalysis (mdanalysis) to generate index file
gmx_bin : str
Run this GROMACS executable to prepare the system
extradirs : list
Recursevely copy these directories to base_dir
extrafiles : list
Copy these files to base_dir
solvate_data : dict
Dictionary containing further data to solvate: 'water_model': water model to be used, 'water_shell': size of
the water shell in A, 'ion_concentration': add ions to this conc, 'pname': name of the positive ion,
'nname': name of the negative ion}
ligand_name : str
Use this as ligand name
water_mol_name : str or list
Use this a water molecule name
gmx_maxwarn : int
Pass this to gmx grompp -maxwarn to suppress GROMACS warnings during system setup
no_checks : bool
Ignore checks and try to go on
verbosity : int
Sets verbosity level
Returns
-------
all_classes.Namespace
"""
if isinstance(water_mol_name, str):
list(water_mol_name)
position_restraint_output = '; Include restraint file\n#ifdef {defname}\n#include "{resfile}"\n#endif\n'
solvate_data = set_default_solvate_data(solvate_data)
# Save intermediate files used to build the system to this dir
build_system_dir = os.path.join(base_dir, 'protein',
'build_system_{}'.format(time.strftime('%H%M%S_%d%m%Y')))
os_util.makedir(build_system_dir)
if extradirs:
for each_extra_dir in extradirs:
shutil.copytree(each_extra_dir, os.path.join(build_system_dir, os.path.split(each_extra_dir)[-1]))
os_util.local_print('Copying directory {} to {}'.format(each_extra_dir, build_system_dir),
msg_verbosity=os_util.verbosity_level.debug,
current_verbosity=verbosity)
if extrafiles:
for each_source in extrafiles:
shutil.copy2(each_source, build_system_dir)
os_util.local_print('Copying file {} to {}'.format(each_source, build_system_dir),
msg_verbosity=os_util.verbosity_level.debug,
current_verbosity=verbosity)
# These are the intermediate build files
timestamp = time.strftime('%H%M%S_%d%m%Y')
build_files_dict = {index: os.path.join(build_system_dir, filename.format(timestamp))
for index, filename in {'protein_pdb': 'protein_step1_{}.pdb',
'protein_top': 'protein_step1_{}.top',
'proteinlig_top': 'proteinlig_step1_{}.top',
'system_pdb': 'protein_step2_{}.pdb',
'system_gro': 'system_step3_{}.gro',
'systemsolv_gro': 'systemsolvated_step4_{}.gro',
'systemsolv_top': 'systemsolv_step4_{}.top',
'genion_mdp': 'genion_step5_{}.mdp',
'mdout_mdp': 'mdout_step6_{}.mdp',
'genion_tpr': 'genion_step6_{}.tpr',
'makeindex_log': 'make_index_step7_{}.log',
'fullsystem_pdb': 'fullsystem_step7_{}.pdb',
'fullsystem_top': 'fullsystem_step7_{}.top',
'center_tpr': 'center_tpr_step8_{}.tpr',
'fullsystemcenter_pdb': 'fullsystem_step8_{}.pdb',
'center_mdout_mdp': 'center_mdout_step8.mdp',
'posres_ca_top': 'posres_protein_Ca_{{}}_{}.itp',
'posres_backbone_top': 'posres_protein_BB_{{}}_{}.itp',
'grompp_center_log': 'grompp_center_step8.log',
'pdb2gmx_log': 'gmx_pdb2gmx_{}.log',
'editconf_log': 'gmx_editconf_{}.log',
'solvate_log': 'gmx_solvate_{}.log',
'grompp_log': 'gmx_grompp_{}.log',
'genion_log': 'gmx_genion_{}.log',
'posres_index_ndx': 'posres_index.ndx',
'index_ndx': 'index.ndx',
'posres_log': 'protein_posres_Ca.log'
}.items()}
# These are the final build files
build_files_dict['full_topology_file'] = topology
build_files_dict['final_index_file'] = index_file
build_files_dict['final_structure_file'] = 'FullSystem.pdb'
output_structure_file = build_files_dict['final_structure_file']
output_topology_file = build_files_dict['full_topology_file']
os_util.local_print('These are the files to be used during automatic system building: {}'
''.format(', '.join(build_files_dict.values())),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
# 1. Prepare and run pdb2gmx
pdb2gmx_list = ['pdb2gmx', '-f', structure_file,
'-p', build_files_dict['protein_top'], '-o', build_files_dict['protein_pdb']]
if solvate_data['water_model'] is not None:
pdb2gmx_list.extend(['-water', solvate_data['water_model']])
water_str = None
else:
water_str = '1'
try:
forcefield_str = int(forcefield)
except ValueError:
pdb2gmx_list.extend(['-ff', forcefield])
forcefield_str = None
communicate_str = ''
if forcefield_str is not None:
communicate_str = '{}\n'.format(forcefield_str)
if water_str is not None:
communicate_str += '{}\n'.format(water_str)
os_util.run_gmx(gmx_bin, pdb2gmx_list, communicate_str, build_files_dict['pdb2gmx_log'], verbosity=verbosity)
# 2. Assemble the complex
# 2.1 Copy the receptor PDB data, stripping all but ATOM and TER records
complex_string = ''.join([each_line for each_line
in os_util.read_file_to_buffer(build_files_dict['protein_pdb'],
die_on_error=True, return_as_list=True,
error_message='Failed to read converted protein '
'file when building the system.',
verbosity=verbosity)
if (each_line.find('ATOM') != -1 or each_line.find('TER') != -1)])
os_util.local_print('Read {} lines from the pdb file {}'
''.format(complex_string.count('\n'), build_files_dict['protein_pdb']),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
# 2.2 Add small molecule PDB
# FIXME: remove the need for setting molecule_name
complex_string += '\n{}'.format(ligand_dualmol.to_pdb_block(molecule_name=ligand_name, verbosity=verbosity))
with open(build_files_dict['system_pdb'], 'w') as fh:
fh.write(complex_string)
os_util.local_print('Wrote the protein + ligand to {} ({} lines)'
''.format(build_files_dict['system_pdb'], complex_string.count('\n')),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
# 2.3. Edit system topology to add ligand parameters
system_topology_list = os_util.read_file_to_buffer(build_files_dict['protein_top'],
die_on_error=True, return_as_list=True,
error_message='Failed to read system topology file '
'when building the system.',
verbosity=verbosity)
try:
ligand_dualmol.dual_topology.set_lambda_state(0)
except AttributeError:
pass
ligand_top = {'ligand.atp': ligand_dualmol.dual_topology.__str__('atomtypes'),
'ligand.itp': ligand_dualmol.dual_topology.__str__('itp')}
for name, contents in ligand_top.items():
with open(os.path.join(build_system_dir, name), 'w') as fh:
fh.write(contents)
ligatoms_list = ['\n', '; Include ligand atomtypes\n', '#include "ligand.atp"\n', '\n']
ligatoms_list.reverse()
ligtop_list = ['\n', '; Include ligand topology\n', '#include "ligand.itp"\n', '\n']
ligtop_list.reverse()
position = os_util.inner_search(re.compile(r'#include\s+\".*forcefield\.itp\"', flags=re.IGNORECASE).match,
system_topology_list, apply_filter=';')
if position is False:
position = os_util.inner_search(re.compile(r'\s*\[\s+defaults\s+]', flags=re.IGNORECASE).match,
system_topology_list, apply_filter=';')
if position is False:
new_file_name = os.path.basename(build_files_dict['protein_top'])
shutil.copy2(build_files_dict['protein_top'], new_file_name)
os_util.local_print('Failed to find a forcefield.itp import or a [ defaults ] in topology file {}. This '
'suggests a problem in topology file formatting. Please, check inputs, especially '
'force field. Copying {} to {}.'
''.format(build_files_dict['protein_top'], build_files_dict['protein_top'],
new_file_name),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
[system_topology_list.insert(position + 2, each_line) for each_line in ligatoms_list]
fn_match = re.compile(r'\s*\[\s+system\s+]', flags=re.IGNORECASE).match
position = os_util.inner_search(fn_match, system_topology_list, apply_filter=';')
if position is False:
new_file_name = os.path.basename(build_files_dict['protein_top'])
shutil.copy2(build_files_dict['protein_top'], new_file_name)
os_util.local_print('Failed to find a [ system ] directive in topology file {}. This suggests a problem in '
'topology file formatting. Please, check inputs, especially force field. Copying {} to {}.'
''.format(build_files_dict['protein_top'], build_files_dict['protein_top'], new_file_name),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
[system_topology_list.insert(position - 1, each_line) for each_line in ligtop_list]
system_topology_list.append('{:<20} {}\n'.format(ligand_dualmol.dual_topology.molecules[0].name, '1'))
with open(build_files_dict['proteinlig_top'], 'w') as fh:
fh.writelines(system_topology_list)
os_util.local_print('Topology file {} edited ({} lines)'
''.format(build_files_dict['proteinlig_top'], system_topology_list.count('\n')),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
# 2.4 Read the name of protein topology files and add to copyfile dict
# This will look for the first occurrence of a #include containing what should be a macromolecule topology, then
# read all subsequent #include lines with the same format, until another directive or including of other
# components (eg, water, ions) are found.
copyfiles = {}
molname = 'protein_step1_{}'.format(timestamp)
search_fn = re.compile(r'#include\s+\"' + molname + r'_[a-zA-Z0-9_-]+\.itp\"', flags=re.IGNORECASE)
position = os_util.inner_search(search_fn.match, system_topology_list, apply_filter=';')
if position is False:
search_fn = re.compile(r'\s*\[\s+moleculetype\s+]', flags=re.IGNORECASE)
if os_util.inner_search(search_fn.match, system_topology_list, apply_filter=';') is False:
new_file_name = os.path.basename(build_files_dict['protein_top'])
shutil.copy2(build_files_dict['protein_top'], new_file_name)
os_util.local_print('Failed to find both a #include directive for protein topologies and a '
'[ moleculetype ] directive in the topology file {}. This suggests a problem in '
'topology file formatting. Please, your check inputs. Copying {} to {}'
''.format(build_files_dict['protein_top'], build_files_dict['protein_top'],
new_file_name),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
else:
for each_line in system_topology_list[position:]:
if each_line == '\n' or each_line.lstrip().startswith(';'):
continue
if not search_fn.match(each_line):
break
else:
protein_itp = re.findall(molname + r'_[a-zA-Z0-9_-]+\.itp', each_line)[0]
copyfiles[os.path.join(build_system_dir, protein_itp)] = protein_itp
if not copyfiles:
if no_checks:
os_util.local_print('Failed to parse #include directives for protein topologies in topology file {}. '
'This should not happen. Because you are running with no_checks, I will try to '
'go on.'
''.format(build_files_dict['protein_top']),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
else:
new_file_name = os.path.basename(build_files_dict['protein_top'])
shutil.copy2(build_files_dict['protein_top'], new_file_name)
os_util.local_print('Failed to parse #include directives for protein topologies in topology file {}. '
'This suggests a problem in topology file formatting. Please, your check inputs. '
'Copying {} to {}.'
''.format(build_files_dict['protein_top'], build_files_dict['protein_top'],
new_file_name),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
# 2.5.1 Tries to find restraint files in the topology (this is the case for a single protein chain)
search_fn = re.compile(r'#ifdef POSRES\s', flags=re.IGNORECASE)
position = os_util.inner_search(search_fn.match, system_topology_list, apply_filter=';')
if position is not False:
for each_line in system_topology_list[position + 1:]:
each_line = each_line.lstrip()
if each_line.startswith(';'):
continue
if each_line.lower().startswith('#include'):
this_filename = re.findall(r'"\w+.itp"', each_line)
try:
this_filename = this_filename[0]
except KeyError:
new_file_name = os.path.basename(build_files_dict['protein_top'])
shutil.copy2(build_files_dict['protein_top'], new_file_name)
os_util.local_print('Failed to parse #include directive for restraint file in topology file {}. '
'This suggests a problem in topology file formatting. Please, your check '
'inputs. Copying {} to {}.'
''.format(build_files_dict['protein_top'], build_files_dict['protein_top'],
new_file_name),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
else:
this_filename = this_filename.replace('"', '')
dest_file_name = os.path.join(build_system_dir, this_filename)
shutil.move(this_filename, dest_file_name)
copyfiles[dest_file_name] = this_filename
elif each_line.lower().startswith('#endif'):
break
# POSRES_PROTEIN restrains heavy protein atoms
system_topology_list[position] = system_topology_list[position].replace('POSRES', 'POSRES_PROTEIN')
# Generate and the add position restraints for protein Ca
for this_filename, restr_group, resrt_define in (
(build_files_dict['posres_ca_top'].format('singlechain'), 'C-alpha', 'POSRES_PROTEIN_CA'),
(build_files_dict['posres_backbone_top'].format('singlechain'), 'Backbone', 'POSRES_PROTEIN_BB')
):
restrt_list = ['genrestr', '-f', build_files_dict['protein_pdb'], '-o', this_filename]
os_util.run_gmx(gmx_bin, restrt_list, f'{restr_group}\n', verbosity=verbosity)
system_topology_list.insert(position,
position_restraint_output.format(defname=resrt_define,
resfile=os.path.basename(this_filename)))
copyfiles[this_filename] = os.path.basename(this_filename)
# Save the modified topology file
with open(build_files_dict['proteinlig_top'], 'w') as fh:
fh.writelines(system_topology_list)
# 2.5.2 Generate and the add position restraints for protein Ca when there are multiple chains
split_chain_list = ['make_ndx', '-f', build_files_dict['protein_pdb'],
'-o', build_files_dict['posres_index_ndx']]
os_util.run_gmx(gmx_bin, split_chain_list, 'splitch 1\nsplitch 3\nsplitch 4\nq\n', verbosity=verbosity)
index_posre_data = read_index_data(build_files_dict['posres_index_ndx'], verbosity=verbosity)
chains_groups_prot = [each_group for each_group in index_posre_data
if re.match(pattern=r'Protein_chain[1-9]+', string=each_group, flags=re.IGNORECASE)
is not None]
chains_groups_calpha = [each_group for each_group in index_posre_data
if re.match(pattern=r'C-alpha_chain[1-9]+', string=each_group, flags=re.IGNORECASE)
is not None]
chains_groups_backbone = [each_group for each_group in index_posre_data
if re.match(pattern=r'Backbone_chain[1-9]+', string=each_group, flags=re.IGNORECASE)
is not None]
chain_restr_data = {}
for each_filename, each_group_list, resrt_define in (
(build_files_dict['posres_ca_top'], chains_groups_calpha, 'POSRES_PROTEIN_CA'),
(build_files_dict['posres_backbone_top'], chains_groups_backbone, 'POSRES_PROTEIN_BB')
):
for n, (prot_group, each_index_group) in enumerate(zip(chains_groups_prot, each_group_list)):
this_filename = each_filename.format(n + 1)
restrt_list = ['genrestr', '-f', build_files_dict['protein_pdb'], '-n',
build_files_dict['posres_index_ndx'], '-o', this_filename]
os_util.run_gmx(gmx_bin, restrt_list, each_index_group + '\n', verbosity=verbosity)
fix_chain_restraint(this_filename, index_posre_data[prot_group][0], verbosity=verbosity)
this_resrt_data = {
'posres_filename': this_filename,
'topology_string': position_restraint_output.format(defname=resrt_define,
resfile=os.path.basename(this_filename))
}
chain_restr_data.setdefault(n, []).append(this_resrt_data)
# 2.5.3 From protein topology files, tries to read position restraints files and add them to copyfile dict
chain_count = 0
for each_file in copyfiles.copy().values():
each_file = os.path.join(build_system_dir, each_file)
this_file_data = os_util.read_file_to_buffer(each_file, die_on_error=True, return_as_list=True,
error_message='Failed to read topology file when building the '
'system.',
verbosity=verbosity)
position = os_util.inner_search('#ifdef POSRES', this_file_data, apply_filter=';')
if position is False:
os_util.local_print('Protein topology file {} does not have a "#ifdef POSRES" directive. I cannot '
'find the position restraint file, so you will may not be able to use position '
'restraints in this system'.format(each_file),
msg_verbosity=os_util.verbosity_level.warning,
current_verbosity=verbosity)
else:
line_data = this_file_data[position + 1].split()
if line_data[0] != '#include':
os_util.local_print('Could not understand your POSRES directive {} in file {}. I cannot '
'find the position restraint file, so you will may not be able to use '
'position restraints in this system'.format(line_data, each_file),
msg_verbosity=os_util.verbosity_level.warning,
current_verbosity=verbosity)
else:
# This topology file includes a chain topology, assumes
old_file_name = line_data[1].strip('"')
new_file_name = os.path.join(build_system_dir, old_file_name)
shutil.move(old_file_name, new_file_name)
copyfiles[new_file_name] = old_file_name
if 'posre_Protein' in os.path.basename(old_file_name):
# This is a protein restraint file. Use POSRES_PROTEIN to restrain heavy protein atoms
this_file_data[position] = this_file_data[position].replace('POSRES', 'POSRES_PROTEIN')
# And position restraints for protein Ca and BB
for this_resrt_data in chain_restr_data[chain_count]:
this_filename = this_resrt_data['posres_filename']
copyfiles[this_filename] = os.path.basename(this_filename)
this_file_data.insert(position, this_resrt_data['topology_string'])
chain_count += 1
# Save the modified topology file
with open(each_file, 'w') as fh:
fh.writelines(this_file_data)
# 3. Generate simulation box (gmx editconf) and solvate the complex (gmx solvate)
box_size = solvate_data['water_shell'] / 10.0
if box_size < 1:
os_util.local_print('You selected a water shell smaller than 10 \u00C5. Note that length units in input files '
'are \u00C5.',
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
editconf_list = ['editconf', '-f', build_files_dict['system_pdb'], '-d', str(box_size),
'-o', build_files_dict['system_gro'], '-bt', solvate_data['box_type']]
os_util.run_gmx(gmx_bin, editconf_list, '', build_files_dict['editconf_log'],
verbosity=verbosity)
# 4. Solvate simulation box
solvent_box = guess_water_box(solvate_data['water_model'], build_files_dict['protein_top'], verbosity=verbosity)
shutil.copy2(build_files_dict['proteinlig_top'], build_files_dict['systemsolv_top'])
solvate_list = ['solvate', '-cp', build_files_dict['system_gro'], '-cs', solvent_box,
'-o', build_files_dict['systemsolv_gro'], '-p', build_files_dict['systemsolv_top']]
os_util.run_gmx(gmx_bin, solvate_list, '', build_files_dict['solvate_log'],
verbosity=verbosity, alt_environment={'GMX_MAXBACKUP': '-1'})
# Some users experienced a problem during the gmx grompp step below, apparently filesystem-related, which could be
# due to a delay in the editing of build_files_dict['systemsolv_top'] by gmx solvate subprocess. The os.sync() may
# fix this by forcing the file to be written to disk.
try:
os.sync()
except AttributeError:
os_util.local_print('os.sync() not found. Is this a non-Unix system or Python version < 3.3?',
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
# 5. Add ions to system
# 5.1. Prepare a dummy mdp to run genion
with open(build_files_dict['genion_mdp'], 'w') as genion_fh:
genion_fh.write('\n')
# 5.3. Prepare a tpr to genion
grompp_list = ['grompp', '-f', build_files_dict['genion_mdp'],
'-c', build_files_dict['systemsolv_gro'], '-p', build_files_dict['systemsolv_top'],
'-o', build_files_dict['genion_tpr'], '-maxwarn', str(gmx_maxwarn),
'-po', build_files_dict['mdout_mdp']]
gmx_data = os_util.run_gmx(gmx_bin, grompp_list, '', build_files_dict['grompp_log'], die_on_error=False,
verbosity=verbosity)
if gmx_data.code != 0:
if re.findall('number of coordinates in coordinate file', gmx_data.stderr) is not False:
os_util.local_print('Failed to run {} {}. Error code {}.\nCommand line was: {}\n\nstdout:\n{}\n\n'
'stderr:\n{}\n\n{}\nThis is likely caused by a failing to edit the intermediate '
'topology file {}. Rerunning with output_hidden_temp_dir=False may solve this issue.'
''.format(gmx_bin, grompp_list[0], gmx_data.code, [gmx_bin] + grompp_list,
gmx_data.stdout, gmx_data.stderr, '=' * 50,
build_files_dict['systemsolv_top']),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
else:
os_util.local_print('Failed to run {} {}. Error code {}.\nCommand line was: {}\n\nstdout:\n{}\n\n'
'stderr:\n{}'
''.format(gmx_bin, grompp_list[0], gmx_data.code, [gmx_bin] + grompp_list,
gmx_data.stdout, gmx_data.stderr),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
# 5.2. Run genion
shutil.copy2(build_files_dict['systemsolv_top'], build_files_dict['fullsystem_top'])
genion_list = ['genion', '-s', build_files_dict['genion_tpr'],
'-p', build_files_dict['fullsystem_top'], '-o', build_files_dict['fullsystem_pdb'],
'-conc', str(solvate_data['ion_concentration']), '-neutral',
'-nname', solvate_data['nname'], '-pname', solvate_data['pname']]
water_name = all_classes.TopologyData.detect_solute_molecule_name(input_file=build_files_dict['genion_tpr'],
test_sol_molecules=water_mol_name,
gmx_bin=gmx_bin, no_checks=no_checks,
verbosity=verbosity)
os_util.run_gmx(gmx_bin, genion_list, '{}\n'.format(water_name), build_files_dict['genion_log'],
alt_environment={'GMX_MAXBACKUP': '-1'}, verbosity=verbosity)
# 5.3 Wrap system into a compact cell
grompp_list = ['grompp', '-f', build_files_dict['genion_mdp'], '-c', build_files_dict['fullsystem_pdb'],
'-p', build_files_dict['fullsystem_top'], '-o', build_files_dict['center_tpr'],
'-maxwarn', str(gmx_maxwarn), '-po', build_files_dict['center_mdout_mdp']]
os_util.run_gmx(gmx_bin, grompp_list, '', build_files_dict['grompp_center_log'],
verbosity=verbosity)
trjconv_list = ['trjconv', '-f', build_files_dict['fullsystem_pdb'], '-s', build_files_dict['center_tpr'],
'-o', build_files_dict['fullsystemcenter_pdb'], '-pbc', 'mol', '-ur', 'compact', '-center']
os_util.run_gmx(gmx_bin, trjconv_list, 'C-alpha\nSystem\n', build_files_dict['grompp_center_log'],
verbosity=verbosity)
# 6. Make index
# Include a Protein_{Ligand} group in case users does not include one
if index_groups is None:
os_util.local_print('Added a Protein_LIG group to the group index, which will be generated '
'automatically', msg_verbosity=os_util.verbosity_level.info,
current_verbosity=verbosity)
if selection_method == 'mdanalysis':
index_groups = {'Protein_LIG': 'resname Protein or resname {}'.format(ligand_name)}
elif selection_method == 'internal':
index_groups = {'Protein_LIG': '"Protein" | "{}"'.format(ligand_name)}
elif 'Protein_LIG' not in index_groups:
os_util.local_print('Added a Protein_LIG group to the group index, which contains the following: {}'
''.format([each_key for each_key in index_groups.keys()]),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
if selection_method == 'mdanalysis':
index_groups.update({'Protein_LIG': 'resname Protein or resname {}'.format(ligand_name)})
elif selection_method == 'internal':
index_groups.update({'Protein_LIG': '"Protein" | "{}"'.format(ligand_name)})
make_index(build_files_dict['index_ndx'], build_files_dict['fullsystem_pdb'], index_groups, selection_method,
gmx_bin=gmx_bin, logfile=build_files_dict['makeindex_log'], water_name=water_name, verbosity=verbosity)
# 7. Copy files to lambda directories
copyfiles.update({build_files_dict['fullsystem_top']: build_files_dict['full_topology_file'],
build_files_dict['fullsystemcenter_pdb']: build_files_dict['final_structure_file'],
build_files_dict['index_ndx']: build_files_dict['final_index_file']})
for each_source, each_dest in copyfiles.items():
os_util.local_print('Copying file {} to {}'
''.format(each_source, os.path.join(base_dir, 'protein',
each_dest)),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
shutil.copy2(each_source, os.path.join(base_dir, 'protein', each_dest))
return all_classes.Namespace({'build_dir': build_system_dir, 'structure': output_structure_file,
'topology': output_topology_file, 'water_name': water_name})
def prepare_output_scripts_data(header_template=None, script_type='bash', submission_args=None,
custom_scheduler_resources=None, additional_options=None, hrex_frequency=0,
collect_type='bin', config_file=None, index_file='index.ndx', temperature=298.15,
gmx_bin='gmx_mpi', n_jobs=1, run_before=None, run_after=None,
scripts_templates='templates/output_files_data.ini', analysis_options=None,
ligand_name='LIG', verbosity=0):
"""Prepare data to be used when generating the output scripts
Parameters
----------
header_template : str or list or dict
Read headers from this file, from this list of files or from this dict. None: selects the internal templates
script_type : str
Type of output scripts, one of dir, tgz, and bin
submission_args : str
Pass this arguments to the submission executable
custom_scheduler_resources : dict or None
If script_type is a scheduler, select this resources when submitting the jobs
additional_options : dict or None
Pass these additional options to the job scheduler, see manual for supported format
hrex_frequency : int
Attempt to exchange replicas every this much frames (Default: 0, no HREX)
collect_type : str
Select script or brinary used to collect rerun data; options: bin, python, no_collect (do not collect), or the
path for a executable to be used to process.
config_file : str
Default output data configuration file - regular users do not need to set this. None: use internal default.
index_file : str
Index file to be used during runs and analysis
temperature : float
Absolute temperature of the sampling
gmx_bin : str
Use this gromacs binary on the run node
n_jobs: int
Use this many jobs during rerun, collect and analysis steps
run_before : str
Run commands in this string or file before everything else on the run script.
run_after : str
Run commands in this string or file after everything else on the run script.
scripts_templates : str
Read default templates from this file. Default: use internal templates.
analysis_options : dict
Extra options to be used in analysis. Default: {'skip_frames': 100, }
ligand_name : str
Use this as ligand name. Warning: currently, setting this may break the run
verbosity : int
Sets the verbosity level
Returns
-------
all_classes.Namespace
A custom Namespace object containing: 'selfextracting_script', 'constantpart', 'header', 'submit_command',
'depend_string', 'collect_executables', 'pack_script', 'shebang', and 'parts'
"""
if analysis_options is None:
analysis_options = {}
analysis_options.setdefault('skip_frames', 100)
config_file = os.path.join(os.path.dirname(__file__), scripts_templates) if config_file is None else config_file
# To be able to read multiline options starting with '#'
outputscript_data = configparser.RawConfigParser(comment_prefixes=';')
outputscript_data.read(config_file)
constant_data = outputscript_data['constant_part']
# Holder for scripts parts (preserving order)
scripts_names = os_util.detect_type(outputscript_data['default']['scripts_names'], test_for_list=True)
if not isinstance(scripts_names, list):
os_util.local_print('Failed to read the output sequence from file {}. This should not happen')
raise SystemExit(-1)
additional_options = os_util.detect_type(additional_options, test_for_dict=True)
if additional_options and not isinstance(additional_options, dict):
os_util.local_print('Failed to read additional_options as a dict. Data read was: "{}"'
''.format(additional_options),
current_verbosity=verbosity, msg_verbosity=os_util.verbosity_level.error)
raise ValueError('dict expected, got {}'.format(type(additional_options)))
output_constantpart = all_classes.Namespace([(s, '') for s in scripts_names])
output_header = ''
if not hrex_frequency:
# User doesn't want HREX
output_constantpart['run'] = constant_data['runnohrex']
else:
# Parse hrex_frequency
hrex_frequency = os_util.detect_type(hrex_frequency)
if collect_type == 'python':
collect_executables = [os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dist', each_file)
for each_file in ['collect_results_from_xvg.py']]
elif collect_type == 'bin':
collect_executables = [os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dist',
'collect_results_from_xvg')]
elif collect_type == 'no_collect':
collect_executables = None
else:
collect_executables = collect_type
if collect_executables:
collect_on_node = os.path.join('..', '..', '..', '..', os.path.basename(collect_executables[0]))
collect_line = "chmod +x {} && " \
"./{} --temperature {} --gmx_bin {} --input *.xvg" \
"".format(collect_on_node, collect_on_node, temperature, gmx_bin)
else:
collect_line = 'echo "Skipping collecting xvg data "'
# Substitute these on the run files
substitution_constant = {'__N_JOBS__': n_jobs, '__LIG_GROUP__': ligand_name, '__COLLECT_BIN__': collect_line,
'__INDEX__': index_file, '__GMXBIN__': gmx_bin, '__HREX__': str(hrex_frequency),
'__SKIP_FRAMES__': analysis_options['skip_frames']}
# Reads constant parts from constant_data into output_constantpart
for step in output_constantpart:
if step not in constant_data and step == 'run':
if hrex_frequency <= 0:
output_constantpart['run'] = constant_data['runnohrex']
else:
output_constantpart['run'] = constant_data['runhrex']
elif step not in constant_data:
continue
else:
output_constantpart[step] = constant_data[step]
for each_holder, each_data in substitution_constant.items():
output_constantpart[step] = output_constantpart[step].replace(each_holder, str(each_data))
if custom_scheduler_resources:
custom_scheduler_resources = os_util.detect_type(custom_scheduler_resources, test_for_dict=True)
if not isinstance(custom_scheduler_resources, dict):
os_util.local_print('Failed to read output_resources as dict (or None or False, ie: selecting '
'default resources). Value "{}" was read as a(n) {}'
''.format(custom_scheduler_resources, type(custom_scheduler_resources)),
current_verbosity=verbosity, msg_verbosity=os_util.verbosity_level.error)
raise TypeError('dict, False, or NoneType expected, got {} instead'
''.format(type(custom_scheduler_resources)))
else:
# Update defaults with user supplied resources
outputscript_data['resources'].update({k: str(v) for k, v in custom_scheduler_resources.items()})
additional_options_data, options_str = None, None
try:
template_section = outputscript_data[script_type]
except KeyError:
# User provided a custom submit command, so they must have used header_template and template_section
# will not be used
template_section = None
submit_command = script_type
depend_string = ''
else:
submit_command = template_section['submit_command']
depend_string = template_section['depend_string']
temp_str = template_section['header']
additional_options_data = os_util.detect_type(template_section['additional_options'], test_for_dict=True)
options_str = template_section['options_str']
for each_substitution, each_value in outputscript_data['resources'].items():
this_step, this_resource = each_substitution.split('_')
if this_step == 'all':
temp_str = temp_str.replace('__{}__'.format(this_resource.upper()), str(each_value))
if additional_options:
for each_option, each_value in additional_options.items():
if each_option in additional_options_data:
temp_str += '\n{} {}'.format(options_str,
additional_options_data[each_option].replace('__VALUE__', each_value))
else:
if each_option[0] != '-':
if len(each_option) == 1:
each_option = '-' + each_option
else:
each_option = '--' + each_option
temp_str += '\n{} {} {}'.format(options_str, each_option, each_value)
output_header = temp_str
if header_template:
# User supplied output_template, try to read these as files
header_template = os_util.detect_type(header_template, test_for_dict=True,
test_for_list=True)
if isinstance(header_template, list):
header_data = [os_util.read_file_to_buffer(each_file, die_on_error=True, return_as_list=True,
error_message='Could not read output_template file.')
for each_file in header_template]
if len(header_data) == 1:
output_header = os_util.read_file_to_buffer(header_data[0], die_on_error=True, return_as_list=True,
error_message='Could not read output_template file.')
else:
os_util.local_print('I can only understand a single file as header_template (config: output_template). '
'I read {} from your input {}.'.format(len(header_data), len(header_template)),
current_verbosity=verbosity,
msg_verbosity=os_util.verbosity_level.error)
# os_util.local_print('When not using split output (default), argument or config file option '
# 'output_template requires a single file. I read {} from your input {}.'
# ''.format(len(output_header), len(header_template)),
# current_verbosity=verbosity,
# msg_verbosity=os_util.verbosity_level.error)
raise SystemExit(1)
elif isinstance(header_template, dict):
output_header = {key: os_util.read_file_to_buffer(each_file, die_on_error=True, return_as_list=True,
error_message='Could not read output_template file.')
for key, each_file in header_template.items()}
else:
os_util.local_print('Failed to read output_template as list or dict (or None or False, ie: selecting '
'default template). Value "{}" was read as a(n) {}'
''.format(header_template, type(header_template)),
current_verbosity=verbosity, msg_verbosity=os_util.verbosity_level.error)
raise TypeError('list, dict, False, or NoneType expected, got {} instead'
''.format(type(header_template)))
elif template_section is None:
os_util.local_print('If a custom submit command is provided via output_scripttype (ie: output_scripttype'
'is not in [{}]), then you must provide custom template files via output_template'
''.format(', '.join([s for s in outputscript_data.sections() if s != 'constant_part'])),
current_verbosity=verbosity, msg_verbosity=os_util.verbosity_level.error)
raise SystemExit(1)
selfextracting_script_output = outputscript_data['default']['selfextracting']
scripts_names.remove('pack')
temp_str = template_section['header']
for each_substitution, each_value in outputscript_data['resources'].items():
this_step, this_resource = each_substitution.split('_')
if this_step == 'pack':
temp_str = temp_str.replace('__{}__'.format(this_resource.upper()), str(each_value))
if options_str and additional_options_data and additional_options:
for each_option, each_value in additional_options.items():
if each_option in additional_options_data:
temp_str += '\n{} {}'.format(options_str,
additional_options_data[each_option].replace('__VALUE__', each_value))
else:
if each_option[0] != '-':
if len(each_option) == 1:
each_option = '-' + each_option
else:
each_option = '--' + each_option
temp_str += '\n{} {} {}'.format(options_str, each_option, each_value)
pack = temp_str
pack += '\n\n' + output_constantpart['pack']
return_data = all_classes.Namespace({'selfextracting_script': selfextracting_script_output,
'constantpart': output_constantpart, 'header': output_header,
'submit_command': submit_command, 'depend_string': depend_string,
'collect_executables': collect_executables, 'pack_script': pack,
'shebang': outputscript_data['default']['shebang'], 'parts': scripts_names})
return_data['submission_args'] = submission_args if submission_args else ''
for key, value in {'run_before': run_before, 'run_after': run_after}.items():
if not value:
return_data[key] = None
else:
file_data = os_util.read_file_to_buffer(value)
if file_data is False:
# Reading as a file failed, must be a string with the commands
return_data[key] = value
return return_data
def process_input_molecule_entry(this_entry, verbosity=0):
""" Process an entry in the input molecules, trying to smartly guess the directory structure
Parameters
----------
this_entry : str
Ligand input to process
verbosity : int
Set the verbosity level
Returns
-------