Ejemplo n.º 1
0
 private boolean getIfBondIsNotRotatable(Molecule mol, IBond bond, IAtomContainer detected) {
   boolean isBondNotRotatable = false;
   int counter = 0;
   IAtom atom0 = bond.getAtom(0);
   IAtom atom1 = bond.getAtom(1);
   if (detected != null) {
     if (detected.contains(bond)) counter += 1;
   }
   if (atom0.getFlag(CDKConstants.ISINRING)) {
     if (atom1.getFlag(CDKConstants.ISINRING)) {
       counter += 1;
     } else {
       if (atom1.getSymbol().equals("H")) counter += 1;
       else counter += 0;
     }
   }
   if (atom0.getSymbol().equals("N") && atom1.getSymbol().equals("C")) {
     if (getIfACarbonIsDoubleBondedToAnOxygen(mol, atom1)) counter += 1;
   }
   if (atom0.getSymbol().equals("C") && atom1.getSymbol().equals("N")) {
     if (getIfACarbonIsDoubleBondedToAnOxygen(mol, atom0)) counter += 1;
   }
   if (counter > 0) isBondNotRotatable = true;
   return isBondNotRotatable;
 }
  private Map<IAtom, List<String>> labelAtomsBySymbol(IAtomContainer atomCont) {
    Map<IAtom, List<String>> label_list = new HashMap<>();

    for (int i = 0; i < atomCont.getAtomCount(); i++) {
      List<String> label = new ArrayList<>(7);
      for (int a = 0; a < 7; a++) {
        label.add(a, "Z9");
      }

      IAtom refAtom = atomCont.getAtom(i);
      /*
       * Important Step: Discriminate between source atom types
       */
      String referenceAtom;
      if (refAtom instanceof IQueryAtom) {
        referenceAtom =
            ((IQueryAtom) refAtom).getSymbol() == null ? "*" : ((IQueryAtom) refAtom).getSymbol();
        //                System.out.println("referenceAtom " + referenceAtom);
      } else if (!(refAtom instanceof IQueryAtom) && this.matchAtomType) {
        referenceAtom =
            refAtom.getAtomTypeName() == null ? refAtom.getSymbol() : refAtom.getAtomTypeName();
      } else {
        referenceAtom = refAtom.getSymbol();
      }
      label.set(0, referenceAtom);
      List<IAtom> connAtoms = atomCont.getConnectedAtomsList(refAtom);

      int counter = 1;

      for (IAtom negAtom : connAtoms) {
        String neighbouringAtom;
        if (refAtom instanceof IQueryAtom) {
          neighbouringAtom =
              ((IQueryAtom) negAtom).getSymbol() == null ? "*" : ((IQueryAtom) negAtom).getSymbol();
          //                    System.out.println("neighbouringAtom " + neighbouringAtom);
        } else if (!(negAtom instanceof IQueryAtom) && this.matchAtomType) {
          neighbouringAtom =
              negAtom.getAtomTypeName() == null ? negAtom.getSymbol() : negAtom.getAtomTypeName();
        } else {
          neighbouringAtom = negAtom.getSymbol();
        }
        label.set(counter, neighbouringAtom);
        counter += 1;
      }
      //            System.out.println("label " + label);
      bubbleSort(label);
      label_list.put(refAtom, label);
    }
    return label_list;
  }
Ejemplo n.º 3
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());
    }
  }
  /**
   * Generate Compatibility Graph Nodes
   *
   * @return
   * @throws IOException
   */
  private int compatibilityGraphNodes() throws IOException {

    compGraphNodes.clear();

    Set<Edge> edges = new HashSet<>();

    int nodeCount = 1;
    Map<IAtom, List<String>> labelAtomsBySymbolA = labelAtomsBySymbol(source);
    Map<IAtom, List<String>> labelAtomsBySymbolB = labelAtomsBySymbol(target);

    for (Map.Entry<IAtom, List<String>> labelA : labelAtomsBySymbolA.entrySet()) {
      //            System.err.println("labelA.getValue() " + labelA.getValue());
      for (Map.Entry<IAtom, List<String>> labelB : labelAtomsBySymbolB.entrySet()) {
        IAtom atom = labelA.getKey();
        if (((atom instanceof IQueryAtom) && ((IQueryAtom) atom).matches(labelB.getKey()))
            || (!(atom instanceof IQueryAtom)
                && atom.getSymbol().equals(labelB.getKey().getSymbol()))) {
          //                        System.err.println("labelB.getValue() " + labelB.getValue());
          int atomNumberI = source.getAtomNumber(labelA.getKey());
          int atomNumberJ = target.getAtomNumber(labelB.getKey());
          Edge e = new Edge(atomNumberI, atomNumberJ);
          if (!edges.contains(e)) {
            edges.add(e);
            compGraphNodes.add(atomNumberI);
            compGraphNodes.add(atomNumberJ);
            compGraphNodes.add(nodeCount);
            nodeCount += 1;
          }
        }
      }
    }
    return 0;
  }
Ejemplo n.º 5
0
  /**
   * Modules for cleaning a molecule
   *
   * @param molecule
   * @return cleaned AtomContainer
   */
  @TestMethod("testCheckAndCleanMolecule")
  public static IAtomContainer checkAndCleanMolecule(IAtomContainer molecule) {
    boolean isMarkush = false;
    for (IAtom atom : molecule.atoms()) {
      if (atom.getSymbol().equals("R")) {
        isMarkush = true;
        break;
      }
    }

    if (isMarkush) {
      System.err.println("Skipping Markush structure for sanity check");
    }

    // Check for salts and such
    if (!ConnectivityChecker.isConnected(molecule)) {
      // lets see if we have just two parts if so, we assume its a salt and just work
      // on the larger part. Ideally we should have a check to ensure that the smaller
      //  part is a metal/halogen etc.
      IMoleculeSet fragments = ConnectivityChecker.partitionIntoMolecules(molecule);
      if (fragments.getMoleculeCount() > 2) {
        System.err.println("More than 2 components. Skipped");
      } else {
        IMolecule frag1 = fragments.getMolecule(0);
        IMolecule frag2 = fragments.getMolecule(1);
        if (frag1.getAtomCount() > frag2.getAtomCount()) {
          molecule = frag1;
        } else {
          molecule = frag2;
        }
      }
    }
    configure(molecule);
    return molecule;
  }
Ejemplo n.º 6
0
 public Rectangle2D layoutElectronPairs(
     IAtom atom, IAtomContainer container, int lonePairCount, Graphics2D g) {
   if (lonePairCount == 0) {
     return null;
   }
   Point2d atomPoint = atom.getPoint2d();
   Rectangle2D atomSymbolBounds = this.getTextBounds(g, atom.getSymbol());
   BitSet positions = this.labelManager.getAtomAnnotationPositions(atom);
   double r = this.params.electronRadius;
   double d = r * 2.0;
   for (int i = 0; i < lonePairCount; ++i) {
     LabelManager.AnnotationPosition position = this.labelManager.getNextSparePosition(positions);
     Vector2d v = this.labelManager.getVectorFromPosition(position);
     Vector2d leftPerp = this.labelManager.getLeftPerpendicularFromPosition(position);
     Vector2d rightPerp = this.labelManager.getRightPerpendicularFromPosition(position);
     double dx = (atomSymbolBounds.getWidth() / 2.0 + d) * v.x;
     double dy = (atomSymbolBounds.getHeight() / 2.0 + d) * v.y;
     Point2d lp = new Point2d(atomPoint.x + dx, atomPoint.y + dy);
     Point2d llp = new Point2d(lp);
     llp.scaleAdd(
         (double) (this.params.lonePairSeparation / 2), (Tuple2d) leftPerp, (Tuple2d) llp);
     Point2d rlp = new Point2d(lp);
     rlp.scaleAdd(
         (double) (this.params.lonePairSeparation / 2), (Tuple2d) rightPerp, (Tuple2d) rlp);
     g.fill(new Ellipse2D.Double(llp.x - r, llp.y - r, d, d));
     g.fill(new Ellipse2D.Double(rlp.x - r, rlp.y - r, d, d));
     positions.set(position.ordinal());
   }
   return null;
 }
Ejemplo n.º 7
0
  /** @cdk.bug 2142400 */
  @Test
  public void testHydrogenCount2() throws Exception {
    String cmlString =
        "<molecule><atomArray>"
            + "<atom id='a1' elementType='C' hydrogenCount='4'/>"
            + "<atom id='a2' elementType='H'/>"
            + "<atom id='a3' elementType='H'/>"
            + "<atom id='a4' elementType='H'/>"
            + "<atom id='a5' elementType='H'/>"
            + "</atomArray>"
            + "<bondArray>"
            + "<bond id='b1' atomRefs2='a1 a2' order='S'/>"
            + "<bond id='b2' atomRefs2='a1 a3' order='S'/>"
            + "<bond id='b3' atomRefs2='a1 a4' order='S'/>"
            + "<bond id='b4' atomRefs2='a1 a5' order='S'/>"
            + "</bondArray></molecule>";

    IChemFile chemFile = parseCMLString(cmlString);
    IMolecule mol = checkForSingleMoleculeFile(chemFile);

    Assert.assertEquals(5, mol.getAtomCount());
    IAtom atom = mol.getAtom(0);
    Assert.assertNotNull(atom);
    Assert.assertEquals("C", atom.getSymbol());
    Assert.assertNotNull(atom.getImplicitHydrogenCount());
    Assert.assertEquals(0, atom.getImplicitHydrogenCount().intValue());
  }
Ejemplo n.º 8
0
 public boolean matches(IAtom atom) {
   if (atom.getSymbol().equals(this.getSymbol()) && atom.getFlag(CDKConstants.ISAROMATIC)) {
     return true;
   } else {
     return false;
   }
 }
  @Test
  public void testSybylAtomTypePerceptionBenzene()
      throws CDKException, FileNotFoundException, IOException, BioclipseException, CoreException,
          InvocationTargetException {

    IAtomContainer ac = MoleculeFactory.makeBenzene();

    ICDKMolecule mol = new CDKMolecule(ac);

    debug.perceiveSybylAtomTypes(mol);

    System.out.println("** BENZENE **");

    System.out.println(AtomContainerDiff.diff(ac, mol.getAtomContainer()));

    for (int i = 0; i < mol.getAtomContainer().getAtomCount(); i++) {
      IAtom a = mol.getAtomContainer().getAtom(i);
      System.out.println("Atom: " + a.getSymbol() + i + ", type=" + a.getAtomTypeName());
    }

    assertEquals("C.ar", mol.getAtomContainer().getAtom(0).getAtomTypeName());
    assertEquals("C.ar", mol.getAtomContainer().getAtom(1).getAtomTypeName());
    assertEquals("C.ar", mol.getAtomContainer().getAtom(2).getAtomTypeName());
    assertEquals("C.ar", mol.getAtomContainer().getAtom(3).getAtomTypeName());
    assertEquals("C.ar", mol.getAtomContainer().getAtom(4).getAtomTypeName());
    assertEquals("C.ar", mol.getAtomContainer().getAtom(5).getAtomTypeName());
  }
  /** Converts an Atom to a MSML Atom element */
  protected AtomType convertAtom(IAtom atom, String parentID) {
    AtomType atomElement = new AtomType();
    String id = "";
    if (atom.getID() != null) {
      id = atom.getID();
    } else {
      id = Integer.toString(atom.hashCode());
    }
    String atomID = parentID + PREFIX_ATOM + id;
    atomElement.setId(atomID);
    atomElement.setCustomId("" + id);
    // atom name
    atomElement.setTitle(atom.getAtomTypeName());
    // element name
    atomElement.setElementType(atom.getSymbol());
    double x, y, z;
    // set choords
    if (atom.getPoint3d() != null) {
      x = atom.getPoint3d().x;
      y = atom.getPoint3d().y;
      z = atom.getPoint3d().z;
    } else { // what if mol in 2d? -> has to use getPoint2d
      x = atom.getPoint2d().x;
      y = atom.getPoint2d().y;
      z = 0.0;
    }
    if (atom.getFormalCharge() != null) {
      atomElement.setFormalCharge(BigInteger.valueOf(atom.getFormalCharge()));
    }
    atomElement.setX3(new Float(x));
    atomElement.setY3(new Float(y));
    atomElement.setZ3(new Float(z));

    return atomElement;
  }
Ejemplo n.º 11
0
 public Rectangle2D layoutAtomSymbol(IAtom atom, Graphics2D g) {
   String text = atom.getSymbol();
   if (atom instanceof PseudoAtom) {
     text = ((PseudoAtom) atom).getLabel();
   }
   g.setFont(this.atomSymbolFont);
   Point2d p = atom.getPoint2d();
   return this.layoutText(text, p, g);
 }
Ejemplo n.º 12
0
  /**
   * Constructor
   *
   * @param queryContainer query atom container
   * @param atom query atom
   * @param shouldMatchBonds bond matching flag
   */
  public DefaultVFAtomMatcher(IAtomContainer queryContainer, IAtom atom, boolean shouldMatchBonds) {
    this();
    this.qAtom = atom;
    this.symbol = atom.getSymbol();
    setBondMatchFlag(shouldMatchBonds);

    //        System.out.println("Atom " + atom.getSymbol());
    //        System.out.println("MAX allowed " + maximumNeighbors);
  }
Ejemplo n.º 13
0
 private boolean isTerminal(IAtom atom, IAtomContainer atomContainer) {
   int numberOfHeavyAtomsConnected = 0;
   for (IAtom connected : atomContainer.getConnectedAtomsList(atom)) {
     if (connected.getSymbol().equals("H")) {
       continue;
     }
     ++numberOfHeavyAtomsConnected;
   }
   return numberOfHeavyAtomsConnected < 2;
 }
  /**
   * compGraphNodesCZero is used to build up of the edges of the compatibility graph
   *
   * @return
   * @throws IOException
   */
  private Integer compatibilityGraphNodesIfCEdgeIsZero() throws IOException {

    int count_nodes = 1;
    List<String> list = new ArrayList<>();
    compGraphNodesCZero = new ArrayList<>(); // Initialize the compGraphNodesCZero List
    LabelContainer labelContainer = LabelContainer.getInstance();
    compGraphNodes.clear();

    for (int i = 0; i < source.getAtomCount(); i++) {
      for (int j = 0; j < target.getAtomCount(); j++) {
        IAtom atom1 = source.getAtom(i);
        IAtom atom2 = target.getAtom(j);

        // You can also check object equal or charge, hydrogen count etc
        if ((atom1 instanceof IQueryAtom)
            && ((IQueryAtom) atom1).matches(atom2)
            && !list.contains(i + "_" + j)) {
          compGraphNodesCZero.add(i);
          compGraphNodesCZero.add(j);
          compGraphNodesCZero.add(labelContainer.getLabelID(atom2.getSymbol())); // i.e C is label 1
          compGraphNodesCZero.add(count_nodes);
          compGraphNodes.add(i);
          compGraphNodes.add(j);
          compGraphNodes.add(count_nodes);
          count_nodes += 1;
          list.add(i + "_" + j);
        } else if (atom1.getSymbol().equalsIgnoreCase(atom2.getSymbol())
            && !list.contains(i + "_" + j)) {
          compGraphNodesCZero.add(i);
          compGraphNodesCZero.add(j);
          compGraphNodesCZero.add(labelContainer.getLabelID(atom1.getSymbol())); // i.e C is label 1
          compGraphNodesCZero.add(count_nodes);
          compGraphNodes.add(i);
          compGraphNodes.add(j);
          compGraphNodes.add(count_nodes);
          count_nodes += 1;
          list.add(i + "_" + j);
        }
      }
    }
    list.clear();
    return count_nodes;
  }
Ejemplo n.º 15
0
  @Test
  public void testAtomElementType3() throws Exception {
    String cmlString = "<molecule id='m1'><atomArray atomID='a1' elementType='C'/></molecule>";

    IChemFile chemFile = parseCMLString(cmlString);
    IMolecule mol = checkForSingleMoleculeFile(chemFile);

    Assert.assertEquals(1, mol.getAtomCount());
    IAtom atom = mol.getAtom(0);
    Assert.assertEquals("C", atom.getSymbol());
  }
Ejemplo n.º 16
0
  @Test
  public void testIsotopicMass() throws Exception {
    String cmlString =
        "<molecule><atomArray><atom id='a1' elementType=\"C\"><scalar dataType=\"xsd:float\" dictRef=\"cdk:isotopicMass\">12.0</scalar></atom></atomArray></molecule>";

    IChemFile chemFile = parseCMLString(cmlString);
    IMolecule mol = checkForSingleMoleculeFile(chemFile);

    Assert.assertEquals(1, mol.getAtomCount());
    IAtom atom = mol.getAtom(0);
    Assert.assertEquals("C", atom.getSymbol());
    Assert.assertEquals(12.0, atom.getExactMass().doubleValue(), 0.01);
  }
Ejemplo n.º 17
0
  @Test
  public void testMassNumber() throws Exception {
    String cmlString =
        "<molecule id='m1'><atomArray><atom id='a1' elementType='C' isotopeNumber='12'/></atomArray></molecule>";

    IChemFile chemFile = parseCMLString(cmlString);
    IMolecule mol = checkForSingleMoleculeFile(chemFile);

    Assert.assertEquals(1, mol.getAtomCount());
    IAtom atom = mol.getAtom(0);
    Assert.assertEquals("C", atom.getSymbol());
    Assert.assertEquals(12, atom.getMassNumber().intValue());
  }
Ejemplo n.º 18
0
  @Test
  public void testAtomicNumber() throws Exception {
    String cmlString =
        "<molecule><atomArray><atom id='a1' elementType=\"C\"><scalar dataType=\"xsd:integer\" dictRef=\"cdk:atomicNumber\">6</scalar></atom></atomArray></molecule>";

    IChemFile chemFile = parseCMLString(cmlString);
    IMolecule mol = checkForSingleMoleculeFile(chemFile);

    Assert.assertEquals(1, mol.getAtomCount());
    IAtom atom = mol.getAtom(0);
    Assert.assertEquals("C", atom.getSymbol());
    Assert.assertEquals(6, atom.getAtomicNumber().intValue());
  }
Ejemplo n.º 19
0
  @Test
  public void testConfigure_IAtom() throws Exception {
    IAtomType atomType;
    IAtom atom = new org.openscience.cdk.Atom("X");
    atom.setAtomTypeName("C.ar");
    AtomTypeFactory factory =
        AtomTypeFactory.getInstance(
            "org/openscience/cdk/config/data/mol2_atomtypes.xml", new ChemObject().getBuilder());
    atomType = factory.configure(atom);
    Assert.assertNotNull(atomType);

    Assert.assertEquals("C", atom.getSymbol());
  }
  @Test
  public void testSybylAtomTypePerceptionFromSMILES()
      throws FileNotFoundException, IOException, BioclipseException, CoreException,
          InvocationTargetException {

    ICDKMolecule mol = cdk.fromSMILES("C1CCCCC1CCOC");

    debug.perceiveSybylAtomTypes(mol);

    for (int i = 0; i < mol.getAtomContainer().getAtomCount(); i++) {
      IAtom a = mol.getAtomContainer().getAtom(i);
      System.out.println("Atom: " + a.getSymbol() + i + ", type=" + a.getAtomTypeName());
    }
  }
Ejemplo n.º 21
0
 private void fixCarbonHCount(IAtomContainer mol) {
   /*
    *  the following line are just a quick fix for this
    *  particluar carbon-only molecule until we have a proper
    *  hydrogen count configurator
    */
   double bondCount = 0;
   org.openscience.cdk.interfaces.IAtom atom;
   for (int f = 0; f < mol.getAtomCount(); f++) {
     atom = mol.getAtom(f);
     bondCount = mol.getBondOrderSum(atom);
     int correction =
         (int) bondCount - (atom.getCharge() != null ? atom.getCharge().intValue() : 0);
     if (atom.getSymbol().equals("C")) {
       atom.setImplicitHydrogenCount(4 - correction);
     } else if (atom.getSymbol().equals("N")) {
       atom.setImplicitHydrogenCount(3 - correction);
     }
     if (standAlone) {
       System.out.println("Hydrogen count for atom " + f + ": " + atom.getImplicitHydrogenCount());
     }
   }
 }
Ejemplo n.º 22
0
 private boolean getIfACarbonIsDoubleBondedToAnOxygen(Molecule mol, IAtom carbonAtom) {
   boolean isDoubleBondedToOxygen = false;
   List<IAtom> neighToCarbon = mol.getConnectedAtomsList(carbonAtom);
   IBond tmpBond;
   int counter = 0;
   for (int nei = 0; nei < neighToCarbon.size(); nei++) {
     IAtom neighbour = neighToCarbon.get(nei);
     if (neighbour.getSymbol().equals("O")) {
       tmpBond = mol.getBond(neighbour, carbonAtom);
       if (tmpBond.getOrder() == IBond.Order.DOUBLE) counter += 1;
     }
   }
   if (counter > 0) isDoubleBondedToOxygen = true;
   return isDoubleBondedToOxygen;
 }
 /**
  * Generate coordinates for all atoms which are singly bonded and have no coordinates. This is
  * useful when hydrogens are present but have no coords. It knows about C, O, N, S only and will
  * give tetrahedral or trigonal geometry elsewhere. Bond lengths are computed from covalent radii
  * if available. Angles are tetrahedral or trigonal
  *
  * @param atomContainer the set of atoms involved
  * @cdk.keyword coordinate calculation
  * @cdk.keyword 3D model
  */
 public static void add3DCoordinates1(AtomContainer atomContainer) {
   // atoms without coordinates
   AtomContainer noCoords = new AtomContainer();
   // get vector of possible referenceAtoms?
   AtomContainer refAtoms = new AtomContainer();
   for (int i = 0; i < atomContainer.getAtomCount(); i++) {
     IAtom atom = atomContainer.getAtom(i);
     // is this atom without 3D coords, and has only one ligand?
     if (atom.getPoint3d() == null) {
       java.util.List connectedAtoms = atomContainer.getConnectedAtomsList(atom);
       if (connectedAtoms.size() == 1) {
         IAtom refAtom = (IAtom) connectedAtoms.get(0);
         ;
         if (refAtom.getPoint3d() != null) {
           refAtoms.addAtom(refAtom);
           // store atoms with no coords and ref atoms in a
           // single container
           noCoords.addAtom(atom);
           noCoords.addAtom(refAtom);
           // bond is required to extract ligands
           noCoords.addBond(new Bond(atom, refAtom, CDKConstants.BONDORDER_SINGLE));
         }
       }
     }
   }
   // now add coordinates to ligands of reference atoms
   // use default length of 1.0, which can be adjusted later
   double length = 1.0;
   double angle = TETRAHEDRAL_ANGLE;
   for (int i = 0; i < refAtoms.getAtomCount(); i++) {
     IAtom refAtom = refAtoms.getAtom(i);
     java.util.List noCoordLigands = noCoords.getConnectedAtomsList(refAtom);
     int nLigands = noCoordLigands.size();
     int nwanted = nLigands;
     String elementType = refAtom.getSymbol();
     // try to deal with lone pairs on small hetero
     if (elementType.equals("N") || elementType.equals("O") || elementType.equals("S")) {
       nwanted = 3;
     }
     Point3d[] newPoints =
         calculate3DCoordinatesForLigands(atomContainer, refAtom, nwanted, length, angle);
     for (int j = 0; j < nLigands; j++) {
       IAtom ligand = (IAtom) noCoordLigands.get(j);
       Point3d newPoint = rescaleBondLength(refAtom, ligand, newPoints[j]);
       ligand.setPoint3d(newPoint);
     }
   }
 }
Ejemplo n.º 24
0
 private boolean shouldDraw(IAtom atom, IAtomContainer atomContainer) {
   String symbol = atom.getSymbol();
   if (symbol.equals("C")) {
     if (this.params.drawCarbons) {
       return true;
     }
     if (this.params.drawTerminalCarbons && this.isTerminal(atom, atomContainer)) {
       return true;
     }
     return this.getAttachedMultipleBondCount(atom, atomContainer) > 1;
   }
   if (symbol.equals("H")) {
     return this.params.drawExplicitHydrogens;
   }
   return true;
 }
  @Test
  public void testSybylAtomTypePerception()
      throws FileNotFoundException, IOException, BioclipseException, CoreException,
          InvocationTargetException {

    String path = getClass().getResource("/testFiles/atp.mol").getPath();
    ICDKMolecule mol = cdk.loadMolecule(new MockIFile(path));

    System.out.println("mol: " + mol.toString());

    debug.perceiveSybylAtomTypes(mol);

    for (int i = 0; i < mol.getAtomContainer().getAtomCount(); i++) {
      IAtom a = mol.getAtomContainer().getAtom(i);
      System.out.println("Atom: " + a.getSymbol() + i + ", type=" + a.getAtomTypeName());
    }
  }
Ejemplo n.º 26
0
 private Rectangle2D layoutCharge(IAtom atom, Graphics2D g) {
   BitSet annotationPositions = this.labelManager.getAtomAnnotationPositions(atom);
   Integer formalCharge = atom.getFormalCharge();
   String chargeText = this.getChargeString(formalCharge);
   Rectangle2D atomBounds = this.getTextBounds(g, atom.getSymbol());
   Rectangle2D chargeBounds = this.getTextBounds(g, chargeText);
   Point2d atomPoint = atom.getPoint2d();
   Point2d chargePoint = new Point2d(atomPoint);
   double chargeDim = Math.min(chargeBounds.getWidth(), chargeBounds.getHeight());
   chargePoint.x += atomBounds.getWidth() / 2.0 + chargeDim / 2.0;
   chargePoint.y -= atomBounds.getHeight() / 2.0;
   annotationPositions.set(LabelManager.AnnotationPosition.NE.ordinal());
   return new Rectangle2D.Double(
       chargePoint.x - chargeBounds.getWidth() / 2.0,
       chargePoint.y - chargeBounds.getHeight() / 2.0,
       chargeBounds.getWidth(),
       chargeBounds.getHeight());
 }
  /**
   * set the active center for this molecule. The active center will be those which correspond with
   * A-B-[C*].
   *
   * <pre>
   * A: Atom
   * -: bond
   * B: Atom
   * -: bond
   * C: Atom with single electron
   *  </pre>
   *
   * @param reactant The molecule to set the activity
   * @throws CDKException
   */
  private void setActiveCenters(IMolecule reactant) throws CDKException {

    Iterator<IAtom> atoms = reactant.atoms().iterator();
    while (atoms.hasNext()) {
      IAtom atomi = atoms.next();
      if (reactant.getConnectedSingleElectronsCount(atomi) == 1 && atomi.getFormalCharge() == 1) {

        Iterator<IBond> bondis = reactant.getConnectedBondsList(atomi).iterator();

        while (bondis.hasNext()) {
          IBond bondi = bondis.next();

          if (bondi.getOrder() == IBond.Order.SINGLE) {

            IAtom atomj = bondi.getConnectedAtom(atomi);
            if (atomj.getFormalCharge() == 0) {

              Iterator<IBond> bondjs = reactant.getConnectedBondsList(atomj).iterator();
              while (bondjs.hasNext()) {
                IBond bondj = bondjs.next();

                if (bondj.equals(bondi)) continue;

                if (bondj.getOrder() == IBond.Order.SINGLE) {

                  IAtom atomk = bondj.getConnectedAtom(atomj);
                  if (atomk.getSymbol().equals("C") && atomk.getFormalCharge() == 0) {
                    atomi.setFlag(CDKConstants.REACTIVE_CENTER, true);
                    atomj.setFlag(CDKConstants.REACTIVE_CENTER, true);
                    atomk.setFlag(CDKConstants.REACTIVE_CENTER, true);
                    bondi.setFlag(CDKConstants.REACTIVE_CENTER, true);
                    bondj.setFlag(CDKConstants.REACTIVE_CENTER, true);
                  }
                }
              }
            }
          }
        }
      }
    }
  }
Ejemplo n.º 28
0
 @Override
 public boolean areRootAtomsDefined() {
   for (Integer rgpNum : rGroupDefinitions.keySet()) {
     boolean represented = false;
     rootLoop:
     for (IAtom rootAtom : this.getRootStructure().atoms()) {
       if (rootAtom instanceof IPseudoAtom && rootAtom.getSymbol().startsWith("R")) {
         IPseudoAtom pseudo = (IPseudoAtom) rootAtom;
         if (pseudo.getLabel().length() > 1) {
           int rootAtomRgrpNumber = Integer.valueOf(pseudo.getLabel().substring(1));
           if (rootAtomRgrpNumber == rgpNum) {
             represented = true;
             break rootLoop;
           }
         }
       }
     }
     if (!represented) {
       return false;
     }
   }
   return true;
 }
Ejemplo n.º 29
0
  /**
   * Prepare the target molecule for analysis.
   *
   * <p>We perform ring perception and aromaticity detection and set up the appropriate properties.
   * Right now, this function is called each time we need to do a query and this is inefficient.
   *
   * @throws CDKException if there is a problem in ring perception or aromaticity detection, which
   *     is usually related to a timeout in the ring finding code.
   */
  private void initializeMolecule() throws CDKException {
    // Code copied from
    // org.openscience.cdk.qsar.descriptors.atomic.AtomValenceDescriptor;
    Map<String, Integer> valencesTable = new HashMap<String, Integer>();
    valencesTable.put("H", 1);
    valencesTable.put("Li", 1);
    valencesTable.put("Be", 2);
    valencesTable.put("B", 3);
    valencesTable.put("C", 4);
    valencesTable.put("N", 5);
    valencesTable.put("O", 6);
    valencesTable.put("F", 7);
    valencesTable.put("Na", 1);
    valencesTable.put("Mg", 2);
    valencesTable.put("Al", 3);
    valencesTable.put("Si", 4);
    valencesTable.put("P", 5);
    valencesTable.put("S", 6);
    valencesTable.put("Cl", 7);
    valencesTable.put("K", 1);
    valencesTable.put("Ca", 2);
    valencesTable.put("Ga", 3);
    valencesTable.put("Ge", 4);
    valencesTable.put("As", 5);
    valencesTable.put("Se", 6);
    valencesTable.put("Br", 7);
    valencesTable.put("Rb", 1);
    valencesTable.put("Sr", 2);
    valencesTable.put("In", 3);
    valencesTable.put("Sn", 4);
    valencesTable.put("Sb", 5);
    valencesTable.put("Te", 6);
    valencesTable.put("I", 7);
    valencesTable.put("Cs", 1);
    valencesTable.put("Ba", 2);
    valencesTable.put("Tl", 3);
    valencesTable.put("Pb", 4);
    valencesTable.put("Bi", 5);
    valencesTable.put("Po", 6);
    valencesTable.put("At", 7);
    valencesTable.put("Fr", 1);
    valencesTable.put("Ra", 2);
    valencesTable.put("Cu", 2);
    valencesTable.put("Mn", 2);
    valencesTable.put("Co", 2);

    // do all ring perception
    AllRingsFinder arf = new AllRingsFinder();
    IRingSet allRings;
    try {
      allRings = arf.findAllRings(atomContainer);
    } catch (CDKException e) {
      logger.debug(e.toString());
      throw new CDKException(e.toString(), e);
    }

    // sets SSSR information
    SSSRFinder finder = new SSSRFinder(atomContainer);
    IRingSet sssr = finder.findEssentialRings();

    for (IAtom atom : atomContainer.atoms()) {

      // add a property to each ring atom that will be an array of
      // Integers, indicating what size ring the given atom belongs to
      // Add SSSR ring counts
      if (allRings.contains(atom)) { // it's in a ring
        atom.setFlag(CDKConstants.ISINRING, true);
        // lets find which ring sets it is a part of
        List<Integer> ringsizes = new ArrayList<Integer>();
        IRingSet currentRings = allRings.getRings(atom);
        int min = 0;
        for (int i = 0; i < currentRings.getAtomContainerCount(); i++) {
          int size = currentRings.getAtomContainer(i).getAtomCount();
          if (min > size) min = size;
          ringsizes.add(size);
        }
        atom.setProperty(CDKConstants.RING_SIZES, ringsizes);
        atom.setProperty(CDKConstants.SMALLEST_RINGS, sssr.getRings(atom));
      } else {
        atom.setFlag(CDKConstants.ISINRING, false);
      }

      // determine how many rings bonds each atom is a part of
      int hCount;
      if (atom.getImplicitHydrogenCount() == CDKConstants.UNSET) hCount = 0;
      else hCount = atom.getImplicitHydrogenCount();

      List<IAtom> connectedAtoms = atomContainer.getConnectedAtomsList(atom);
      int total = hCount + connectedAtoms.size();
      for (IAtom connectedAtom : connectedAtoms) {
        if (connectedAtom.getSymbol().equals("H")) {
          hCount++;
        }
      }
      atom.setProperty(CDKConstants.TOTAL_CONNECTIONS, total);
      atom.setProperty(CDKConstants.TOTAL_H_COUNT, hCount);

      if (valencesTable.get(atom.getSymbol()) != null) {
        int formalCharge =
            atom.getFormalCharge() == CDKConstants.UNSET ? 0 : atom.getFormalCharge();
        atom.setValency(valencesTable.get(atom.getSymbol()) - formalCharge);
      }
    }

    for (IBond bond : atomContainer.bonds()) {
      if (allRings.getRings(bond).getAtomContainerCount() > 0) {
        bond.setFlag(CDKConstants.ISINRING, true);
      }
    }

    for (IAtom atom : atomContainer.atoms()) {
      List<IAtom> connectedAtoms = atomContainer.getConnectedAtomsList(atom);

      int counter = 0;
      IAtom any;
      for (IAtom connectedAtom : connectedAtoms) {
        any = connectedAtom;
        if (any.getFlag(CDKConstants.ISINRING)) {
          counter++;
        }
      }
      atom.setProperty(CDKConstants.RING_CONNECTIONS, counter);
    }

    // check for atomaticity
    try {
      AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(atomContainer);
      CDKHueckelAromaticityDetector.detectAromaticity(atomContainer);
    } catch (CDKException e) {
      logger.debug(e.toString());
      throw new CDKException(e.toString(), e);
    }
  }
    public String perceiveSybylAtomTypes(IMolecule mol)
                        throws InvocationTargetException {
        
        ICDKMolecule cdkmol;
        
        try {
            cdkmol = cdk.asCDKMolecule(mol);
        } 
        catch (BioclipseException e) {
            System.out.println("Error converting cdk10 to cdk");
            e.printStackTrace();
            throw new InvocationTargetException(e);
        }
        
        IAtomContainer ac = cdkmol.getAtomContainer();
        CDKAtomTypeMatcher cdkMatcher 
            = CDKAtomTypeMatcher.getInstance(ac.getBuilder());
        AtomTypeMapper mapper 
            = AtomTypeMapper.getInstance(
                 "org/openscience/cdk/dict/data/cdk-sybyl-mappings.owl" );

        IAtomType[] sybylTypes = new IAtomType[ac.getAtomCount()];
        
        int atomCounter = 0;
        int a=0;
        for (IAtom atom : ac.atoms()) {
            IAtomType type;
            try {
                type = cdkMatcher.findMatchingAtomType(ac, atom);
            } 
            catch (CDKException e) {
                type = null;
            }
            if (type==null) {
//                logger.debug("AT null for atom: " + atom);
                type = atom.getBuilder().newAtomType(atom.getSymbol());
                type.setAtomTypeName("X");
            }
            AtomTypeManipulator.configure(atom, type);
            a++;
        }
        try {
            CDKHueckelAromaticityDetector.detectAromaticity(ac);
//            System.out.println("Arom: " 
//                + CDKHueckelAromaticityDetector.detectAromaticity(ac) );
		    } 
        catch (CDKException e) {
			    logger.debug("Failed to perceive aromaticity: " + e.getMessage());
		    }
        for (IAtom atom : ac.atoms()) {
            String mappedType = mapper.mapAtomType(atom.getAtomTypeName());
            if ("C.2".equals(mappedType)
                    && atom.getFlag(CDKConstants.ISAROMATIC)) {
                mappedType = "C.ar";
            } 
            else if ("N.pl3".equals(mappedType)
                    && atom.getFlag(CDKConstants.ISAROMATIC)) {
                mappedType = "N.ar";
            }
            try {
                sybylTypes[atomCounter] = factory.getAtomType(mappedType);
		        } 
            catch (NoSuchAtomTypeException e) {
                // yes, setting null's here is important
                sybylTypes[atomCounter] = null; 
			      }
            atomCounter++;
        }
        StringBuffer result = new StringBuffer();
        // now that full perception is finished, we can set atom type names:
        for (int i = 0; i < sybylTypes.length; i++) {
            if (sybylTypes[i] != null) {
                ac.getAtom(i).setAtomTypeName(sybylTypes[i].getAtomTypeName());
            } 
            else {
                ac.getAtom(i).setAtomTypeName("X");
            }
            
            result.append(i).append(':').append(ac.getAtom(i).getAtomTypeName())
                  /*.append("\n")*/;

        }
        return result.toString();
    }