-
Notifications
You must be signed in to change notification settings - Fork 154
/
StructureDiagramGenerator.java
2911 lines (2566 loc) · 118 KB
/
StructureDiagramGenerator.java
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
/* Copyright (C) 1997-2007 Christoph Steinbeck <steinbeck@users.sf.net>
*
* Contact: cdk-devel@lists.sourceforge.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
* All we ask is that proper credit is given for our work, which includes
* - but is not limited to - adding the above copyright notice to the beginning
* of your source code files, and to any copyright notice that you may distribute
* with programs based on this work.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
package org.openscience.cdk.layout;
import org.openscience.cdk.CDKConstants;
import org.openscience.cdk.config.Elements;
import org.openscience.cdk.exception.CDKException;
import org.openscience.cdk.geometry.GeometryUtil;
import org.openscience.cdk.graph.ConnectedComponents;
import org.openscience.cdk.graph.ConnectivityChecker;
import org.openscience.cdk.graph.Cycles;
import org.openscience.cdk.graph.GraphUtil;
import org.openscience.cdk.interfaces.IAtom;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IAtomContainerSet;
import org.openscience.cdk.interfaces.IBond;
import org.openscience.cdk.interfaces.IChemObjectBuilder;
import org.openscience.cdk.interfaces.IElement;
import org.openscience.cdk.interfaces.IPseudoAtom;
import org.openscience.cdk.interfaces.IReaction;
import org.openscience.cdk.interfaces.IRing;
import org.openscience.cdk.interfaces.IRingSet;
import org.openscience.cdk.interfaces.IStereoElement;
import org.openscience.cdk.isomorphism.AtomMatcher;
import org.openscience.cdk.isomorphism.BondMatcher;
import org.openscience.cdk.isomorphism.Pattern;
import org.openscience.cdk.isomorphism.VentoFoggia;
import org.openscience.cdk.ringsearch.RingPartitioner;
import org.openscience.cdk.sgroup.Sgroup;
import org.openscience.cdk.sgroup.SgroupBracket;
import org.openscience.cdk.sgroup.SgroupKey;
import org.openscience.cdk.sgroup.SgroupType;
import org.openscience.cdk.stereo.DoubleBondStereochemistry;
import org.openscience.cdk.tools.ILoggingTool;
import org.openscience.cdk.tools.LoggingToolFactory;
import org.openscience.cdk.tools.manipulator.AtomContainerManipulator;
import org.openscience.cdk.tools.manipulator.ReactionManipulator;
import org.openscience.cdk.tools.manipulator.RingSetManipulator;
import javax.vecmath.Point2d;
import javax.vecmath.Vector2d;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import static java.util.Comparator.comparingInt;
/**
* Generates 2D coordinates for a molecule.
*
* <b>Basic Usage:</b>
* If you just want to generate coordinate for a molecule (or reaction) you
* can use the following one-liner:
* <pre>
* new StructureDiagramGenerator().generateCoordinates(molecule);
* </pre>
* The older versions of the API suggested using the following a
* set/generate/get idiom but this performs an unnecessary (in most cases) copy.
* <pre>
* StructureDiagramGenerator sdg = new StructureDiagramGenerator();
* sdg.setMolecule(molecule); // cloned!
* sdg.generateCoordinates();
* molecule = sdg.getMolecule();
* </pre>
* This idiom only needs to be used when 'fixing' parts of an existing
* layout with {@link #setMolecule(IAtomContainer, boolean, Set, Set)}
* <br/>
*
* @author steinbeck
* @cdk.created 2004-02-02
* @cdk.keyword Layout
* @cdk.keyword Structure Diagram Generation (SDG)
* @cdk.keyword 2D-coordinates
* @cdk.keyword Coordinate generation, 2D
* @cdk.dictref blue-obelisk:layoutMolecule
* @cdk.module sdg
* @cdk.githash
* @cdk.bug 1536561
* @cdk.bug 1788686
*/
public class StructureDiagramGenerator {
static final double DEFAULT_BOND_LENGTH = 1.5;
static final double SGROUP_BRACKET_PADDING_FACTOR = 0.5;
private static final Vector2d DEFAULT_BOND_VECTOR = new Vector2d(0, 1);
private static final IdentityTemplateLibrary DEFAULT_TEMPLATE_LIBRARY = IdentityTemplateLibrary.loadFromResource("custom-templates.smi")
.add(IdentityTemplateLibrary.loadFromResource("chebi-ring-templates.smi"));
private static final double RAD_30 = Math.toRadians(-30);
private static final ILoggingTool logger = LoggingToolFactory.createLoggingTool(StructureDiagramGenerator.class);
public static final Comparator<IAtomContainer> LARGEST_FIRST_COMPARATOR = new Comparator<IAtomContainer>() {
@Override
public int compare(IAtomContainer o1, IAtomContainer o2) {
return Integer.compare(o2.getBondCount(), o1.getBondCount());
}
};
private IAtomContainer molecule;
private IRingSet sssr;
private final double bondLength = DEFAULT_BOND_LENGTH;
private Vector2d firstBondVector;
private final RingPlacer ringPlacer = new RingPlacer();
private final AtomPlacer atomPlacer = new AtomPlacer();
private MacroCycleLayout macroPlacer = null;
private List<IRingSet> ringSystems = null;
private Set<IAtom> afix = null;
private Set<IBond> bfix = null;
private boolean useIdentTemplates = true;
private boolean alignMappedReaction = true;
// show we orient the structure (false: keep de facto ring systems drawn
// the right way up)
private boolean selectOrientation = true;
/**
* Identity templates - for laying out primary ring system.
*/
private IdentityTemplateLibrary identityLibrary;
/**
* The empty constructor.
*/
public StructureDiagramGenerator() {
this(DEFAULT_TEMPLATE_LIBRARY);
}
private StructureDiagramGenerator(IdentityTemplateLibrary identityLibrary) {
this.identityLibrary = identityLibrary;
}
/**
* Creates an instance of this class while assigning a molecule to be layed
* out.
*
* @param molecule The molecule to be layed out.
*/
public StructureDiagramGenerator(IAtomContainer molecule) {
this();
setMolecule(molecule, false);
}
/**
* <p>Convenience method for generating 2D coordinates.</p>
*
* <p>The method is short-hand for calling:</p>
* <pre>
* sdg.setMolecule(mol, false);
* sdg.generateCoordinates();
* </pre>
*
* @param mol molecule to layout
* @throws CDKException problem with layout
*/
public final void generateCoordinates(IAtomContainer mol) throws CDKException {
setMolecule(mol, false);
generateCoordinates();
}
/**
* <p>Convenience method to generate 2D coordinates for a reaction. If atom-atom
* maps are present on a reaction, the substructures are automatically aligned.</p>
* <p>This feature can be disabled by changing the {@link #setAlignMappedReaction(boolean)}</p>
*
* @param reaction reaction to layout
* @throws CDKException problem with layout
*/
public final void generateCoordinates(final IReaction reaction) throws CDKException {
// layout products and agents
for (IAtomContainer mol : reaction.getProducts().atomContainers())
generateCoordinates(mol);
for (IAtomContainer mol : reaction.getAgents().atomContainers())
generateCoordinates(mol);
// do not align = simple layout of reactants
if (alignMappedReaction) {
final Set<IBond> mapped = ReactionManipulator.findMappedBonds(reaction);
Map<Integer, List<Map<Integer, IAtom>>> refmap = new HashMap<>();
for (IAtomContainer mol : reaction.getProducts().atomContainers()) {
Cycles.markRingAtomsAndBonds(mol);
final ConnectedComponents cc = new ConnectedComponents(GraphUtil.toAdjListSubgraph(mol, mapped));
final IAtomContainerSet parts = ConnectivityChecker.partitionIntoMolecules(mol, cc.components());
for (IAtomContainer part : parts.atomContainers()) {
// skip single atoms (unmapped)
if (part.getAtomCount() == 1)
continue;
final Map<Integer, IAtom> map = new HashMap<>();
for (IAtom atom : part.atoms()) {
// safe as substructure should only be mapped bonds and therefore atoms!
int idx = atom.getProperty(CDKConstants.ATOM_ATOM_MAPPING);
if (map.put(idx, atom) == null)
refmap.computeIfAbsent(idx, k -> new ArrayList<>()).add(map);
}
}
}
Map<IAtom,IAtom> afix = new HashMap<>();
Set<IBond> bfix = new HashSet<>();
for (IAtomContainer mol : reaction.getReactants().atomContainers()) {
Cycles.markRingAtomsAndBonds(mol);
final ConnectedComponents cc = new ConnectedComponents(GraphUtil.toAdjListSubgraph(mol, mapped));
final IAtomContainerSet parts = ConnectivityChecker.partitionIntoMolecules(mol, cc.components());
// we only aligned the largest part
IAtomContainer largest = null;
for (IAtomContainer part : parts.atomContainers()) {
if (largest == null || part.getBondCount() > largest.getBondCount())
largest = part;
}
afix.clear();
bfix.clear();
boolean aggresive = false;
if (largest != null && largest.getAtomCount() > 1) {
int idx = largest.getAtom(0).getProperty(CDKConstants.ATOM_ATOM_MAPPING);
// select the largest and use those coordinates
Map<Integer, IAtom> reference = select(refmap.getOrDefault(idx, Collections.emptyList()));
for (IAtom atom : largest.atoms()) {
idx = atom.getProperty(CDKConstants.ATOM_ATOM_MAPPING);
final IAtom src = reference.get(idx);
if (src == null) continue;
if (!aggresive) {
// no way to get the container of 'src' without
// lots of refactoring, instead we just use the
// new API points - first checking these will not
// fail
if (src.getContainer() != null
&& atom.getContainer() != null
&& AtomPlacer.isColinear(src, src.bonds())
!= AtomPlacer.isColinear(atom, atom.bonds()))
continue;
}
atom.setPoint2d(new Point2d(src.getPoint2d()));
afix.put(atom, src);
}
}
if (!afix.isEmpty()) {
if (aggresive) {
for (IBond bond : mol.bonds()) {
if (afix.containsKey(bond.getBegin()) && afix.containsKey(bond.getEnd())) {
// only fix acyclic bonds if the source atoms were also acyclic
if (!bond.isInRing()) {
IAtom srcBeg = afix.get(bond.getBegin());
IAtom srcEnd = afix.get(bond.getEnd());
for (IAtomContainer product : reaction.getProducts().atomContainers()) {
IBond srcBond = product.getBond(srcBeg, srcEnd);
if (srcBond != null) {
if (!srcBond.isInRing())
bfix.add(bond); // safe to add
break;
}
}
} else {
bfix.add(bond);
}
}
}
} else {
for (IBond bond : mol.bonds()) {
if (afix.containsKey(bond.getBegin()) && afix.containsKey(bond.getEnd())) {
// only fix bonds that match their ring membership status
IAtom srcBeg = afix.get(bond.getBegin());
IAtom srcEnd = afix.get(bond.getEnd());
for (IAtomContainer product : reaction.getProducts().atomContainers()) {
IBond srcBond = product.getBond(srcBeg, srcEnd);
if (srcBond != null) {
if (srcBond.isInRing() == bond.isInRing())
bfix.add(bond);
break;
}
}
}
}
afix.clear();
for (IBond bond : bfix) {
afix.put(bond.getBegin(), null);
afix.put(bond.getEnd(), null);
}
int[] parts2 = new int[mol.getAtomCount()];
int numParts = 0;
Deque<IAtom> queue = new ArrayDeque<>();
for (IAtom atom : afix.keySet()) {
if (parts2[mol.indexOf(atom)] != 0)
continue;
parts2[mol.indexOf(atom)] = ++numParts;
for (IBond bond : mol.getConnectedBondsList(atom)) {
if (bfix.contains(bond))
queue.add(bond.getOther(atom));
}
while (!queue.isEmpty()) {
atom = queue.poll();
if (parts2[mol.indexOf(atom)] != 0)
continue;
parts2[mol.indexOf(atom)] = numParts;
for (IBond bond : mol.getConnectedBondsList(atom)) {
if (bfix.contains(bond))
queue.add(bond.getOther(atom));
}
}
}
if (numParts > 1) {
int best = 0;
int bestSize = 0;
for (int part = 1; part <= numParts; part++) {
int size = 0;
for (int j : parts2) {
if (j == part)
++size;
}
if (size > bestSize) {
bestSize = size;
best = part;
}
}
for (IAtom atom : new ArrayList<>(afix.keySet())) {
if (parts2[mol.indexOf(atom)] != best) {
afix.remove(atom);
bfix.removeAll(mol.getConnectedBondsList(atom));
}
}
}
}
}
setMolecule(mol, false, afix.keySet(), bfix);
generateCoordinates();
}
// reorder reactants such that they are in the same order they appear on the right
reaction.getReactants().sortAtomContainers(new Comparator<IAtomContainer>() {
@Override
public int compare(IAtomContainer a, IAtomContainer b) {
Point2d aCenter = GeometryUtil.get2DCenter(a);
Point2d bCenter = GeometryUtil.get2DCenter(b);
if (aCenter == null || bCenter == null)
return 0;
else
return Double.compare(aCenter.x, bCenter.x);
}
});
} else {
for (IAtomContainer mol : reaction.getReactants().atomContainers())
generateCoordinates(mol);
}
}
private Map<Integer, IAtom> select(Collection<Map<Integer, IAtom>> refs) {
Map<Integer, IAtom> largest = Collections.emptyMap();
for (Map<Integer, IAtom> ref : refs) {
if (ref.size() > largest.size())
largest = ref;
}
return largest;
}
public void setMolecule(IAtomContainer mol, boolean clone) {
setMolecule(mol, clone, Collections.emptySet(), Collections.emptySet());
}
/**
* Assigns a molecule to be laid out. After, setting the molecule call generateCoordinates() to assign
* 2D coordinates. An optional set of atoms/bonds can be parsed in to allow partial layout, these will
* be 'fixed' in place. This only applies to non-cloned molecules, and only atoms with coordinates can
* be fixed.
*
* @param mol the molecule for which coordinates are to be generated.
* @param clone Should the whole process be performed with a cloned copy?
* @param afix Atoms that should be fixed in place, coordinates are not changed.
* @param bfix Bonds that should be fixed in place, they will not be flipped, bent, or streched.
*/
public void setMolecule(IAtomContainer mol, boolean clone, Set<IAtom> afix, Set<IBond> bfix) {
if (clone) {
if (!afix.isEmpty() || !bfix.isEmpty())
throw new IllegalArgumentException("Laying out a cloned molecule, can't fix atom or bonds.");
try {
this.molecule = mol.clone();
} catch (CloneNotSupportedException e) {
logger.error("Should clone, but exception occurred: ", e.getMessage());
logger.debug(e);
}
} else {
this.molecule = mol;
}
this.afix = afix;
this.bfix = bfix;
for (IAtom atom : molecule.atoms()) {
boolean afixed = afix.contains(atom);
if (afixed && atom.getPoint2d() == null) {
afixed = false;
afix.remove(atom);
}
if (afixed) {
atom.setFlag(CDKConstants.ISPLACED, true);
atom.setFlag(CDKConstants.VISITED, true);
} else {
atom.setPoint2d(null);
atom.setFlag(CDKConstants.ISPLACED, false);
atom.setFlag(CDKConstants.VISITED, false);
atom.setFlag(CDKConstants.ISINRING, false);
atom.setFlag(CDKConstants.ISALIPHATIC, false);
}
}
atomPlacer.setMolecule(this.molecule);
ringPlacer.setMolecule(this.molecule);
ringPlacer.setAtomPlacer(this.atomPlacer);
macroPlacer = new MacroCycleLayout(mol);
selectOrientation = afix.isEmpty();
}
/**
* Sets whether to use templates or not. Some complicated ring systems
* like adamantane are only nicely layouted when using templates. This
* option is by default set true.
*
* @param useTemplates set true to use templates, false otherwise
* @deprecated always false, substructure templates are not used anymore
*/
@Deprecated
public void setUseTemplates(boolean useTemplates) {
}
/**
* Set whether identity templates are used. Identity templates use an exact match
* are are very fast. They are used for layout of the 'primary' ring system
* in de facto orientation.
*
* @param use whether to use identity templates
*/
public void setUseIdentityTemplates(boolean use) {
this.useIdentTemplates = use;
}
/**
* Returns whether the use of templates is enabled or disabled.
*
* @return true, when the use of templates is enables, false otherwise
* @deprecated always false, substructure templates are not used anymore
*/
@Deprecated
public boolean getUseTemplates() {
return false;
}
/**
* Sets the templateHandler attribute of the StructureDiagramGenerator object
*
* @param templateHandler The new templateHandler value
* @deprecated substructure templates are no longer used for layout but those provided here
* will be converted to identity templates
*/
@Deprecated
public void setTemplateHandler(TemplateHandler templateHandler) {
IdentityTemplateLibrary lib = templateHandler.toIdentityTemplateLibrary();
lib.add(identityLibrary);
identityLibrary = lib; // new ones take priority
}
/**
* Gets the templateHandler attribute of the StructureDiagramGenerator object
*
* @return The templateHandler value
* @deprecated always null, substructure templates are not used anymore
*/
@Deprecated
public TemplateHandler getTemplateHandler() {
return null;
}
/**
* Assings a molecule to be layed out. Call generateCoordinates() to do the
* actual layout.
*
* @param molecule the molecule for which coordinates are to be generated.
*/
public void setMolecule(IAtomContainer molecule) {
setMolecule(molecule, true);
}
/**
* Set whether reaction reactants should be allignned to their product.
*
* @param align align setting
*/
public void setAlignMappedReaction(boolean align) {
this.alignMappedReaction = align;
}
/**
* Returns the molecule, usually used after a call of generateCoordinates()
*
* @return The molecule with new coordinates (if generateCoordinates() had
* been called)
*/
public IAtomContainer getMolecule() {
return molecule;
}
/**
* This method uses generateCoordinates, but it removes the hydrogens first,
* lays out the structure and then adds them again.
*
* @throws CDKException if an error occurs
* @see #generateCoordinates
* @deprecated use {@link #generateCoordinates()}
*/
@Deprecated
public void generateExperimentalCoordinates() throws CDKException {
generateExperimentalCoordinates(DEFAULT_BOND_VECTOR);
}
/**
* Generates 2D coordinates on the non-hydrogen skeleton, after which
* coordinates for the hydrogens are calculated.
*
* @param firstBondVector the vector of the first bond to lay out
* @throws CDKException if an error occurs
* @deprecated use {@link #generateCoordinates()}
*/
@Deprecated
public void generateExperimentalCoordinates(Vector2d firstBondVector) throws CDKException {
// first make a shallow copy: Atom/Bond references are kept
IAtomContainer original = molecule;
IAtomContainer shallowCopy = molecule.getBuilder().newInstance(IAtomContainer.class, molecule);
// delete single-bonded H's from
//IAtom[] atoms = shallowCopy.getAtoms();
for (IAtom curAtom : shallowCopy.atoms()) {
if (curAtom.getAtomicNumber() == IElement.H) {
if (shallowCopy.getConnectedBondsCount(curAtom) < 2) {
shallowCopy.removeAtom(curAtom);
curAtom.setPoint2d(null);
}
}
}
// do layout on the shallow copy
molecule = shallowCopy;
generateCoordinates(firstBondVector);
double bondLength = GeometryUtil.getBondLengthAverage(molecule);
// ok, now create the coordinates for the hydrogens
HydrogenPlacer hPlacer = new HydrogenPlacer();
molecule = original;
hPlacer.placeHydrogens2D(molecule, bondLength);
}
/**
* The main method of this StructurDiagramGenerator. Assign a molecule to the
* StructurDiagramGenerator, call the generateCoordinates() method and get
* your molecule back.
*
* @param firstBondVector The vector of the first bond to lay out
* @throws CDKException if an error occurs
*/
public void generateCoordinates(Vector2d firstBondVector) throws CDKException {
generateCoordinates(firstBondVector, false, false);
}
/**
* The main method of this StructureDiagramGenerator. Assign a molecule to the
* StructureDiagramGenerator, call the generateCoordinates() method and get
* your molecule back.
*
* @param firstBondVector the vector of the first bond to lay out
* @param isConnected the 'molecule' attribute is guaranteed to be connected (we have checked)
* @param isSubLayout the 'molecule' is being laid out as part of a large collection of fragments
* @throws CDKException problem occurred during layout
*/
private void generateCoordinates(Vector2d firstBondVector, boolean isConnected, boolean isSubLayout) throws CDKException {
// defensive copy, vectors are mutable!
if (firstBondVector == DEFAULT_BOND_VECTOR)
firstBondVector = new Vector2d(firstBondVector);
final int numAtoms = molecule.getAtomCount();
final int numBonds = molecule.getBondCount();
this.firstBondVector = firstBondVector;
// if molecule contains only one Atom, don't fail, simply set
// coordinates to simplest: 0,0. See bug #780545
logger.debug("Entry point of generateCoordinates()");
logger.debug("We have a molecules with " + numAtoms + " atoms.");
if (numAtoms == 0) {
return;
}
if (numAtoms == 1) {
molecule.getAtom(0).setPoint2d(new Point2d(0, 0));
return;
} else if (molecule.getBondCount() == 1 && molecule.getAtomCount() == 2) {
double xOffset = 0;
for (IAtom atom : molecule.atoms()) {
atom.setPoint2d(new Point2d(xOffset, 0));
xOffset += bondLength;
}
return;
}
// intercept fragment molecules and lay them out in a grid
if (!isConnected) {
final IAtomContainerSet frags = ConnectivityChecker.partitionIntoMolecules(molecule);
if (frags.getAtomContainerCount() > 1) {
IAtomContainer rollback = molecule;
// large => small (e.g. salt will appear on the right)
List<IAtomContainer> fragList = toList(frags);
fragList.sort(LARGEST_FIRST_COMPARATOR);
generateFragmentCoordinates(molecule, fragList);
// don't call set molecule as it wipes x,y coordinates!
// this looks like a self assignment but actually the fragment
// method changes this.molecule
this.molecule = rollback;
atomPlacer.setMolecule(this.molecule);
ringPlacer.setMolecule(this.molecule);
macroPlacer = new MacroCycleLayout(this.molecule);
return;
}
}
// initial layout seeding either from a ring system of longest chain
seedLayout();
// Now, do the layout of the rest of the molecule
int iter = 0;
for (; !AtomPlacer.allPlaced(molecule) && iter < numAtoms; iter++) {
logger.debug("*** Start of handling the rest of the molecule. ***");
// layout for all acyclic parts of the molecule which are
// connected to the parts which have already been laid out.
layoutAcyclicParts();
// layout cyclic parts of the molecule which
// are connected to the parts which have already been laid out.
layoutCyclicParts();
}
// display reasonable error on failed layout, otherwise we'll have a NPE somewhere
if (iter == numAtoms && !AtomPlacer.allPlaced(molecule))
throw new CDKException("Could not generate layout? If a set of 'fixed' atoms were provided"
+ " try removing these and regenerating the layout.");
if (!isSubLayout) {
// correct double-bond stereo, this changes the layout and in reality
// should be done during the initial placement
if (molecule.stereoElements().iterator().hasNext())
CorrectGeometricConfiguration.correct(molecule);
}
refinePlacement(molecule);
finalizeLayout(molecule);
// stereo must be after refinement (due to flipping!)
if (!isSubLayout)
assignStereochem(molecule);
}
/**
* Determine if any atoms in a connected molecule are fixed (i.e. already have coordinates/
* have been placed).
*
* @param mol the moleucle to check
* @return atoms are fixed
*/
private boolean hasFixedPart(final IAtomContainer mol) {
if (afix.isEmpty()) return false;
for (IAtom atom : mol.atoms())
if (afix.contains(atom))
return true;
return false;
}
private void seedLayout() throws CDKException {
final int numAtoms = this.molecule.getAtomCount();
final int numBonds = this.molecule.getBondCount();
if (hasFixedPart(molecule)) {
// no seeding needed as the molecule has atoms with coordinates, just calc rings if needed
if (prepareRingSystems() > 0) {
for (IRingSet rset : ringSystems) {
if (rset.getFlag(CDKConstants.ISPLACED)) {
ringPlacer.placeRingSubstituents(rset, bondLength);
} else {
List<IRing> placed = new ArrayList<>();
List<IRing> unplaced = new ArrayList<>();
for (IAtomContainer ring : rset.atomContainers()) {
if (ring.getFlag(CDKConstants.ISPLACED))
placed.add((IRing) ring);
else
unplaced.add((IRing) ring);
}
// partially laid out rings
if (placed.isEmpty()) {
for (IRing ring : unplaced) {
if (ringPlacer.completePartiallyPlacedRing(rset, ring, bondLength))
placed.add(ring);
}
unplaced.removeAll(placed);
}
while (!unplaced.isEmpty() && !placed.isEmpty()) {
for (IAtomContainer ring : placed) {
ringPlacer.placeConnectedRings(rset, (IRing) ring, RingPlacer.FUSED, bondLength);
ringPlacer.placeConnectedRings(rset, (IRing) ring, RingPlacer.BRIDGED, bondLength);
ringPlacer.placeConnectedRings(rset, (IRing) ring, RingPlacer.SPIRO, bondLength);
}
Iterator<IRing> unplacedIter = unplaced.iterator();
placed.clear();
while (unplacedIter.hasNext()) {
IRing ring = unplacedIter.next();
if (ring.getFlag(CDKConstants.ISPLACED)) {
unplacedIter.remove();
placed.add(ring);
}
}
}
if (allPlaced(rset)) {
rset.setFlag(CDKConstants.ISPLACED, true);
ringPlacer.placeRingSubstituents(rset, bondLength);
}
}
}
}
} else if (prepareRingSystems() > 0) {
logger.debug("*** Start of handling rings. ***");
prepareRingSystems();
// We got our ring systems now choose the best one based on size and
// number of heteroatoms
RingPlacer.countHetero(ringSystems);
ringSystems.sort(RingPlacer.RING_COMPARATOR);
int respect = layoutRingSet(firstBondVector, ringSystems.get(0));
// rotate monocyclic and when >= 4 polycyclic
if (respect == 1) {
if (ringSystems.get(0).getAtomContainerCount() == 1) {
respect = 0;
} else if (ringSystems.size() >= 4) {
int numPoly = 0;
for (IRingSet rset : ringSystems)
if (rset.getAtomContainerCount() > 1)
numPoly++;
if (numPoly >= 4)
respect = 0;
}
}
if (respect == 1 || respect == 2)
selectOrientation = false;
logger.debug("First RingSet placed");
// place of all the directly connected atoms of this ring system
ringPlacer.placeRingSubstituents(ringSystems.get(0), bondLength);
} else {
logger.debug("*** Start of handling purely aliphatic molecules. ***");
// We are here because there are no rings in the molecule so we get the longest chain in the molecule
// and placed in on a horizontal axis
logger.debug("Searching initialLongestChain for this purely aliphatic molecule");
IAtomContainer longestChain = AtomPlacer.getInitialLongestChain(molecule);
logger.debug("Found linear chain of length " + longestChain.getAtomCount());
logger.debug("Setting coordinated of first atom to 0,0");
longestChain.getAtom(0).setPoint2d(new Point2d(0, 0));
longestChain.getAtom(0).setFlag(CDKConstants.ISPLACED, true);
// place the first bond such that the whole chain will be horizontally alligned on the x axis
logger.debug("Attempting to place the first bond such that the whole chain will be horizontally alligned on the x axis");
if (firstBondVector != null && firstBondVector != DEFAULT_BOND_VECTOR)
atomPlacer.placeLinearChain(longestChain, firstBondVector, bondLength);
else
atomPlacer.placeLinearChain(longestChain, new Vector2d(Math.cos(RAD_30), Math.sin(RAD_30)), bondLength);
logger.debug("Placed longest aliphatic chain");
}
}
private int prepareRingSystems() {
final int numRings = Cycles.markRingAtomsAndBonds(molecule);
// compute SSSR/MCB
if (numRings > 0) {
sssr = Cycles.sssr(molecule).toRingSet();
if (sssr.getAtomContainerCount() < 1)
throw new IllegalStateException("Molecule expected to have rings, but had none?");
// Give a handle of our molecule to the ringPlacer
ringPlacer.checkAndMarkPlaced(sssr);
// Partition the smallest set of smallest rings into disconnected
// ring system. The RingPartioner returns a Vector containing
// RingSets. Each of the RingSets contains rings that are connected
// to each other either as bridged ringsystems, fused rings or via
// spiro connections.
ringSystems = RingPartitioner.partitionRings(sssr);
// set the in-ring db stereo
for (IStereoElement se : molecule.stereoElements()) {
if (se.getConfigClass() == IStereoElement.CisTrans) {
IBond stereoBond = (IBond) se.getFocus();
IBond firstCarrier = (IBond) se.getCarriers().get(0);
IBond secondCarrier = (IBond) se.getCarriers().get(1);
for (IRingSet ringSet : ringSystems) {
for (IAtomContainer ring : ringSet.atomContainers()) {
if (ring.contains(stereoBond)) {
List<IBond> begBonds = ring.getConnectedBondsList(stereoBond.getBegin());
List<IBond> endBonds = ring.getConnectedBondsList(stereoBond.getEnd());
begBonds.remove(stereoBond);
endBonds.remove(stereoBond);
// something odd wrong, just skip it
if (begBonds.size() != 1 || endBonds.size() != 1)
continue;
boolean flipped = begBonds.contains(firstCarrier) != endBonds.contains(secondCarrier);
int cfg = flipped ? se.getConfigOrder() ^ 0x3 : se.getConfigOrder();
ring.addStereoElement(new DoubleBondStereochemistry(stereoBond,
new IBond[]{begBonds.get(0), endBonds.get(0)},
cfg));
}
}
}
}
}
} else {
sssr = molecule.getBuilder().newInstance(IRingSet.class);
ringSystems = new ArrayList<>();
}
return numRings;
}
private void assignStereochem(IAtomContainer molecule) {
// XXX: can't check this unless we store 'unspecified' double bonds
// if (!molecule.stereoElements().iterator().hasNext())
// return;
// assign up/down labels, this doesn't not alter layout and could be
// done on-demand (e.g. when writing a MDL Molfile)
NonplanarBonds.assign(molecule);
}
private void refinePlacement(IAtomContainer molecule) {
AtomPlacer.prioritise(molecule);
// refine the layout by rotating, bending, and stretching bonds
LayoutRefiner refiner = new LayoutRefiner(molecule, afix, bfix);
refiner.refine();
// check for attachment points, these override the direction which we rorate structures
IAtom begAttach = null;
for (IAtom atom : molecule.atoms()) {
if (atom instanceof IPseudoAtom && ((IPseudoAtom) atom).getAttachPointNum() == 1) {
begAttach = atom;
selectOrientation = true;
break;
}
}
// choose the orientation in which to display the structure
if (selectOrientation) {
// no attachment point, rotate to maximise horizontal spread etc.
if (begAttach == null) {
selectOrientation(molecule, DEFAULT_BOND_LENGTH, 1);
}
// use attachment point bond to rotate
else {
final List<IBond> attachBonds = molecule.getConnectedBondsList(begAttach);
if (attachBonds.size() == 1) {
IAtom end = attachBonds.get(0).getOther(begAttach);
Point2d xyBeg = begAttach.getPoint2d();
Point2d xyEnd = end.getPoint2d();
// snap to horizontal '*-(end)-{rest of molecule}'
GeometryUtil.rotate(molecule,
GeometryUtil.get2DCenter(molecule),
-Math.atan2(xyEnd.y - xyBeg.y, xyEnd.x - xyBeg.x));
// put the larger part of the structure is above the bond so fragments are drawn
// semi-consistently
double ylo = 0;
double yhi = 0;
for (IAtom atom : molecule.atoms()) {
double yDelta = xyBeg.y - atom.getPoint2d().y;
if (yDelta > 0 && yDelta > yhi) {
yhi = yDelta;
} else if (yDelta < 0 && yDelta < ylo) {
ylo = yDelta;
}
}
// mirror points if larger part is below
if (Math.abs(ylo) < yhi)
for (IAtom atom : molecule.atoms())
atom.getPoint2d().y = -atom.getPoint2d().y;
// rotate pointing downwards 30-degrees
GeometryUtil.rotate(molecule,
GeometryUtil.get2DCenter(molecule),
-Math.toRadians(30));
}
}
}
}
/**
* Finalize the molecule layout, primarily updating Sgroups.
*
* @param mol molecule being laid out
*/
private void finalizeLayout(IAtomContainer mol) {
placeMultipleGroups(mol);
placePositionalVariation(mol);
placeSgroupBrackets(mol);
}
/**
* Calculates a histogram of bond directions, this allows us to select an
* orientation that has bonds at nice angles (e.g. 60/120 deg). The limit
* parameter is used to quantize the vectors within a range. For example
* a limit of 60 will fill the histogram 0..59 and Bond's orientated at 0,
* 60, 120 degrees will all be counted in the 0 bucket.
*
* @param mol molecule
* @param counts the histogram is stored here, will be cleared
* @param lim wrap angles to the (180 max)
* @return number of aligned bonds
*/
private static void calcDirectionHistogram(Iterable<IBond> bonds,
int[] counts,
int lim) {
if (lim > 180)
throw new IllegalArgumentException("limit must be ≤ 180");
Arrays.fill(counts, 0);
for (IBond bond : bonds) {
Point2d beg = bond.getBegin().getPoint2d();
Point2d end = bond.getEnd().getPoint2d();
Vector2d vec = new Vector2d(end.x - beg.x, end.y - beg.y);
if (vec.x < 0)
vec.negate();
double angle = Math.PI/2 + Math.atan2(vec.y, vec.x);
counts[(int)(Math.round(Math.toDegrees(angle))%lim)]++;
}
}
private List<IBond> getNonContractedNonTerminalBonds(IAtomContainer mol) {
List<Sgroup> sgroups = mol.getProperty(CDKConstants.CTAB_SGROUPS);