-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenetic_Algorithm_Functions.py
2628 lines (2055 loc) · 109 KB
/
Genetic_Algorithm_Functions.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
from rdkit import Chem
from rdkit.Chem import Draw
import rdkit
from random import sample
from rdkit.Chem import AllChem
from rdkit.Chem.rdMolDescriptors import CalcMolFormula
from random import choice as rnd
import random
from copy import deepcopy
import subprocess
import ast
import pandas as pd
import re
from math import log10
import os
from gt4sd.properties import PropertyPredictorRegistry
from rdkit import DataStructs
from rdkit.Chem import rdFingerprintGenerator
import numpy as np
from scipy.constants import Boltzmann
from scipy.optimize import curve_fit
import sys, argparse
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy import integrate
from tqdm import trange
from os.path import join as join
from os import chdir
from os import getcwd
from os import listdir
import os
import gzip
import shutil
import json
import fnmatch
import math
import six
from rdkit import Chem
from rdkit.Chem import Descriptors
import pandas as pd
from xgboost import XGBRegressor
import joblib
def MolCheckandPlot(StartingMoleculeUnedited, StartingMolecule, showdiff, Verbose=False):
Mut_Mol = StartingMolecule.GetMol()
MutMolSMILES = Chem.MolToSmiles(Mut_Mol)
RI = Mut_Mol.GetRingInfo()
try:
NumRings = RI.GetNumRings()
except:
RI = None
if RI != None:
NumAromaticRings = Chem.rdMolDescriptors.CalcNumAromaticRings(StartingMolecule)
if NumAromaticRings == 0:
Chem.SanitizeMol(StartingMolecule, sanitizeOps=rdkit.Chem.rdmolops.SanitizeFlags.SANITIZE_ADJUSTHS, catchErrors=True)
Chem.SanitizeMol(StartingMolecule, sanitizeOps=rdkit.Chem.rdmolops.SanitizeFlags.SANITIZE_CLEANUP, catchErrors=True)
Chem.SanitizeMol(StartingMolecule, sanitizeOps=rdkit.Chem.rdmolops.SanitizeFlags.SANITIZE_FINDRADICALS, catchErrors=True)
Chem.SanitizeMol(StartingMolecule, sanitizeOps=rdkit.Chem.rdmolops.SanitizeFlags.SANITIZE_PROPERTIES, catchErrors=True)
Chem.SanitizeMol(StartingMolecule, sanitizeOps=rdkit.Chem.rdmolops.SanitizeFlags.SANITIZE_SETCONJUGATION, catchErrors=True)
Chem.SanitizeMol(StartingMolecule, sanitizeOps=rdkit.Chem.rdmolops.SanitizeFlags.SANITIZE_SETHYBRIDIZATION, catchErrors=True)
Mut_Mol_Sanitized = Chem.SanitizeMol(StartingMolecule, sanitizeOps=rdkit.Chem.rdmolops.SanitizeFlags.SANITIZE_SYMMRINGS, catchErrors=True)
print('Non-Aromatic Cyclic Hydrocarbon')
print(MutMolSMILES)
else:
Mut_Mol_Sanitized = Chem.SanitizeMol(Mut_Mol, catchErrors=True)
else:
Mut_Mol_Sanitized = Chem.SanitizeMol(Mut_Mol, catchErrors=True)
if len(Chem.GetMolFrags(Mut_Mol)) != 1:
if Verbose:
print('Fragmented result, trying new mutation')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
if showdiff:
view_difference(StartingMoleculeUnedited, Mut_Mol)
elif Mut_Mol_Sanitized != rdkit.Chem.rdmolops.SanitizeFlags.SANITIZE_NONE:
if Verbose:
print('Validity Check Failed')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
if Verbose:
print('Validity Check Passed')
if showdiff:
view_difference(StartingMoleculeUnedited, Mut_Mol)
return Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES
def AddAtom(StartingMolecule, NewAtoms, BondTypes, showdiff=False, Verbose=False):
"""
Function that adds atom from a list of selected atoms to a starting molecule.
Need to ensure that probability of this is zero if length of molecule is too short.
Takes molecule, adds atom based on defined probabilities of position.
Arguments:
- StartingMolecule: SMILES String of Starting Molecule
- NewAtoms: List of atoms that could be added to starting molecule
- Show Difference: If True, shows illustration of changes to molecule
"""
StartingMoleculeUnedited = deepcopy(StartingMolecule)
try:
# Change to an editable object
StartingMolecule = Chem.RWMol(StartingMoleculeUnedited)
# Add selected atom from list of addable atoms
StartingMolecule.AddAtom(Chem.Atom(int(rnd(NewAtoms))))
# Storing indexes of newly added atom and atoms from intial molecule
frags = Chem.GetMolFrags(StartingMolecule)
# Check which object is the newly added atom
for ind, frag in enumerate(frags):
if len(frag) == 1:
#Store index of new atom in object
NewAtomIdx = frags[ind]
else:
StartMolIdxs = frags[ind]
StartingMolecule.AddBond(rnd(StartMolIdxs), NewAtomIdx[0], rnd(BondTypes))
#Sanitize molecule
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited, StartingMolecule, showdiff)
except:
if Verbose:
print('Add atom mutation failed, returning empty objects')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
return Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES, StartingMoleculeUnedited
def ReplaceAtom(StartingMolecule, NewAtoms, fromAromatic=False, showdiff=False, Verbose=False):
"""
Function to replace atom from a selected list of atoms from a starting molecule.
Args:
- StartingMolecule: SMILES String of Starting Molecule
- NewAtoms: List of atoms that could be added to starting molecule
- FromAromatic: If True, will replace atoms from aromatic rings
"""
"""
Steps:
1. Get the indexes of all the bonds in the molecule
2. Check if there are any bonds that are aromatic
3. Select index of atom that will be replaced
4. Get bond and bondtype of atom to be replaced
5. Create new bond of same type where atom was removed
"""
StartingMoleculeUnedited = deepcopy(StartingMolecule)
AtomIdxs = []
for atom in StartingMoleculeUnedited.GetAtoms():
if fromAromatic == False:
# Check if atom is Aromatic
if atom.GetIsAromatic():
continue
elif atom.IsInRing():
continue
else:
AtomIdxs.append(atom.GetIdx())
else:
AtomIdxs.append(atom.GetIdx())
if Verbose:
print(f'Number of Bonds atom has = {len(atom.GetBonds())}')
#Select atom to be deleted from list of atom indexes, check that this list is greater than 0
if len(AtomIdxs) == 0:
if Verbose:
print('Empty Atom Index List')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
#Select a random atom from the index of potential replacement atoms
ReplaceAtomIdx = rnd(AtomIdxs)
#Exclude replaced atom type from list of atoms to do replacing with
ReplaceAtomType = StartingMoleculeUnedited.GetAtomWithIdx(ReplaceAtomIdx).GetSymbol()
AtomReplacements = [x for x in NewAtoms if x != ReplaceAtomType]
StartingMolecule = Chem.RWMol(StartingMoleculeUnedited)
#Replace atom
ReplacementAtom = rnd(AtomReplacements)
StartingMolecule.ReplaceAtom(ReplaceAtomIdx, Chem.Atom(ReplacementAtom), preserveProps=True)
if Verbose:
print(f'{StartingMoleculeUnedited.GetAtomWithIdx(ReplaceAtomIdx).GetSymbol()}\
replaced with {Chem.Atom(ReplacementAtom).GetSymbol()}')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited, StartingMolecule, showdiff)
return Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES, StartingMoleculeUnedited
def ReplaceBond(StartingMolecule, Bonds, showdiff=True, Verbose=False):
"""
Function to replace bond type with a different bond type from a selected list of bonds within a starting molecule.
Args:
- StartingMolecule: SMILES String of Starting Molecule
- Bonds: List of bonds that could be used to replace bond in starting molecule
"""
"""
Steps:
1. Get the indexes of all the bonds in the molecule
2. Check if there are any bonds that are aromatic
3. Select index of bond that will be replaced
4. Get index and bondtype of bond to be replaced
"""
StartingMoleculeUnedited = deepcopy(StartingMolecule)
BondIdxs = []
for bond in StartingMoleculeUnedited.GetBonds():
# Check if atom is Aromatic
if bond.GetIsAromatic():
continue
else:
BondIdxs.append(bond.GetIdx())
#Select atom to be deleted from list of atom indexes, check that this list is greater than 0
#Random selection of bond to be replaced
if len(BondIdxs) > 0:
ReplaceBondIdx = rnd(BondIdxs)
#Excluding selected bond's bond order from list of potential new bond orders
ReplaceBondType = StartingMoleculeUnedited.GetBondWithIdx(ReplaceBondIdx).GetBondType()
BondReplacements = [x for x in Bonds if x != ReplaceBondType]
StartingMolecule = Chem.RWMol(StartingMoleculeUnedited)
#Get atoms that selected bond is bonded to
ReplacedBond = StartingMolecule.GetBondWithIdx(ReplaceBondIdx)
Atom1 = ReplacedBond.GetBeginAtomIdx()
Atom2 = ReplacedBond.GetEndAtomIdx()
#Replace bond, randomly selecting new bond order from list of possible bond orders
StartingMolecule.RemoveBond(Atom1, Atom2)
StartingMolecule.AddBond(Atom1, Atom2, rnd(BondReplacements))
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited, StartingMolecule, showdiff)
else:
if Verbose:
print('Empty Bond Index List')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
return Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES, StartingMoleculeUnedited
def AddFragment(StartingMolecule, Fragment, InsertStyle, showdiff=True, Verbose=False):
"""
Function to add a fragment from a selected list of fragments to starting molecule.
Args:
- StartingMolecule: SMILES String of Starting Molecule
- Fragments: List of fragments
- showdiff
- InsertStyle: Whether to add fragment to edge or within molecule
"""
"""
Steps:
1. Select fragment to be added to starting molecule
2. Determine whether fragment is going to be inserted within or appended to end of molecule
3. If inserting fragment within molecule:
- Combine starting molecule and fragment into single disconnected Mol object
- Split atom indexes of starting molecule and fragment and save in different objects
- Check number of bonds each atom has in starting molecule and fragment, exclude any atoms that don't have
exactly two bonds
- Get the atom neighbors of selected atom
- Remove one of selected atom's bonds with its neighbors, select which randomly but store which bond is severed
- Calculate terminal atoms of fragment (atoms with only one bond, will be at least two, return total number of
fragments, store terminal atom indexes in a list)
- Randomly select two terminal atoms from terminal atoms list of fragment
- Create a new bond between each of the neighbors of the target atom and each of the terminal atoms on the
fragment, specify which type of bond, with highest likelihood that it is a single bond
"""
StartingMoleculeUnedited = StartingMolecule
try:
#Always check if fragment is a cyclic (benzene) molecule
if len(Fragment.GetAromaticAtoms()) == len(Fragment.GetAtoms()):
if Verbose:
print('Fragment aromatic, inappropriate function')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
elif len((StartingMoleculeUnedited.GetAromaticAtoms())) == len(StartingMoleculeUnedited.GetAtoms()):
if Verbose:
print('Starting molecule is completely aromatic')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
# Add fragment to Mol object of starting molecule
StartingMolecule = Chem.RWMol(StartingMoleculeUnedited)
StartingMolecule.InsertMol(Fragment)
# Get indexes of starting molecule and fragment, store them in separate objects
frags = Chem.GetMolFrags(StartingMolecule)
StartMolIdxs = frags[0]
FragIdxs = frags[1]
OneBondAtomsMolecule = []
TwoBondAtomsMolecule = []
AromaticAtomsMolecule = []
OneBondAtomsFragment = []
TwoBondAtomsFragment = []
# Getting atoms in starting molecule with different amount of bonds, storing indexes in list
for index in StartMolIdxs:
Atom = StartingMolecule.GetAtomWithIdx(int(index))
if Atom.GetIsAromatic() and len(Atom.GetBonds()) == 2:
AromaticAtomsMolecule.append(index)
elif len(Atom.GetBonds()) == 2:
TwoBondAtomsMolecule.append(index)
elif len(Atom.GetBonds()) == 1:
OneBondAtomsMolecule.append(index)
else:
continue
# Getting atoms in fragment with varying bonds, storing indexes in listv
for index in FragIdxs:
Atom = StartingMolecule.GetAtomWithIdx(int(index))
if len(Atom.GetBonds()) == 1:
OneBondAtomsFragment.append(index)
elif len(Atom.GetBonds()) == 2:
TwoBondAtomsFragment.append(index)
### INSERTING FRAGMENT AT RANDOM POINT WITHIN STARTING MOLECULE
if InsertStyle == 'Within':
if len(OneBondAtomsMolecule) == 0:
if Verbose:
print('No one-bonded terminal atoms in starting molecule, returning empty object')
Mut_Mol = None
Mut_Mol_Sanitized = None
MutMolSMILES = None
else:
# Select random two bonded atom, not including aromatic
AtomRmv = rnd(TwoBondAtomsMolecule)
# Get atom neighbor indexes, remove bonds between selected atom and neighbors
neighbors = [x.GetIdx() for x in StartingMolecule.GetAtomWithIdx(AtomRmv).GetNeighbors()]
# Randomly choose which bond of target atom to sever
SeverIdx = rnd([0,1])
StartingMolecule.RemoveBond(neighbors[SeverIdx], AtomRmv)
#Create a bond between the fragment and the now segmented fragments of the starting molecule
#For situation where bond before target atom is severed
if SeverIdx == 0:
StartingMolecule.AddBond(OneBondAtomsFragment[0], AtomRmv - 1, Chem.BondType.SINGLE)
StartingMolecule.AddBond(OneBondAtomsFragment[1], AtomRmv, Chem.BondType.SINGLE)
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited, StartingMolecule, showdiff)
#For situation where bond after target atom is severed
elif SeverIdx != 0:
StartingMolecule.AddBond(OneBondAtomsFragment[0], AtomRmv + 1, Chem.BondType.SINGLE)
StartingMolecule.AddBond(OneBondAtomsFragment[1], AtomRmv, Chem.BondType.SINGLE)
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited, StartingMolecule, showdiff)
### INSERTING FRAGMENT AT END OF STARTING MOLECULE
elif InsertStyle == 'Edge':
# Choose whether fragment will be added to an aromatic or non-aromatic bond
FragAdd = rnd(['Aromatic', 'Non-Aromatic'])
if len(OneBondAtomsMolecule) == 0:
if Verbose:
print('No one-bonded terminal atoms in starting molecule, returning empty object')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
elif FragAdd == 'Non-Aromatic' or len(AromaticAtomsMolecule) == 0:
#Randomly choose atom from fragment (including aromatic)
FragAtom = rnd(FragIdxs)
#Select random terminal from starting molecule
AtomRmv = rnd(OneBondAtomsMolecule)
#Attach fragment to end of molecule
StartingMolecule.AddBond(FragAtom, AtomRmv, Chem.BondType.SINGLE)
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited, StartingMolecule, showdiff)
elif len(AromaticAtomsMolecule) > 0:
#Randomly select 2 bonded (non-branch base) aromatic atom
ArmtcAtom = rnd(AromaticAtomsMolecule)
#Randomly select terminal atom from fragment
FragAtom = rnd(OneBondAtomsFragment)
#Add Bond
StartingMolecule.AddBond(ArmtcAtom, FragAtom, Chem.BondType.SINGLE)
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited, StartingMolecule, showdiff)
else:
if Verbose:
print('Edge case, returning empty objects')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
except Exception as E:
if Verbose:
print(E)
print('Index error, starting molecule probably too short, trying different mutation')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
return Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES, StartingMoleculeUnedited
def RemoveFragment(InputMolecule, BondTypes, showdiff=False, Verbose=False):
"""
StartingMolecule: Mol
Steps to implement replace fragment function
Take in starting molecule
Check which molecules are
Perform random fragmentation of molecule by performing x random cuts
- Will need to keep hold of terminal ends of each molecule
* Do this by checking fragment for atoms with only one bonded atom
- Will need to check fragment being removed does not completely mess up molecule
Stitch remaning molecules back together by their terminal ends
Will allow x attempts for this to happen before giving up on this mutation(?)
Only implement this mutation when number of atoms exceeds a certain number e.g. 5/6 max mol length
Max fragment removal length of 2/5 max mol length
"""
try:
StartingMoleculeUnedited = deepcopy(InputMolecule)
# Change Mol onject
StartingMolecule = Chem.RWMol(StartingMoleculeUnedited)
# Get list of Bond Indexes
AtomIdxs = []
# Check if there are aromatic rings (RI = Ring Info object)
RI = StartingMolecule.GetRingInfo()
AromaticAtomsObject = StartingMolecule.GetAromaticAtoms()
AromaticAtoms = []
for x in AromaticAtomsObject:
AromaticAtoms.append(x.GetIdx())
if len(AromaticAtoms) > 0:
# Choose whether to remove aromatic ring or not
RemoveRing = rnd([True, False])
else:
RemoveRing = False
if Verbose:
print(f'Attempting to remove aromatic ring: {RemoveRing}')
if RemoveRing and len(AromaticAtoms) > 0:
try:
ChosenRing = rnd(RI.AtomRings())
"""
Once ring is chosen:
- Go through each atom in chosen aromatic ring
- Check the bonds of each atom to see if aromatic or not
- If bond is not aromatic check which atom in the bond was not aromatic
*Save the atom and bond index of the non aromatic atom/bond
- If only one non-aromatic bond, just sever bond and return molecule
- If exactly two non-aromatic bonds, sever both then create bond between the terminal atoms
- If more than two non-aromatic atoms
*Select two of the non-aromatic atoms and create a bond between them, if valence violated, discard attempt
"""
BondIdxs = []
AtomIdxs = []
for AtomIndex in ChosenRing:
Atom = StartingMolecule.GetAtomWithIdx(AtomIndex) #Get indexes of atoms in chosen ring
for Bond in Atom.GetBonds():
if Bond.IsInRing() == False:
BondAtoms = [Bond.GetBeginAtom(), Bond.GetEndAtom()] #Get atoms associated to non-ring bond
BondIdxs.append(BondAtoms)
for At in BondAtoms:
if At.GetIsAromatic() == False:
AtomIdxs.append(At.GetIdx())
"""
To remove fragment:
Sever the selected bonds from above
Create single/double bond between two of the non-aromatic atoms in the AtomIdxs
"""
for B in BondIdxs:
StartingMolecule.RemoveBond(B[0].GetIdx(), B[1].GetIdx())
if len(AtomIdxs) > 1:
BondingAtoms = [AtomIdxs[0], AtomIdxs[1]]
StartingMolecule.AddBond(BondingAtoms[0], BondingAtoms[1], rnd(BondTypes))
#Return Largest fragment as final mutated molecule
mol_frags = Chem.GetMolFrags(StartingMolecule, asMols=True)
StartingMolecule = max(mol_frags, default=StartingMolecule, key=lambda m: m.GetNumAtoms())
StartingMolecule = Chem.RWMol(StartingMolecule) #Need to convert back to editable mol to use with 'MolCheckandPlot'
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited,
StartingMolecule,
showdiff)
except Exception as E:
if Verbose:
print(E)
print('Remove Aromatic ring failed, returning empty objects')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
StartingMoleculeAtoms = StartingMolecule.GetAtoms()
AtomIdxs = [x.GetIdx() for x in StartingMoleculeAtoms if x.GetIdx() not in AromaticAtoms]
# Need to check and remove atom indexes where the atom is bonded to an atom that is aromatic
UnwantedAtomIdxs = []
for AtIdx in AtomIdxs:
Check_Atom = StartingMolecule.GetAtomWithIdx(AtIdx)
Neighbors = Check_Atom.GetNeighbors()
for Neighbor in Neighbors:
if Neighbor.IsInRing() == True or len(Neighbors) <= 1:
UnwantedAtomIdxs.append(AtIdx)
# Save indexes of atoms that are neither aromatic nor bonded to an aromatic atom
FinalAtomIdxs = [x for x in AtomIdxs if x not in UnwantedAtomIdxs]
# Select two random atoms for fragmentation
selected_atoms = random.sample(FinalAtomIdxs, 2)
# Get bonds of selected atoms
SeveringBonds = []
for atomidx in selected_atoms:
atom = StartingMolecule.GetAtomWithIdx(atomidx)
BondIdxs = [x.GetIdx() for x in atom.GetBonds()]
SeveringBonds.append(random.sample(FinalAtomIdxs, 1))
# Save index of atom on other side of chosen bond that was severed
SeveringBonds = [x[0] for x in SeveringBonds]
for b_idx in SeveringBonds:
b = StartingMolecule.GetBondWithIdx(b_idx)
StartingMolecule.RemoveBond(b.GetBeginAtomIdx(), b.GetEndAtomIdx())
frags = Chem.GetMolFrags(StartingMolecule)
# Only proceed if the removed fragment is less than a quarter the length of the molecule
if len(frags)==3 and len(frags[1]) <= len(StartingMoleculeUnedited.GetAtoms())*0.4 and len(frags[1]) >= 2:
Mol1 = frags[0]
Mol2 = frags[-1]
# Get rid of atoms in mol fragments that are aromatic or bonded to an aromatic
#Need to get highest atom index in molecule that isn't in an aromatic ring
Mol1 = [x for x in Mol1 if x in FinalAtomIdxs]
Mol2 = [x for x in Mol2 if x in FinalAtomIdxs]
StartingMolecule = Chem.RWMol(StartingMolecule)
StartingMolecule.AddBond(Mol1[-1], Mol2[0], rnd(BondTypes))
mol_frags = Chem.GetMolFrags(StartingMolecule, asMols=True)
#Return the largest fragment as the final molecule
StartingMolecule = max(mol_frags, default=StartingMolecule, key=lambda m: m.GetNumAtoms())
StartingMolecule = Chem.RWMol(StartingMolecule) #Need to convert back to editable mol to use with 'MolCheckandPlot'
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited,
StartingMolecule,
showdiff)
else:
if Verbose:
print('Remove fragment failed, returning empty objects')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
except Exception as E:
if Verbose:
print(E)
print('Remove fragment failed, returning empty objects')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
try:
Mut_Mol
except:
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
return Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES
def Mol_Crossover(StartingMolecule, CrossMol, showdiff=False, Verbose=False):
try:
"""
Take in two molecules, the molecule to be mutated, and a list of molecules to crossover with?
Randomly fragment each molecule
Create bond between randomly selected atoms on the molecule
Need to make sure that we are not bonding an aromatic to an aromatic
Write code to save which molecule was crossed over with
"""
StartingMoleculeUnedited = deepcopy(StartingMolecule)
StartingMolecule = Chem.RWMol(StartingMoleculeUnedited)
CrossMolecule = Chem.RWMol(CrossMol)
# Need to check and remove atom indexes where the atom is bonded to an atom that is aromatic
#StartMol
StartMolRI = StartingMolecule.GetRingInfo()
StartMolAromaticBonds = StartMolRI.BondRings()
StartMolAromaticBondsList = []
for tup in StartMolAromaticBonds:
for bond in tup:
StartMolAromaticBondsList.append(int(bond))
StartMolBondIdxs = [int(x.GetIdx()) for x in StartingMolecule.GetBonds()]
StartMolBondIdxsFinal = [x for x in StartMolBondIdxs if x not in StartMolAromaticBondsList]
StartMolSelectedBond = StartingMolecule.GetBondWithIdx(rnd(StartMolBondIdxsFinal))
StartingMolecule.RemoveBond(StartMolSelectedBond.GetBeginAtomIdx(), StartMolSelectedBond.GetEndAtomIdx())
StartMolFrags = Chem.GetMolFrags(StartingMolecule, asMols=True)
StartingMolecule = max(StartMolFrags, default=StartingMolecule, key=lambda m: m.GetNumAtoms())
#CrossMol
CrossMolRI = CrossMolecule.GetRingInfo()
CrossMolAromaticBonds = CrossMolRI.BondRings()
CrossMolAromaticBondsList = []
for tup in CrossMolAromaticBonds:
for bond in tup:
CrossMolAromaticBondsList.append(int(bond))
CrossMolBondIdxs = [int(x.GetIdx()) for x in CrossMolecule.GetBonds()]
CrossMolBondIdxsFinal = [x for x in CrossMolBondIdxs if x not in CrossMolAromaticBondsList]
CrossMolSelectedBond = CrossMolecule.GetBondWithIdx(rnd(CrossMolBondIdxsFinal))
CrossMolecule.RemoveBond(CrossMolSelectedBond.GetBeginAtomIdx(), CrossMolSelectedBond.GetEndAtomIdx())
CrossMolFrags = Chem.GetMolFrags(CrossMolecule, asMols=True)
CrossMolecule = max(CrossMolFrags, default=CrossMolecule, key=lambda m: m.GetNumAtoms())
InsertStyle = rnd(['Within', 'Egde'])
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES, StartingMoleculeUnedited = AddFragment(StartingMolecule,
CrossMolecule,
InsertStyle,
showdiff,
Verbose)
except Exception as E:
print(E)
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES, StartingMoleculeUnedited = None, None, None, None
return Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES, StartingMoleculeUnedited
def RemoveAtom(StartingMolecule, BondTypes, fromAromatic=False, showdiff=True):
"""
Function to replace atom from a selected list of atoms from a starting molecule.
Args:
- StartingMolecule: SMILES String of Starting Molecule
- FromAromatic: If True, will remove atoms from aromatic rings
Steps:
1. Get the indexes of all the bonds in the molecule
2. Check if there are any atoms that are aromatic
3. Select index of atom that will be replaced, from list of atoms with one or two neighbors only
4. Get bond and bondtype of bonds selected atom has with its neighbor(s)
5. If selected atom has one neighbor, remove atom and return edited molecule
6. If selected atom has two neighbors:
a. Get indexes of atoms bonded to selected atom
b. Randomly select bond type to create between left over atoms
c. Remove selected atom and create new bond of selected bond type between left over atoms
"""
StartingMoleculeUnedited = deepcopy(StartingMolecule)
#try:
# Store indexes of atoms in molecule
AtomIdxs = []
# Check if starting molecule is completely aromatic
for atom in StartingMoleculeUnedited.GetAtoms():
if len((StartingMoleculeUnedited.GetAromaticAtoms())) == len(StartingMoleculeUnedited.GetAtoms()):
print('Starting molecule is completely aromatic')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
AtomIdxs.append(atom.GetIdx())
# Make editable mol object from starting molecule
StartingMolecule = Chem.RWMol(StartingMoleculeUnedited)
# Get number of bonds each atom in the molecule has and storing them in separate objects
OneBondAtomsMolecule = []
TwoBondAtomsMolecule = []
AromaticAtomsMolecule = []
# Getting atoms in starting molecule with different amount of bonds, storing indexes in list
for index in AtomIdxs:
Atom = StartingMolecule.GetAtomWithIdx(int(index))
if Atom.GetIsAromatic() and len(Atom.GetBonds()) == 2:
AromaticAtomsMolecule.append(index)
elif len(Atom.GetBonds()) == 2:
TwoBondAtomsMolecule.append(index)
elif len(Atom.GetBonds()) == 1:
OneBondAtomsMolecule.append(index)
else:
continue
#Select atom to be deleted from list of atom indexes, check that this list is greater than 0
if len(AtomIdxs) == 0:
print('Empty Atom Index List')
Mut_Mol = None
Mut_Mol_Sanitized = None
MutMolSMILES = None
elif fromAromatic and len(AromaticAtomsMolecule) > 0 and len(OneBondAtomsMolecule) > 0 and len(TwoBondAtomsMolecule) > 0:
# Add the lists of the atoms with different numbers of bonds into one object
OneBondAtomsMolecule.extend(TwoBondAtomsMolecule).extend(AromaticAtomsMolecule)
Indexes = OneBondAtomsMolecule
RemoveAtomIdx = rnd(Indexes)
RemoveAtomNeigbors = StartingMolecule.GetAtomWithIdx(RemoveAtomIdx).GetNeighbors()
elif len(OneBondAtomsMolecule) > 0 and len(TwoBondAtomsMolecule) > 0:
#Select a random atom from the index of potential replacement atoms that aren't aromatic
OneBondAtomsMolecule.extend(TwoBondAtomsMolecule)
Indexes = OneBondAtomsMolecule
RemoveAtomIdx = rnd(Indexes)
RemoveAtomNeigbors = StartingMolecule.GetAtomWithIdx(RemoveAtomIdx).GetNeighbors()
if len(RemoveAtomNeigbors) == 1:
StartingMolecule.RemoveAtom(RemoveAtomIdx)
elif len(RemoveAtomNeigbors) == 2:
try:
StartingMolecule.RemoveAtom(RemoveAtomIdx)
StartingMolecule.AddBond(RemoveAtomNeigbors[0].GetIdx(), RemoveAtomNeigbors[1].GetIdx(), rnd(BondTypes))
except:
print('Error adding bond between atoms in Remove Atom function, bond may already exist')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
print('Removed atom has illegal number of neighbors')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
# Check number of heavy atoms before and after, should have reduced by one
if StartingMoleculeUnedited.GetNumHeavyAtoms() == StartingMolecule.GetNumHeavyAtoms():
print('Atom removal failed, returning empty object')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
# Check what atom was removed from where
print(f'{StartingMoleculeUnedited.GetAtomWithIdx(RemoveAtomIdx).GetSymbol()} removed from position {RemoveAtomIdx}')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited, StartingMolecule, showdiff)
else:
print('Atom removal failed, returning empty object')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
# except:
# print('Atom removal could not be performed, returning empty objects')
# Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
return Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES, StartingMoleculeUnedited
def InsertAromatic(StartingMolecule, AromaticMolecule, InsertStyle='Within', showdiff=False, Verbose=False):
"""
Function to insert an aromatic atom into a starting molecule
4. If inserting aromatic ring:
- Check if fragment is aromatic
- Combine starting molecule and fragment into single disconnected Mol object
- Split atom indexes of starting molecule and fragment and save in different objects
- Check number of bonds each atom has in starting molecule and fragment, exclude any atoms that don't have
exactly two bonds
- Randomly select one of 2-bonded atoms and store the index of the Atom, and store bond objects of atom's bonds
- Get the atom neighbors of selected atom
- Remove selected atom
- Select two unique atoms from cyclic atom
- Create a new bond between each of the neighbors of the removed atom and each of the terminal atoms on the
fragment
"""
print(f'InsertStyle is: {InsertStyle}')
StartingMoleculeUnedited = deepcopy(StartingMolecule)
Fragment = AromaticMolecule
#Always check if fragment or starting molecule is a cyclic (benzene) molecule
try:
if len(Fragment.GetAromaticAtoms()) != len(Fragment.GetAtoms()):
if Verbose:
print('Fragment is not cyclic')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
elif len((StartingMoleculeUnedited.GetAromaticAtoms())) == len(StartingMoleculeUnedited.GetAtoms()):
if Verbose:
print('Starting molecule is completely aromatic')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
Chem.SanitizeMol(Fragment)
# Add fragment to Mol object of starting molecule
StartingMolecule = Chem.RWMol(StartingMoleculeUnedited)
StartingMolecule.InsertMol(Fragment)
# Get indexes of starting molecule and fragment, store them in separate objects
frags = Chem.GetMolFrags(StartingMolecule)
StartMolIdxs = frags[0]
FragIdxs = frags[1]
OneBondAtomsMolecule = []
TwoBondAtomsMolecule = []
AromaticAtomsMolecule = []
# Getting atoms in starting molecule with different amount of bonds, storing indexes in lists
for index in StartMolIdxs:
Atom = StartingMolecule.GetAtomWithIdx(int(index))
if Atom.GetIsAromatic():
AromaticAtomsMolecule.append(index)
if len(Atom.GetBonds()) == 2:
TwoBondAtomsMolecule.append(index)
elif len(Atom.GetBonds()) == 1:
OneBondAtomsMolecule.append(index)
else:
continue
if InsertStyle == 'Within':
# Randomly choose two unique atoms from aromatic molecule
ArmtcAtoms = sample(FragIdxs, 2)
# Select random two bonded atom
AtomRmv = rnd(TwoBondAtomsMolecule)
# Get atom neighbor indexes, remove bonds between selected atom and neighbors
neighbors = [x.GetIdx() for x in StartingMolecule.GetAtomWithIdx(AtomRmv).GetNeighbors()]
# Randomly choose which bond of target atom to sever
SeverIdx = rnd([0,1])
# Sever the selected bond
StartingMolecule.RemoveBond(neighbors[SeverIdx], AtomRmv)
#For situation where bond before target atom is severed
if SeverIdx == 0:
StartingMolecule.AddBond(ArmtcAtoms[0], AtomRmv - 1, Chem.BondType.SINGLE)
StartingMolecule.AddBond(ArmtcAtoms[1], AtomRmv, Chem.BondType.SINGLE)
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited,
StartingMolecule,
showdiff)
#For situation where bond after target atom is severed
else:
StartingMolecule.AddBond(ArmtcAtoms[0], AtomRmv + 1, Chem.BondType.SINGLE)
StartingMolecule.AddBond(ArmtcAtoms[1], AtomRmv, Chem.BondType.SINGLE)
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited,
StartingMolecule,
showdiff)
elif InsertStyle == 'Edge':
if len(OneBondAtomsMolecule) == 0:
print('No one-bonded terminal atoms in starting molecule, returning empty object')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
else:
# Randomly choose two unique atoms from aromatic molecule
ArmtcAtoms = rnd(FragIdxs)
# Select random one bonded atom
AtomRmv = rnd(OneBondAtomsMolecule)
StartingMolecule.AddBond(ArmtcAtoms, AtomRmv, Chem.BondType.SINGLE)
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = MolCheckandPlot(StartingMoleculeUnedited,
StartingMolecule,
showdiff)
else:
print('Edge case, returning empty objects')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
except:
print('Index error, starting molecule probably too short, trying different mutation')
Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES = None, None, None
return Mut_Mol, Mut_Mol_Sanitized, MutMolSMILES, StartingMoleculeUnedited
def Mutate(StartingMolecule, Mutation, AromaticMolecule, AtomicNumbers, BondTypes,
Atoms, showdiff, Fragments, Napthalenes, Mols):
print(f'Mutation being performed: {Mutation}')
if Mutation == 'AddAtom':
result = AddAtom(StartingMolecule, AtomicNumbers, BondTypes, showdiff=showdiff)
elif Mutation == 'ReplaceAtom':
result = ReplaceAtom(StartingMolecule, Atoms, fromAromatic=False, showdiff=showdiff)
elif Mutation == 'ReplaceBond':
result = ReplaceBond(StartingMolecule, BondTypes, showdiff=showdiff)
elif Mutation == 'RemoveAtom':
result = RemoveAtom(StartingMolecule, BondTypes, fromAromatic=False, showdiff=showdiff)
elif Mutation == 'AddFragment':
InsertStyle = rnd(['Within', 'Egde'])
result = AddFragment(StartingMolecule, rnd(Fragments), InsertStyle=InsertStyle, showdiff=showdiff)
elif Mutation == 'Napthalenate':
InsertStyle = rnd(['Within', 'Egde'])
result = Napthalenate(StartingMolecule, rnd(Napthalenes), InsertStyle=InsertStyle, showdiff=showdiff)
elif Mutation == 'Glycolate':
InsertStyle = rnd(['Within', 'Egde'])
result = Glycolate(StartingMolecule, InsertStyle=InsertStyle, showdiff=showdiff)
elif Mutation == 'Esterify':
InsertStyle = rnd(['Within', 'Egde'])
result = Esterify(StartingMolecule, InsertStyle=InsertStyle, showdiff=showdiff)
elif Mutation == 'RemoveFragment':
result = RemoveFragment(StartingMolecule, BondTypes)
elif Mutation == 'ReplaceCandidate':
result = ReplaceCandidate(Mols, BondTypes, AtomicNumbers, Atoms, Fragments,
Napthalenes, AromaticMolecule, showdiff)
else:
InsertStyle = rnd(['Within', 'Egde'])
result = InsertAromatic(StartingMolecule, AromaticMolecule, showdiff=showdiff, InsertStyle=InsertStyle)
return result
def CheckSubstruct(MutMol):
### Check for unwanted substructures
#Checking for sequential oxgens
SingleBondOxygens = MutMol.HasSubstructMatch(Chem.MolFromSmarts('OO'))
DoubleBondOxygens = MutMol.HasSubstructMatch(Chem.MolFromSmarts('O=O'))
DoubleCDoubleO = MutMol.HasSubstructMatch(Chem.MolFromSmarts('C=C=O'))
DoubleCDoubleC = MutMol.HasSubstructMatch(Chem.MolFromSmarts('C=C=C'))
BridgeHead = MutMol.HasSubstructMatch(Chem.MolFromSmarts('c-c'))
### Remove C=C bonds that aren't aromatic
# Check for sequence of single or double bonded oxygens or Bridgehead carbonds
if SingleBondOxygens or DoubleBondOxygens or DoubleCDoubleO or DoubleCDoubleC or BridgeHead:
print('Undesirable substructure found, returning empty object')
return True
else:
return False
def runcmd(cmd, verbose = False, *args, **kwargs):
#bascially allows python to run a bash command, and the code makes sure
#the error of the subproceess is communicated if it fails
process = subprocess.run(
cmd,
text=True,
shell=True)
return process
def GeneratePDB(SMILES, PATH, CONFORMATTEMPTS=10):
"""
Function that generates PDB file from RDKit Mol object, for use with Packmol
Inputs:
- SMILES: SMILES string to be converted to PDB
- PATH: Location that the PDB will stored
- CONFORMATTEMPTS: Max number of tries (x5000) to find converged conformer for molecule
"""
SMILESMol = Chem.MolFromSmiles(SMILES) # Create mol object
SMILESMol = Chem.AddHs(SMILESMol) # Need to make Hydrogens explicit
AllChem.EmbedMolecule(SMILESMol, AllChem.ETKDG()) #Create conformer using ETKDG method
# Initial parameters for conformer optimisation
MMFFSMILES = 1
ConformAttempts = 1
MaxConformAttempts = CONFORMATTEMPTS
# Ensure that script continues to iterate until acceptable conformation found
while MMFFSMILES !=0 and ConformAttempts <= MaxConformAttempts: # Checking if molecule converged
MMFFSMILES = Chem.rdForceFieldHelpers.MMFFOptimizeMolecule(SMILESMol, maxIters=5000)