Example #1
1
  @Test
  public void testMDMoleculeCustomization() {
    StringWriter writer = new StringWriter();

    CMLWriter cmlWriter = new CMLWriter(writer);
    cmlWriter.registerCustomizer(new MDMoleculeCustomizer());
    try {
      IAtomContainer molecule = makeMDBenzene();
      cmlWriter.write(molecule);

    } catch (Exception exception) {
      logger.error("Error while creating an CML2 file: ", exception.getMessage());
      logger.debug(exception);
      Assert.fail(exception.getMessage());
    }
    String cmlContent = writer.toString();
    logger.debug("****************************** testMDMoleculeCustomization()");
    logger.debug(cmlContent);
    logger.debug("******************************");
    //        System.out.println("****************************** testMDMoleculeCustomization()");
    //        System.out.println(cmlContent);
    //        System.out.println("******************************");
    Assert.assertTrue(cmlContent.indexOf("xmlns:md") != -1);
    Assert.assertTrue(cmlContent.indexOf("md:residue\"") != -1);
    Assert.assertTrue(cmlContent.indexOf("md:resNumber\"") != -1);
    Assert.assertTrue(cmlContent.indexOf("md:chargeGroup\"") != -1);
    Assert.assertTrue(cmlContent.indexOf("md:cgNumber\"") != -1);
    Assert.assertTrue(cmlContent.indexOf("md:switchingAtom\"") != -1);
  }
Example #2
0
 /**
  * Selects an optimum edge for elimination in structures without N2 nodes.
  *
  * <p>This might be severely broken! Would have helped if there was an explanation of how this
  * algorithm worked.
  *
  * @param ring
  * @param molecule
  */
 private IBond checkEdges(IRing ring, IAtomContainer molecule) {
   IRing r1, r2;
   IRingSet ringSet = ring.getBuilder().newInstance(IRingSet.class);
   IBond bond;
   int minMaxSize = Integer.MAX_VALUE;
   int minMax = 0;
   logger.debug("Molecule: " + molecule);
   Iterator<IBond> bonds = ring.bonds().iterator();
   while (bonds.hasNext()) {
     bond = (IBond) bonds.next();
     molecule.removeElectronContainer(bond);
     r1 = getRing(bond.getAtom(0), molecule);
     r2 = getRing(bond.getAtom(1), molecule);
     logger.debug("checkEdges: " + bond);
     if (r1.getAtomCount() > r2.getAtomCount()) {
       ringSet.addAtomContainer(r1);
     } else {
       ringSet.addAtomContainer(r2);
     }
     molecule.addBond(bond);
   }
   for (int i = 0; i < ringSet.getAtomContainerCount(); i++) {
     if (((IRing) ringSet.getAtomContainer(i)).getBondCount() < minMaxSize) {
       minMaxSize = ((IRing) ringSet.getAtomContainer(i)).getBondCount();
       minMax = i;
     }
   }
   return (IBond) ring.getElectronContainer(minMax);
 }
Example #3
0
 /**
  * Starts the reading of the CML file. Whenever a new Molecule is read, a event is thrown to the
  * ReaderListener.
  */
 public void process() throws CDKException {
   logger.debug("Started parsing from input...");
   try {
     parser.setFeature("http://xml.org/sax/features/validation", false);
     logger.info("Deactivated validation");
   } catch (SAXException e) {
     logger.warn("Cannot deactivate validation.");
   }
   parser.setContentHandler(new EventCMLHandler(this, builder));
   parser.setEntityResolver(new CMLResolver());
   parser.setErrorHandler(new CMLErrorHandler());
   try {
     logger.debug("Parsing from Reader");
     parser.parse(new InputSource(input));
   } catch (IOException e) {
     String error = "Error while reading file: " + e.getMessage();
     logger.error(error);
     logger.debug(e);
     throw new CDKException(error, e);
   } catch (SAXParseException saxe) {
     SAXParseException spe = (SAXParseException) saxe;
     String error = "Found well-formedness error in line " + spe.getLineNumber();
     logger.error(error);
     logger.debug(saxe);
     throw new CDKException(error, saxe);
   } catch (SAXException saxe) {
     String error = "Error while parsing XML: " + saxe.getMessage();
     logger.error(error);
     logger.debug(saxe);
     throw new CDKException(error, saxe);
   }
 }
Example #4
0
 /**
  * Returns the ring that is formed by the atoms in the given vector.
  *
  * @param vec The vector that contains the atoms of the ring
  * @param mol The molecule this ring is a substructure of
  * @return The ring formed by the given atoms
  */
 private IRing prepareRing(List vec, IAtomContainer mol) {
   // add the atoms in vec to the new ring
   int atomCount = vec.size();
   IRing ring = mol.getBuilder().newInstance(IRing.class, atomCount);
   IAtom[] atoms = new IAtom[atomCount];
   vec.toArray(atoms);
   ring.setAtoms(atoms);
   // add the bonds in mol to the new ring
   try {
     IBond b;
     for (int i = 0; i < atomCount - 1; i++) {
       b = mol.getBond(atoms[i], atoms[i + 1]);
       if (b != null) {
         ring.addBond(b);
       } else {
         logger.error("This should not happen.");
       }
     }
     b = mol.getBond(atoms[0], atoms[atomCount - 1]);
     if (b != null) {
       ring.addBond(b);
     } else {
       logger.error("This should not happen either.");
     }
   } catch (Exception exc) {
     logger.debug(exc);
   }
   logger.debug("found Ring  ", ring);
   return ring;
 }
Example #5
0
 public Point2d getPoint2d() {
   Point2d point2d = super.getPoint2d();
   if (point2d == null) {
     logger.debug("Getting point2d: null");
   } else {
     logger.debug("Getting point2d: x=" + point2d.x + ", y=" + point2d.y);
   }
   return point2d;
 }
Example #6
0
 public Point3d getPoint3d() {
   Point3d point3d = super.getPoint3d();
   if (point3d == null) {
     logger.debug("Getting point3d: null");
   } else {
     logger.debug("Getting point3d: x=" + point3d.x + ", y=" + point3d.y, ", z=" + point3d.z);
   }
   return point3d;
 }
  /** Returns true if another IMolecule can be read. */
  public boolean hasNext() {
    if (!nextAvailableIsKnown) {
      hasNext = false;

      // now try to parse the next Molecule
      try {
        if ((currentLine = input.readLine()) != null) {
          currentFormat = (IChemFormat) MDLFormat.getInstance();
          StringBuffer buffer = new StringBuffer();
          while (currentLine != null && !currentLine.equals("M  END")) {
            // still in a molecule
            buffer.append(currentLine);
            buffer.append(System.getProperty("line.separator"));

            currentLine = input.readLine();

            // do MDL molfile version checking
            if (currentLine.contains("V2000") || currentLine.contains("v2000")) {
              currentFormat = (IChemFormat) MDLV2000Format.getInstance();
            } else if (currentLine.contains("V3000") || currentLine.contains("v3000")) {
              currentFormat = (IChemFormat) MDLV3000Format.getInstance();
            }
          }
          buffer.append(currentLine);
          buffer.append(System.getProperty("line.separator"));
          logger.debug("MDL file part read: ", buffer);
          ISimpleChemObjectReader reader = factory.createReader(currentFormat);
          reader.setReader(new StringReader(buffer.toString()));
          if (currentFormat instanceof MDLV2000Format) {
            reader.addChemObjectIOListener(this);
            ((MDLV2000Reader) reader).customizeJob();
          }
          nextMolecule = (IMolecule) reader.read(builder.newInstance(IMolecule.class));

          // note that a molecule may have 0 atoms, but still
          // be useful (by having SD tags for example), so just
          // check for null'ness rather than atom count
          hasNext = nextMolecule != null;

          // now read the data part
          currentLine = input.readLine();
          readDataBlockInto(nextMolecule);
        } else {
          hasNext = false;
        }
      } catch (Exception exception) {
        logger.error("Error while reading next molecule: " + exception.getMessage());
        logger.debug(exception);
        hasNext = false;
      }
      if (!hasNext) nextMolecule = null;
      nextAvailableIsKnown = true;
    }
    return hasNext;
  }
Example #8
0
 /**
  * Place all hydrogens connected to atoms which have already been laid out.
  *
  * @param container atom container
  * @param bondLength bond length to user
  */
 @TestMethod("testBug933572,testH2")
 public void placeHydrogens2D(final IAtomContainer container, final double bondLength) {
   logger.debug("placing hydrogens on all atoms");
   for (IAtom atom : container.atoms()) {
     // only place hydrogens for atoms which have coordinates
     if (atom.getPoint2d() != null) {
       placeHydrogens2D(container, atom, bondLength);
     }
   }
   logger.debug("hydrogen placement complete");
 }
Example #9
0
 private void init() {
   boolean success = false;
   // If JAXP is prefered (comes with Sun JVM 1.4.0 and higher)
   if (!success) {
     try {
       javax.xml.parsers.SAXParserFactory spf = javax.xml.parsers.SAXParserFactory.newInstance();
       spf.setNamespaceAware(true);
       javax.xml.parsers.SAXParser saxParser = spf.newSAXParser();
       parser = saxParser.getXMLReader();
       logger.info("Using JAXP/SAX XML parser.");
       success = true;
     } catch (ParserConfigurationException | SAXException e) {
       logger.warn("Could not instantiate JAXP/SAX XML reader: ", e.getMessage());
       logger.debug(e);
     }
   }
   // Aelfred is first alternative.
   if (!success) {
     try {
       parser =
           (XMLReader)
               this.getClass()
                   .getClassLoader()
                   .loadClass("gnu.xml.aelfred2.XmlReader")
                   .newInstance();
       logger.info("Using Aelfred2 XML parser.");
       success = true;
     } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
       logger.warn("Could not instantiate Aelfred2 XML reader!");
       logger.debug(e);
     }
   }
   // Xerces is second alternative
   if (!success) {
     try {
       parser =
           (XMLReader)
               this.getClass()
                   .getClassLoader()
                   .loadClass("org.apache.xerces.parsers.SAXParser")
                   .newInstance();
       logger.info("Using Xerces XML parser.");
       success = true;
     } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
       logger.warn("Could not instantiate Xerces XML reader!");
       logger.debug(e);
     }
   }
   if (!success) {
     logger.error("Could not instantiate any XML parser!");
   }
 }
Example #10
0
  /** @cdk.bug 891021 */
  @Test
  public void testBug891021() throws Exception {
    IAtomContainer molecule = null;
    String filename = "data/mdl/too.many.rings.mol";
    InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename);
    MDLV2000Reader reader = new MDLV2000Reader(ins, Mode.STRICT);
    molecule = (IAtomContainer) reader.read((IChemObject) new AtomContainer());
    logger.debug("Testing " + filename);

    IRingSet ringSet = new SSSRFinder(molecule).findSSSR();
    logger.debug("Found ring set of size: " + ringSet.getAtomContainerCount());
    Assert.assertEquals(57, ringSet.getAtomContainerCount());
  }
Example #11
0
 private String readLine() throws CDKException {
   String line = null;
   try {
     line = input.readLine();
     logger.debug("read line: " + line);
   } catch (Exception exception) {
     String error = "Unexpected error while reading file: " + exception.getMessage();
     logger.error(error);
     logger.debug(exception);
     throw new CDKException(error, exception);
   }
   return line;
 }
Example #12
0
 /**
  * A unit test for JUnit
  *
  * @exception Exception Description of the Exception
  */
 @Test
 public void testResolveOverlap2() throws Exception {
   logger.debug("Test case with neither bond nor atom overlap");
   String filename = "data/cml/overlaptest2.cml";
   InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename);
   CMLReader reader = new CMLReader(ins);
   IChemFile chemFile = (IChemFile) reader.read(new ChemFile());
   IAtomContainer atomContainer =
       (IAtomContainer) ChemFileManipulator.getAllAtomContainers(chemFile).get(0);
   // MoleculeViewer2D.display(new AtomContainer(atomContainer), false);
   double score = new OverlapResolver().getOverlapScore(atomContainer, new Vector(), new Vector());
   Assert.assertEquals(0.0, score, 0.0001);
   logger.debug("End of test case with neither bond nor atom overlap");
 }
Example #13
0
  /**
   * Generated coordinates for a given ring, which is connected to a spiro ring. The rings share
   * exactly one atom.
   *
   * @param ring The ring to be placed
   * @param sharedAtoms The atoms of this ring, also members of another ring, which are already
   *     placed
   * @param sharedAtomsCenter The geometric center of these atoms
   * @param ringCenterVector A vector pointing the the center of the new ring
   * @param bondLength The standard bondlength
   */
  public void placeSpiroRing(
      IRing ring,
      IAtomContainer sharedAtoms,
      Point2d sharedAtomsCenter,
      Vector2d ringCenterVector,
      double bondLength) {

    logger.debug("placeSpiroRing");
    double radius = getNativeRingRadius(ring, bondLength);
    Point2d ringCenter = new Point2d(sharedAtomsCenter);
    ringCenterVector.normalize();
    ringCenterVector.scale(radius);
    ringCenter.add(ringCenterVector);
    double addAngle = 2 * Math.PI / ring.getRingSize();

    IAtom startAtom = sharedAtoms.getAtom(0);

    // double centerX = ringCenter.x;
    // double centerY = ringCenter.y;

    // int direction = 1;

    IAtom currentAtom = startAtom;
    double startAngle =
        GeometryTools.getAngle(
            startAtom.getPoint2d().x - ringCenter.x, startAtom.getPoint2d().y - ringCenter.y);
    /*
     * Get one bond connected to the spiro bridge atom.
     * It doesn't matter in which direction we draw.
     */
    java.util.List bonds = ring.getConnectedBondsList(startAtom);

    IBond currentBond = (IBond) bonds.get(0);

    Vector atomsToDraw = new Vector();
    /*
     * Store all atoms to draw in consequtive order relative to the
     * chosen bond.
     */
    for (int i = 0; i < ring.getBondCount(); i++) {
      currentBond = ring.getNextBond(currentBond, currentAtom);
      currentAtom = currentBond.getConnectedAtom(currentAtom);
      atomsToDraw.addElement(currentAtom);
    }
    logger.debug("currentAtom  " + currentAtom);
    logger.debug("startAtom  " + startAtom);

    atomPlacer.populatePolygonCorners(atomsToDraw, ringCenter, startAngle, addAngle, radius);
  }
Example #14
0
  @Test
  public void testLoopProblem() throws Exception {
    String filename = "data/mdl/ring_03419.mol";
    InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename);
    MDLV2000Reader reader = new MDLV2000Reader(ins, Mode.STRICT);
    IAtomContainer molecule = (IAtomContainer) reader.read((IChemObject) new AtomContainer());
    logger.debug("Testing " + filename);

    IRingSet ringSet = new SSSRFinder(molecule).findSSSR();
    logger.debug("Found ring set of size: " + ringSet.getAtomContainerCount());
    Assert.assertEquals(12, ringSet.getAtomContainerCount());
    for (int f = 0; f < ringSet.getAtomContainerCount(); f++) {
      IRing ring = (IRing) ringSet.getAtomContainer(f);
      logger.debug("ring: " + toString(ring, molecule));
    }
  }
Example #15
0
  /**
   * Performs the pharmacophore matching.
   *
   * @param atomContainer The target molecule. Must have 3D coordinates
   * @param initializeTarget If <i>true</i>, the target molecule specified in the first argument
   *     will be analyzed to identify matching pharmacophore groups. If <i>false</i> this is not
   *     performed. The latter case is only useful when dealing with conformers since for a given
   *     molecule, all conformers will have the same pharmacophore groups and only the constraints
   *     will change from one conformer to another.
   * @return true is the target molecule contains the query pharmacophore
   * @throws org.openscience.cdk.exception.CDKException if the query pharmacophore was not set or
   *     the query is invalid or if the molecule does not have 3D coordinates
   */
  public boolean matches(IAtomContainer atomContainer, boolean initializeTarget)
      throws CDKException {
    if (!GeometryUtil.has3DCoordinates(atomContainer))
      throw new CDKException("Molecule must have 3D coordinates");
    if (pharmacophoreQuery == null)
      throw new CDKException("Must set the query pharmacophore before matching");
    if (!checkQuery(pharmacophoreQuery))
      throw new CDKException(
          "A problem in the query. Make sure all pharmacophore groups of the same symbol have the same same SMARTS");
    String title = (String) atomContainer.getProperty(CDKConstants.TITLE);

    if (initializeTarget) pharmacophoreMolecule = getPharmacophoreMolecule(atomContainer);
    else {
      // even though the atoms comprising the pcore groups are
      // constant, their coords will differ, so we need to make
      // sure we get the latest set of effective coordinates
      for (IAtom iAtom : pharmacophoreMolecule.atoms()) {
        PharmacophoreAtom patom = (PharmacophoreAtom) iAtom;
        List<Integer> tmpList = new ArrayList<Integer>();
        for (int idx : patom.getMatchingAtoms()) tmpList.add(idx);
        Point3d coords = getEffectiveCoordinates(atomContainer, tmpList);
        patom.setPoint3d(coords);
      }
    }

    if (pharmacophoreMolecule.getAtomCount() < pharmacophoreQuery.getAtomCount()) {
      logger.debug("Target [" + title + "] did not match the query SMARTS. Skipping constraints");
      return false;
    }

    mappings = Pattern.findSubstructure(pharmacophoreQuery).matchAll(pharmacophoreMolecule);

    // XXX: doing one search then discarding
    return mappings.atLeast(1);
  }
Example #16
0
  /**
   * Layout all rings in the given RingSet that are connected to a given Ring
   *
   * @param rs The RingSet to be searched for rings connected to Ring
   * @param ring The Ring for which all connected rings in RingSet are to be layed out.
   */
  void placeConnectedRings(IRingSet rs, IRing ring, int handleType, double bondLength) {
    IRingSet connectedRings = rs.getConnectedRings(ring);
    IRing connectedRing;
    IAtomContainer sharedAtoms;
    int sac;
    Point2d oldRingCenter, sharedAtomsCenter, tempPoint;
    Vector2d tempVector, oldRingCenterVector, newRingCenterVector;

    //		logger.debug(rs.reportRingList(molecule));
    for (IAtomContainer container : connectedRings.atomContainers()) {
      connectedRing = (IRing) container;
      if (!connectedRing.getFlag(CDKConstants.ISPLACED)) {
        //				logger.debug(ring.toString(molecule));
        //				logger.debug(connectedRing.toString(molecule));
        sharedAtoms = AtomContainerManipulator.getIntersection(ring, connectedRing);
        sac = sharedAtoms.getAtomCount();
        logger.debug("placeConnectedRings-> connectedRing: " + (ring.toString()));
        if ((sac == 2 && handleType == FUSED)
            || (sac == 1 && handleType == SPIRO)
            || (sac > 2 && handleType == BRIDGED)) {
          sharedAtomsCenter = GeometryTools.get2DCenter(sharedAtoms);
          oldRingCenter = GeometryTools.get2DCenter(ring);
          tempVector = (new Vector2d(sharedAtomsCenter));
          newRingCenterVector = new Vector2d(tempVector);
          newRingCenterVector.sub(new Vector2d(oldRingCenter));
          oldRingCenterVector = new Vector2d(newRingCenterVector);
          logger.debug(
              "placeConnectedRing -> tempVector: "
                  + tempVector
                  + ", tempVector.length: "
                  + tempVector.length());
          logger.debug("placeConnectedRing -> bondCenter: " + sharedAtomsCenter);
          logger.debug(
              "placeConnectedRing -> oldRingCenterVector.length(): "
                  + oldRingCenterVector.length());
          logger.debug(
              "placeConnectedRing -> newRingCenterVector.length(): "
                  + newRingCenterVector.length());
          tempPoint = new Point2d(sharedAtomsCenter);
          tempPoint.add(newRingCenterVector);
          placeRing(connectedRing, sharedAtoms, sharedAtomsCenter, newRingCenterVector, bondLength);
          connectedRing.setFlag(CDKConstants.ISPLACED, true);
          placeConnectedRings(rs, connectedRing, handleType, bondLength);
        }
      }
    }
  }
  /**
   * @param removeHydrogen
   * @param reaction
   * @param algorithm
   */
  public CalculationProcess(
      boolean removeHydrogen, IReaction reaction, IMappingAlgorithm algorithm) {

    /*
     * This case handles rings cases where 6 membered ring reduces to 5 membered rings Example KEGG reaction R01432
     * of Isomerase class
     */
    super(reaction);

    //        System.out.println("I am CalculationProcess");
    this.removeHydrogen = removeHydrogen;
    logger.debug("\n|++++++++++++++++++++++++++++|");
    logger.debug("Performing Atom-Atom Mapping ....... " + reaction.getID() + " .......");
    logger.debug("\n|++++++++++++++++++++++++++++|");
    this.algorithm = algorithm;
    run();
  }
 private String skipOtherFieldHeaderLines(String str) throws IOException {
   while (str.startsWith("> ")) {
     logger.debug("data header line: ", currentLine);
     currentLine = input.readLine();
     str = new String(currentLine);
   }
   return str;
 }
Example #19
0
 /**
  * A unit test for JUnit
  *
  * @exception Exception Description of the Exception
  */
 @Test
 public void testResolveOverlap4() throws Exception {
   double overlapScore = 0;
   logger.debug("Test case with atom clash");
   String filename = "data/cml/overlaptest.cml";
   InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename);
   CMLReader reader = new CMLReader(ins);
   IChemFile chemFile = (IChemFile) reader.read(new ChemFile());
   IAtomContainer atomContainer =
       (IAtomContainer) ChemFileManipulator.getAllAtomContainers(chemFile).get(0);
   // MoleculeViewer2D.display(new AtomContainer(atomContainer), false);
   OverlapResolver or = new OverlapResolver();
   overlapScore = or.resolveOverlap(atomContainer, null);
   // MoleculeViewer2D.display(new AtomContainer(atomContainer), false);
   Assert.assertEquals(0.0, overlapScore, 0.0001);
   logger.debug("End of test case with atom clash");
 }
Example #20
0
 /**
  * A unit test for JUnit
  *
  * @exception Exception Description of the Exception
  */
 @Test
 public void testResolveOverlap5() throws Exception {
   double overlapScore = 0;
   logger.debug("Test case with atom clash");
   IAtomContainer atomContainer =
       new SmilesParser(DefaultChemObjectBuilder.getInstance())
           .parseSmiles("OC4C(N2C1=C(C(=NC(=N1)SC)SC)C3=C2N=CN=C3N)OC(C4O)CO");
   StructureDiagramGenerator sdg = new StructureDiagramGenerator();
   sdg.setMolecule(new AtomContainer(atomContainer));
   sdg.generateCoordinates();
   atomContainer = sdg.getMolecule();
   OverlapResolver or = new OverlapResolver();
   overlapScore = or.resolveOverlap(atomContainer, null);
   // MoleculeViewer2D.display(new AtomContainer(atomContainer), true);
   Assert.assertEquals(0.0, overlapScore, 0.0001);
   logger.debug("End of test case with atom clash");
 }
  /**
   * Initiate process. It is needed to call the addExplicitHydrogensToSatisfyValency from the class
   * tools.HydrogenAdder.
   *
   * @param reactants reactants of the reaction
   * @param agents agents of the reaction (Must be in this case null)
   * @exception CDKException Description of the Exception
   */
  @TestMethod("testInitiate_IMoleculeSet_IMoleculeSet")
  public IReactionSet initiate(IMoleculeSet reactants, IMoleculeSet agents) throws CDKException {

    logger.debug("initiate reaction: HeterolyticCleavagePBReaction");

    if (reactants.getMoleculeCount() != 1) {
      throw new CDKException("HeterolyticCleavagePBReaction only expects one reactant");
    }
    if (agents != null) {
      throw new CDKException("HeterolyticCleavagePBReaction don't expects agents");
    }

    IReactionSet setOfReactions =
        DefaultChemObjectBuilder.getInstance().newInstance(IReactionSet.class);
    IMolecule reactant = reactants.getMolecule(0);

    /* if the parameter hasActiveCenter is not fixed yet, set the active centers*/
    IParameterReact ipr = super.getParameterClass(SetReactionCenter.class);
    if (ipr != null && !ipr.isSetParameter()) setActiveCenters(reactant);

    Iterator<IBond> bondis = reactant.bonds().iterator();
    while (bondis.hasNext()) {
      IBond bondi = bondis.next();
      IAtom atom1 = bondi.getAtom(0);
      IAtom atom2 = bondi.getAtom(1);
      if (bondi.getFlag(CDKConstants.REACTIVE_CENTER)
          && bondi.getOrder() != IBond.Order.SINGLE
          && atom1.getFlag(CDKConstants.REACTIVE_CENTER)
          && atom2.getFlag(CDKConstants.REACTIVE_CENTER)
          && (atom1.getFormalCharge() == CDKConstants.UNSET ? 0 : atom1.getFormalCharge()) == 0
          && (atom2.getFormalCharge() == CDKConstants.UNSET ? 0 : atom2.getFormalCharge()) == 0
          && reactant.getConnectedSingleElectronsCount(atom1) == 0
          && reactant.getConnectedSingleElectronsCount(atom2) == 0) {

        /**/
        for (int j = 0; j < 2; j++) {

          ArrayList<IAtom> atomList = new ArrayList<IAtom>();
          if (j == 0) {
            atomList.add(atom1);
            atomList.add(atom2);
          } else {
            atomList.add(atom2);
            atomList.add(atom1);
          }
          ArrayList<IBond> bondList = new ArrayList<IBond>();
          bondList.add(bondi);

          IMoleculeSet moleculeSet = reactant.getBuilder().newInstance(IMoleculeSet.class);
          moleculeSet.addMolecule(reactant);
          IReaction reaction = mechanism.initiate(moleculeSet, atomList, bondList);
          if (reaction == null) continue;
          else setOfReactions.addReaction(reaction);
        }
      }
    }
    return setOfReactions;
  }
 public void processIOSettingQuestion(IOSetting setting) {
   if (setting.getName().equals(forceReadAs3DCoords.getName())) {
     try {
       setting.setSetting(forceReadAs3DCoords.getSetting());
     } catch (CDKException e) {
       logger.debug("Could not propagate forceReadAs3DCoords setting");
     }
   }
 }
Example #23
0
 private boolean isReady() throws CDKException {
   try {
     return input.ready();
   } catch (Exception exception) {
     String error = "Unexpected error while reading file: " + exception.getMessage();
     logger.error(error);
     logger.debug(exception);
     throw new CDKException(error, exception);
   }
 }
Example #24
0
 public Object clone() throws CloneNotSupportedException {
   Object clone = null;
   try {
     clone = super.clone();
   } catch (Exception exception) {
     logger.error("Could not clone DebugAtom: " + exception.getMessage(), exception);
     logger.debug(exception);
   }
   return clone;
 }
 private String extractFieldData(String str) throws IOException {
   StringBuilder data = new StringBuilder();
   while (str.trim().length() > 0) {
     logger.debug("data line: ", currentLine);
     data.append(str);
     currentLine = input.readLine();
     str = new String(currentLine).trim();
   }
   return data.toString();
 }
 private synchronized void run() {
   switch (algorithm) {
     case MIN:
       logger.debug("Processing Reaction for Local Minimum: ");
       delta = (int) calRelation(reaction, MIN);
       break;
     case MAX:
       logger.debug("Processing Reaction for Global Minimum: ");
       delta = (int) calRelation(reaction, MAX);
       break;
     case MIXTURE:
       logger.debug("Processing Reaction for Max-Mixture Model: ");
       delta = (int) calRelation(reaction, MIXTURE);
       break;
     case RINGS:
       logger.debug("Processing Reaction for Ring Model: ");
       delta = (int) calRelation(reaction, RINGS);
       break;
   }
 }
 /** @inheritDoc */
 @TestMethod(
     "testIsEmpty_MoleculeSet,testIsEmpty_RingSet,testIsEmpty_Crystal,testIsEmpty_ReactionSet")
 @Override
 public boolean isEmpty() {
   boolean res = true;
   if (setOfMolecules != null && !setOfMolecules.isEmpty()) res = false;
   if (setOfReactions != null && !setOfReactions.isEmpty()) res = false;
   if (ringSet != null && !ringSet.isEmpty()) res = false;
   if (crystal != null && !crystal.isEmpty()) res = false;
   logger.debug("Checking if chemModel is empty: ", res);
   return res;
 }
Example #28
0
  /**
   * Positions the aliphatic substituents of a ring system
   *
   * @param rs The RingSystem for which the substituents are to be laid out
   * @return A list of atoms that where laid out
   */
  public IAtomContainer placeRingSubstituents(IRingSet rs, double bondLength) {
    logger.debug("RingPlacer.placeRingSubstituents() start");
    IRing ring = null;
    IAtom atom = null;
    IRingSet rings = null;
    IAtomContainer unplacedPartners = rs.getBuilder().newInstance(IAtomContainer.class);
    IAtomContainer sharedAtoms = rs.getBuilder().newInstance(IAtomContainer.class);
    IAtomContainer primaryAtoms = rs.getBuilder().newInstance(IAtomContainer.class);
    IAtomContainer treatedAtoms = rs.getBuilder().newInstance(IAtomContainer.class);
    Point2d centerOfRingGravity = null;
    for (int j = 0; j < rs.getAtomContainerCount(); j++) {
      ring = (IRing) rs.getAtomContainer(j); /* Get the j-th Ring in RingSet rs */
      for (int k = 0; k < ring.getAtomCount(); k++) {
        unplacedPartners.removeAllElements();
        sharedAtoms.removeAllElements();
        primaryAtoms.removeAllElements();
        atom = ring.getAtom(k);
        rings = rs.getRings(atom);
        centerOfRingGravity = GeometryTools.get2DCenter(rings);
        atomPlacer.partitionPartners(atom, unplacedPartners, sharedAtoms);
        atomPlacer.markNotPlaced(unplacedPartners);
        try {
          for (int f = 0; f < unplacedPartners.getAtomCount(); f++) {
            logger.debug(
                "placeRingSubstituents->unplacedPartners: "
                    + (molecule.getAtomNumber(unplacedPartners.getAtom(f)) + 1));
          }
        } catch (Exception exc) {
        }

        treatedAtoms.add(unplacedPartners);
        if (unplacedPartners.getAtomCount() > 0) {
          atomPlacer.distributePartners(
              atom, sharedAtoms, centerOfRingGravity, unplacedPartners, bondLength);
        }
      }
    }
    logger.debug("RingPlacer.placeRingSubstituents() end");
    return treatedAtoms;
  }
Example #29
0
  /**
   * Place hydrogens connected to the provided atom <i>atom</i> using the specified
   * <i>bondLength</i>.
   *
   * @param container atom container
   * @param bondLength bond length to user
   * @throws IllegalArgumentException thrown if the <i>atom</i> or <i>container</i> was null or the
   *     atom has connected atoms which have not been placed.
   */
  @TestMethod("testNoConnections,testNullContainer,unplacedNonHydrogen")
  public void placeHydrogens2D(IAtomContainer container, IAtom atom, double bondLength) {

    if (container == null)
      throw new IllegalArgumentException("cannot place hydrogens, no container provided");
    if (atom.getPoint2d() == null)
      throw new IllegalArgumentException("cannot place hydrogens on atom without coordinates");

    logger.debug(
        "placing hydrogens connected to atom ", atom.getSymbol(),
        ": ", atom.getPoint2d());
    logger.debug("bond length", bondLength);

    AtomPlacer atomPlacer = new AtomPlacer();
    atomPlacer.setMolecule(container);

    List<IAtom> connected = container.getConnectedAtomsList(atom);
    IAtomContainer placed = container.getBuilder().newInstance(IAtomContainer.class);
    IAtomContainer unplaced = container.getBuilder().newInstance(IAtomContainer.class);

    // divide connected atoms into those which are have and haven't been placed
    for (final IAtom conAtom : connected) {
      if (conAtom.getPoint2d() == null) {
        if (conAtom.getSymbol().equals("H")) {
          unplaced.addAtom(conAtom);
        } else {
          throw new IllegalArgumentException(
              "cannot place hydrogens, atom has connected" + " non-hydrogens without coordinates");
        }
      } else {
        placed.addAtom(conAtom);
      }
    }

    logger.debug("Atom placement before procedure:");
    logger.debug("Centre atom ", atom.getSymbol(), ": ", atom.getPoint2d());
    for (int i = 0; i < unplaced.getAtomCount(); i++) {
      logger.debug("H-" + i, ": ", unplaced.getAtom(i).getPoint2d());
    }

    Point2d centerPlacedAtoms = GeometryTools.get2DCenter(placed);
    atomPlacer.distributePartners(atom, placed, centerPlacedAtoms, unplaced, bondLength);

    logger.debug("Atom placement after procedure:");
    logger.debug("Centre atom ", atom.getSymbol(), ": ", atom.getPoint2d());
    for (int i = 0; i < unplaced.getAtomCount(); i++) {
      logger.debug("H-" + i, ": ", unplaced.getAtom(i).getPoint2d());
    }
  }
Example #30
0
 /**
  * Generated coordinates for a given ring. Multiplexes to special handlers for the different
  * possible situations (spiro-, fusion-, bridged attachement)
  *
  * @param ring The ring to be placed
  * @param sharedAtoms The atoms of this ring, also members of another ring, which are already
  *     placed
  * @param sharedAtomsCenter The geometric center of these atoms
  * @param ringCenterVector A vector pointing the the center of the new ring
  * @param bondLength The standard bondlength
  */
 public void placeRing(
     IRing ring,
     IAtomContainer sharedAtoms,
     Point2d sharedAtomsCenter,
     Vector2d ringCenterVector,
     double bondLength) {
   int sharedAtomCount = sharedAtoms.getAtomCount();
   logger.debug("placeRing -> sharedAtomCount: " + sharedAtomCount);
   if (sharedAtomCount > 2) {
     placeBridgedRing(ring, sharedAtoms, sharedAtomsCenter, ringCenterVector, bondLength);
   } else if (sharedAtomCount == 2) {
     placeFusedRing(ring, sharedAtoms, sharedAtomsCenter, ringCenterVector, bondLength);
   } else if (sharedAtomCount == 1) {
     placeSpiroRing(ring, sharedAtoms, sharedAtomsCenter, ringCenterVector, bondLength);
   }
 }