Debian Codegraph @

rcdkjar/src/org/guha/rcdk/view/RcdkDepictor.java

raw
1 package org.guha.rcdk.view;
2
3 import com.google.common.collect.ArrayListMultimap;
4 import com.google.common.collect.Multimap;
5 import org.openscience.cdk.CDKConstants;
6 import org.openscience.cdk.depict.Abbreviations;
7 import org.openscience.cdk.depict.Depiction;
8 import org.openscience.cdk.depict.DepictionGenerator;
9 import org.openscience.cdk.exception.CDKException;
10 import org.openscience.cdk.interfaces.*;
11 import org.openscience.cdk.renderer.color.CDK2DAtomColors;
12 import org.openscience.cdk.renderer.color.IAtomColorer;
13 import org.openscience.cdk.renderer.color.UniColor;
14 import org.openscience.cdk.sgroup.Sgroup;
15 import org.openscience.cdk.sgroup.SgroupKey;
16 import org.openscience.cdk.sgroup.SgroupType;
17 import org.openscience.cdk.silent.SilentChemObjectBuilder;
18 import org.openscience.cdk.smiles.SmilesParser;
19 import org.openscience.cdk.smiles.smarts.SmartsPattern;
20 import org.openscience.cdk.tools.manipulator.AtomContainerManipulator;
21
22 import javax.imageio.ImageIO;
23 import java.awt.*;
24 import java.awt.image.BufferedImage;
25 import java.io.ByteArrayOutputStream;
26 import java.io.IOException;
27 import java.util.*;
28
29 /**
30 * Wrapper around CDK depiction workflow, independent of how it will be displayed.
31 *
32 * @author Rajarshi Guha
33 */
34 public class RcdkDepictor {
35 int width = 300;
36 int height = 300;
37
38 double zoom = 1.3;
39 String style = "cow";
40 String annotate = "off";
41 String abbr = "on";
42 boolean suppressh = true;
43 boolean showTitle = false;
44 int smaLimit = 100;
45 String sma = "";
46
47 private final IChemObjectBuilder builder = SilentChemObjectBuilder.getInstance();
48 private final DepictionGenerator generator = new DepictionGenerator();
49 private SmilesParser smipar = new SmilesParser(builder);
50 private final Abbreviations abbreviations = new Abbreviations();
51 private final Abbreviations reagents = new Abbreviations();
52
53
54 public RcdkDepictor(int width, int height) throws IOException {
55 this(width, height, 1.3, "cow", "off", "on", true, false, 100, "");
56 }
57
58 public RcdkDepictor(int width, int height, double zoom, String style, String annotate, String abbr,
59 boolean suppressh, boolean showTitle, int smaLimit, String sma) throws IOException {
60 this.width = width;
61 this.height = height;
62 this.zoom = zoom;
63 this.style = style;
64 this.annotate = annotate;
65 this.abbr = abbr;
66 this.suppressh = suppressh;
67 this.showTitle = showTitle;
68 this.smaLimit = smaLimit;
69 this.sma = sma;
70
71 boolean alignRxnMap = true;
72 String fmt = "PNG";
73
74 this.abbreviations.loadFromFile("/org/openscience/cdk/app/abbreviations.smi");
75 this.reagents.loadFromFile("/org/openscience/cdk/app/reagents.smi");
76 DepictionGenerator myGenerator = generator.withSize(width, height).withZoom(zoom);
77 myGenerator = withStyle(myGenerator, style);
78 switch (annotate) {
79 case "number":
80 myGenerator = myGenerator.withAtomNumbers();
81 abbr = "false";
82 break;
83 case "mapidx":
84 myGenerator = myGenerator.withAtomMapNumbers();
85 break;
86 case "atomvalue":
87 myGenerator = myGenerator.withAtomValues();
88 break;
89 case "colmap":
90 myGenerator = myGenerator.withAtomMapHighlight(new Color[]{new Color(169, 199, 255),
91 new Color(185, 255, 180),
92 new Color(255, 162, 162),
93 new Color(253, 139, 255),
94 new Color(255, 206, 86),
95 new Color(227, 227, 227)})
96 .withOuterGlowHighlight(6d);
97 break;
98 }
99 }
100
101 public int getWidth() {
102 return width;
103 }
104
105 public void setWidth(int width) {
106 this.width = width;
107 }
108
109 public int getHeight() {
110 return height;
111 }
112
113 public void setHeight(int height) {
114 this.height = height;
115 }
116
117 public double getZoom() {
118 return zoom;
119 }
120
121 public void setZoom(double zoom) {
122 this.zoom = zoom;
123 }
124
125 public String getStyle() {
126 return style;
127 }
128
129 public void setStyle(String style) {
130 this.style = style;
131 }
132
133 public String getAnnotate() {
134 return annotate;
135 }
136
137 public void setAnnotate(String annotate) {
138 this.annotate = annotate;
139 }
140
141 public String getAbbr() {
142 return abbr;
143 }
144
145 public void setAbbr(String abbr) {
146 this.abbr = abbr;
147 }
148
149 public boolean isSuppressh() {
150 return suppressh;
151 }
152
153 public void setSuppressh(boolean suppressh) {
154 this.suppressh = suppressh;
155 }
156
157 public boolean isShowTitle() {
158 return showTitle;
159 }
160
161 public void setShowTitle(boolean showTitle) {
162 this.showTitle = showTitle;
163 }
164
165 public int getSmaLimit() {
166 return smaLimit;
167 }
168
169 public void setSmaLimit(int smaLimit) {
170 this.smaLimit = smaLimit;
171 }
172
173 public String getSma() {
174 return sma;
175 }
176
177 public void setSma(String sma) {
178 this.sma = sma;
179 }
180
181 public BufferedImage getImage(IAtomContainer atomContainer) throws CDKException {
182 return generate(atomContainer).toImg();
183 }
184
185 public byte[] getFormat(IAtomContainer atomContainer, String fmt) throws CDKException, IOException {
186 final String fmtlc = fmt.toLowerCase(Locale.ROOT);
187 Depiction depiction = generate(atomContainer);
188 switch (fmtlc) {
189 case Depiction.SVG_FMT:
190 return depiction.toSvgStr().getBytes();
191 case Depiction.PDF_FMT:
192 return depiction.toPdfStr().getBytes();
193 case Depiction.PNG_FMT:
194 case Depiction.JPG_FMT:
195 case Depiction.GIF_FMT:
196 ByteArrayOutputStream bao = new ByteArrayOutputStream();
197 ImageIO.write(depiction.toImg(), fmtlc, bao);
198 return bao.toByteArray();
199 }
200 throw new IllegalArgumentException("Unsupported format.");
201 }
202
203 private Depiction generate(IAtomContainer atomContainer) throws CDKException {
204 DepictionGenerator myGenerator = generator.withSize(width, height).withZoom(zoom);
205 myGenerator = withStyle(myGenerator, style);
206 switch (annotate) {
207 case "number":
208 myGenerator = myGenerator.withAtomNumbers();
209 abbr = "false";
210 break;
211 case "mapidx":
212 myGenerator = myGenerator.withAtomMapNumbers();
213 break;
214 case "atomvalue":
215 myGenerator = myGenerator.withAtomValues();
216 break;
217 case "colmap":
218 myGenerator = myGenerator.withAtomMapHighlight(new Color[]{new Color(169, 199, 255),
219 new Color(185, 255, 180),
220 new Color(255, 162, 162),
221 new Color(253, 139, 255),
222 new Color(255, 206, 86),
223 new Color(227, 227, 227)})
224 .withOuterGlowHighlight(6d);
225 break;
226 }
227 // myGenerator = myGenerator.withMappedRxnAlign(alignRxnMap);
228
229 final boolean isRxn = false; //!smi.contains("V2000") && isRxnSmi(smi);
230 final boolean isRgp = false; //smi.contains("RG:");
231 IReaction rxn = null;
232 IAtomContainer mol = atomContainer;
233 java.util.List<IAtomContainer> mols = null;
234 Set<IChemObject> highlight;
235
236 if (isRxn) {
237 //rxn = smipar.parseReactionSmiles(smi);
238 if (suppressh) {
239 for (IAtomContainer component : rxn.getReactants().atomContainers())
240 AtomContainerManipulator.suppressHydrogens(component);
241 for (IAtomContainer component : rxn.getProducts().atomContainers())
242 AtomContainerManipulator.suppressHydrogens(component);
243 for (IAtomContainer component : rxn.getAgents().atomContainers())
244 AtomContainerManipulator.suppressHydrogens(component);
245 }
246
247
248 highlight = findHits(sma, rxn, mol, smaLimit);
249 abbreviate(rxn, abbr, annotate);
250 } else {
251 //mol = loadMol(smi);
252 if (suppressh) {
253 AtomContainerManipulator.suppressHydrogens(mol);
254 }
255 highlight = findHits(sma, rxn, mol, smaLimit);
256 abbreviate(mol, abbr, annotate);
257 }
258
259
260 if (suppressh)
261 AtomContainerManipulator.suppressHydrogens(atomContainer);
262 highlight = findHits(sma, rxn, atomContainer, smaLimit);
263 abbreviate(atomContainer, abbr, annotate);
264
265 switch (style) {
266 case "nob":
267 myGenerator = myGenerator.withHighlight(highlight,
268 new Color(0xffaaaa));
269 break;
270 case "bow":
271 case "wob":
272 myGenerator = myGenerator.withHighlight(highlight,
273 new Color(0xff0000));
274 break;
275 default:
276 myGenerator = myGenerator.withHighlight(highlight,
277 new Color(0xaaffaa));
278 break;
279 }
280
281 if (showTitle) {
282 if (isRxn)
283 myGenerator = myGenerator.withRxnTitle();
284 else
285 myGenerator = myGenerator.withMolTitle();
286 }
287
288 final Depiction depiction = isRxn ? myGenerator.depict(rxn)
289 : isRgp ? myGenerator.depict(mols, mols.size(), 1)
290 : myGenerator.depict(atomContainer);
291 return depiction;
292 }
293
294 private void contractHydrates(IAtomContainer mol) {
295 Set<IAtom> hydrate = new HashSet<>();
296 for (IAtom atom : mol.atoms()) {
297 if (atom.getAtomicNumber() == 8 &&
298 atom.getImplicitHydrogenCount() == 2 &&
299 mol.getConnectedAtomsList(atom).size() == 0)
300 hydrate.add(atom);
301 }
302 if (hydrate.size() < 2)
303 return;
304 @SuppressWarnings("unchecked")
305 java.util.List<Sgroup> sgroups = mol.getProperty(CDKConstants.CTAB_SGROUPS, java.util.List.class);
306
307 if (sgroups == null)
308 mol.setProperty(CDKConstants.CTAB_SGROUPS,
309 sgroups = new ArrayList<>());
310 else
311 sgroups = new ArrayList<>(sgroups);
312
313 Sgroup sgrp = new Sgroup();
314 for (IAtom atom : hydrate)
315 sgrp.addAtom(atom);
316 sgrp.putValue(SgroupKey.CtabParentAtomList,
317 Collections.singleton(hydrate.iterator().next()));
318 sgrp.setType(SgroupType.CtabMultipleGroup);
319 sgrp.setSubscript(Integer.toString(hydrate.size()));
320
321 sgroups.add(sgrp);
322 }
323
324 private boolean add(Set<IAtom> set, Set<IAtom> atomsToAdd) {
325 boolean res = true;
326 for (IAtom atom : atomsToAdd) {
327 if (!set.add(atom))
328 res = false;
329 }
330 return res;
331 }
332
333 private void abbreviate(IReaction rxn, String mode, String annotate) {
334 Multimap<IAtomContainer, Sgroup> sgroupmap = ArrayListMultimap.create();
335 switch (mode.toLowerCase()) {
336 case "true":
337 case "on":
338 case "yes":
339 for (IAtomContainer mol : rxn.getReactants().atomContainers()) {
340 contractHydrates(mol);
341 Set<IAtom> atoms = new HashSet<>();
342 java.util.List<Sgroup> newSgroups = new ArrayList<>();
343 for (Sgroup sgroup : abbreviations.generate(mol)) {
344 if (add(atoms, sgroup.getAtoms()))
345 newSgroups.add(sgroup);
346 }
347 sgroupmap.putAll(mol, newSgroups);
348 }
349 for (IAtomContainer mol : rxn.getProducts().atomContainers()) {
350 contractHydrates(mol);
351 Set<IAtom> atoms = new HashSet<>();
352 java.util.List<Sgroup> newSgroups = new ArrayList<>();
353 for (Sgroup sgroup : abbreviations.generate(mol)) {
354 if (add(atoms, sgroup.getAtoms()))
355 newSgroups.add(sgroup);
356 }
357 sgroupmap.putAll(mol, newSgroups);
358 }
359 for (IAtomContainer mol : rxn.getAgents().atomContainers()) {
360 contractHydrates(mol);
361 reagents.apply(mol);
362 abbreviations.apply(mol);
363 }
364 break;
365 case "groups":
366 for (IAtomContainer mol : rxn.getAgents().atomContainers()) {
367 contractHydrates(mol);
368 abbreviations.apply(mol);
369 }
370 break;
371 case "reagents":
372 for (IAtomContainer mol : rxn.getAgents().atomContainers()) {
373 contractHydrates(mol);
374 reagents.apply(mol);
375 }
376 break;
377 }
378
379 Set<String> include = new HashSet<>();
380 for (Map.Entry<IAtomContainer, Sgroup> e : sgroupmap.entries()) {
381 final IAtomContainer mol = e.getKey();
382 final Sgroup abbrv = e.getValue();
383 int numAtoms = mol.getAtomCount();
384 if (abbrv.getBonds().isEmpty()) {
385 include.add(abbrv.getSubscript());
386 } else {
387 int numAbbr = abbrv.getAtoms().size();
388 double f = numAbbr / (double) numAtoms;
389 if (numAtoms - numAbbr > 1 && f <= 0.4) {
390 include.add(abbrv.getSubscript());
391 }
392 }
393 }
394
395 for (Map.Entry<IAtomContainer, Collection<Sgroup>> e : sgroupmap.asMap().entrySet()) {
396 final IAtomContainer mol = e.getKey();
397
398 java.util.List<Sgroup> sgroups = mol.getProperty(CDKConstants.CTAB_SGROUPS);
399 if (sgroups == null)
400 sgroups = new ArrayList<>();
401 else
402 sgroups = new ArrayList<>(sgroups);
403 mol.setProperty(CDKConstants.CTAB_SGROUPS, sgroups);
404
405 for (Sgroup abbrv : e.getValue()) {
406 if (include.contains(abbrv.getSubscript()))
407 sgroups.add(abbrv);
408 }
409 }
410 }
411
412 private void abbreviate(IAtomContainer mol, String mode, String annotate) {
413 switch (mode.toLowerCase()) {
414 case "true":
415 case "on":
416 case "yes":
417 case "groups":
418 contractHydrates(mol);
419 abbreviations.apply(mol);
420 break;
421 case "reagents":
422 contractHydrates(mol);
423 break;
424 }
425 // remove abbreviations of mapped atoms
426 if ("mapidx".equals(annotate)) {
427 java.util.List<Sgroup> sgroups = mol.getProperty(CDKConstants.CTAB_SGROUPS);
428 java.util.List<Sgroup> filtered = new ArrayList<>();
429 if (sgroups != null) {
430 for (Sgroup sgroup : sgroups) {
431 // turn off display short-cuts
432 if (sgroup.getType() == SgroupType.CtabAbbreviation ||
433 sgroup.getType() == SgroupType.CtabMultipleGroup) {
434 boolean okay = true;
435 for (IAtom atom : sgroup.getAtoms()) {
436 if (atom.getProperty(CDKConstants.ATOM_ATOM_MAPPING) != null) {
437 okay = false;
438 break;
439 }
440 }
441 if (okay) filtered.add(sgroup);
442 } else {
443 filtered.add(sgroup);
444 }
445 }
446 mol.setProperty(CDKConstants.CTAB_SGROUPS, filtered);
447 }
448 }
449 }
450
451 private boolean isRxnSmi(String smi) {
452 return smi.split(" ")[0].contains(">");
453 }
454
455 private static DepictionGenerator withStyle(DepictionGenerator generator, String style) {
456 switch (style) {
457 case "cow":
458 generator = generator.withAtomColors(new CDK2DAtomColors())
459 .withBackgroundColor(Color.WHITE)
460 .withOuterGlowHighlight();
461 break;
462 case "bow":
463 generator = generator.withAtomColors(new UniColor(Color.BLACK))
464 .withBackgroundColor(Color.WHITE);
465 break;
466 case "wob":
467 generator = generator.withAtomColors(new UniColor(Color.WHITE))
468 .withBackgroundColor(Color.BLACK);
469 break;
470 case "cob":
471 generator = generator.withAtomColors(new RcdkDepictor.CobColorer())
472 .withBackgroundColor(Color.BLACK)
473 .withOuterGlowHighlight();
474 break;
475 case "nob":
476 generator = generator.withAtomColors(new RcdkDepictor.NobColorer())
477 .withBackgroundColor(Color.BLACK)
478 .withOuterGlowHighlight();
479 break;
480 }
481 return generator;
482 }
483
484 private static final class CobColorer implements IAtomColorer {
485 private final CDK2DAtomColors colors = new CDK2DAtomColors();
486
487 @Override
488 public Color getAtomColor(IAtom atom) {
489 Color res = colors.getAtomColor(atom);
490 if (res.equals(Color.BLACK))
491 return Color.WHITE;
492 else
493 return res;
494 }
495
496 @Override
497 public Color getAtomColor(IAtom atom, Color color) {
498 Color res = colors.getAtomColor(atom);
499 if (res.equals(Color.BLACK))
500 return Color.WHITE;
501 else
502 return res;
503 }
504 }
505
506 /**
507 * Neon-on-black atom colors.
508 */
509 private static final class NobColorer implements IAtomColorer {
510 private final CDK2DAtomColors colors = new CDK2DAtomColors();
511 private final Color NEON = new Color(0x00FF0E);
512
513 @Override
514 public Color getAtomColor(IAtom atom) {
515 Color res = colors.getAtomColor(atom);
516 if (res.equals(Color.BLACK))
517 return NEON;
518 else
519 return res;
520 }
521
522 @Override
523 public Color getAtomColor(IAtom atom, Color color) {
524 Color res = colors.getAtomColor(atom, color);
525 if (res.equals(Color.BLACK))
526 return NEON;
527 else
528 return res;
529 }
530 }
531
532 /**
533 * Find matching atoms and bonds in the reaction or molecule.
534 *
535 * @param sma SMARTS pattern
536 * @param rxn reaction
537 * @param mol molecule
538 * @return set of matched atoms and bonds
539 */
540 private Set<IChemObject> findHits(final String sma, final IReaction rxn, final IAtomContainer mol,
541 final int limit) {
542
543
544 Set<IChemObject> highlight = new HashSet<>();
545 if (!sma.isEmpty()) {
546 SmartsPattern smartsPattern;
547 try {
548 smartsPattern = SmartsPattern.create(sma, null);
549 } catch (Exception | Error e) {
550 return Collections.emptySet();
551 }
552 if (mol != null) {
553 for (Map<IChemObject, IChemObject> m : smartsPattern.matchAll(mol)
554 .limit(limit)
555 .uniqueAtoms()
556 .toAtomBondMap()) {
557 for (Map.Entry<IChemObject, IChemObject> e : m.entrySet()) {
558 highlight.add(e.getValue());
559 }
560 }
561 } else if (rxn != null) {
562 for (Map<IChemObject, IChemObject> m : smartsPattern.matchAll(rxn)
563 .limit(limit)
564 .uniqueAtoms()
565 .toAtomBondMap()) {
566 for (Map.Entry<IChemObject, IChemObject> e : m.entrySet()) {
567 highlight.add(e.getValue());
568 }
569 }
570 }
571 }
572 return highlight;
573
574 }
575
576 }