Esempio n. 1
0
  /** @cdk.bug 1535055 */
  @Test
  public void testBug1535055() throws Exception {
    SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance());
    IAtomContainer mol = sp.parseSmiles("COC(=O)c1ccc2c(c1)c1ccccc1[nH]2");
    CDKHueckelAromaticityDetector.detectAromaticity(mol);
    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol);
    SmilesGenerator sg = new SmilesGenerator();
    sg.setUseAromaticityFlag(true);
    String s1 = sg.createSMILES(mol);

    String filename = "data/cml/bug1535055.cml";
    InputStream ins = this.getClass().getClassLoader().getResourceAsStream(filename);
    CMLReader reader = new CMLReader(ins);
    IChemFile chemFile = (IChemFile) reader.read(new ChemFile());

    // test the resulting ChemFile content
    Assert.assertNotNull(chemFile);
    IAtomContainer mol2 = ChemFileManipulator.getAllAtomContainers(chemFile).get(0);
    CDKHueckelAromaticityDetector.detectAromaticity(mol2);
    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol2);
    String s2 = sg.createSMILES(mol2);

    Assert.assertTrue(s1.contains("[nH]"));
    Assert.assertTrue(s2.contains("[nH]"));
  }
  @Test
  public void testfp2() throws Exception {
    SmilesParser parser = new SmilesParser(NoNotificationChemObjectBuilder.getInstance());
    IFingerprinter printer = new MACCSFingerprinter();

    IMolecule mol1 = parser.parseSmiles("CC(N)CCCN");
    IMolecule mol2 = parser.parseSmiles("CC(N)CCC");
    IMolecule mol3 = parser.parseSmiles("CCCC");

    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol1);
    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol2);
    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol3);

    CDKHueckelAromaticityDetector.detectAromaticity(mol1);
    CDKHueckelAromaticityDetector.detectAromaticity(mol2);
    CDKHueckelAromaticityDetector.detectAromaticity(mol3);

    BitSet bs1 = printer.getFingerprint(mol1);
    BitSet bs2 = printer.getFingerprint(mol2);
    BitSet bs3 = printer.getFingerprint(mol3);

    Assert.assertFalse(bs1.get(124));
    Assert.assertFalse(bs2.get(124));
    Assert.assertFalse(bs3.get(124));

    Assert.assertFalse(FingerprinterTool.isSubset(bs1, bs2));
    Assert.assertTrue(FingerprinterTool.isSubset(bs2, bs3));
  }
Esempio n. 3
0
File: Misc.java Progetto: egonw/cdkr
  public static void main(String[] args) throws Exception, CloneNotSupportedException, IOException {
    SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance());
    IAtomContainer mol1 = sp.parseSmiles("c1cccc(COC(=O)NC(CC(C)C)C(=O)NC(CCc2ccccc2)C(=O)COC)c1");
    IAtomContainer mol2 = sp.parseSmiles("c1cccc(COC(=O)NC(CC(C)C)C(=O)NCC#N)c1");
    CDKHueckelAromaticityDetector.detectAromaticity(mol1);
    CDKHueckelAromaticityDetector.detectAromaticity(mol2);
    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol2);
    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol1);
    IAtomContainer mcs = getMcsAsNewContainer(mol1, mol2);
    MoleculeImage mi = new MoleculeImage(mcs);
    byte[] bytes = mi.getBytes(300, 300);
    FileOutputStream fos = new FileOutputStream("test.png");
    fos.write(bytes);

    int[][] map = getMcsAsAtomIndexMapping(mol1, mol2);
    for (int i = 0; i < map.length; i++) {
      System.out.println(map[i][0] + " <-> " + map[i][1]);
    }
  }
 public BitSet process(IAtomContainer target) throws AmbitException {
   try {
     IAtomContainer ac = cfg.process(target);
     aromaticDetector.detectAromaticity(ac);
     return getStructureKeyBits(ac);
   } catch (CDKException x) {
     throw new AmbitException(x.getMessage());
   } catch (AmbitException x) {
     throw x;
   } catch (Exception x) {
     throw new AmbitException(x);
   }
 }
  @Test
  public void testQuinone() throws Exception {

    IAtomContainer mol = MoleculeFactory.makeQuinone();
    Assert.assertNotNull("Created molecule was null", mol);

    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol);
    CDKHueckelAromaticityDetector.detectAromaticity(mol);

    EquivalentClassPartitioner partitioner = new EquivalentClassPartitioner(mol);
    int[] eqCl = partitioner.getTopoEquivClassbyHuXu(mol);
    Partition autP = ArrayToPartition.convert(eqCl, 1);

    Assert.assertEquals("Wrong number of equivalent classes", 3, autP.size());
    Partition expected = Partition.fromString("0,7|1,4|2,3,5,6");
    Assert.assertEquals("Wrong class assignment", expected, autP);
  }
  private Java2DRenderer prepareRenderer(IMolecule mol) throws Exception {

    Renderer2DModel r2dm;
    Java2DRenderer renderer;
    Dimension imgSize;

    try {
      CDKHueckelAromaticityDetector.detectAromaticity(mol);
    } catch (CDKException cdke) {
      cdke.printStackTrace();
    }

    try {

      imgSize = new Dimension(vRenderSizeX, vRenderSizeY);

      r2dm = new Renderer2DModel();
      r2dm.setDrawNumbers(false);
      r2dm.showAtomTypeNames();
      r2dm.setBackgroundDimension(imgSize);
      r2dm.setBackColor(Color.WHITE);
      r2dm.setDrawNumbers(false);
      r2dm.setUseAntiAliasing(true);
      r2dm.setColorAtomsByType(true);
      r2dm.setShowImplicitHydrogens(true);
      r2dm.setShowExplicitHydrogens(this.showHydrogen);
      r2dm.setIsCompact(this.isCompact);
      r2dm.setShowReactionBoxes(false);
      r2dm.setKekuleStructure(false);
      r2dm.setBondWidth(3);

      // r2dm.setFont(new java.awt.Font("SansSerif", java.awt.Font.PLAIN, 14));

      renderer = new Java2DRenderer(r2dm);

      // 1200,900
      // create renderer to render MOLString into an java.awt.Image
      // renders 2D structures

    } catch (Exception e) {
      e.printStackTrace();
      throw new Exception("Creation of renderer failed");
    }

    return renderer;
  }
  /**
   * Fixes Aromaticity of the molecule i.e. need to find rings and aromaticity again since added H's
   *
   * @param mol
   */
  @TestMethod("testFixAromaticity")
  public static void configure(IAtomContainer mol) {
    // need to find rings and aromaticity again since added H's

    IRingSet ringSet = null;
    try {
      AllRingsFinder arf = new AllRingsFinder();
      ringSet = arf.findAllRings(mol);
    } catch (Exception e) {
      e.printStackTrace();
    }

    try {
      // figure out which atoms are in aromatic rings:
      CDKHydrogenAdder cdk = CDKHydrogenAdder.getInstance(DefaultChemObjectBuilder.getInstance());
      cdk.addImplicitHydrogens(mol);
      ExtAtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(mol);

      CDKHueckelAromaticityDetector.detectAromaticity(mol);
      // figure out which rings are aromatic:
      RingSetManipulator.markAromaticRings(ringSet);
      // figure out which simple (non cycles) rings are aromatic:

      // only atoms in 6 membered rings are aromatic
      // determine largest ring that each atom is a part of

      for (int i = 0; i < mol.getAtomCount(); i++) {
        mol.getAtom(i).setFlag(CDKConstants.ISAROMATIC, false);
        jloop:
        for (int j = 0; j < ringSet.getAtomContainerCount(); j++) {
          // logger.debug(i+"\t"+j);
          IRing ring = (IRing) ringSet.getAtomContainer(j);
          if (!ring.getFlag(CDKConstants.ISAROMATIC)) {
            continue jloop;
          }
          boolean haveatom = ring.contains(mol.getAtom(i));
          // logger.debug("haveatom="+haveatom);
          if (haveatom && ring.getAtomCount() == 6) {
            mol.getAtom(i).setFlag(CDKConstants.ISAROMATIC, true);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 8
0
  @Test
  public void testWriteAromatic() throws Exception {
    StringWriter stringWriter = new StringWriter();
    IAtomContainer benzene = TestMoleculeFactory.makeBenzene();
    addImplicitHydrogens(benzene);
    CDKHueckelAromaticityDetector.detectAromaticity(benzene);

    SMILESWriter smilesWriter = new SMILESWriter(stringWriter);
    Properties prop = new Properties();
    prop.setProperty("UseAromaticity", "true");
    PropertiesListener listener = new PropertiesListener(prop);
    smilesWriter.addChemObjectIOListener(listener);
    smilesWriter.customizeJob();
    smilesWriter.write(benzene);
    smilesWriter.close();
    Assert.assertFalse(stringWriter.toString().contains("C=C"));
    Assert.assertTrue(stringWriter.toString().contains("ccc"));
  }
Esempio n. 9
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 static void main(final String[] args) {

    //        String mf;
    //        String molfile;

    try {
      //            BufferedReader reader = new BufferedReader(new FileReader("renderTest.mol"));
      //            StringBuffer   sbuff  = new StringBuffer();
      //            String         line;
      //
      //            while ( (line = reader.readLine()) != null ) {
      //                sbuff.append(line + "\n");
      //            }
      //            reader.close();
      //            molfile = sbuff.toString();
      //            System.out.println(molfile);

      // the graph
      SmilesParser sp = new SmilesParser(DefaultChemObjectBuilder.getInstance());
      PubChemWebService pw = new PubChemWebService();
      String PCID = "1148";
      IAtomContainer container = pw.getSingleMol(PCID);
      container = AtomContainerManipulator.removeHydrogens(container);
      //            IAtomContainer container = sp.parseSmiles("OC1C(O)=COC(CO)C1(O)");

      // Render.Draw(container, "test");

      IMolecule test = new Molecule(container);
      StructureDiagramGenerator sdg = new StructureDiagramGenerator();
      sdg.setMolecule(test);
      sdg.generateCoordinates();
      IMolecule mol = sdg.getMolecule();

      // adds implicit H atoms to molecule
      //    		CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.getInstance(mol.getBuilder());
      //    		for (IAtom atom : mol.atoms()) {
      //    			IAtomType type = matcher.findMatchingAtomType(mol, atom);
      //	    		AtomTypeManipulator.configure(atom, type);
      //			}
      //
      //    		CDKHydrogenAdder adder = CDKHydrogenAdder.getInstance(mol.getBuilder());
      //    		adder.addImplicitHydrogens(mol);
      //    		AtomContainerManipulator.convertImplicitToExplicitHydrogens(mol);

      // detects aromaticity; used to display aromatic ring systems correctly
      CDKHueckelAromaticityDetector.detectAromaticity(mol);

      Render.Draw(mol, "test");

      DisplayStructureVector test12 =
          new DisplayStructureVector(200, 200, "/home/swolf/", true, true);
      // test12.writeMOL2PNGFile(mol, "test_cdk12.png");
      //    		test12.writeMOL2PDFFile(mol, new File("/home/swolf/test_cdk12.pdf"));
      test12.writeMOL2SVGFile(mol, new File("/home/swolf/" + PCID + ".svg"));

      // ChemRenderer crender = new ChemRenderer();
      // crender.writeMOL2PNGFile(mol, new File("/home/swolf/test_new.png"));
      // crender.writeMOL2EPSFile(mol, new File("/home/swolf/test_new.eps"));
      // crender.writeMOL2PDFFile(mol, new File("/home/swolf/test_new.pdf"));

      // crender.writeMOL2SVGFile(molfile,new File("Output.svg"));

    } catch (Exception e) {
      System.out.println("Error: " + e.getMessage() + ".");
      e.printStackTrace();
    }
  }
Esempio n. 11
0
  /**
   * Calculate the count of atoms of the largest chain in the supplied {@link IAtomContainer}.
   *
   * <p>
   *
   * <p>The method require two parameters:
   *
   * <ol>
   *   <li>if checkAromaticity is true, the method check the aromaticity,
   *   <li>if false, means that the aromaticity has already been checked
   * </ol>
   *
   * <p>
   *
   * <p>Same for checkRingSystem, if true the CDKConstant.ISINRING will be set
   *
   * @param atomContainer The {@link AtomContainer} for which this descriptor is to be calculated
   * @return the number of atoms in the largest chain of this AtomContainer
   * @see #setParameters
   */
  @TestMethod("testCalculate_IAtomContainer")
  public DescriptorValue calculate(IAtomContainer atomContainer) {
    IAtomContainer container;
    try {
      container = (IAtomContainer) atomContainer.clone();
    } catch (CloneNotSupportedException e) {
      return getDummyDescriptorValue(e);
    }

    // logger.debug("LargestChainDescriptor");
    boolean[] originalFlag4 = new boolean[container.getAtomCount()];
    for (int i = 0; i < originalFlag4.length; i++) {
      originalFlag4[i] = container.getAtom(i).getFlag(4);
    }
    if (checkRingSystem) {
      IRingSet rs;
      try {
        rs = new SpanningTree(container).getBasicRings();
      } catch (NoSuchAtomException e) {
        return getDummyDescriptorValue(e);
      }
      for (int i = 0; i < container.getAtomCount(); i++) {
        if (rs.contains(container.getAtom(i))) {
          container.getAtom(i).setFlag(CDKConstants.ISINRING, true);
        }
      }
    }

    if (checkAromaticity) {
      try {
        AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(container);
        CDKHueckelAromaticityDetector.detectAromaticity(container);
      } catch (CDKException e) {
        return getDummyDescriptorValue(e);
      }
    }

    // get rid of hydrogens in our local copy
    container = AtomContainerManipulator.removeHydrogens(container);

    int largestChainAtomsCount = 0;
    // IAtom[] atoms = container.getAtoms();
    ArrayList<IAtom> startSphere;
    ArrayList<IAtom> path;
    // Set all VisitedFlags to False
    for (int i = 0; i < container.getAtomCount(); i++) {
      container.getAtom(i).setFlag(CDKConstants.VISITED, false);
    }

    // logger.debug("Set all atoms to Visited False");
    for (int i = 0; i < container.getAtomCount(); i++) {
      IAtom atomi = container.getAtom(i);
      // chain sp3
      // logger.debug("atom:"+i+" maxBondOrder:"+container.getMaximumBondOrder(atoms[i])+"
      // Aromatic:"+atoms[i].getFlag(CDKConstants.ISAROMATIC)+"
      // Ring:"+atoms[i].getFlag(CDKConstants.ISINRING)+"
      // FormalCharge:"+atoms[i].getFormalCharge()+" Charge:"+atoms[i].getCharge()+"
      // Flag:"+atoms[i].getFlag(CDKConstants.VISITED));
      if ((!atomi.getFlag(CDKConstants.ISAROMATIC) && !atomi.getFlag(CDKConstants.ISINRING))
          & !atomi.getFlag(CDKConstants.VISITED)) {
        // logger.debug("...... -> containercepted");
        startSphere = new ArrayList<IAtom>();
        path = new ArrayList<IAtom>();
        startSphere.add(atomi);
        try {
          breadthFirstSearch(container, startSphere, path);
        } catch (CDKException e) {
          return getDummyDescriptorValue(e);
        }
        if (path.size() > largestChainAtomsCount) {
          largestChainAtomsCount = path.size();
        }
      }
    }

    return new DescriptorValue(
        getSpecification(),
        getParameterNames(),
        getParameters(),
        new IntegerResult(largestChainAtomsCount),
        getDescriptorNames());
  }
    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();
    }
Esempio n. 13
0
File: Misc.java Progetto: egonw/cdkr
  /**
   * Loads one or more files into IAtomContainer objects.
   *
   * <p>This method does not need knowledge of the format since it is autodetected. Note that if
   * aromaticity detection or atom typing is specified and fails for a specific molecule, that
   * molecule will be set to <i>null</i>
   *
   * @param filenames An array of String's containing the filenames of the structures we want to
   *     load
   * @param doAromaticity If true, then aromaticity perception is performed
   * @param doTyping If true, atom typing and configuration is performed. This will use the internal
   *     CDK atom typing scheme
   * @return An array of AtoContainer's
   * @throws CDKException if there is an error when reading a file
   */
  public static IAtomContainer[] loadMolecules(
      String[] filenames, boolean doAromaticity, boolean doTyping, boolean doIsotopes)
      throws CDKException, IOException {
    Vector<IAtomContainer> v = new Vector<IAtomContainer>();
    IChemObjectBuilder builder = DefaultChemObjectBuilder.getInstance();
    try {
      int i;
      int j;

      for (i = 0; i < filenames.length; i++) {
        File input = new File(filenames[i]);
        ReaderFactory readerFactory = new ReaderFactory();
        ISimpleChemObjectReader reader = readerFactory.createReader(new FileReader(input));

        if (reader == null) { // see if it's a SMI file
          if (filenames[i].endsWith(".smi")) {
            reader = new SMILESReader(new FileReader(input));
          }
        }
        IChemFile content = (IChemFile) reader.read(builder.newInstance(IChemFile.class));
        if (content == null) continue;

        List<IAtomContainer> c = ChemFileManipulator.getAllAtomContainers(content);

        // we should do this loop in case we have files
        // that contain multiple molecules
        v.addAll(c);
      }

    } catch (Exception e) {
      e.printStackTrace();
      throw new CDKException(e.toString());
    }

    // convert the vector to a simple array
    IAtomContainer[] retValues = new IAtomContainer[v.size()];
    for (int i = 0; i < v.size(); i++) {
      retValues[i] = v.get(i);
    }

    // before returning, lets make see if we
    // need to perceive aromaticity and atom typing
    if (doAromaticity) {
      for (int i = 0; i < retValues.length; i++) {
        try {
          CDKHueckelAromaticityDetector.detectAromaticity(retValues[i]);
        } catch (CDKException e) {
          retValues[i] = null;
        }
      }
    }

    if (doTyping) {
      for (int i = 0; i < retValues.length; i++) {
        try {
          AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(retValues[i]);
        } catch (CDKException e) {
          retValues[i] = null;
        }
      }
    }

    if (doIsotopes) {
      IsotopeFactory ifac = IsotopeFactory.getInstance(DefaultChemObjectBuilder.getInstance());
      for (IAtomContainer retValue : retValues) {
        ifac.configureAtoms(retValue);
      }
    }

    return retValues;
  }
Esempio n. 14
0
  @TestMethod(value = "testCalculate_IAtomContainer")
  public DescriptorValue calculate(
      IAtom atom, IAtomContainer atomContainer, IRingSet precalculatedringset) {
    IAtomContainer varAtomContainer;
    try {
      varAtomContainer = (IAtomContainer) atomContainer.clone();
    } catch (CloneNotSupportedException e) {
      return getDummyDescriptorValue(e);
    }

    int atomPosition = atomContainer.getAtomNumber(atom);
    IAtom clonedAtom = varAtomContainer.getAtom(atomPosition);

    DoubleArrayResult rdfProtonCalculatedValues = new DoubleArrayResult(gsr_desc_length);
    if (!atom.getSymbol().equals("H")) {
      return getDummyDescriptorValue(new CDKException("Invalid atom specified"));
    }

    ///////////////////////// FIRST SECTION OF MAIN METHOD: DEFINITION OF MAIN VARIABLES
    ///////////////////////// AND AROMATICITY AND PI-SYSTEM AND RINGS DETECTION

    Molecule mol = new Molecule(varAtomContainer);
    if (varAtomContainer != acold) {
      acold = varAtomContainer;
      // DETECTION OF pi SYSTEMS
      varAtomContainerSet = ConjugatedPiSystemsDetector.detect(mol);
      if (precalculatedringset == null)
        try {
          varRingSet = (new AllRingsFinder()).findAllRings(varAtomContainer);
        } catch (CDKException e) {
          return getDummyDescriptorValue(e);
        }
      else varRingSet = precalculatedringset;
      try {
        GasteigerMarsiliPartialCharges peoe = new GasteigerMarsiliPartialCharges();
        peoe.assignGasteigerMarsiliSigmaPartialCharges(mol, true);
      } catch (Exception ex1) {
        return getDummyDescriptorValue(ex1);
      }
    }
    if (checkAromaticity) {
      try {
        AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(varAtomContainer);
        CDKHueckelAromaticityDetector.detectAromaticity(varAtomContainer);
      } catch (CDKException e) {
        return getDummyDescriptorValue(e);
      }
    }
    IRingSet rsAtom;
    Ring ring;
    IRingSet ringsWithThisBond;
    // SET ISINRING FLAGS FOR BONDS
    Iterator<IBond> bondsInContainer = varAtomContainer.bonds().iterator();
    while (bondsInContainer.hasNext()) {
      IBond bond = bondsInContainer.next();
      ringsWithThisBond = varRingSet.getRings(bond);
      if (ringsWithThisBond.getAtomContainerCount() > 0) {
        bond.setFlag(CDKConstants.ISINRING, true);
      }
    }

    // SET ISINRING FLAGS FOR ATOMS
    IRingSet ringsWithThisAtom;

    for (int w = 0; w < varAtomContainer.getAtomCount(); w++) {
      ringsWithThisAtom = varRingSet.getRings(varAtomContainer.getAtom(w));
      if (ringsWithThisAtom.getAtomContainerCount() > 0) {
        varAtomContainer.getAtom(w).setFlag(CDKConstants.ISINRING, true);
      }
    }

    IAtomContainer detected = varAtomContainerSet.getAtomContainer(0);

    // neighboors[0] is the atom joined to the target proton:
    List<IAtom> neighboors = mol.getConnectedAtomsList(clonedAtom);
    IAtom neighbour0 = neighboors.get(0);

    // 2', 3', 4', 5', 6', and 7' atoms up to the target are detected:
    List<IAtom> atomsInSecondSphere = mol.getConnectedAtomsList(neighbour0);
    List<IAtom> atomsInThirdSphere;
    List<IAtom> atomsInFourthSphere;
    List<IAtom> atomsInFifthSphere;
    List<IAtom> atomsInSixthSphere;
    List<IAtom> atomsInSeventhSphere;

    // SOME LISTS ARE CREATED FOR STORING OF INTERESTING ATOMS AND BONDS DURING DETECTION
    ArrayList<Integer> singles = new ArrayList<Integer>(); // list of any bond not rotatable
    ArrayList<Integer> doubles = new ArrayList<Integer>(); // list with only double bonds
    ArrayList<Integer> atoms = new ArrayList<Integer>(); // list with all the atoms in spheres
    // atoms.add( Integer.valueOf( mol.getAtomNumber(neighboors[0]) ) );
    ArrayList<Integer> bondsInCycloex =
        new ArrayList<Integer>(); // list for bonds in cycloexane-like rings

    // 2', 3', 4', 5', 6', and 7' bonds up to the target are detected:
    IBond secondBond; // (remember that first bond is proton bond)
    IBond thirdBond; //
    IBond fourthBond; //
    IBond fifthBond; //
    IBond sixthBond; //
    IBond seventhBond; //

    // definition of some variables used in the main FOR loop for detection of interesting atoms and
    // bonds:
    boolean theBondIsInA6MemberedRing; // this is like a flag for bonds which are in cycloexane-like
    // rings (rings with more than 4 at.)
    IBond.Order bondOrder;
    int bondNumber;
    int sphere;

    // THIS MAIN FOR LOOP DETECT RIGID BONDS IN 7 SPHERES:
    for (IAtom curAtomSecond : atomsInSecondSphere) {
      secondBond = mol.getBond(neighbour0, curAtomSecond);
      if (mol.getAtomNumber(curAtomSecond) != atomPosition
          && getIfBondIsNotRotatable(mol, secondBond, detected)) {
        sphere = 2;
        bondOrder = secondBond.getOrder();
        bondNumber = mol.getBondNumber(secondBond);
        theBondIsInA6MemberedRing = false;
        checkAndStore(
            bondNumber,
            bondOrder,
            singles,
            doubles,
            bondsInCycloex,
            mol.getAtomNumber(curAtomSecond),
            atoms,
            sphere,
            theBondIsInA6MemberedRing);
        atomsInThirdSphere = mol.getConnectedAtomsList(curAtomSecond);
        if (atomsInThirdSphere.size() > 0) {
          for (IAtom curAtomThird : atomsInThirdSphere) {
            thirdBond = mol.getBond(curAtomThird, curAtomSecond);
            // IF THE ATOMS IS IN THE THIRD SPHERE AND IN A CYCLOEXANE-LIKE RING, IT IS STORED IN
            // THE PROPER LIST:
            if (mol.getAtomNumber(curAtomThird) != atomPosition
                && getIfBondIsNotRotatable(mol, thirdBond, detected)) {
              sphere = 3;
              bondOrder = thirdBond.getOrder();
              bondNumber = mol.getBondNumber(thirdBond);
              theBondIsInA6MemberedRing = false;

              // if the bond is in a cyclohexane-like ring (a ring with 5 or more atoms, not
              // aromatic)
              // the boolean "theBondIsInA6MemberedRing" is set to true
              if (!thirdBond.getFlag(CDKConstants.ISAROMATIC)) {
                if (!curAtomThird.equals(neighbour0)) {
                  rsAtom = varRingSet.getRings(thirdBond);
                  for (int f = 0; f < rsAtom.getAtomContainerCount(); f++) {
                    ring = (Ring) rsAtom.getAtomContainer(f);
                    if (ring.getRingSize() > 4 && ring.contains(thirdBond)) {
                      theBondIsInA6MemberedRing = true;
                    }
                  }
                }
              }
              checkAndStore(
                  bondNumber,
                  bondOrder,
                  singles,
                  doubles,
                  bondsInCycloex,
                  mol.getAtomNumber(curAtomThird),
                  atoms,
                  sphere,
                  theBondIsInA6MemberedRing);
              theBondIsInA6MemberedRing = false;
              atomsInFourthSphere = mol.getConnectedAtomsList(curAtomThird);
              if (atomsInFourthSphere.size() > 0) {
                for (IAtom curAtomFourth : atomsInFourthSphere) {
                  fourthBond = mol.getBond(curAtomThird, curAtomFourth);
                  if (mol.getAtomNumber(curAtomFourth) != atomPosition
                      && getIfBondIsNotRotatable(mol, fourthBond, detected)) {
                    sphere = 4;
                    bondOrder = fourthBond.getOrder();
                    bondNumber = mol.getBondNumber(fourthBond);
                    theBondIsInA6MemberedRing = false;
                    checkAndStore(
                        bondNumber,
                        bondOrder,
                        singles,
                        doubles,
                        bondsInCycloex,
                        mol.getAtomNumber(curAtomFourth),
                        atoms,
                        sphere,
                        theBondIsInA6MemberedRing);
                    atomsInFifthSphere = mol.getConnectedAtomsList(curAtomFourth);
                    if (atomsInFifthSphere.size() > 0) {
                      for (IAtom curAtomFifth : atomsInFifthSphere) {
                        fifthBond = mol.getBond(curAtomFifth, curAtomFourth);
                        if (mol.getAtomNumber(curAtomFifth) != atomPosition
                            && getIfBondIsNotRotatable(mol, fifthBond, detected)) {
                          sphere = 5;
                          bondOrder = fifthBond.getOrder();
                          bondNumber = mol.getBondNumber(fifthBond);
                          theBondIsInA6MemberedRing = false;
                          checkAndStore(
                              bondNumber,
                              bondOrder,
                              singles,
                              doubles,
                              bondsInCycloex,
                              mol.getAtomNumber(curAtomFifth),
                              atoms,
                              sphere,
                              theBondIsInA6MemberedRing);
                          atomsInSixthSphere = mol.getConnectedAtomsList(curAtomFifth);
                          if (atomsInSixthSphere.size() > 0) {
                            for (IAtom curAtomSixth : atomsInSixthSphere) {
                              sixthBond = mol.getBond(curAtomFifth, curAtomSixth);
                              if (mol.getAtomNumber(curAtomSixth) != atomPosition
                                  && getIfBondIsNotRotatable(mol, sixthBond, detected)) {
                                sphere = 6;
                                bondOrder = sixthBond.getOrder();
                                bondNumber = mol.getBondNumber(sixthBond);
                                theBondIsInA6MemberedRing = false;
                                checkAndStore(
                                    bondNumber,
                                    bondOrder,
                                    singles,
                                    doubles,
                                    bondsInCycloex,
                                    mol.getAtomNumber(curAtomSixth),
                                    atoms,
                                    sphere,
                                    theBondIsInA6MemberedRing);
                                atomsInSeventhSphere = mol.getConnectedAtomsList(curAtomSixth);
                                if (atomsInSeventhSphere.size() > 0) {
                                  for (IAtom curAtomSeventh : atomsInSeventhSphere) {
                                    seventhBond = mol.getBond(curAtomSeventh, curAtomSixth);
                                    if (mol.getAtomNumber(curAtomSeventh) != atomPosition
                                        && getIfBondIsNotRotatable(mol, seventhBond, detected)) {
                                      sphere = 7;
                                      bondOrder = seventhBond.getOrder();
                                      bondNumber = mol.getBondNumber(seventhBond);
                                      theBondIsInA6MemberedRing = false;
                                      checkAndStore(
                                          bondNumber,
                                          bondOrder,
                                          singles,
                                          doubles,
                                          bondsInCycloex,
                                          mol.getAtomNumber(curAtomSeventh),
                                          atoms,
                                          sphere,
                                          theBondIsInA6MemberedRing);
                                    }
                                  }
                                }
                              }
                            }
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    // Variables
    double[] values; // for storage of results of other methods
    double distance;
    double sum;
    double smooth = -20;
    double partial;
    int position;
    double limitInf;
    double limitSup;
    double step;

    //////////////////////// THE FOUTH DESCRIPTOR IS gS(r), WHICH TAKES INTO ACCOUNT SINGLE BONDS IN
    // RIGID SYSTEMS

    Vector3d a_a = new Vector3d();
    Vector3d a_b = new Vector3d();
    Vector3d b_a = new Vector3d();
    Vector3d b_b = new Vector3d();
    Point3d middlePoint = new Point3d();
    double angle = 0;

    if (singles.size() > 0) {
      double dist0;
      double dist1;
      IAtom singleBondAtom0;
      IAtom singleBondAtom1;
      distance = 0;
      position = 0;
      IBond theSingleBond = null;
      limitInf = 0;
      limitSup = Math.PI / 2;
      step = (limitSup - limitInf) / 7;
      smooth = -1.15;
      int counter = 0;
      for (double ghs = 0; ghs < limitSup; ghs = ghs + step) {
        sum = 0;
        for (int sing = 0; sing < singles.size(); sing++) {
          angle = 0;
          partial = 0;
          Integer thisSingleBond = singles.get(sing);
          position = thisSingleBond;
          theSingleBond = mol.getBond(position);
          middlePoint = theSingleBond.get3DCenter();
          singleBondAtom0 = theSingleBond.getAtom(0);
          singleBondAtom1 = theSingleBond.getAtom(1);
          dist0 = calculateDistanceBetweenTwoAtoms(singleBondAtom0, atom);
          dist1 = calculateDistanceBetweenTwoAtoms(singleBondAtom1, atom);

          a_a.set(middlePoint.x, middlePoint.y, middlePoint.z);
          if (dist1 > dist0)
            a_b.set(
                singleBondAtom0.getPoint3d().x,
                singleBondAtom0.getPoint3d().y,
                singleBondAtom0.getPoint3d().z);
          else
            a_b.set(
                singleBondAtom1.getPoint3d().x,
                singleBondAtom1.getPoint3d().y,
                singleBondAtom1.getPoint3d().z);
          b_a.set(middlePoint.x, middlePoint.y, middlePoint.z);
          b_b.set(atom.getPoint3d().x, atom.getPoint3d().y, atom.getPoint3d().z);

          values = calculateDistanceBetweenAtomAndBond(atom, theSingleBond);

          angle = calculateAngleBetweenTwoLines(a_a, a_b, b_a, b_b);
          // System.out.println("ANGLe: "+angle+ " "+ mol.getAtomNumber(atomsInSingleBond[0]) +" "
          // +mol.getAtomNumber(atomsInSingleBond[1]));

          partial =
              (1 / (Math.pow(values[0], 2))) * Math.exp(smooth * (Math.pow((ghs - angle), 2)));
          sum += partial;
        }
        // gSr_function.add(new Double(sum));
        rdfProtonCalculatedValues.add(sum);
        logger.debug("RDF gSr prob.: " + sum + " at distance " + ghs);
        counter++;
      }
    } else {
      return getDummyDescriptorValue(new CDKException("Some error occurred. Please report"));
    }
    return new DescriptorValue(
        getSpecification(),
        getParameterNames(),
        getParameters(),
        rdfProtonCalculatedValues,
        getDescriptorNames());
  }
  /**
   * Search if the setOfAtomContainer contains the atomContainer
   *
   * @param set ISetOfAtomContainer object where to search
   * @param atomContainer IAtomContainer to search
   * @return True, if the atomContainer is contained
   */
  private boolean existAC(IAtomContainerSet set, IAtomContainer atomContainer) {

    IAtomContainer acClone = null;
    try {
      acClone = (IMolecule) atomContainer.clone();
      if (!lookingSymmetry) {
        /*remove all aromatic flags*/
        for (IAtom atom : acClone.atoms()) atom.setFlag(CDKConstants.ISAROMATIC, false);
        for (IBond bond : acClone.bonds()) bond.setFlag(CDKConstants.ISAROMATIC, false);
      }
    } catch (CloneNotSupportedException e1) {
      e1.printStackTrace();
    }

    for (int i = 0; i < acClone.getAtomCount(); i++)
      //			if(acClone.getAtom(i).getID() == null)
      acClone.getAtom(i).setID("" + acClone.getAtomNumber(acClone.getAtom(i)));

    if (lookingSymmetry) {
      try {
        CDKHueckelAromaticityDetector.detectAromaticity(acClone);
      } catch (CDKException e) {
        e.printStackTrace();
      }
    } else {
      if (!lookingSymmetry) {
        /*remove all aromatic flags*/
        for (IAtom atom : acClone.atoms()) atom.setFlag(CDKConstants.ISAROMATIC, false);
        for (IBond bond : acClone.bonds()) bond.setFlag(CDKConstants.ISAROMATIC, false);
      }
    }
    for (int i = 0; i < set.getAtomContainerCount(); i++) {
      IAtomContainer ss = set.getAtomContainer(i);
      for (int j = 0; j < ss.getAtomCount(); j++)
        //				if(ss.getAtom(j).getID() == null)
        ss.getAtom(j).setID("" + ss.getAtomNumber(ss.getAtom(j)));

      try {

        if (!lookingSymmetry) {
          QueryAtomContainer qAC =
              QueryAtomContainerCreator.createSymbolChargeIDQueryContainer(acClone);
          if (UniversalIsomorphismTester.isIsomorph(ss, qAC)) {
            QueryAtomContainer qAC2 =
                QueryAtomContainerCreator.createSymbolAndBondOrderQueryContainer(acClone);
            if (UniversalIsomorphismTester.isIsomorph(ss, qAC2)) return true;
          }
        } else {
          QueryAtomContainer qAC =
              QueryAtomContainerCreator.createSymbolAndChargeQueryContainer(acClone);
          CDKHueckelAromaticityDetector.detectAromaticity(ss);
          if (UniversalIsomorphismTester.isIsomorph(ss, qAC)) return true;
        }

      } catch (CDKException e1) {
        System.err.println(e1);
        logger.error(e1.getMessage());
        logger.debug(e1);
      }
    }
    return false;
  }