private static void replaceReferencesWithClones(final IChemModel chemModel)
			throws CDKException {
		// we make references in products/reactants clones, since same compounds
		// in different reactions need separate layout (different positions etc)
		if (chemModel.getReactionSet() != null) {
			for (final IReaction reaction : chemModel.getReactionSet()
					.reactions()) {
				int i = 0;
				final IAtomContainerSet products = reaction.getProducts();
				for (final IAtomContainer product : products.atomContainers()) {
					try {
						products.replaceAtomContainer(i, product.clone());
					} catch (final CloneNotSupportedException e) {
					}
					i++;
				}
				i = 0;
				final IAtomContainerSet reactants = reaction.getReactants();
				for (final IAtomContainer reactant : reactants.atomContainers()) {
					try {
						reactants.replaceAtomContainer(i, reactant.clone());
					} catch (final CloneNotSupportedException e) {
					}
					i++;
				}
			}
		}
	}
 /**
  * Takes an object which subclasses IChemObject, e.g.Molecule, and will read this (from file,
  * database, internet etc). If the specific implementation does not support a specific IChemObject
  * it will throw an Exception.
  *
  * @param object The object that subclasses IChemObject
  * @return The IChemObject read
  * @exception CDKException
  */
 public IChemObject read(IChemObject object) throws CDKException {
   if (object instanceof IReaction) {
     return (IChemObject) readReaction(object.getBuilder());
   } else if (object instanceof IReactionSet) {
     IReactionSet reactionSet = object.getBuilder().newReactionSet();
     reactionSet.addReaction(readReaction(object.getBuilder()));
     return reactionSet;
   } else if (object instanceof IChemModel) {
     IChemModel model = object.getBuilder().newChemModel();
     IReactionSet reactionSet = object.getBuilder().newReactionSet();
     reactionSet.addReaction(readReaction(object.getBuilder()));
     model.setReactionSet(reactionSet);
     return model;
   } else if (object instanceof IChemFile) {
     IChemFile chemFile = object.getBuilder().newChemFile();
     IChemSequence sequence = object.getBuilder().newChemSequence();
     sequence.addChemModel((IChemModel) read(object.getBuilder().newChemModel()));
     chemFile.addChemSequence(sequence);
     return chemFile;
   } else {
     throw new CDKException(
         "Only supported are Reaction and ChemModel, and not "
             + object.getClass().getName()
             + ".");
   }
 }
	public static IChemModel emptyModel() {
		final IChemModel chemModel = DefaultChemObjectBuilder.getInstance()
				.newInstance(IChemModel.class);
		chemModel.setMoleculeSet(chemModel.getBuilder().newInstance(
				IAtomContainerSet.class));
		chemModel.getMoleculeSet().addAtomContainer(
				chemModel.getBuilder().newInstance(IAtomContainer.class));
		return chemModel;
	}
Пример #4
0
 private IChemModel readChemModel(IChemModel chemModel) throws CDKException {
   IAtomContainerSet setOfMolecules = chemModel.getMoleculeSet();
   if (setOfMolecules == null) {
     setOfMolecules = chemModel.getBuilder().newInstance(IAtomContainerSet.class);
   }
   IAtomContainer m = readAtomContainer(chemModel.getBuilder().newInstance(IAtomContainer.class));
   if (m != null && m instanceof IAtomContainer) {
     setOfMolecules.addAtomContainer((IAtomContainer) m);
   }
   chemModel.setMoleculeSet(setOfMolecules);
   return chemModel;
 }
Пример #5
0
 @TestMethod("testReadReactions1")
 public <T extends IChemObject> T read(T object) throws CDKException {
   if (object instanceof IReaction) {
     return (T) readReaction(object.getBuilder());
   } else if (object instanceof IChemModel) {
     IChemModel model = object.getBuilder().newInstance(IChemModel.class);
     IReactionSet reactionSet = object.getBuilder().newInstance(IReactionSet.class);
     reactionSet.addReaction(readReaction(object.getBuilder()));
     model.setReactionSet(reactionSet);
     return (T) model;
   } else {
     throw new CDKException(
         "Only supported are Reaction and ChemModel, and not "
             + object.getClass().getName()
             + ".");
   }
 }
  private IChemFile readChemFile() throws CDKException {
    IChemSequence seq = file.getBuilder().newChemSequence();
    IChemModel model = file.getBuilder().newChemModel();
    IMoleculeSet containerSet = file.getBuilder().newMoleculeSet();
    IMolecule container = file.getBuilder().newMolecule();

    int lineNumber = 0;

    try {
      String line = input.readLine();
      while (input.ready() && line != null) {
        logger.debug((lineNumber++) + ": ", line);
        String command = null;
        if (isCommand(line)) {
          command = getCommand(line);
          int lineCount = getContentLinesCount(line);
          if ("ATOMS".equals(command)) {
            processAtomsBlock(lineCount, container);
          } else if ("BONDS".equals(command)) {
            processBondsBlock(lineCount, container);
          } else if ("IDENT".equals(command)) {
            processIdentBlock(lineCount, container);
          } else if ("NAME".equals(command)) {
            processNameBlock(lineCount, container);
          } else {
            // skip lines
            logger.warn("Dropping block: ", command);
            for (int i = 0; i < lineCount; i++) input.readLine();
          }
        } else {
          logger.warn("Unexpected content at line: ", lineNumber);
        }
        line = input.readLine();
      }
      containerSet.addAtomContainer(container);
      model.setMoleculeSet(containerSet);
      seq.addChemModel(model);
      file.addChemSequence(seq);
    } catch (Exception exception) {
      String message = "Error while parsing CTX file: " + exception.getMessage();
      logger.error(message);
      logger.debug(exception);
      throw new CDKException(message, exception);
    }
    return file;
  }
	private static void removeDuplicateAtomContainers(final IChemModel chemModel) {
		// we remove molecules which are in AtomContainerSet as well as in a
		// reaction
		final IReactionSet reactionSet = chemModel.getReactionSet();
		final IAtomContainerSet moleculeSet = chemModel.getMoleculeSet();
		if (reactionSet != null && moleculeSet != null) {
			final List<IAtomContainer> aclist = ReactionSetManipulator
					.getAllAtomContainers(reactionSet);
			for (int i = moleculeSet.getAtomContainerCount() - 1; i >= 0; i--) {
				for (int k = 0; k < aclist.size(); k++) {
					final String label = moleculeSet.getAtomContainer(i)
							.getID();
					if (aclist.get(k).getID().equals(label)) {
						chemModel.getMoleculeSet().removeAtomContainer(i);
						break;
					}
				}
			}
		}
	}
	private static void setReactionIDs(final IChemModel chemModel) {
		// we give all reactions an ID, in case they have none
		// IDs are needed for handling in JCP
		final IReactionSet reactionSet = chemModel.getReactionSet();
		if (reactionSet != null) {
			int i = 0;
			for (final IReaction reaction : reactionSet.reactions()) {
				if (reaction.getID() == null) {
					reaction.setID("Reaction " + ++i);
				}
			}
		}
	}
Пример #9
0
  private IReaction checkForXReactionFile(IChemFile chemFile, int numberOfReactions) {
    Assert.assertNotNull(chemFile);

    Assert.assertEquals(chemFile.getChemSequenceCount(), 1);
    org.openscience.cdk.interfaces.IChemSequence seq = chemFile.getChemSequence(0);
    Assert.assertNotNull(seq);

    Assert.assertEquals(seq.getChemModelCount(), 1);
    org.openscience.cdk.interfaces.IChemModel model = seq.getChemModel(0);
    Assert.assertNotNull(model);

    IReactionSet reactionSet = model.getReactionSet();
    Assert.assertNotNull(reactionSet);

    Assert.assertEquals(reactionSet.getReactionCount(), numberOfReactions);
    IReaction reaction = null;
    for (int i = 0; i < numberOfReactions; i++) {
      reaction = reactionSet.getReaction(i);
      Assert.assertNotNull(reaction);
    }
    return reaction;
  }
Пример #10
0
  private IMolecule checkForXMoleculeFile(IChemFile chemFile, int numberOfMolecules) {
    Assert.assertNotNull(chemFile);

    Assert.assertEquals(chemFile.getChemSequenceCount(), 1);
    org.openscience.cdk.interfaces.IChemSequence seq = chemFile.getChemSequence(0);
    Assert.assertNotNull(seq);

    Assert.assertEquals(seq.getChemModelCount(), 1);
    org.openscience.cdk.interfaces.IChemModel model = seq.getChemModel(0);
    Assert.assertNotNull(model);

    org.openscience.cdk.interfaces.IMoleculeSet moleculeSet = model.getMoleculeSet();
    Assert.assertNotNull(moleculeSet);

    Assert.assertEquals(moleculeSet.getMoleculeCount(), numberOfMolecules);
    IMolecule mol = null;
    for (int i = 0; i < numberOfMolecules; i++) {
      mol = moleculeSet.getMolecule(i);
      Assert.assertNotNull(mol);
    }
    return mol;
  }
	/**
	 * Clean up chemical model ,removing duplicates empty molecules etc
	 * 
	 * @param chemModel
	 * @param avoidOverlap
	 * @throws CDKException
	 */
	public static void cleanUpChemModel(final IChemModel chemModel,
			final boolean avoidOverlap, final AbstractJChemPaintPanel panel)
			throws CDKException {
		JChemPaint.setReactionIDs(chemModel);
		JChemPaint.replaceReferencesWithClones(chemModel);

		// check the model is not completely empty
		if (ChemModelManipulator.getBondCount(chemModel) == 0
				&& ChemModelManipulator.getAtomCount(chemModel) == 0) {
			throw new CDKException(
					"Structure does not have bonds or atoms. Cannot depict structure.");
		}
		JChemPaint.removeDuplicateAtomContainers(chemModel);
		JChemPaint.checkCoordinates(chemModel);
		JChemPaint.removeEmptyAtomContainers(chemModel);

		if (avoidOverlap) {
			try {
				ControllerHub.avoidOverlap(chemModel);
			} catch (final Exception e) {
				JOptionPane.showMessageDialog(panel,
						GT._("Structure could not be generated"));
				throw new CDKException("Cannot depict structure");
			}
		}

		// We update implicit Hs in any case
		final CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher
				.getInstance(chemModel.getBuilder());
		for (final IAtomContainer container : ChemModelManipulator
				.getAllAtomContainers(chemModel)) {
			for (final IAtom atom : container.atoms()) {
				if (!(atom instanceof IPseudoAtom)) {
					try {
						final IAtomType type = matcher.findMatchingAtomType(
								container, atom);
						if (type != null
								&& type.getFormalNeighbourCount() != null) {
							final int connectedAtomCount = container
									.getConnectedAtomsCount(atom);
							atom.setImplicitHydrogenCount(type
									.getFormalNeighbourCount()
									- connectedAtomCount);
						}
					} catch (final CDKException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
	private static void checkCoordinates(final IChemModel chemModel)
			throws CDKException {
		for (final IAtomContainer next : ChemModelManipulator
				.getAllAtomContainers(chemModel)) {
			if (!GeometryTools.get2DCoordinateCoverage(next).equals(
					GeometryTools.CoordinateCoverage.FULL)) {
				final String error = GT._("Not all atoms have 2D coordinates."
						+ " JCP can only show full 2D specified structures."
						+ " Shall we lay out the structure?");
				final int answer = JOptionPane.showConfirmDialog(null, error,
						"No 2D coordinates", JOptionPane.YES_NO_OPTION);

				if (answer == JOptionPane.NO_OPTION) {
					throw new CDKException(
							GT._("Cannot display without 2D coordinates"));
				} else {
					// CreateCoordinatesForFileDialog frame =
					// new CreateCoordinatesForFileDialog(chemModel);
					// frame.pack();
					// frame.show();

					WaitDialog.showDialog();
					final List<IAtomContainer> acs = ChemModelManipulator
							.getAllAtomContainers(chemModel);
					generate2dCoordinates(acs);
					WaitDialog.hideDialog();
					return;
				}
			}
		}

		/*
		 * Add implicit hydrogens (in ControllerParameters,
		 * autoUpdateImplicitHydrogens is true by default, so we need to do that
		 * anyway)
		 */
		final CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(chemModel
				.getBuilder());
		for (final IAtomContainer molecule : ChemModelManipulator
				.getAllAtomContainers(chemModel)) {
			if (molecule != null) {
				try {
					hAdder.addImplicitHydrogens(molecule);
				} catch (final CDKException e) {
					// do nothing
				}
			}
		}
	}
	public static JChemPaintPanel showInstance(final IChemModel chemModel,
			final String title, final boolean debug) {
		final JFrame f = new JFrame(title + " - JChemPaint");
		chemModel.setID(title);
		f.addWindowListener(new JChemPaintPanel.AppCloser());
		f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		final JChemPaintPanel p = new JChemPaintPanel(chemModel,
				GUI_APPLICATION, debug, null, new ArrayList<String>());
		p.updateStatusBar();
		f.setPreferredSize(new Dimension(800, 494)); // 1.618
		f.add(p);
		f.pack();
		final Point point = GraphicsEnvironment.getLocalGraphicsEnvironment()
				.getCenterPoint();
		final int w2 = f.getWidth() / 2;
		final int h2 = f.getHeight() / 2;
		f.setLocation(point.x - w2, point.y - h2);
		f.setVisible(true);
		frameList.add(f);
		return p;
	}
	private static void removeEmptyAtomContainers(final IChemModel chemModel) {
		final IAtomContainerSet moleculeSet = chemModel.getMoleculeSet();
		if (moleculeSet != null && moleculeSet.getAtomContainerCount() == 0) {
			chemModel.setMoleculeSet(null);
		}
	}
	/**
	 * Inserts a molecule into the current set, usually from Combobox or Insert
	 * field, with possible shifting of the existing set.
	 * 
	 * @param chemPaintPanel
	 * @param molecule
	 * @param generateCoordinates
	 * @param shiftPanel
	 * @throws CDKException
	 */
	public static void generateModel(
			final AbstractJChemPaintPanel chemPaintPanel,
			IAtomContainer molecule, final boolean generateCoordinates,
			final boolean shiftPasted) throws CDKException {
		if (molecule == null) {
			return;
		}

		final IChemModel chemModel = chemPaintPanel.getChemModel();
		IAtomContainerSet moleculeSet = chemModel.getMoleculeSet();
		if (moleculeSet == null) {
			moleculeSet = new AtomContainerSet();
		}

		// On copy & paste on top of an existing drawn structure, prevent the
		// pasted section to be drawn exactly on top or to far away from the
		// original by shifting it to a fixed position next to it.

		if (shiftPasted) {
			double maxXCurr = Double.NEGATIVE_INFINITY;
			double minXPaste = Double.POSITIVE_INFINITY;

			for (final IAtomContainer atc : moleculeSet.atomContainers()) {
				// Detect the right border of the current structure..
				for (final IAtom atom : atc.atoms()) {
					if (atom.getPoint2d().x > maxXCurr) {
						maxXCurr = atom.getPoint2d().x;
					}
				}
				// Detect the left border of the pasted structure..
				for (final IAtom atom : molecule.atoms()) {
					if (atom.getPoint2d().x < minXPaste) {
						minXPaste = atom.getPoint2d().x;
					}
				}
			}

			if (maxXCurr != Double.NEGATIVE_INFINITY
					&& minXPaste != Double.POSITIVE_INFINITY) {
				// Shift the pasted structure to be nicely next to the existing
				// one.
				final int MARGIN = 1;
				final double SHIFT = maxXCurr - minXPaste;
				for (final IAtom atom : molecule.atoms()) {
					atom.setPoint2d(new Point2d(atom.getPoint2d().x + MARGIN
							+ SHIFT, atom.getPoint2d().y));
				}
			}
		}

		if (generateCoordinates) {
			// now generate 2D coordinates
			final StructureDiagramGenerator sdg = new StructureDiagramGenerator();
			sdg.setTemplateHandler(new TemplateHandler(moleculeSet.getBuilder()));
			try {
				sdg.setMolecule(molecule);
				sdg.generateCoordinates(new Vector2d(0, 1));
				molecule = sdg.getMolecule();
			} catch (final Exception exc) {
				JOptionPane.showMessageDialog(chemPaintPanel,
						GT._("Structure could not be generated"));
				throw new CDKException("Cannot depict structure");
			}
		}

		if (moleculeSet.getAtomContainer(0).getAtomCount() == 0) {
			moleculeSet.getAtomContainer(0).add(molecule);
		} else {
			moleculeSet.addAtomContainer(molecule);
		}

		final IUndoRedoFactory undoRedoFactory = chemPaintPanel.get2DHub()
				.getUndoRedoFactory();
		final UndoRedoHandler undoRedoHandler = chemPaintPanel.get2DHub()
				.getUndoRedoHandler();

		if (undoRedoFactory != null) {
			final IUndoRedoable undoredo = undoRedoFactory
					.getAddAtomsAndBondsEdit(chemPaintPanel.get2DHub()
							.getIChemModel(), molecule, null, "Paste",
							chemPaintPanel.get2DHub());
			undoRedoHandler.postEdit(undoredo);
		}

		chemPaintPanel.getChemModel().setMoleculeSet(moleculeSet);
		chemPaintPanel.updateUndoRedoControls();
		chemPaintPanel.get2DHub().updateView();
	}
Пример #16
0
  /**
   * Read a ChemFile from a file in MDL SDF format.
   *
   * @return The ChemFile that was read from the MDL file.
   */
  private IChemFile readChemFile(IChemFile chemFile) throws CDKException {
    IChemSequence chemSequence = chemFile.getBuilder().newInstance(IChemSequence.class);

    IChemModel chemModel = chemFile.getBuilder().newInstance(IChemModel.class);
    IAtomContainerSet setOfMolecules = chemFile.getBuilder().newInstance(IAtomContainerSet.class);
    IAtomContainer m = readAtomContainer(chemFile.getBuilder().newInstance(IAtomContainer.class));
    if (m != null && m instanceof IAtomContainer) {
      setOfMolecules.addAtomContainer((IAtomContainer) m);
    }
    chemModel.setMoleculeSet(setOfMolecules);
    chemSequence.addChemModel(chemModel);

    setOfMolecules = chemFile.getBuilder().newInstance(IAtomContainerSet.class);
    chemModel = chemFile.getBuilder().newInstance(IChemModel.class);
    String str;
    try {
      String line;
      while ((line = input.readLine()) != null) {
        logger.debug("line: ", line);
        // apparently, this is a SDF file, continue with
        // reading mol files
        str = new String(line);
        if (str.equals("$$$$")) {
          m = readAtomContainer(chemFile.getBuilder().newInstance(IAtomContainer.class));

          if (m != null && m instanceof IAtomContainer) {
            setOfMolecules.addAtomContainer((IAtomContainer) m);

            chemModel.setMoleculeSet(setOfMolecules);
            chemSequence.addChemModel(chemModel);

            setOfMolecules = chemFile.getBuilder().newInstance(IAtomContainerSet.class);
            chemModel = chemFile.getBuilder().newInstance(IChemModel.class);
          }
        } else {
          // here the stuff between 'M  END' and '$$$$'
          if (m != null) {
            // ok, the first lines should start with '>'
            String fieldName = null;
            if (str.startsWith("> ")) {
              // ok, should extract the field name
              str.substring(2); // String content =
              int index = str.indexOf("<");
              if (index != -1) {
                int index2 = str.substring(index).indexOf(">");
                if (index2 != -1) {
                  fieldName = str.substring(index + 1, index + index2);
                }
              }
            }
            if (line == null) {
              throw new CDKException("Expecting data line here, but found null!");
            }
            StringBuilder data = new StringBuilder();
            int dataLineCount = 0;
            boolean lineIsContinued = false;
            while ((line = input.readLine()) != null) {

              if (line.equals(" ") && dataLineCount == 0) {
                // apparently a file can have a field whose value is a single space. Moronic
                // we check for it *before* trimming it. ideally we should check for any length
                // of whitespace

                // In adition some SD files have the blank line after the value line contain
                // a space, rather than being a true blank line. So we only store a blank value
                // line if it's the first line after the key line
                data.append(line);
                lineIsContinued = false;
                dataLineCount++;
                if (!lineIsContinued && dataLineCount > 1)
                  data.append(System.getProperty("line.separator"));
                continue;
              }

              line = line.trim();
              if (line.length() == 0) break;

              if (line.equals("$$$$")) {
                logger.error("Expecting data line here, but found end of molecule: ", line);
                break;
              }
              logger.debug("data line: ", line);
              lineIsContinued = false; // reset property
              dataLineCount++;

              // preserve newlines, unless the line is exactly 80 chars;
              // in that case it is assumed to continue on the next line.
              // See MDL documentation.
              if (!lineIsContinued && dataLineCount > 1)
                data.append(System.getProperty("line.separator"));

              // add the data line
              data.append(line);

              // check if the line will be continued on the next line
              if (line.length() == 80) lineIsContinued = true;
            }

            if (fieldName != null) {
              logger.info("fieldName, data: ", fieldName, ", ", data);
              m.setProperty(fieldName, data.toString());
            }
          }
        }
      }
    } catch (CDKException cdkexc) {
      throw cdkexc;
    } catch (Exception exception) {
      String error = "Error while parsing SDF";
      logger.error(error);
      logger.debug(exception);
      throw new CDKException(error, exception);
    }
    try {
      input.close();
    } catch (Exception exc) {
      String error = "Error while closing file: " + exc.getMessage();
      logger.error(error);
      throw new CDKException(error, exc);
    }

    chemFile.addChemSequence(chemSequence);
    return chemFile;
  }