forked from luancarvalhomartins/PyAutoFEP
-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmerge_topologies.py
1926 lines (1669 loc) · 118 KB
/
merge_topologies.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
#
# merge_topologies.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 os
import re
from copy import deepcopy
import time
from collections.abc import Callable
import itertools
from rdkit import RDLogger
import rdkit.Chem
import rdkit.Chem.rdFMCS
import rdkit.Chem.rdForceFieldHelpers
import rdkit.ForceField.rdForceField
from rdkit.Chem.AllChem import ConstrainedEmbed, DeleteSubstructs, ShapeProtrudeDist, ShapeTanimotoDist, AlignMol, \
GetCrippenO3A, GetO3A
from rdkit.Chem.AllChem import GetMolFrags
import mol_util
import all_classes
import os_util
import savestate_util
@os_util.trace
def constrained_embed_forcefield(molecule, core, core_conf_id=-1, atom_map=None, num_conformations=1, randomseed=2342,
restraint_steps=(10.0, 50.0, 100.0), minimization_steps=5,
force_field=rdkit.Chem.AllChem.UFFGetMoleculeForceField, verbosity=0, **kwargs):
""" Use force field minimization to constrain molecule to core, without Embed code
Parameters
----------
molecule : rdkit.Chem.Mol
Mobile molecule to be embed
core : rdkit.Chem.Mol
Reference molecule
core_conf_id : int
Use this core conformation
atom_map : list
Use this atoms to map molecule -> core atoms, default get match automatically
num_conformations : int
Generate this many conformations
randomseed : int
Random seed to the conformer generator
restraint_steps : list
Apply restraints sequentially from this list, default (10.0, 50.0, 100.0)
minimization_steps : int
Run this much minimization steps
force_field : function
Get force field function, default UFF
verbosity : int
Set verbosity level
Returns
-------
list
"""
default_values = {'randomSeed': randomseed, 'ignoreSmoothingFailures': True, 'enforceChirality': True,
'maxAttempts': 50, 'boxSizeMult': 5.0, 'randNegEig': True, 'numZeroFail': 1, 'forceTol': 1.0e-3,
'energyTol': 1.0e-4, 'useExpTorsionAnglePrefs': True, 'useBasicKnowledge': True, 'maxIters': 50,
'minLen': 0, 'maxLen': 0, 'maxIts': 200}
[kwargs.setdefault(key, value) for key, value in default_values.items()]
required_values = {'useRandomCoords': True, 'clearConfs': False}
[kwargs.__setitem__(key, value) for key, value in required_values.items()]
new_conf_ids = []
if not atom_map:
adjusted_core = mol_util.adjust_query_properties(core, verbosity=verbosity)
atom_map = []
for ai, aj in enumerate(molecule.GetSubstructMatch(adjusted_core)):
if not (molecule.GetAtomWithIdx(aj).GetAtomicNum() == 1 or
adjusted_core.GetAtomWithIdx(ai).GetAtomicNum() == 1):
atom_map.append((aj, ai))
if not atom_map:
os_util.local_print('Failed to match molecule {} to core {} in constrained_embed_forcefield. Cannot '
'continue'.format(rdkit.Chem.MolToSmiles(molecule),
rdkit.Chem.MolToSmiles(adjusted_core)),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise ValueError("Molecule doesn't match the core")
# FIXME: parallelize this code
for this_conformations in range(num_conformations):
this_conf_id = rdkit.Chem.AllChem.EmbedMolecule(molecule, randomSeed=randomseed,
ignoreSmoothingFailures=kwargs['ignoreSmoothingFailures'],
clearConfs=kwargs['clearConfs'],
useRandomCoords=kwargs['useRandomCoords'],
enforceChirality=kwargs['enforceChirality'],
maxAttempts=kwargs['maxAttempts'],
boxSizeMult=kwargs['boxSizeMult'],
randNegEig=kwargs['randNegEig'],
numZeroFail=kwargs['numZeroFail'],
forceTol=kwargs['forceTol'],
useExpTorsionAnglePrefs=kwargs['useExpTorsionAnglePrefs'],
useBasicKnowledge=kwargs['useBasicKnowledge'])
if this_conf_id < 0:
os_util.local_print('Failed to embed molecule {} in constrained_embed_forcefield. Cannot continue.'
''.format(rdkit.Chem.MolToSmiles(molecule)),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
return False
else:
new_conf_ids.append(this_conf_id)
# align the embedded conformation onto the core:
rdkit.Chem.AllChem.AlignMol(molecule, core, refCid=core_conf_id, prbCid=this_conf_id, atomMap=atom_map,
maxIters=kwargs['maxIters'])
sanitize_return = rdkit.Chem.SanitizeMol(molecule, catchErrors=True)
if sanitize_return != 0:
os_util.local_print('Could not sanitize molecule {} (SMILES="{}")\nError {} when running '
'rdkit.Chem.SanitizeMol.'
''.format(molecule.GetProp("_Name"), rdkit.Chem.MolToSmiles(molecule), sanitize_return),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
ff = force_field(molecule, confId=this_conf_id)
conf = core.GetConformer(core_conf_id)
for this_restraint in restraint_steps:
for dest_atom, core_atom in atom_map:
p = conf.GetAtomPosition(core_atom)
p_idx = ff.AddExtraPoint(p.x, p.y, p.z, fixed=True) - 1
ff.AddDistanceConstraint(p_idx, dest_atom, minLen=kwargs['minLen'], maxLen=kwargs['maxLen'],
forceConstant=this_restraint)
ff.Initialize()
ff.Minimize(maxIts=kwargs['maxIts'], energyTol=kwargs['energyTol'], forceTol=kwargs['forceTol'])
for _ in range(minimization_steps):
if ff.Minimize(maxIts=kwargs['maxIts'], energyTol=kwargs['energyTol'], forceTol=kwargs['forceTol']):
break
# Align molecule again
rdkit.Chem.AllChem.AlignMol(molecule, core, refCid=core_conf_id, prbCid=this_conf_id, atomMap=atom_map,
maxIters=kwargs['maxIters'])
return new_conf_ids
def get_o3a_score(molecule_a, molecule_b, conf_a=-1, conf_b=-1, max_iters=0, **kwargs):
""" Wrapper for GetO3A
"""
o3a_data = GetO3A(prbMol=molecule_a, refMol=molecule_b, prbCid=conf_a, refCid=conf_b, maxIters=max_iters,
**kwargs)
return -o3a_data.Score()
def get_crippen_o3a_score(molecule_a, molecule_b, conf_a=-1, conf_b=-1, max_iters=0, **kwargs):
"""Wrapper for GetCrippenO3A
"""
o3a_data = GetCrippenO3A(prbMol=molecule_a, refMol=molecule_b, prbCid=conf_a, refCid=conf_b, maxIters=max_iters,
**kwargs)
return -o3a_data.Score()
@os_util.trace
def constrained_embed_shapeselect(molecule, target, core_conf_id=-1, matching_atoms=None, coord_map=None,
randomseed=2342, num_conformers=200, volume_function='tanimoto',
rigid_molecule_threshold=1, num_threads=0, mcs=None, atom_map=None, save_state=None,
verbosity=0, **kwargs):
""" Embed a molecule to target used a constrained core and maximizing volume similarity, as measured by
volume_function. Symmetry will be taken in account.
Parameters
----------
molecule : rdkit.Chem.Mol
Molecule to be embed
target : rdkit.Chem.Mol
Molecule to be uses as a source of constraints. If coord_map is supplied, this will be ignored.
core_conf_id : int
Id of the target conformation to use (default: detect)
matching_atoms : dict
A dictionary mapping atoms in molecule to matching atoms in target. If None (default), find_mcs will be used to
generate a match.
coord_map : dict
A dictionary mapping atom IDs->coordinates. This will require some atoms to have fixed coordinates in the
resulting conformation. Note that passing this will cause constrained_embed_shapeselect to ignore target.
randomseed : int
Pass this random seed to EmbedMolecule and EmbedMultipleConfs
num_conformers : int
Generate this much trial conformers to find a best shape match
volume_function : str
Use this function for calculate shape similarity ('protude', 'tanimoto' (default), 'o3a', and 'crippeno3a'), or
any user defined function
rigid_molecule_threshold : int
Consider a molecule to be rigid if up to this many heavy atoms are not constrained (default 1; -1:
molecule is always flexible)
num_threads : int
Use this many threads during conformer generation (0: max supported)
mcs : str
Use this SMARTS as common core beteween molecule and target
atom_map : list
If supplied, only an atom map containing all atom pairs in this atom_map will be returned
save_state : savestate_util.SavableState
Save state data
verbosity : int
Set verbosity level
Returns
-------
rdkit.Chem.Mol
Molecule embed to target
"""
# Check input
if matching_atoms and coord_map:
raise ValueError("matching_atoms and coord_map are mutually exclusive")
default_values = {'maxAttempts': 50, 'numConfs': num_conformers, 'randomSeed': randomseed, 'useRandomCoords': True,
'clearConfs': True, 'ignoreSmoothingFailures': True, 'useExpTorsionAnglePrefs': True,
'enforceChirality': True, 'boxSizeMult': 5.0, 'numThreads': num_threads, 'gridSpacing': 0.5,
'vdwScale': 0.8, 'stepSize': 0.25, 'maxLayers': -1, 'ignoreHs': True, 'maxMatches': 32}
[kwargs.setdefault(key, value) for key, value in default_values.items()]
if kwargs['clearConfs']:
# Clear conformer data
molecule.RemoveAllConformers()
if matching_atoms is None and coord_map is None:
if mcs is not None:
this_mcs = mcs
else:
try:
target.GetProp('_Name')
except KeyError:
target.SetProp('_Name', '<< Unnamed molecule SMILES={} >>'.format(rdkit.Chem.MolToSmiles(target)))
if kwargs.get('mcs_type', 'graph') == 'graph':
# completeRingsOnly and matchValences are required to prepare a dual topology
this_mcs = find_mcs([rdkit.Chem.RemoveHs(molecule), rdkit.Chem.RemoveHs(target)], matchValences=True,
ringMatchesRingOnly=True, completeRingsOnly=True, verbosity=verbosity,
savestate=save_state, **kwargs).smartsString
os_util.local_print('MCS between molecules {} and {} was obtained by find_mcs and is {}'
''.format(molecule.GetProp('_Name'), target.GetProp('_Name'), this_mcs),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
elif kwargs.get('mcs_type', 'graph') == '3d':
# 3D MCS requires hydrogens, so keep Hs here and remove them below
this_mcs = find_mcs_3d(molecule_a=molecule, molecule_b=target,
num_threads=kwargs.get('num_threads', 0), verbosity=verbosity,
savestate=save_state, maxMatches=kwargs['maxMatches']).smartsString
os_util.local_print('MCS between molecules {} and {} was obtained by find_mcs_3d and is {}'
''.format(molecule.GetProp('_Name'), target.GetProp('_Name'),
this_mcs),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
else:
os_util.local_print('MCS type {} not know, please select between "graph" and "3d"'
''.format(kwargs.get('mcs_type')),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
raise ValueError('MCS type {} not know, please select between "graph" and "3d"'
''.format(kwargs.get('mcs_type')))
core_mol = rdkit.Chem.MolFromSmarts(this_mcs)
if core_mol is None:
os_util.local_print('Could not detect/convert common core between target mol and {}\nError when running'
' rdkit.Chem.MolFromSmarts\nThis is the Smarts which failed to be converted: {}'
''.format(molecule.GetProp("_Name"), this_mcs),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
sanitize_return = rdkit.Chem.SanitizeMol(core_mol, catchErrors=True)
if sanitize_return != 0:
os_util.local_print('Could not sanitize common core between target mol and {}\nError {} when running '
'rdkit.Chem.SanitizeMol\nThis is the molecule representing the common core between '
'structures (without sanitization): {}'
''.format(molecule.GetProp("_Name"), sanitize_return,
rdkit.Chem.MolToSmiles(core_mol)),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
try:
core_mol = rdkit.Chem.RemoveHs(core_mol)
except (rdkit.Chem.rdchem.AtomValenceException, rdkit.Chem.rdchem.KekulizeException,
rdkit.Chem.rdchem.AtomKekulizeException, rdkit.Chem.AtomSanitizeException):
core_mol = rdkit.Chem.RemoveHs(core_mol, sanitize=False)
if core_mol.GetNumHeavyAtoms() == molecule.GetNumHeavyAtoms():
try:
target_name = target.GetProp('_Name')
except KeyError:
target_name = str(target)
os_util.local_print('The detected or supplied core between molecules {} (SMILES="{}") and {} (SMILES="{}") '
'has the same number of heavy atoms as molecule {} ({} heavy atoms). Falling back to '
'constrained_embed_forcefield with num_conformations=1.'
''.format(molecule.GetProp("_Name"), rdkit.Chem.MolToSmiles(molecule), target_name,
rdkit.Chem.MolToSmiles(target), molecule.GetProp("_Name"),
molecule.GetNumHeavyAtoms()),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
this_atom_map = get_atom_map(molecule_a=molecule, molecule_b=target, core_mol=core_mol,
min_atom_map=atom_map, verbosity=verbosity)
tmp_kwargs = kwargs.copy()
tmp_kwargs['enforceChirality'] = True
constrained_embed_forcefield(molecule, core=target, core_conf_id=core_conf_id, randomseed=randomseed,
atom_map=this_atom_map, num_conformations=1, verbosity=verbosity, **tmp_kwargs)
return molecule
temp_core_structure = mol_util.loose_replace_side_chains(target, core_mol, use_chirality=True)
if temp_core_structure is None:
try:
target_name = target.GetProp('_Name')
except KeyError:
target_name = target.__str__()
os_util.local_print('Could not process the core structure to embed while working with the molecule '
'{} (SMILES={}). mol_util.loose_replace_side_chains(target, core_mol) failed. '
'core_mol: {} (SMARTS={}) target: {} (SMARTS={})'
''.format(molecule.GetProp('_Name'),
rdkit.Chem.MolToSmiles(molecule), core_mol,
rdkit.Chem.MolToSmarts(core_mol),
target_name, rdkit.Chem.MolToSmiles(target)),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
else:
core_mol = temp_core_structure
# Remove * atoms from common core
core_mol = DeleteSubstructs(core_mol, rdkit.Chem.MolFromSmiles('*'))
if core_mol is None:
os_util.local_print('Could not delete side chains between target mol and {}\n\t'
'DeleteSubstructs(core_mol, rdkit.Chem.MolFromSmiles("*")) failed.\n\t'
'core_mol: {} (SMARTS={})'
''.format(molecule.GetProp("_Name"),
core_mol, rdkit.Chem.MolToSmarts(core_mol)),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
os_util.local_print('This is the Smiles representation of the common core: {}'
''.format(rdkit.Chem.MolToSmiles(core_mol)),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
try:
core_mol = rdkit.Chem.RemoveHs(core_mol)
except (rdkit.Chem.rdchem.AtomValenceException, rdkit.Chem.rdchem.KekulizeException,
rdkit.Chem.rdchem.AtomKekulizeException, rdkit.Chem.AtomSanitizeException):
os_util.local_print('Failed to sanitize the molecular representation of the common core: {}. Could not '
'remove Hs. Going on.'
''.format(rdkit.Chem.MolToSmiles(core_mol)),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
core_mol = mol_util.adjust_query_properties(core_mol, verbosity=verbosity)
# Prepare a coordinate map to supply to EmbedMultipleConfs
if atom_map is not None:
matches = [get_atom_map(molecule_a=molecule, molecule_b=target, core_mol=core_mol, min_atom_map=atom_map,
verbosity=verbosity)]
else:
matches = get_atom_map(molecule_a=molecule, molecule_b=target, core_mol=core_mol, multiple_matches=True,
verbosity=verbosity)
os_util.local_print('There are {} possible matches between the target and molecule "{}" (SMILE={}). Starting '
''.format(len(matches), molecule.GetProp("_Name"), rdkit.Chem.MolToSmiles(molecule)),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
for match in matches:
if len(match) + rigid_molecule_threshold >= molecule.GetNumHeavyAtoms():
# If there are too few atoms to be sampled, just generate a single conformation. This will often be
# triggered when the perturbations are small or we are constraining to a reference of the same molecule
num_conformers = 1
os_util.local_print('The endpoint {} would have {} constrained atoms and {} not constrained ones. A '
'single conformation will be generated (rigid_molecule_threshold = {})'
''.format(molecule.GetProp('_Name'),
len(match), molecule.GetNumHeavyAtoms() - len(match),
rigid_molecule_threshold),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
else:
num_conformers = kwargs['numConfs']
coord_map = {endpoint_atom: target.GetConformer(core_conf_id).GetAtomPosition(core_atom)
for endpoint_atom, core_atom in match}
try:
confs = rdkit.Chem.AllChem.EmbedMultipleConfs(molecule, maxAttempts=kwargs['maxAttempts'],
numConfs=num_conformers, randomSeed=kwargs['randomSeed'],
useRandomCoords=kwargs['useRandomCoords'],
clearConfs=False, coordMap=coord_map,
ignoreSmoothingFailures=kwargs['ignoreSmoothingFailures'],
useExpTorsionAnglePrefs=kwargs['useExpTorsionAnglePrefs'],
enforceChirality=kwargs['enforceChirality'],
boxSizeMult=kwargs['boxSizeMult'],
numThreads=kwargs['numThreads'])
except RuntimeError:
confs = []
if len(confs) == 0:
os_util.local_print('EmbedMultipleConfs failed to generate conformations. Retrying with force field '
'optimization-based constrained embed.',
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
constrained_embed_forcefield(molecule, core=core_mol, core_conf_id=core_conf_id, randomseed=randomseed,
atom_map=atom_map, **kwargs)
if molecule.GetNumConformers() == 0:
os_util.local_print('Failed to generate conformations to molecule {}. Cannot continue. A possible reason '
'for this error is that you are trying to invert a stereocenter, but mcs_type is '
'graph instead of 3d (mcs_type={}).'
''.format(molecule.GetProp("_Name"), kwargs.get('mcs_type', 'graph')),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(-1)
else:
if not coord_map:
coord_map = {endpoint_atom: target.GetConformer(core_conf_id).GetAtomPosition(target_atom)
for target_atom, endpoint_atom in matching_atoms.items()}
non_resrt_heavy_atoms = len([each_atom for each_atom in molecule.GetAtoms()
if each_atom.GetAtomicNum() > 1 and each_atom.GetAtomicNum() not in coord_map])
if non_resrt_heavy_atoms > rigid_molecule_threshold:
# If there are too few atoms to be sampled, just generate a single conformation. This will often be
# triggered when the perturbations are small or we are constraining to a reference of the same molecule
num_conformers = 1
os_util.local_print('The endpoint {} would have {} constrained atoms and {} not constrained heavy atoms. A '
'single conformation will be generated (rigid_molecule_threshold = {})'
''.format(molecule.GetProp('_Name'), len(coord_map), non_resrt_heavy_atoms,
rigid_molecule_threshold),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
else:
num_conformers = kwargs['numConfs']
try:
new_confs = rdkit.Chem.AllChem.EmbedMultipleConfs(molecule, maxAttempts=kwargs['maxAttempts'],
numConfs=num_conformers,
randomSeed=kwargs['randomSeed'],
useRandomCoords=kwargs['useRandomCoords'],
clearConfs=kwargs['clearConfs'], coordMap=coord_map,
ignoreSmoothingFailures=kwargs['ignoreSmoothingFailures'],
useExpTorsionAnglePrefs=kwargs['useExpTorsionAnglePrefs'],
enforceChirality=kwargs['enforceChirality'],
boxSizeMult=kwargs['boxSizeMult'],
numThreads=kwargs['numThreads'])
except RuntimeError:
new_confs = []
if len(list(new_confs)) == 0:
os_util.local_print('Failed to generate conformations to molecule {} using EmbedMultipleConfs. Falling '
'back to constrained_embed_forcefield. This may take a while.'
''.format(molecule.GetProp("_Name")),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
if matching_atoms:
atom_map = [(ai, aj) for ai, aj in matching_atoms.items()]
constrained_embed_forcefield(molecule, core=target, atom_map=atom_map, num_conformations=num_conformers,
randomseed=randomseed, verbosity=verbosity, **kwargs)
if molecule.GetNumConformers() == 0:
rdkit.Chem.AssignStereochemistry(molecule)
chiral_data_mol = rdkit.Chem.FindMolChiralCenters(molecule)
os_util.local_print('Failed to generate conformations to molecule {}. Cannot continue. A possible reason '
'for this error is that you are trying to invert a stereocenter, but mcs_type is '
'graph instead of 3d (mcs_type={}, chiral_data_mol={}).'
''.format(molecule.GetProp("_Name"), kwargs.get('mcs_type', 'graph'), chiral_data_mol),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(-1)
os_util.local_print('{} conformations were generated to molecule {}'
''.format(molecule.GetNumConformers(),
molecule.GetProp("_Name")),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
# Use this volume-based comparison function to rank conformation pairs
if volume_function == 'protude':
volume_function = ShapeProtrudeDist
elif volume_function == 'tanimoto':
volume_function = ShapeTanimotoDist
elif volume_function == 'o3a':
volume_function = get_o3a_score
elif volume_function == 'crippen_o3a':
volume_function = get_crippen_o3a_score
elif isinstance(volume_function, Callable):
# volume_function is already the function, do nothing
pass
else:
os_util.local_print('Shape similarity comparison "{}" not understood. Please, select from "protude", '
'"tanimoto", "o3a" or "crippen_o3a".'.format(volume_function),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
if volume_function in [ShapeProtrudeDist, ShapeTanimotoDist]:
# Use extended specific extended options for ShapeProtrudeDist and ShapeTanimotoDist
rms_list = [volume_function(molecule, target, conformer.GetId(), core_conf_id,
gridSpacing=kwargs['gridSpacing'], vdwScale=kwargs['vdwScale'],
stepSize=kwargs['stepSize'], maxLayers=kwargs['maxLayers'],
ignoreHs=kwargs['ignoreHs'])
for conformer in molecule.GetConformers() if conformer.Is3D()]
elif volume_function in [get_o3a_score, get_crippen_o3a_score]:
# Use extended specific extended options for GetO3A and GetCrippenO3A, which currently are none
rms_list = [volume_function(molecule, target, conformer.GetId(), core_conf_id)
for conformer in molecule.GetConformers() if conformer.Is3D()]
else:
# The function signature is unknown, but it must at least accept the molecule objects and the conf ids
rms_list = [volume_function(molecule, target, conformer.GetId(), core_conf_id)
for conformer in molecule.GetConformers() if conformer.Is3D()]
# Find the index for best solution
best_solution = rms_list.index(min(rms_list))
os_util.local_print('This is the statistics of volume similarity of the conformations generated in'
' constrained_embed_shapeselect, as scored by function {}:\n Number of conformers: {}\n'
'Mean similarity: {}\nMost similar: {} (item: {})'
''.format(volume_function, len(rms_list), sum(rms_list) / len(rms_list),
max(rms_list), best_solution),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
all_conf_ids = [i.GetId() for i in molecule.GetConformers()]
[molecule.RemoveConformer(conformer) for conformer in all_conf_ids if conformer != best_solution]
return molecule
@os_util.trace
def constrained_embed_dualmol(pseudomolecule, target, core_conf_id=-1, pseudomol_conf_id=-1, randomseed=2342,
num_conformers=50, volume_function='tanimoto', rigid_molecule_threshold=1,
num_threads=0, mcs=None, mcs_type='graph', max_matches=32, savestate=None, verbosity=0):
""" Generates an embedding of a dual-topology pseudomolecule to target using MCS,
:param all_classes.MergedTopologies pseudomolecule: pseudomolecule to be embed
:param rdkit.Chem.Mol target: the molecule to use as a source of constraints
:param int core_conf_id: id of the core conformation to use (default: detect)
:param int pseudomol_conf_id: id of the pseudomolecule conformation to save to (default: detect)
:param int randomseed: seed for rdkit.Chem.EmbedMolecule (only used if num_conformers == 1)
:param int num_conformers: generate this much trial conformers to find a best shape match
:param str volume_function: use this function for calculate shape similarity ('protude' or 'tanimoto' (default))
:param int rigid_molecule_threshold: consider a molecule to be rigid if up to this many heavy atoms are not
constrained (-1: off)
:param int num_threads: use this many threads during conformer generation (0: max supported)
:param str mcs: use this SMARTS as common core to merge molecules
:param str mcs_type: use this type of MCS to detect the common core
:param str max_matches: if mcs_type=3d, limit the number of matches to this number
:param savestate_util.SavableState savestate: saved state data
:param int verbosity: set verbosity level
:rtype: all_classes.MergedTopologies
"""
# Iterate over states B and A, use EmbedMultipleConfs to embed num_conformers possible structures to
# core_structure
# Prepare a temporary copy of molecules A and B, but remove original conformers to make sure we don't get one
# of them in the rms_dict
RDLogger.DisableLog('rdApp.*')
temp_mol_a = rdkit.Chem.Mol(pseudomolecule.molecule_a)
temp_mol_b = rdkit.Chem.Mol(pseudomolecule.molecule_b)
temp_mol_a = constrained_embed_shapeselect(temp_mol_a, target, core_conf_id=core_conf_id, randomseed=randomseed,
num_conformers=num_conformers, volume_function=volume_function,
rigid_molecule_threshold=rigid_molecule_threshold,
num_threads=num_threads, mcs=mcs, maxMatches=max_matches,
save_state=savestate, verbosity=verbosity, mcs_type=mcs_type)
coord_map = {j: temp_mol_a.GetConformer().GetAtomPosition(i) for i, j in pseudomolecule.atom_map}
temp_mol_b = constrained_embed_shapeselect(temp_mol_b, target, core_conf_id=core_conf_id, coord_map=coord_map,
randomseed=randomseed, num_conformers=num_conformers,
volume_function=volume_function,
rigid_molecule_threshold=rigid_molecule_threshold,
num_threads=num_threads, mcs=mcs, maxMatches=max_matches,
save_state=savestate, verbosity=verbosity, mcs_type=mcs_type)
# Copy coordinates of the best conformers to pseudomolecule's molecules A and B
pseudomolecule.molecule_a.RemoveAllConformers()
pseudomolecule.molecule_b.RemoveAllConformers()
pseudomolecule.molecule_a.AddConformer(temp_mol_a.GetConformer())
pseudomolecule.molecule_b.AddConformer(temp_mol_b.GetConformer())
# Copy coordinates of best conformers to pseudomolecule.dual_molecule
for new_each_endpoint_molecule in [temp_mol_a, temp_mol_b]:
# Unless save_state = None, this MCS will be loaded from it
if mcs is not None:
this_mcs = mcs
elif 'mcs' in pseudomolecule:
this_mcs = pseudomolecule.mcs
else:
try:
target.GetProp('_Name')
except KeyError:
target.SetProp('_Name', '<< Unnamed molecule SMILES={} >>'.format(rdkit.Chem.MolToSmiles(target)))
if mcs_type == 'graph':
# completeRingsOnly and matchValences are required to prepare a dual topology
this_mcs = find_mcs([rdkit.Chem.RemoveHs(new_each_endpoint_molecule), rdkit.Chem.RemoveHs(target)],
matchValences=True, ringMatchesRingOnly=True, completeRingsOnly=True,
verbosity=verbosity, savestate=savestate).smartsString
os_util.local_print('MCS between molecules {} and {} was obtained by find_mcs and is {}'
''.format(new_each_endpoint_molecule.GetProp('_Name'), target.GetProp('_Name'),
this_mcs), msg_verbosity=os_util.verbosity_level.info,
current_verbosity=verbosity)
elif mcs_type == '3d':
this_mcs = find_mcs_3d(molecule_a=new_each_endpoint_molecule, molecule_b=target,
num_threads=num_threads, maxMatches=max_matches, verbosity=verbosity,
savestate=savestate).smartsString
os_util.local_print('MCS between molecules {} and {} was obtained by find_mcs_3d and is {}'
''.format(new_each_endpoint_molecule.GetProp('_Name'), target.GetProp('_Name'),
this_mcs),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
else:
os_util.local_print('MCS type {} not know, please select between "graph" and "3d"'
''.format(mcs_type),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
raise ValueError('MCS type {} not know, please select between "graph" and "3d"'
''.format(mcs_type))
core_structure = rdkit.Chem.MolFromSmarts(this_mcs)
core_structure = mol_util.adjust_query_properties(core_structure, verbosity=verbosity)
translation_list = new_each_endpoint_molecule.GetSubstructMatch(core_structure)
this_conformation = pseudomolecule.dual_molecule.GetConformer(pseudomol_conf_id)
for targetmol_index, dual_topology_index in enumerate(translation_list):
this_conformation.SetAtomPosition(dual_topology_index,
new_each_endpoint_molecule.GetConformer().GetAtomPosition(
targetmol_index))
return pseudomolecule
def dualmol_to_pdb_block(pseudomolecule, molecule_name=None, confId=-1, verbosity=0):
""" Returns a PDB block for a pseudomolecule.
:param MergedTopologies pseudomolecule: pseudomolecule to be embed
:param molecule_name: use this as molecule name (this will not overwrite data on pseudomolecule, only output PDB
will be affected)
:param int confId: selects which conformation to output (-1 = default)
:param int verbosity: control verbosity level
:rtype: str
"""
os_util.local_print('Entering dualmol_to_pdb_block(pseudomolecule={}, verbosity={}, confId={})'
''.format(pseudomolecule, verbosity, confId), msg_verbosity=os_util.verbosity_level.debug,
current_verbosity=verbosity)
# Prepare PDB, do not print CONECT records
flavor = (2 | 8)
molecule_a_pdb = rdkit.Chem.MolToPDBBlock(pseudomolecule.molecule_a, confId=confId, flavor=flavor).split('\n')
molecule_b_pdb = [each_line
for each_line in rdkit.Chem.MolToPDBBlock(pseudomolecule.molecule_b,
confId=confId, flavor=flavor).split('\n')
if each_line.find('HETATM') == 0 or each_line.find('ATOM') == 0]
# Suppress END record and empty line after molecule A
# TODO edit COMPND record?
return_list = molecule_a_pdb[:-2]
core_structure = mol_util.adjust_query_properties(pseudomolecule.common_core_mol, verbosity=verbosity)
# Compute atoms present only in topology B
only_in_b = [each_atom.GetIdx()
for each_atom in pseudomolecule.molecule_b.GetAtoms()
if each_atom.GetIdx() not in
pseudomolecule.molecule_b.GetSubstructMatch(core_structure)]
os_util.local_print('These are the atoms present only in topology B: {}'.format(only_in_b),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
# Iterate over molecule_b_pdb, adding atoms present only in B to return_list. Use Idx + 1 to match PDB numbering
for each_atom, new_index in zip((each_line for idx, each_line in enumerate(molecule_b_pdb) if idx in only_in_b),
range(pseudomolecule.molecule_a.GetNumAtoms() + 1,
pseudomolecule.molecule_a.GetNumAtoms() + len(only_in_b) + 1)):
new_atom_line = each_atom[:6] + '{:>5}'.format(new_index) + each_atom[11:]
return_list.append(new_atom_line)
if molecule_name:
temp_pdb_data = []
for each_line in return_list:
if each_line.find('HETATM') == 0 or each_line.find('ATOM') == 0:
each_line = each_line[:17] + '{:>3}'.format(molecule_name) + each_line[20:]
temp_pdb_data.append(each_line)
return_list = temp_pdb_data
return_list.extend(['TER', '\n'])
return '\n'.join(return_list)
def merge_topologies(molecule_a, molecule_b, file_topology1, file_topology2, no_checks=False, savestate=None, mcs=None,
atom_map=None, verbosity=0, **kwargs):
"""Reads two molecule files and topology files, and merge them into a dual topology structure.
Parameters
----------
molecule_a : rdkit.Chem.rdkit
molecule A
molecule_b : rdkit.Chem.rdkit
molecule B
file_topology1 : list
GROMACS-compatible topology of molecule A
file_topology2 : list
GROMACS-compatible topology of molecule B
no_checks : bool
ignore all tests and try to go on
savestate : savestate_util.SavableState
saved state data
atom_map : list
if supplied, only an atom map containing all atom pairs in this min_atom_map will be returned, must be a
iterable of tuples or lists
mcs : str
use this SMARTS as common core to merge molecules
verbosity : int
sets verbosity level
Returns
-------
MergedTopologies
"""
# TODO: set default kwargs here
molecule1 = mol_util.process_dummy_atoms(molecule_a, verbosity=verbosity)
molecule2 = mol_util.process_dummy_atoms(molecule_b, verbosity=verbosity)
os_util.local_print('Molecule 1 name is {}; molecule 2 name is {}'
''.format(molecule1.GetProp("_Name"), molecule2.GetProp("_Name")),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
topology1 = all_classes.TopologyData(file_topology1, verbosity=verbosity)
if topology1.num_molecules == 0:
os_util.local_print('Failed to read topology data from {}. Please, check your input file.'
''.format(file_topology1),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
topology2 = all_classes.TopologyData(file_topology2, verbosity=verbosity)
if topology2.num_molecules == 0:
os_util.local_print('Failed to read topology data from {}. Please, check your input file.'
''.format(file_topology2),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
# Do some tests
if not no_checks:
if molecule1.GetProp("_Name") == molecule2.GetProp("_Name"):
os_util.local_print('Molecules A ({}) and B ({}) have the same name {}. Check your input files. Names are '
'read from mol2 or, if it fails, read from filaname.'
''.format(rdkit.Chem.MolToSmiles(molecule_a),
rdkit.Chem.MolToSmiles(molecule_b),
molecule1.GetProp("_Name")),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise ValueError('molecules names are equal')
defaults_pattern = re.compile(r'(?:\[\s+)defaults(?:\s+]).*', flags=re.IGNORECASE)
for (each_molecule, each_topology, each_top_file) in \
[[molecule1, topology1, file_topology1],
[molecule2, topology2, file_topology2]]:
if any(filter(defaults_pattern.match, map(str, each_topology.output_sequence))):
os_util.local_print('{} contains a [ defaults ] directive!'.format(each_top_file),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
try:
non_matching_names = [(mol2_name.GetProp('_TriposAtomName'), top_name.atom_name)
for mol2_name, top_name
in zip(each_molecule.GetAtoms(), each_topology.molecules[0].atoms_dict.values())
if mol2_name.GetProp('_TriposAtomName') != top_name.atom_name]
except KeyError as error:
if error.args[0] == '_TriposAtomName':
os_util.local_print('Failed to read atom names from {}. I will not check topology atom names '
'against the structure atom names. '.format(each_top_file),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
break
if len(non_matching_names):
os_util.local_print('Not matching atom names between files {} and {}. Atom names from {} will be '
'used!\n'
''.format(each_top_file, each_molecule.GetProp('_Name'), each_top_file)
+ '=' * 50
+ '\nThese are the non-matching names:\n{:<25}{:<25}'
''.format('{}'.format(each_molecule.GetProp('_Name')),
'{}'.format(each_top_file)),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
for mol2_name, top_name in non_matching_names:
os_util.local_print('{:<25}{:<25}'.format(mol2_name, top_name),
msg_verbosity=os_util.verbosity_level.warning, current_verbosity=verbosity)
os_util.local_print('=' * 50, msg_verbosity=os_util.verbosity_level.warning,
current_verbosity=verbosity)
if each_topology.num_molecules > 1:
os_util.local_print('Topology file {} contains {} molecules, but I can only understand one '
'moleculetype per file.'
''.format(each_molecule.GetProp('_Name'), each_topology.num_molecules),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise ValueError('only one molecule accepted, but {} found'.format(each_topology.num_molecules))
if each_topology.molecules[0].num_atoms != each_molecule.GetNumAtoms():
os_util.local_print('Topology file {} contains {} atoms, but molecule file {} contain {} atoms'
''.format(each_top_file, each_topology.molecules[0].num_atoms,
each_molecule.GetProp('_Name'), each_molecule.GetNumAtoms()),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise ValueError('number of atoms mismatch')
# Calculates the charge difference
delta_charge = rdkit.Chem.GetFormalCharge(molecule1) - rdkit.Chem.GetFormalCharge(molecule2)
moleculetype_a = topology1.molecules[0]
moleculetype_b = topology2.molecules[0]
if not mcs:
if kwargs.get('mcs_type', 'graph') == 'graph':
# completeRingsOnly and matchValences are required to prepare a dual topology
common_core_smiles = find_mcs([molecule1, molecule2], matchValences=True, ringMatchesRingOnly=True,
completeRingsOnly=True, verbosity=verbosity, savestate=savestate,
**kwargs).smartsString
os_util.local_print('MCS between molecules {} and {} was obtained by find_mcs and is {}'
''.format(molecule1.GetProp('_Name'), molecule2.GetProp('_Name'), common_core_smiles),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
elif kwargs.get('mcs_type', 'graph') == '3d':
common_core_smiles = find_mcs_3d(molecule_a=molecule1, molecule_b=molecule2,
num_threads=kwargs.get('num_threads', 0),
maxMatches=kwargs.get('maxMatches', 32),
verbosity=verbosity, savestate=savestate).smartsString
os_util.local_print('MCS between molecules {} and {} was obtained by find_mcs_3d and is {}'
''.format(molecule1.GetProp('_Name'), molecule2.GetProp('_Name'), common_core_smiles),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
else:
os_util.local_print('MCS type {} not know, please select between "graph" and "3d"'
''.format(kwargs.get('mcs_type')),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
raise ValueError('MCS type {} not know, please select between "graph" and "3d"'
''.format(kwargs.get('mcs_type')))
else:
# User supplied an MCS, do not save it
common_core_smiles = mcs
if savestate:
os_util.local_print('You supplied both a MCS and a save_state object. Input MCS will be not saved, as it '
'was not computed here', msg_verbosity=os_util.verbosity_level.warning,
current_verbosity=verbosity)
savestate = None
# Prepare a pseudomolecule representing the common core between molecules 1 and 2
core_structure = rdkit.Chem.MolFromSmarts(common_core_smiles)
if core_structure is None:
os_util.local_print('Could not detect/convert common core between topologies\n\tError when running '
'rdkit.Chem.MolFromSmarts(common_core_smiles)\n\tcommon_core_smiles = {}'
''.format(common_core_smiles),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
# Reconstruct a molecule based on common core and coordinates from molecule1
temp_core_structure = mol_util.loose_replace_side_chains(molecule1, core_structure, use_chirality=True)
if temp_core_structure is None:
os_util.local_print('Could not process the core structure to embed while working with the molecule '
'{} (SMILES={}). mol_util.loose_replace_side_chains(target, core_mol) failed. '
'core_query: {} (SMARTS={})'
''.format(molecule1, rdkit.Chem.MolToSmiles(molecule1), core_structure,
rdkit.Chem.MolToSmarts(core_structure)),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
else:
core_structure = temp_core_structure
# Remove * atoms from common core. Note: if there are more than 10 substitution points, this will fail.
core_structure = DeleteSubstructs(core_structure, rdkit.Chem.MolFromSmarts('[1,2,3,4,5,6,7,8,9#0]'))
if core_structure == '':
os_util.local_print('Could not detect/convert common core between topologies',
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
os_util.local_print('Error when running core_structure = DeleteSubstructs(core_structure, '
'rdkit.Chem.MolFromSmiles("*"))',
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
os_util.local_print('This is the Smiles representation of core_structure: {}'
''.format(rdkit.Chem.MolToSmiles(core_structure)),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
raise SystemExit(1)
os_util.local_print('This is the common core structure: {}'.format(core_structure),
msg_verbosity=os_util.verbosity_level.info, current_verbosity=verbosity)
# Get the list of matching atoms from common_atoms -> molecule1 and common_atoms -> molecule2, then map to
# into molecule1 -> molecule2
core_structure = mol_util.adjust_query_properties(core_structure, verbosity=verbosity)
common_atoms = get_atom_map(molecule_a=molecule1, molecule_b=molecule2, core_mol=core_structure,
min_atom_map=atom_map, verbosity=verbosity)
if len(common_atoms) < 3:
os_util.local_print('Less than 3 common atoms were found between molecule {} (SMILES={}) and {} (SMILES={})'
''.format(molecule1.GetProp("_Name"), molecule1, molecule2.GetProp("_Name"),
', '.join(map(str, common_atoms))),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
os_util.local_print('These are the common atoms between {} and {}: {}'
''.format(molecule1.GetProp("_Name"), molecule2.GetProp("_Name"),
', '.join(map(str, common_atoms))),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
# Atoms present only in state B. Id + 1 to match Gromacs atom numbering
only_in_b = [each_atom.GetIdx() + 1 for each_atom in molecule2.GetAtoms()
if each_atom.GetIdx() not in map(lambda x: x[1], common_atoms)]
# Atoms present only in state A. Id + 1 to match Gromacs atom numbering
only_in_a = [each_atom.GetIdx() + 1 for each_atom in molecule1.GetAtoms()
if each_atom.GetIdx() not in map(lambda x: x[0], common_atoms)]
os_util.local_print('These are the atoms present only in {}: {}'
''.format(molecule1.GetProp("_Name"), ', '.join(map(str, only_in_a))),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
os_util.local_print('These are the atoms present only in {}: {}'
''.format(molecule2.GetProp("_Name"), ', '.join(map(str, only_in_b))),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
# Use topology A as base to prepare a dual topology
dual_topology = all_classes.DualTopologyData(file_topology1)
# Rename atoms to identify common core and topology A
for each_atom in dual_topology.molecules[0].atoms_dict.values():
if each_atom.atom_index in [a + 1 for a, b in common_atoms]:
# Atom present in A and B, I will only perturb the charges
newname = '{}_const_idx{}'.format(each_atom.atom_name, each_atom.atom_index)
b_idx = [b + 1 for a, b in common_atoms if a + 1 == each_atom.atom_index][0]
atom_b_charge = topology2.molecules[0].atoms_dict[b_idx].q_e
dual_topology.add_dual_atom_add_atomtype(newname, each_atom,
topology1.atomtype_dict[each_atom.atom_type], mol_region='const',
q_a=each_atom.q_e, q_b=atom_b_charge, vdw_v_a=None, vdw_w_a=None,
vdw_v_b=None, vdw_w_b=None, verbosity=verbosity)
else:
# Atom only in A, charge and VdW at B = 0.0 (dummy atom)
newname = '{}_topA_idx{}'.format(each_atom.atom_name, each_atom.atom_index)
dual_topology.add_dual_atom_add_atomtype(newname, each_atom, topology1.atomtype_dict[each_atom.atom_type],
mol_region='A', q_a=None, vdw_v_a=None, vdw_w_a=None, q_b=0.0,
vdw_v_b=0.0, vdw_w_b=0.0, verbosity=verbosity)
os_util.local_print('These are the atoms present in topology B only:\n{}'
''.format('\n'.join(['\t{}: {}'.format(each_atom, data.atom_type)
for each_atom, data in topology1.molecules[0].atoms_dict.items()
if each_atom in only_in_b])),
msg_verbosity=os_util.verbosity_level.debug, current_verbosity=verbosity)
# Prepares a dict connecting the old atom index from Topology B to new atom to be added to dual topology
new_b_indices = dict(zip(only_in_b, range(moleculetype_a.num_atoms + 1,
moleculetype_a.num_atoms + len(only_in_b) + 1)))
atom_translation_dict = dict([(b + 1, a + 1) for a, b in common_atoms])
atom_translation_dict.update(new_b_indices)
# Selects terms from B which contains atoms in the B region of dual topology (by searching in only in B)
new_molecule = dual_topology.molecules[0]
for each_atom, new_index in new_b_indices.items():
# Creates a new atom from each_atom in topology B and updates its name
new_atom = deepcopy(moleculetype_b.atoms_dict[each_atom])
newname = '{}_topB_idx{}'.format(new_atom.atom_name, new_index)
new_atom.atom_index = new_index
new_atom.charge_group_number = new_index
dual_topology.add_dual_atom_add_atomtype(newname, new_atom, topology2.atomtype_dict[new_atom.atom_type],
mol_region='B', q_a=0.0, vdw_v_a=0.0, vdw_w_a=0.0, q_b=None,
vdw_v_b=None, vdw_w_b=None, verbosity=verbosity)
# Also add atom to atoms_dict and output sequence
last_atom = new_molecule.output_sequence.index(new_molecule.atoms_dict[new_index - 1])
new_molecule.output_sequence.insert(last_atom + 1, new_atom)
new_molecule.atoms_dict[new_index] = new_atom
# Suppress unused atomtypes
for key, each_atomtype in dual_topology.atomtype_dict.items():
if each_atomtype.atom_type not in [each_atom.atom_type for each_atom in new_molecule.atoms_dict.values()]:
suppress_line = '; {} Suppressed\n'.format(new_molecule._format_inline(each_atomtype))
dual_topology.output_sequence[dual_topology.output_sequence.index(each_atomtype)] = suppress_line
dual_topology.atomtype_dict[key] = suppress_line
# Iterates over possible terms
for term_group_name in ['bonds_dict', 'pairs_dict', 'pairsnb_dict', 'exclusions_dict', 'angles_dict', 'dihe_dict',
'constraints_dict', 'vsites2_dict', 'vsites3_dict', 'vsites4_dict']:
term_group = getattr(moleculetype_b, term_group_name)
new_term_group = getattr(new_molecule, term_group_name)
# Iterates over terms of this type containing the atom being modified
for each_bonded_term in term_group.search_all_with_index(only_in_b):
new_bonded_term = deepcopy(each_bonded_term)
new_bonded_term.comments = 'Added by dual top; {}'.format(new_bonded_term.comments)
# Updates the atoms indices with indices for dual topology
if term_group.n_fields is not None:
[setattr(new_bonded_term, field_name, atom_translation_dict[this_each_atom])
for this_each_atom, field_name in zip(new_bonded_term[:term_group.n_fields], new_bonded_term._fields)]
else:
if term_group_name != 'exclusions_dict':
# FIXME: support N-body virtual sites here (also need to add virtual_sitesn parser to topology
# reader
os_util.local_print('Cannot parse term {} in molecule {}. N-body virtual site is not currently'
' supported by dual-topology code.'
''.format(term_group_name, new_molecule.GetProp('_Name')),
msg_verbosity=os_util.verbosity_level.error, current_verbosity=verbosity)
raise SystemExit(1)
for this_each_atom, field_name in zip(new_bonded_term[:-1], new_bonded_term._fields):
setattr(new_bonded_term, field_name, atom_translation_dict[this_each_atom])
# Then adds the term to the dual topology object at the end of the directive
last_position = new_molecule.output_sequence.index(new_term_group[-1])
new_molecule.output_sequence.insert(last_position + 1, new_bonded_term)
new_term_group.append(new_bonded_term)