/
fmcs.py
2824 lines (2259 loc) · 103 KB
/
fmcs.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 python
# This work was funded by Roche and generously donated to the free
# and open source cheminformatics community.
## Copyright (c) 2012 Andrew Dalke Scientific AB
## Andrew Dalke <dalke@dalkescientific.com>
##
## All rights reserved.
##
## Redistribution and use in source and binary forms, with or without
## modification, are permitted provided that the following conditions are
## met:
##
## * Redistributions of source code must retain the above copyright
## notice, this list of conditions and the following disclaimer.
##
## * Redistributions in binary form must reproduce the above copyright
## notice, this list of conditions and the following disclaimer in
## the documentation and/or other materials provided with the
## distribution.
##
## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
## HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""FMCS - Find Maximum Common Substructure
This software finds the maximum common substructure of a set of
structures and reports it as a SMARTS strings.
This implements what I think is a new algorithm for the MCS problem.
The core description is:
best_substructure = None
pick one structure as the query, and other as the targets
for each substructure in the query graph:
convert it to a SMARTS string based on the desired match properties
if the SMARTS pattern exists in all of the targets:
then this is a common substructure
keep track of the maximum such common structure,
The SMARTS string depends on the desired match properties. For
example, if ring atoms are only allowed to match ring atoms then an
aliphatic ring carbon in the query is converted to the SMARTS "[C;R]",
and the double-bond ring bond converted to "=;@" while the respectice
chain-only version are "[C;!R]" and "=;!@".
The algorithm I outlined earlier will usually take a long time. There
are several ways to speed it up.
== Bond elimination ==
As the first step, remove bonds which obviously cannot be part of the
MCS.
This requires atom and bond type information, which I store as SMARTS
patterns. A bond can only be in the MCS if its canonical bond type is
present in all of the structures. A bond type is string made of the
SMARTS for one atom, the SMARTS for the bond, and the SMARTS for the
other atom. The canonical bond type is the lexographically smaller of
the two possible bond types for a bond.
The atom and bond SMARTS depend on the type comparison used.
The "ring-matches-ring-only" option adds an "@" or "!@" to the bond
SMARTS, so that the canonical bondtype for "C-C" becomes [#6]-@[#6] or
[#6]-!@[#6] if the bond is in a ring or not in a ring, and if atoms
are compared by element and bonds are compared by bondtype. (This
option does not add "R" or "!R" to the atom SMARTS because there
should be a single bond in the MCS of c1ccccc1O and CO.)
The result of all of this atom and bond typing is a "TypedMolecule"
for each input structure.
I then find which canonical bondtypes are present in all of the
structures. I convert each TypedMolecule into a
FragmentedTypedMolecule which has the same atom information but only
those bonds whose bondtypes are in all of the structures. This can
break a structure into multiple, disconnected fragments, hence the
name.
(BTW, I would like to use the fragmented molecules as the targets
because I think the SMARTS match would go faster, but the RDKit SMARTS
matcher doesn't like them. I think it's because the new molecule
hasn't been sanitized and the underlying data structure the ring
information doesn't exist. Instead, I use the input structures for the
SMARTS match.)
== Use the structure with the smallest largest fragment as the query ==
== and sort the targets by the smallest largest fragment ==
I pick one of the FragmentedTypedMolecule instances as the source of
substructure enumeration. Which one?
My heuristic is to use the one with the smallest largest fragment.
Hopefully it produces the least number of subgraphs, but that's also
related to the number of rings, so a large linear graph will product
fewer subgraphs than a small fused ring system. I don't know how to
quantify that.
For each of the fragmented structures, I find the number of atoms in
the fragment with the most atoms, and I find the number of bonds in
the fragment with the most bonds. These might not be the same
fragment.
I sort the input structures by the number of bonds in the largest
fragment, with ties broken first on the number of atoms, and then on
the input order. The smallest such structure is the query structure,
and the remaining are the targets.
== Use a breadth-first search and a priority queue to ==
== enumerate the fragment subgraphs ==
I extract each of the fragments from the FragmentedTypedMolecule into
a TypedFragment, which I use to make an EnumerationMolecule. An
enumeration molecule contains a pair of directed edges for each atom,
which simplifies the enumeration algorithm.
The enumeration algorithm is based around growing a seed. A seed
contains the current subgraph atoms and bonds as well as an exclusion
set of bonds which cannot be used for future grown. The initial seed
is the first bond in the fragment, which may potentially grow to use
the entire fragment. The second seed is the second bond in the
fragment, which is excluded from using the first bond in future
growth. The third seed starts from the third bond, which may not use
the first or second bonds during growth, and so on.
A seed can grow along bonds connected to an atom in the seed but which
aren't already in the seed and aren't in the set of excluded bonds for
the seed. If there are no such bonds then subgraph enumeration ends
for this fragment. Given N bonds there are 2**N-1 possible ways to
grow, which is just the powerset of the available bonds, excluding the
no-growth case.
This breadth-first growth takes into account all possibilties of using
the available N bonds so all of those bonds are added to the exclusion
set of the newly expanded subgraphs.
For performance reasons, the bonds used for growth are separated into
'internal' bonds, which connect two atoms already in the subgraph, and
'external' bonds, which lead outwards to an atom not already in the
subgraph.
Each seed growth can add from 0 to N new atoms and bonds. The goal is
to maximize the subgraph size so the seeds are stored in a priority
queue, ranked so the seed with the most bonds is processed first. This
turns the enumeration into something more like a depth-first search.
== Prune seeds which aren't found in all of the structures ==
At each stage of seed growth I check that the new seed exists in all
of the original structures. (Well, all except the one which I
enumerate over in the first place; by definition that one will match.)
If it doesn't match then there's no reason to include this seed or any
larger seeds made from it.
The check is easy; I turn the subgraph into its corresponding SMARTS
string and use RDKit's normal SMARTS matcher to test for a match.
There are three ways to generate a SMARTS string: 1) arbitrary, 2)
canonical, 3) hybrid.
I have not tested #1. During most of the development I assumed that
SMARTS matches across a few hundred structures would be slow, so that
the best solution is to generate a *canonical* SMARTS and cache the
match information.
Well, it turns out that my canonical SMARTS match code takes up most
of the FMCS run-time. If I drop the canonicalization step then the
code averages about 5-10% faster. This isn't the same as #1 - I still
do the initial atom assignment based on its neighborhood, which is
like a circular fingerprint of size 2 and *usually* gives a consistent
SMARTS pattern, which I can then cache.
However, there are times when the non-canonical SMARTS code is slower.
Obviously one is if there are a lot of structures, and another if is
there is a lot of symmetry. I'm still working on characterizing this.
== Maximize atoms? or bonds? ==
The above algorithm enumerates all subgraphs of the query and
identifies those subgraphs which are common to all input structures.
It's trivial then to keep track of the current "best" subgraph, which
can defined as having the subgraph with the most atoms, or the most
bonds. Both of those options are implemented.
It would not be hard to keep track of all other subgraphs which are
the same size.
== --complete-ring-only implementation ==
The "complete ring only" option is implemented by first enabling the
"ring-matches-ring-only" option, as otherwise it doesn't make sense.
Second, in order to be a "best" subgraph, all bonds in the subgraph
which are ring bonds in the original molecule must also be in a ring
in the subgraph. This is handled as a post-processing step.
(Note: some possible optimizations, like removing ring bonds from
structure fragments which are not in a ring, are not yet implemented.)
== Prune seeds which have no potential for growing large enough ==
Given a seed, its set of edges available for growth, and the set of
excluded bonds, figure out the maximum possible growth for the seed.
If this maximum possible is less than the current best subgraph then
prune.
This requires a graph search, currently done in Python, which is a bit
expensive. To speed things up, I precompute some edge information.
That is, if I know that a given bond is a chain bond (not in a ring)
then I can calculate the maximum number of atoms and bonds for seed
growth along that bond, in either direction. However, precomputation
doesn't take into account the excluded bonds, so after a while the
predicted value is too high.
Again, I'm still working on characterizing this, and an implementation
in C++ would have different tradeoffs.
"""
__version__ = "1.1"
__version_info = (1, 1, 0)
import sys
try:
from rdkit import Chem
except ImportError:
sys.stderr.write("Please install RDKit from http://www.rdkit.org/\n")
raise
import copy
import itertools
import re
import time
import weakref
from collections import Counter, defaultdict, namedtuple
from heapq import heapify, heappop, heappush
from itertools import chain, combinations
### A place to set global options
# (Is this really useful?)
class Default(object):
timeout = None
timeoutString = "none"
maximize = "bonds"
atomCompare = "elements"
bondCompare = "bondtypes"
matchValences = False
ringMatchesRingOnly = False
completeRingsOnly = False
####### Atom type and bond type information #####
# Lookup up the atomic symbol given its atomic number
_get_symbol = Chem.GetPeriodicTable().GetElementSymbol
# Lookup table to get the SMARTS for an atom given its element
# This uses the '#<n>' notation for atoms which may be aromatic.
# Eg, '#6' for carbon, instead of 'C,c'.
# Use the standard element symbol for atoms which can't be aromatic.
class AtomSmartsNoAromaticity(dict):
def __missing__(self, eleno):
value = _get_symbol(eleno)
self[eleno] = value
return value
_atom_smarts_no_aromaticity = AtomSmartsNoAromaticity()
# Initialize to the ones which need special treatment
# RDKit supports b, c, n, o, p, s, se, and te.
# Daylight and OpenSMILES don't 'te' but do support 'as'
# I don't want 'H'-is-hydrogen to get confused with 'H'-as-has-hydrogens.
# For better portability, I use the '#' notation for all of them.
for eleno in (1, 5, 6, 7, 8, 15, 16, 33, 34, 52):
_atom_smarts_no_aromaticity[eleno] = "#" + str(eleno)
assert _atom_smarts_no_aromaticity[6] == "#6"
assert _atom_smarts_no_aromaticity[2] == "He"
# Match any atom
def atom_typer_any(atoms):
return ["*"] * len(atoms)
# Match atom by atomic element; usually by symbol
def atom_typer_elements(atoms):
return [_atom_smarts_no_aromaticity[atom.GetAtomicNum()] for atom in atoms]
# Match atom by isotope number. This depends on the RDKit version
if hasattr(Chem.Atom, "GetIsotope"):
def atom_typer_isotopes(atoms):
return ["%d*" % atom.GetIsotope() for atom in atoms]
else:
# Before mid-2012, RDKit only supported atomic mass, not isotope.
# [12*] matches atoms whose mass is 12.000 +/- 0.5/1000
# This generally works, excepting elements which have no
# Tc, Pm, Po, At, Rn, Fr, Ra, Ac, Np, Pu, Am, Cm,
# Bk, Cf, Es, Fm, Md, No, Lr
# natural abundance; [98Tc] is the same as [Tc], etc.
# This leads to problems because I don't have a way to
# define the SMARTS for "no defined isotope." In SMILES/SMARTS
# that's supposed to be through isotope 0.
# The best I can do is force the non-integer masses to 0 and
# use isotope 0 to match them. That's clumsy, but it gives
# the expected result.
def atom_typer_isotopes(atoms):
atom_smarts_types = []
for atom in atoms:
mass = atom.GetMass()
int_mass = int(round(mass * 1000))
if int_mass % 1000 == 0:
# This is close enough that RDKit's match will work
atom_smarts = "%d*" % (int_mass // 1000)
else:
# Probably in natural abundance. In any case,
# there's no SMARTS for this pattern, so force
# everything to 0.
atom.SetMass(0.0) # XX warning; in-place modification of the input!
atom_smarts = "0*"
atom_smarts_types.append(atom_smarts)
return atom_smarts_types
# Match any bond
def bond_typer_any(bonds):
return ["~"] * len(bonds)
# Match bonds based on bond type, including aromaticity
def bond_typer_bondtypes(bonds):
# Aromaticity matches are important
bond_smarts_types = []
for bond in bonds:
bond_term = bond.GetSmarts()
if not bond_term:
# The SMILES "", means "single or aromatic" as SMARTS.
# Figure out which one.
if bond.GetIsAromatic():
bond_term = ':'
else:
bond_term = '-'
bond_smarts_types.append(bond_term)
return bond_smarts_types
atom_typers = {
"any": atom_typer_any,
"elements": atom_typer_elements,
"isotopes": atom_typer_isotopes,
}
bond_typers = {
"any": bond_typer_any,
"bondtypes": bond_typer_bondtypes,
}
default_atom_typer = atom_typers[Default.atomCompare]
default_bond_typer = bond_typers[Default.bondCompare]
####### Support code for handling user-defined atom classes
# User-defined atom classes are handled in a round-about fashion. The
# fmcs code doesn't know atom classes, but it can handle isotopes.
# It's easy to label the atom isotopes and do an "isotopes" atom
# comparison. The hard part is if you want to get the match
# information back using the original structure data, without the
# tweaked isotopes.
# My solution uses "save_isotopes" and "save_atom_classes" to store
# the old isotope information and the atom class assignments (both
# ordered by atom position), associated with the molecule.
# Use "restore_isotopes()" to restore the molecule's isotope values
# from the saved values. Ise "get_selected_atom_classes" to get the
# atom classes used by specified atom indices.
if hasattr(Chem.Atom, "GetIsotope"):
def get_isotopes(mol):
return [atom.GetIsotope() for atom in mol.GetAtoms()]
def set_isotopes(mol, isotopes):
if mol.GetNumAtoms() != len(isotopes):
raise ValueError("Mismatch between the number of atoms and the number of isotopes")
for atom, isotope in zip(mol.GetAtoms(), isotopes):
atom.SetIsotope(isotope)
else:
# Backward compatibility. Before mid-2012, RDKit only supported atomic mass, not isotope.
def get_isotopes(mol):
return [atom.GetMass() for atom in mol.GetAtoms()]
def set_isotopes(mol, isotopes):
if mol.GetNumAtoms() != len(isotopes):
raise ValueError("Mismatch between the number of atoms and the number of isotopes")
for atom, isotope in zip(mol.GetAtoms(), isotopes):
atom.SetMass(isotope)
_isotope_dict = weakref.WeakKeyDictionary()
_atom_class_dict = weakref.WeakKeyDictionary()
def save_isotopes(mol, isotopes):
_isotope_dict[mol] = isotopes
def save_atom_classes(mol, atom_classes):
_atom_class_dict[mol] = atom_classes
def get_selected_atom_classes(mol, atom_indices):
atom_classes = _atom_class_dict.get(mol, None)
if atom_classes is None:
return None
return [atom_classes[index] for index in atom_indices]
def restore_isotopes(mol):
try:
isotopes = _isotope_dict[mol]
except KeyError:
raise ValueError("no isotopes to restore")
set_isotopes(mol, isotopes)
def assign_isotopes_from_class_tag(mol, atom_class_tag):
try:
atom_classes = mol.GetProp(atom_class_tag)
except KeyError:
raise ValueError("Missing atom class tag %r" % (atom_class_tag, ))
fields = atom_classes.split()
if len(fields) != mol.GetNumAtoms():
raise ValueError(
"Mismatch between the number of atoms (#%d) and the number of atom classes (%d)" %
(mol.GetNumAtoms(), len(fields)))
new_isotopes = []
for field in fields:
if not field.isdigit():
raise ValueError("Atom class %r from tag %r must be a number" % (field, atom_class_tag))
isotope = int(field)
if not (1 <= isotope <= 10000):
raise ValueError("Atom class %r from tag %r must be in the range 1 to 10000" %
(field, atom_class_tag))
new_isotopes.append(isotope)
save_isotopes(mol, get_isotopes(mol))
save_atom_classes(mol, new_isotopes)
set_isotopes(mol, new_isotopes)
### Different ways of storing atom/bond information about the input structures ###
# A TypedMolecule contains the input molecule, unmodified, along with
# atom type, and bond type information; both as SMARTS fragments. The
# "canonical_bondtypes" uniquely characterizes a bond; two bonds will
# match if and only if their canonical bondtypes match. (Meaning:
# bonds must be of equivalent type, and must go between atoms of
# equivalent types.)
class TypedMolecule(object):
def __init__(self, rdmol, rdmol_atoms, rdmol_bonds, atom_smarts_types, bond_smarts_types,
canonical_bondtypes):
self.rdmol = rdmol
# These exist as a performance hack. It's faster to store the
# atoms and bond as a Python list than to do GetAtoms() and
# GetBonds() again. The stage 2 TypedMolecule does not use
# these.
self.rdmol_atoms = rdmol_atoms
self.rdmol_bonds = rdmol_bonds
# List of SMARTS to use for each atom and bond
self.atom_smarts_types = atom_smarts_types
self.bond_smarts_types = bond_smarts_types
# List of canonical bondtype strings
self.canonical_bondtypes = canonical_bondtypes
# Question: Do I also want the original_rdmol_indices? With
# the normal SMARTS I can always do the substructure match
# again to find the indices, but perhaps this will be needed
# when atom class patterns are fully implemented.
# Start with a set of TypedMolecules. Find the canonical_bondtypes
# which only exist in all them, then fragment each TypedMolecule to
# produce a FragmentedTypedMolecule containing the same atom
# information but containing only bonds with those
# canonical_bondtypes.
class FragmentedTypedMolecule(object):
def __init__(self, rdmol, rdmol_atoms, orig_atoms, orig_bonds, atom_smarts_types,
bond_smarts_types, canonical_bondtypes):
self.rdmol = rdmol
self.rdmol_atoms = rdmol_atoms
self.orig_atoms = orig_atoms
self.orig_bonds = orig_bonds
# List of SMARTS to use for each atom and bond
self.atom_smarts_types = atom_smarts_types
self.bond_smarts_types = bond_smarts_types
# List of canonical bondtype strings
self.canonical_bondtypes = canonical_bondtypes
# A FragmentedTypedMolecule can contain multiple fragments. Once I've
# picked the FragmentedTypedMolecule to use for enumeration, I extract
# each of the fragments as the basis for an EnumerationMolecule.
class TypedFragment(object):
def __init__(self, rdmol, orig_atoms, orig_bonds, atom_smarts_types, bond_smarts_types,
canonical_bondtypes):
self.rdmol = rdmol
self.orig_atoms = orig_atoms
self.orig_bonds = orig_bonds
self.atom_smarts_types = atom_smarts_types
self.bond_smarts_types = bond_smarts_types
self.canonical_bondtypes = canonical_bondtypes
# The two possible bond types are
# atom1_smarts + bond smarts + atom2_smarts
# atom2_smarts + bond smarts + atom1_smarts
# The canonical bond type is the lexically smaller of these two.
def get_canonical_bondtypes(rdmol, bonds, atom_smarts_types, bond_smarts_types):
canonical_bondtypes = []
for bond, bond_smarts in zip(bonds, bond_smarts_types):
atom1_smarts = atom_smarts_types[bond.GetBeginAtomIdx()]
atom2_smarts = atom_smarts_types[bond.GetEndAtomIdx()]
if atom1_smarts > atom2_smarts:
atom1_smarts, atom2_smarts = atom2_smarts, atom1_smarts
canonical_bondtypes.append("[%s]%s[%s]" % (atom1_smarts, bond_smarts, atom2_smarts))
return canonical_bondtypes
# Create a TypedMolecule using the element-based typing scheme
# TODO: refactor this. It doesn't seem right to pass boolean flags.
def get_typed_molecule(rdmol, atom_typer, bond_typer, matchValences=Default.matchValences,
ringMatchesRingOnly=Default.ringMatchesRingOnly):
atoms = list(rdmol.GetAtoms())
atom_smarts_types = atom_typer(atoms)
# Get the valence information, if requested
if matchValences:
new_atom_smarts_types = []
for (atom, atom_smarts_type) in zip(atoms, atom_smarts_types):
valence = atom.GetImplicitValence() + atom.GetExplicitValence()
valence_str = "v%d" % valence
if "," in atom_smarts_type:
atom_smarts_type += ";" + valence_str
else:
atom_smarts_type += valence_str
new_atom_smarts_types.append(atom_smarts_type)
atom_smarts_types = new_atom_smarts_types
# Store and reuse the bond information because I use it twice.
# In a performance test, the times went from 2.0 to 1.4 seconds by doing this.
bonds = list(rdmol.GetBonds())
bond_smarts_types = bond_typer(bonds)
if ringMatchesRingOnly:
new_bond_smarts_types = []
for bond, bond_smarts in zip(bonds, bond_smarts_types):
if bond.IsInRing():
if bond_smarts == ":":
# No need to do anything; it has to be in a ring
pass
else:
if "," in bond_smarts:
bond_smarts += ";@"
else:
bond_smarts += "@"
else:
if "," in bond_smarts:
bond_smarts += ";!@"
else:
bond_smarts += "!@"
new_bond_smarts_types.append(bond_smarts)
bond_smarts_types = new_bond_smarts_types
canonical_bondtypes = get_canonical_bondtypes(rdmol, bonds, atom_smarts_types, bond_smarts_types)
return TypedMolecule(rdmol, atoms, bonds, atom_smarts_types, bond_smarts_types,
canonical_bondtypes)
# Create a TypedMolecule using the user-defined atom classes (Not implemented!)
def get_specified_types(rdmol, atom_types, ringMatchesRingOnly):
raise NotImplementedError("not tested!")
# Make a copy because I will do some destructive edits
rdmol = copy.copy(rdmol)
atom_smarts_types = []
atoms = list(mol.GetAtoms())
for atom, atom_type in zip(atoms, atom_types):
atom.SetAtomicNum(0)
atom.SetMass(atom_type)
atom_term = "%d*" % (atom_type, )
if ringMatchesRingOnly:
if atom.IsInRing():
atom_term += "R"
else:
atom_term += "!R"
atom_smarts_types.append('[' + atom_term + ']')
bonds = list(rdmol.GetBonds())
bond_smarts_types = get_bond_smarts_types(mol, bonds, ringMatchesRingOnly)
canonical_bondtypes = get_canonical_bondtypes(mol, bonds, atom_smarts_types, bond_smarts_types)
return TypedMolecule(mol, atoms, bonds, atom_smarts_types, bond_smarts_types, canonical_bondtypes)
def convert_input_to_typed_molecules(mols, atom_typer, bond_typer, matchValences,
ringMatchesRingOnly):
typed_mols = []
for molno, rdmol in enumerate(mols):
typed_mol = get_typed_molecule(rdmol, atom_typer, bond_typer, matchValences=matchValences,
ringMatchesRingOnly=ringMatchesRingOnly)
typed_mols.append(typed_mol)
return typed_mols
def _check_atom_classes(molno, num_atoms, atom_classes):
if num_atoms != len(atom_classes):
raise ValueError("mols[%d]: len(atom_classes) must be the same as the number of atoms" %
(molno, ))
for atom_class in atom_classes:
if not isinstance(atom_class, int):
raise ValueError("mols[%d]: atom_class elements must be integers" % (molno, ))
if not (1 <= atom_class < 1000):
raise ValueError("mols[%d]: atom_class elements must be in the range 1 <= value < 1000" %
(molno, ))
#############################################
# This section deals with finding the canonical bondtype counts and
# making new TypedMolecule instances where the atoms contain only the
# bond types which are in all of the structures.
# In the future I would like to keep track of the bond types which are
# in the current subgraph. If any subgraph bond type count is ever
# larger than the maximum counts computed across the whole set, then
# prune. But so far I don't have a test set which drives the need for
# that.
# Return a dictionary mapping iterator item to occurrence count
def get_counts(it):
return dict(Counter(it))
# Merge two count dictionaries, returning the smallest count for any
# entry which is in both.
def intersect_counts(counts1, counts2):
d = {}
for k, v1 in counts1.items():
if k in counts2:
d[k] = min(v1, counts2[k])
return d
# Figure out which canonical bonds SMARTS occur in every molecule
def get_canonical_bondtype_counts(typed_mols):
overall_counts = defaultdict(list)
for typed_mol in typed_mols:
bondtype_counts = get_counts(typed_mol.canonical_bondtypes)
for k, v in bondtype_counts.items():
overall_counts[k].append(v)
return overall_counts
# If I know which bondtypes exist in all of the structures, I can
# remove all bonds which aren't in all structures. RDKit's Molecule
# class doesn't let me edit in-place, so I end up making a new one
# which doesn't have unsupported bond types.
def remove_unknown_bondtypes(typed_mol, supported_canonical_bondtypes):
emol = Chem.EditableMol(Chem.Mol())
# Copy all of the atoms, even those which don't have any bonds.
for atom in typed_mol.rdmol_atoms:
emol.AddAtom(atom)
# Copy over all the bonds with a supported bond type.
# Make sure to update the bond SMARTS and canonical bondtype lists.
orig_bonds = []
new_bond_smarts_types = []
new_canonical_bondtypes = []
for bond, bond_smarts, canonical_bondtype in zip(typed_mol.rdmol_bonds,
typed_mol.bond_smarts_types,
typed_mol.canonical_bondtypes):
if canonical_bondtype in supported_canonical_bondtypes:
orig_bonds.append(bond)
new_bond_smarts_types.append(bond_smarts)
new_canonical_bondtypes.append(canonical_bondtype)
emol.AddBond(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx(), bond.GetBondType())
new_mol = emol.GetMol()
return FragmentedTypedMolecule(new_mol, list(new_mol.GetAtoms()), typed_mol.rdmol_atoms,
orig_bonds, typed_mol.atom_smarts_types, new_bond_smarts_types,
new_canonical_bondtypes)
# The molecule at this point has been (potentially) fragmented by
# removing bonds with unsupported bond types. The MCS cannot contain
# more atoms than the fragment of a given molecule with the most
# atoms, and the same for bonds. Find those upper limits. Note that
# the fragment with the most atoms is not necessarily the one with the
# most bonds.
def find_upper_fragment_size_limits(rdmol, atoms):
max_num_atoms = 0
max_twice_num_bonds = 0
for atom_indices in Chem.GetMolFrags(rdmol):
max_num_atoms = max(max_num_atoms, len(atom_indices))
# Every bond is connected to two atoms, so this is the
# simplest way to count the number of bonds in the fragment.
twice_num_bonds = 0
for atom_index in atom_indices:
# XXX Why is there no 'atom.GetNumBonds()'?
# Ichiru Take: len(atoms[atom_index].GetBonds()) would be more efficient but I don't know the input type.
twice_num_bonds += len(atoms[atom_index].GetBonds())
max_twice_num_bonds = max(max_twice_num_bonds, twice_num_bonds)
return max_num_atoms, max_twice_num_bonds // 2
####### Convert the selected TypedMolecule into an EnumerationMolecule
# I convert one of the typed fragment molecules (specifically, the one
# with the smallest largest fragment score) into a list of
# EnumerationMolecule instances. Each fragment from the typed molecule
# gets turned into an EnumerationMolecule.
# An EnumerationMolecule contains the data I need to enumerate all of
# its subgraphs.
# An EnumerationMolecule contains a list of 'Atom's and list of 'Bond's.
# Atom and Bond indices are offsets into those respective lists.
# An Atom has a list of "bond_indices", which are offsets into the bonds.
# A Bond has a 2-element list of "atom_indices", which are offsets into the atoms.
EnumerationMolecule = namedtuple("Molecule", "rdmol atoms bonds directed_edges")
Atom = namedtuple("Atom", "real_atom atom_smarts bond_indices is_in_ring")
Bond = namedtuple("Bond", "real_bond bond_smarts canonical_bondtype atom_indices is_in_ring")
# A Bond is linked to by two 'DirectedEdge's; one for each direction.
# The DirectedEdge.bond_index references the actual RDKit bond instance.
# 'end_atom_index' is the index of the destination atom of the directed edge
# This is used in a 'directed_edges' dictionary so that
# [edge.end_atom_index for edge in directed_edges[atom_index]]
# is the list of all atom indices connected to 'atom_index'
DirectedEdge = namedtuple("DirectedEdge", "bond_index end_atom_index")
# A Subgraph is a list of atom and bond indices in an EnumerationMolecule
Subgraph = namedtuple("Subgraph", "atom_indices bond_indices")
def get_typed_fragment(typed_mol, atom_indices):
rdmol = typed_mol.rdmol
rdmol_atoms = typed_mol.rdmol_atoms
# I need to make a new RDKit Molecule containing only the fragment.
# XXX Why is that? Do I use the molecule for more than the number of atoms and bonds?
# Copy over the atoms
emol = Chem.EditableMol(Chem.Mol())
atom_smarts_types = []
atom_map = {}
for i, atom_index in enumerate(atom_indices):
atom = rdmol_atoms[atom_index]
emol.AddAtom(atom)
atom_smarts_types.append(typed_mol.atom_smarts_types[atom_index])
atom_map[atom_index] = i
# Copy over the bonds.
orig_bonds = []
bond_smarts_types = []
new_canonical_bondtypes = []
for bond, orig_bond, bond_smarts, canonical_bondtype in zip(rdmol.GetBonds(),
typed_mol.orig_bonds,
typed_mol.bond_smarts_types,
typed_mol.canonical_bondtypes):
begin_atom_idx = bond.GetBeginAtomIdx()
end_atom_idx = bond.GetEndAtomIdx()
count = (begin_atom_idx in atom_map) + (end_atom_idx in atom_map)
# Double check that I have a proper fragment
if count == 2:
bond_smarts_types.append(bond_smarts)
new_canonical_bondtypes.append(canonical_bondtype)
emol.AddBond(atom_map[begin_atom_idx], atom_map[end_atom_idx], bond.GetBondType())
orig_bonds.append(orig_bond)
elif count == 1:
raise AssertionError("connected/disconnected atoms?")
return TypedFragment(emol.GetMol(),
[typed_mol.orig_atoms[atom_index] for atom_index in atom_indices],
orig_bonds, atom_smarts_types, bond_smarts_types, new_canonical_bondtypes)
def fragmented_mol_to_enumeration_mols(typed_mol, minNumAtoms=2):
if minNumAtoms < 2:
raise ValueError("minNumAtoms must be at least 2")
fragments = []
for atom_indices in Chem.GetMolFrags(typed_mol.rdmol):
# No need to even look at fragments which are too small.
if len(atom_indices) < minNumAtoms:
continue
# Convert a fragment from the TypedMolecule into a new
# TypedMolecule containing only that fragment.
# You might think I could merge 'get_typed_fragment()' with
# the code to generate the EnumerationMolecule. You're
# probably right. This code reflects history. My original code
# didn't break the typed molecule down to its fragments.
typed_fragment = get_typed_fragment(typed_mol, atom_indices)
rdmol = typed_fragment.rdmol
atoms = []
for atom, orig_atom, atom_smarts_type in zip(rdmol.GetAtoms(), typed_fragment.orig_atoms,
typed_fragment.atom_smarts_types):
bond_indices = [bond.GetIdx() for bond in atom.GetBonds()]
#assert atom.GetSymbol() == orig_atom.GetSymbol()
atom_smarts = '[' + atom_smarts_type + ']'
atoms.append(Atom(atom, atom_smarts, bond_indices, orig_atom.IsInRing()))
directed_edges = defaultdict(list)
bonds = []
for bond_index, (bond, orig_bond, bond_smarts, canonical_bondtype) in enumerate(
zip(rdmol.GetBonds(), typed_fragment.orig_bonds, typed_fragment.bond_smarts_types,
typed_fragment.canonical_bondtypes)):
atom_indices = [bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()]
bonds.append(Bond(bond, bond_smarts, canonical_bondtype, atom_indices, orig_bond.IsInRing()))
directed_edges[atom_indices[0]].append(DirectedEdge(bond_index, atom_indices[1]))
directed_edges[atom_indices[1]].append(DirectedEdge(bond_index, atom_indices[0]))
fragment = EnumerationMolecule(rdmol, atoms, bonds, dict(directed_edges))
fragments.append(fragment)
# Optimistically try the largest fragments first
fragments.sort(key=lambda fragment: len(fragment.atoms), reverse=True)
return fragments
####### Canonical SMARTS generation using Weininger, Weininger, and Weininger's CANGEN
# CANGEN "combines two separate algorithms, CANON and GENES. The
# first stage, CANON, labels a molecular structure with canonical
# labels. ... Each atom is given a numerical label on the basis of its
# topology. In the second stage, GENES generates the unique SMILES
# ... . [It] selects the starting atom and makes branching decisions
# by referring to the canonical labels as needed."
# CANON is based on the fundamental theorem of arithmetic, that is,
# the unique prime factorization theorem. Which means I need about as
# many primes as I have atoms.
# I could have a fixed list of a few thousand primes but I don't like
# having a fixed upper limit to my molecule size. I modified the code
# Georg Schoelly posted at http://stackoverflow.com/a/568618/64618 .
# This is one of many ways to generate an infinite sequence of primes.
def gen_primes():
d = defaultdict(list)
q = 2
while 1:
if q not in d:
yield q
d[q * q].append(q)
else:
for p in d[q]:
d[p + q].append(p)
del d[q]
q += 1
_prime_stream = gen_primes()
# Code later on uses _primes[n] and if that fails, calls _get_nth_prime(n)
_primes = []
def _get_nth_prime(n):
# Keep appending new primes from the stream until I have enough.
current_size = len(_primes)
while current_size <= n:
_primes.append(next(_prime_stream))
current_size += 1
return _primes[n]
# Prime it with more values then will likely occur
_get_nth_prime(1000)
###
# The CANON algorithm is documented as:
# (1) Set atomic vector to initial invariants. Go to step 3.
# (2) Set vector to product of primes corresponding to neighbors' ranks.
# (3) Sort vector, maintaining stability over previous ranks.
# (4) Rank atomic vector.
# (5) If not invariants partitioning, go to step 2.
# (6) On first pass, save partitioning as symmetry classes [fmcs doesn't need this]
# (7) If highest rank is smaller than number of nodes, break ties, go to step 2
# (8) ... else done.
# I track the atom information as a list of CangenNode instances.
class CangenNode(object):
# Using __slots__ improves get_initial_cangen_nodes performance by over 10%
# and dropped my overall time (in one benchmark) from 0.75 to 0.73 seconds
__slots__ = ["index", "atom_smarts", "value", "neighbors", "rank", "outgoing_edges"]
def __init__(self, index, atom_smarts):
self.index = index
self.atom_smarts = atom_smarts # Used to generate the SMARTS output
self.value = 0
self.neighbors = []
self.rank = 0
self.outgoing_edges = []
# The outgoing edge information is used to generate the SMARTS output
# The index numbers are offsets in the subgraph, not in the original molecule
OutgoingEdge = namedtuple("OutgoingEdge",
"from_atom_index bond_index bond_smarts other_node_idx other_node")
# Convert a Subgraph of a given EnumerationMolecule into a list of
# CangenNodes. This contains the more specialized information I need
# for canonicalization and for SMARTS generation.
def get_initial_cangen_nodes(subgraph, enumeration_mol, atom_assignment,
do_initial_assignment=True):
# The subgraph contains a set of atom and bond indices in the enumeration_mol.
# The CangenNode corresponds to an atom in the subgraph, plus relations
# to other atoms in the subgraph.
# I need to convert from offsets in molecule space to offset in subgraph space.
# Map from enumeration mol atom indices to subgraph/CangenNode list indices
atom_map = {}
cangen_nodes = []
atoms = enumeration_mol.atoms
canonical_labels = []
for i, atom_index in enumerate(subgraph.atom_indices):
atom_map[atom_index] = i
cangen_nodes.append(CangenNode(i, atoms[atom_index].atom_smarts))
canonical_labels.append([])
# Build the neighbor and directed edge lists
for bond_index in subgraph.bond_indices:
bond = enumeration_mol.bonds[bond_index]
from_atom_index, to_atom_index = bond.atom_indices
from_subgraph_atom_index = atom_map[from_atom_index]