Exemple #1
0
  void expandNode(Node node) {
    // System.out.println(node.toString(target));
    QuerySequenceElement el = sequence.get(node.sequenceElNum);

    if (el.center == null) // This node describers a bond that closes a ring
    {
      // Checking whether this bond is present in the target
      IAtom tAt0 = node.atoms[query.getAtomNumber(el.atoms[0])];
      IAtom tAt1 = node.atoms[query.getAtomNumber(el.atoms[1])];
      IBond tBo = target.getBond(tAt0, tAt1);
      if (tBo != null)
        if (el.bonds[0].matches(tBo)) {
          node.sequenceElNum++;
          // stack.push(node);
          if (node.sequenceElNum == sequence.size()) {
            // The node is not added in the stack if the end of the sequence is reached
            isomorphismFound = true;
            if (FlagStoreIsomorphismNode) isomorphismNodes.add(node);
          } else stack.push(node);
        }
    } else {
      targetAt.clear();
      IAtom tAt = node.atoms[el.centerNum];
      List<IAtom> conAt = target.getConnectedAtomsList(tAt);
      for (int i = 0; i < conAt.size(); i++) {
        if (!containsAtom(node.atoms, conAt.get(i))) targetAt.add(conAt.get(i));
      }

      if (el.atoms.length <= targetAt.size()) generateNodes(node);
    }
  }
Exemple #2
0
  void executeSequence(boolean stopAtFirstMapping) {
    isomorphismFound = false;
    stack.clear();

    // Initial nodes
    QuerySequenceElement el = sequence.get(0);
    for (int k = 0; k < target.getAtomCount(); k++) {
      IAtom at = target.getAtom(k);
      if (el.center.matches(at)) {
        Node node = new Node();
        node.sequenceElNum = 0;
        node.nullifyAtoms(query.getAtomCount());
        node.atoms[el.centerNum] = at;
        stack.push(node);
      }
    }

    // Expanding the tree of all possible mappings
    if (stopAtFirstMapping) {
      while (!stack.isEmpty()) {
        expandNode(stack.pop());
        if (isomorphismFound) break;
      }
    } else {
      while (!stack.isEmpty()) expandNode(stack.pop());
    }
  }
Exemple #3
0
 /** A unit test for JUnit */
 @Test
 public void testPartitioning() {
   String smiles = "";
   IAtomContainer molecule = new AtomContainer();
   SmilesGenerator sg = new SmilesGenerator();
   Atom sodium = new Atom("Na");
   sodium.setFormalCharge(+1);
   Atom hydroxyl = new Atom("O");
   hydroxyl.setImplicitHydrogenCount(1);
   hydroxyl.setFormalCharge(-1);
   molecule.addAtom(sodium);
   molecule.addAtom(hydroxyl);
   try {
     smiles = sg.createSMILES(molecule);
   } catch (Exception exc) {
     System.out.println(exc);
     if (!standAlone) {
       Assert.fail();
     }
   }
   if (standAlone) {
     System.err.println("SMILES: " + smiles);
   }
   Assert.assertTrue(smiles.indexOf(".") != -1);
 }
Exemple #4
0
  /**
   * If no isomorphism is found the result is empty vector
   *
   * @param container
   * @return
   */
  public List<List<IAtom>> getAllIsomorphismMappings(IAtomContainer container) {
    if (query == null) return null;
    target = container;
    FlagStoreIsomorphismNode = true;
    isomorphismNodes.clear();
    List<List<IAtom>> result = new ArrayList<List<IAtom>>();

    if (query.getAtomCount() == 1) {
      SMARTSAtom qa = (SMARTSAtom) query.getAtom(0);
      for (int i = 0; i < target.getAtomCount(); i++) {
        if (qa.matches(target.getAtom(i))) {
          List<IAtom> v = new ArrayList<IAtom>();
          v.add(target.getAtom(i));
          result.add(v);
        }
      }
      return result;
    }

    TopLayer.setAtomTopLayers(target, TopLayer.TLProp);
    executeSequence(false);

    if (isomorphismFound) {
      // Getting the data from the all stored Nodes
      for (int k = 0; k < isomorphismNodes.size(); k++) {
        Node node = isomorphismNodes.get(k);
        List<IAtom> v = new ArrayList<IAtom>();
        for (int i = 0; i < node.atoms.length; i++) v.add(node.atoms[i]);
        result.add(v);
      }
    }
    return result;
  }
  /**
   * 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);
  }
 public String perceiveCDKAtomTypes(IMolecule mol)
             throws InvocationTargetException {
     
     ICDKMolecule cdkmol;
     
     try {
         cdkmol = cdk.asCDKMolecule(mol);
     } 
     catch ( BioclipseException e ) {
         e.printStackTrace();
         throw new InvocationTargetException(
                       e, "Error while creating a ICDKMolecule" );
     }
     
     IAtomContainer ac = cdkmol.getAtomContainer();
     CDKAtomTypeMatcher cdkMatcher 
         = CDKAtomTypeMatcher.getInstance(ac.getBuilder());
     
     StringBuffer result = new StringBuffer();
     int i = 1;
     for (IAtom atom : ac.atoms()) {
         IAtomType type = null;
         try {
             type = cdkMatcher.findMatchingAtomType(ac, atom);
         } 
         catch ( CDKException e ) {}
         result.append(i).append(':').append(
             type != null ? type.getAtomTypeName() : "null"
         ).append('\n'); // FIXME: should use NEWLINE here
         i++;
     }
     return result.toString();
 }
 public void addHydrogens(IAtomContainer mol, IAtom atom, int n) {
   for (int i = 0; i < n; i++) {
     IAtom h = builder.newInstance(IAtom.class, "H");
     mol.addAtom(h);
     mol.addBond(builder.newInstance(IBond.class, atom, h));
   }
 }
 /**
  * Performs a breadthFirstSearch in an AtomContainer starting with a particular sphere, which
  * usually consists of one start atom, and searches for a pi system.
  *
  * @param container The AtomContainer to be searched
  * @param sphere A sphere of atoms to start the search with
  * @param path A ArrayList which stores the atoms belonging to the pi system
  * @throws org.openscience.cdk.exception.CDKException Description of the Exception
  */
 private void breadthFirstSearch(IAtomContainer container, List<IAtom> sphere, List<IAtom> path)
     throws CDKException {
   IAtom atom;
   IAtom nextAtom;
   List<IAtom> newSphere = new ArrayList<IAtom>();
   // logger.debug("Start of breadthFirstSearch");
   for (int i = 0; i < sphere.size(); i++) {
     atom = sphere.get(i);
     // logger.debug("BreadthFirstSearch around atom " + (atomNr + 1));
     List<IBond> bonds = container.getConnectedBondsList(atom);
     for (IBond bond : bonds) {
       nextAtom = bond.getConnectedAtom(atom);
       if ((!nextAtom.getFlag(CDKConstants.ISAROMATIC) && !nextAtom.getFlag(CDKConstants.ISINRING))
           & !nextAtom.getFlag(CDKConstants.VISITED)) {
         // logger.debug("BDS> AtomNr:"+container.getAtomNumber(nextAtom)+"
         // maxBondOrder:"+container.getMaximumBondOrder(nextAtom)+"
         // Aromatic:"+nextAtom.getFlag(CDKConstants.ISAROMATIC)+"
         // FormalCharge:"+nextAtom.getFormalCharge()+" Charge:"+nextAtom.getCharge()+"
         // Flag:"+nextAtom.getFlag(CDKConstants.VISITED));
         path.add(nextAtom);
         // logger.debug("BreadthFirstSearch is meeting new atom " + (nextAtomNr + 1));
         nextAtom.setFlag(CDKConstants.VISITED, true);
         if (container.getConnectedBondsCount(nextAtom) > 1) {
           newSphere.add(nextAtom);
         }
       } else {
         nextAtom.setFlag(CDKConstants.VISITED, true);
       }
     }
   }
   if (newSphere.size() > 0) {
     breadthFirstSearch(container, newSphere, path);
   }
 }
  @Test
  public void methyleneCyclopropeneTest() {
    IAtomContainer mol = builder.newInstance(IAtomContainer.class);
    AbstractSignatureTest.addCarbons(mol, 4);
    AbstractSignatureTest.addHydrogens(mol, 1, 2);
    AbstractSignatureTest.addHydrogens(mol, 2, 1);
    AbstractSignatureTest.addHydrogens(mol, 3, 1);
    mol.addBond(0, 1, IBond.Order.DOUBLE);
    mol.addBond(0, 2, IBond.Order.SINGLE);
    mol.addBond(0, 3, IBond.Order.SINGLE);
    mol.addBond(2, 3, IBond.Order.DOUBLE);
    MoleculeSignature molSig = new MoleculeSignature(mol);

    String sigFor2Height1 = molSig.signatureStringForVertex(2, 1);
    String sigFor3Height1 = molSig.signatureStringForVertex(3, 1);
    Assert.assertTrue(
        "Height 1 signatures for atoms 2 and 3" + " should be the same",
        sigFor2Height1.equals(sigFor3Height1));

    String sigFor2Height2 = molSig.signatureStringForVertex(2, 1);
    String sigFor3Height2 = molSig.signatureStringForVertex(3, 1);
    Assert.assertTrue(
        "Height 2 signatures for atoms 2 and 3" + " should be the same",
        sigFor2Height2.equals(sigFor3Height2));
  }
Exemple #10
0
  public static IAtomContainer getMcsAsNewContainer(IAtomContainer mol1, IAtomContainer mol2)
      throws CDKException, CloneNotSupportedException {
    Isomorphism mcs = new Isomorphism(org.openscience.cdk.smsd.interfaces.Algorithm.DEFAULT, true);
    mcs.init(mol1, mol2, true, true);
    mcs.setChemFilters(true, true, true);

    mol1 = mcs.getReactantMolecule();
    mol2 = mcs.getProductMolecule();

    IAtomContainer mcsmolecule =
        DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class, mol1);

    List<IAtom> atomsToBeRemoved = new ArrayList<IAtom>();
    for (IAtom atom : mcsmolecule.atoms()) {
      int index = mcsmolecule.getAtomNumber(atom);
      if (!mcs.getFirstMapping().containsKey(index)) {
        atomsToBeRemoved.add(atom);
      }
    }

    for (IAtom atom : atomsToBeRemoved) {
      mcsmolecule.removeAtomAndConnectedElectronContainers(atom);
    }

    return mcsmolecule;
  }
Exemple #11
0
  public void timeFile(File dir, String filename) throws CDKException, IOException {
    IAtomContainer atomContainer = readFile(new File(dir, filename));
    long start;

    start = System.currentTimeMillis();
    EquivalentClassPartitioner it = new EquivalentClassPartitioner(atomContainer);
    int equivalentClass[] = it.getTopoEquivClassbyHuXu(atomContainer);
    Partition huXuPartition = ArrayToPartition.convert(equivalentClass, 1);
    long elapsedHuXu = System.currentTimeMillis() - start;

    start = System.currentTimeMillis();
    AtomDiscretePartitionRefiner refiner = new AtomDiscretePartitionRefiner();
    refiner.refine(atomContainer);
    Partition refinedPartition = refiner.getAutomorphismPartition();
    long elapsedRef = System.currentTimeMillis() - start;
    long order = refiner.getAutomorphismGroup().order();

    boolean partitionsEqual = refinedPartition.equals(huXuPartition);

    System.out.println(
        filename
            + "\t"
            + atomContainer.getAtomCount()
            + "\t"
            + elapsedRef
            + "\t"
            + elapsedHuXu
            + "\t"
            + order
            + "\t"
            + refinedPartition.size()
            + "\t"
            + partitionsEqual);
  }
 /**
  * Procedure required by the CDOInterface. This function is only supposed to be called by the JCFL
  * library
  */
 public void endObject(String objectType) {
   logger.debug("END: " + objectType);
   if (objectType.equals("Molecule")) {
     eventReader.fireFrameRead();
     clearData();
   } else if (objectType.equals("Atom")) {
     currentMolecule.addAtom(currentAtom);
   } else if (objectType.equals("Bond")) {
     logger.debug("Bond(" + bond_id + "): " + bond_a1 + ", " + bond_a2 + ", " + bond_order);
     if (bond_a1 > currentMolecule.getAtomCount() || bond_a2 > currentMolecule.getAtomCount()) {
       logger.error(
           "Cannot add bond between at least one non-existant atom: "
               + bond_a1
               + " and "
               + bond_a2);
     } else {
       IAtom a1 = currentMolecule.getAtom(bond_a1);
       IAtom a2 = currentMolecule.getAtom(bond_a2);
       IBond b = builder.newBond(a1, a2, bond_order);
       if (bond_id != null) b.setID(bond_id);
       if (bond_stereo != -99) {
         b.setStereo(bond_stereo);
       }
       currentMolecule.addBond(b);
     }
   }
 }
Exemple #13
0
  /**
   * This function returns null if no isomorphism is found
   *
   * @param container
   * @return
   */
  public List<IAtom> getIsomorphismMapping(IAtomContainer container) {
    if (query == null) return null;
    target = container;
    FlagStoreIsomorphismNode = true;
    isomorphismNodes.clear();

    if (query.getAtomCount() == 1) {
      SMARTSAtom qa = (SMARTSAtom) query.getAtom(0);
      for (int i = 0; i < target.getAtomCount(); i++) {
        if (qa.matches(target.getAtom(i))) {
          List<IAtom> v = new ArrayList<IAtom>();
          v.add(target.getAtom(i));
          return (v);
        }
      }
      return null;
    }

    TopLayer.setAtomTopLayers(target, TopLayer.TLProp);
    executeSequence(true);

    if (isomorphismFound) {
      // Getting the data from the Node
      Node node = isomorphismNodes.get(0);
      List<IAtom> v = new ArrayList<IAtom>();
      for (int i = 0; i < node.atoms.length; i++) v.add(node.atoms[i]);

      return (v);
    } else return (null);
  }
  /**
   * Calculates the eccentric connectivity
   *
   * @param container Parameter is the atom container.
   * @return An IntegerResult value representing the eccentric connectivity index
   */
  @TestMethod("testCalculate_IAtomContainer")
  public DescriptorValue calculate(IAtomContainer container) {
    IAtomContainer local = AtomContainerManipulator.removeHydrogens(container);

    int natom = local.getAtomCount();
    int[][] admat = AdjacencyMatrix.getMatrix(local);
    int[][] distmat = PathTools.computeFloydAPSP(admat);

    int eccenindex = 0;
    for (int i = 0; i < natom; i++) {
      int max = -1;
      for (int j = 0; j < natom; j++) {
        if (distmat[i][j] > max) max = distmat[i][j];
      }
      int degree = local.getConnectedBondsCount(i);
      eccenindex += max * degree;
    }
    IntegerResult retval = new IntegerResult(eccenindex);
    return new DescriptorValue(
        getSpecification(),
        getParameterNames(),
        getParameters(),
        retval,
        getDescriptorNames(),
        null);
  }
 @Test
 public void testGetChiralAtom() {
   TetrahedralChirality chirality =
       new TetrahedralChirality(molecule.getAtom(1), ligands, Stereo.CLOCKWISE);
   Assert.assertNotNull(chirality);
   Assert.assertEquals(molecule.getAtom(1), chirality.getChiralAtom());
 }
	private static void replaceReferencesWithClones(final IChemModel chemModel)
			throws CDKException {
		// we make references in products/reactants clones, since same compounds
		// in different reactions need separate layout (different positions etc)
		if (chemModel.getReactionSet() != null) {
			for (final IReaction reaction : chemModel.getReactionSet()
					.reactions()) {
				int i = 0;
				final IAtomContainerSet products = reaction.getProducts();
				for (final IAtomContainer product : products.atomContainers()) {
					try {
						products.replaceAtomContainer(i, product.clone());
					} catch (final CloneNotSupportedException e) {
					}
					i++;
				}
				i = 0;
				final IAtomContainerSet reactants = reaction.getReactants();
				for (final IAtomContainer reactant : reactants.atomContainers()) {
					try {
						reactants.replaceAtomContainer(i, reactant.clone());
					} catch (final CloneNotSupportedException e) {
					}
					i++;
				}
			}
		}
	}
 public IAtomContainer cyclopentylcyclopentane() {
   IAtom[] atoms =
       new IAtom[] {
         new Atom("C"),
         new Atom("C"),
         new Atom("C"),
         new Atom("C"),
         new Atom("C"),
         new Atom("C"),
         new Atom("C"),
         new Atom("C"),
         new Atom("C"),
         new Atom("C"),
       };
   IBond[] bonds =
       new IBond[] {
         new Bond(atoms[0], atoms[1], SINGLE),
         new Bond(atoms[0], atoms[4], SINGLE),
         new Bond(atoms[1], atoms[2], SINGLE),
         new Bond(atoms[2], atoms[3], SINGLE),
         new Bond(atoms[3], atoms[4], SINGLE),
         new Bond(atoms[5], atoms[6], SINGLE),
         new Bond(atoms[5], atoms[9], SINGLE),
         new Bond(atoms[6], atoms[7], SINGLE),
         new Bond(atoms[7], atoms[8], SINGLE),
         new Bond(atoms[8], atoms[9], SINGLE),
         new Bond(atoms[8], atoms[0], SINGLE),
       };
   IAtomContainer mol = new AtomContainer(0, 0, 0, 0);
   mol.setAtoms(atoms);
   mol.setBonds(bonds);
   return mol;
 }
Exemple #18
0
  /**
   * Returns a CIP-expanded array of side chains of a ligand. If the ligand atom is only connected
   * to the chiral atom, the method will return an empty list. The expansion involves the CIP rules,
   * so that a double bonded oxygen will be represented twice in the list.
   *
   * @param ligand the {@link ILigand} for which to return the ILigands
   * @return a {@link ILigand} array with the side chains of the ligand atom
   */
  @TestMethod("testGetLigandLigands")
  public static ILigand[] getLigandLigands(ILigand ligand) {
    if (ligand instanceof TerminalLigand) return new ILigand[0];

    IAtomContainer container = ligand.getAtomContainer();
    IAtom ligandAtom = ligand.getLigandAtom();
    IAtom centralAtom = ligand.getCentralAtom();
    VisitedAtoms visitedAtoms = ligand.getVisitedAtoms();
    List<IBond> bonds = container.getConnectedBondsList(ligandAtom);
    // duplicate ligands according to bond order, following the CIP rules
    List<ILigand> ligands = new ArrayList<ILigand>();
    for (IBond bond : bonds) {
      if (bond.contains(centralAtom)) {
        if (Order.SINGLE == bond.getOrder()) continue;
        int duplication = getDuplication(bond.getOrder()) - 1;
        if (duplication > 0) {
          for (int i = 1; i <= duplication; i++) {
            ligands.add(new TerminalLigand(container, visitedAtoms, ligandAtom, centralAtom));
          }
        }
      } else {
        int duplication = getDuplication(bond.getOrder());
        IAtom connectedAtom = bond.getConnectedAtom(ligandAtom);
        if (visitedAtoms.isVisited(connectedAtom)) {
          ligands.add(new TerminalLigand(container, visitedAtoms, ligandAtom, connectedAtom));
        } else {
          ligands.add(new Ligand(container, visitedAtoms, ligandAtom, connectedAtom));
        }
        for (int i = 2; i <= duplication; i++) {
          ligands.add(new TerminalLigand(container, visitedAtoms, ligandAtom, connectedAtom));
        }
      }
    }
    return ligands.toArray(new ILigand[0]);
  }
  /**
   * 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;
  }
Exemple #20
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);
 }
Exemple #21
0
 /**
  * removes all bonds connected to the given atom leaving it with degree zero.
  *
  * @param atom The atom to be disconnecred
  * @param molecule The molecule containing the atom
  */
 private void trim(IAtom atom, IAtomContainer molecule) {
   List<IBond> bonds = molecule.getConnectedBondsList(atom);
   for (int i = 0; i < bonds.size(); i++) {
     molecule.removeElectronContainer((IBond) bonds.get(i));
   }
   // you are erased! Har, har, har.....  >8-)
 }
Exemple #22
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;
 }
  /**
   * @param list
   * @param source
   * @param target
   */
  protected synchronized void identifySingleAtomsMatchedParts(
      List<CDKRMap> list, IAtomContainer source, IAtomContainer target) {

    //        List<IAtom> array1 = new ArrayList<>();
    //        List<IAtom> array2 = new ArrayList<>();

    /* We have serial numbers of the bonds/Atoms to delete
     * Now we will collect the actual bond/Atoms rather than
     * serial number for deletion. RonP flag check whether reactant is
     * mapped on product or Vise Versa
     */
    TreeMap<Integer, Integer> atomNumbersFromContainer = new TreeMap<>();

    for (CDKRMap rmap : list) {
      // System.err.print("Map " + o.getClass());

      IAtom sAtom = source.getAtom(rmap.getId1());
      IAtom tAtom = target.getAtom(rmap.getId2());

      //            array1.add(sAtom);
      //            array2.add(tAtom);
      int indexI = source.getAtomNumber(sAtom);
      int indexJ = target.getAtomNumber(tAtom);

      atomNumbersFromContainer.put(indexI, indexJ);

      /*Added the Mapping Numbers to the FinalMapping*
       */
      getMappings().add(atomNumbersFromContainer);
    }
  }
Exemple #24
0
  @TestMethod("testCalculate_IAtomContainer")
  public DescriptorValue calculate(IAtomContainer container) {

    // removeHydrogens does a deep copy, so no need to clone
    IAtomContainer localAtomContainer = AtomContainerManipulator.removeHydrogens(container);
    CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.getInstance(container.getBuilder());
    Iterator<IAtom> atoms = localAtomContainer.atoms().iterator();
    while (atoms.hasNext()) {
      IAtom atom = atoms.next();
      IAtomType type;
      try {
        type = matcher.findMatchingAtomType(localAtomContainer, atom);
        AtomTypeManipulator.configure(atom, type);
      } catch (Exception e) {
        return getDummyDescriptorValue(new CDKException("Error in atom typing: " + e.getMessage()));
      }
    }
    CDKHydrogenAdder hAdder = CDKHydrogenAdder.getInstance(container.getBuilder());
    try {
      hAdder.addImplicitHydrogens(localAtomContainer);
    } catch (CDKException e) {
      return getDummyDescriptorValue(
          new CDKException("Error in hydrogen addition: " + e.getMessage()));
    }

    List subgraph3 = order3(localAtomContainer);
    List subgraph4 = order4(localAtomContainer);
    List subgraph5 = order5(localAtomContainer);
    List subgraph6 = order6(localAtomContainer);

    double order3s = ChiIndexUtils.evalSimpleIndex(localAtomContainer, subgraph3);
    double order4s = ChiIndexUtils.evalSimpleIndex(localAtomContainer, subgraph4);
    double order5s = ChiIndexUtils.evalSimpleIndex(localAtomContainer, subgraph5);
    double order6s = ChiIndexUtils.evalSimpleIndex(localAtomContainer, subgraph6);

    double order3v, order4v, order5v, order6v;
    try {
      order3v = ChiIndexUtils.evalValenceIndex(localAtomContainer, subgraph3);
      order4v = ChiIndexUtils.evalValenceIndex(localAtomContainer, subgraph4);
      order5v = ChiIndexUtils.evalValenceIndex(localAtomContainer, subgraph5);
      order6v = ChiIndexUtils.evalValenceIndex(localAtomContainer, subgraph6);
    } catch (CDKException e) {
      return getDummyDescriptorValue(
          new CDKException("Error in substructure search: " + e.getMessage()));
    }
    DoubleArrayResult retval = new DoubleArrayResult();
    retval.add(order3s);
    retval.add(order4s);
    retval.add(order5s);
    retval.add(order6s);

    retval.add(order3v);
    retval.add(order4v);
    retval.add(order5v);
    retval.add(order6v);

    return new DescriptorValue(
        getSpecification(), getParameterNames(), getParameters(), retval, getDescriptorNames());
  }
Exemple #25
0
 /**
  * Helper method, used to help construct a configuration.
  *
  * @param atom
  * @param container
  * @return the array position of atom in container
  */
 private int getAtomPosition(IAtom atom, IAtomContainer container) {
   for (int i = 0; i < container.getAtomCount(); i++) {
     if (atom.equals(container.getAtom(i))) {
       return i;
     }
   }
   return -1;
 }
Exemple #26
0
 /**
  * Helper method, used to help construct a configuration.
  *
  * @param bond
  * @param container
  * @return the array position of the bond in the container
  */
 private int getBondPosition(IBond bond, IAtomContainer container) {
   for (int i = 0; i < container.getBondCount(); i++) {
     if (bond.equals(container.getBond(i))) {
       return i;
     }
   }
   return -1;
 }
  public static IAtomContainer makeFragment4() {
    IAtomContainer mol = DefaultChemObjectBuilder.getInstance().newInstance(IAtomContainer.class);
    mol.addAtom(new Atom("C")); // 0
    mol.addAtom(new Atom("C")); // 1

    mol.addBond(0, 1, IBond.Order.SINGLE); // 1
    return mol;
  }
 public int findFirstAtomIndexForSymbol(IAtomContainer container, String symbol) {
   for (int i = 0; i < container.getAtomCount(); i++) {
     if (container.getAtom(i).getSymbol().equals(symbol)) {
       return i;
     }
   }
   return -1;
 }
Exemple #29
0
 private double caclModelScale(Collection<IAtomContainer> mols) {
   List<IBond> bonds = new ArrayList<>();
   for (IAtomContainer mol : mols) {
     for (IBond bond : mol.bonds()) {
       bonds.add(bond);
     }
   }
   return calcModelScaleForBondLength(medianBondLength(bonds));
 }
Exemple #30
0
 /**
  * Creates a ligand attached to a single chiral atom, where the involved atoms are identified by
  * there index in the {@link IAtomContainer}. For ligand atom, {@link #HYDROGEN} can be passed as
  * index, which will indicate the presence of an implicit hydrogen, not explicitly present in the
  * chemical graph of the given <code>container</code>.
  *
  * @param container {@link IAtomContainer} for which the returned {@link ILigand}s are defined
  * @param visitedAtoms a list of atoms already visited in the analysis
  * @param chiralAtom an integer pointing to the {@link IAtom} index of the chiral atom
  * @param ligandAtom an integer pointing to the {@link IAtom} index of the {@link ILigand}
  * @return the created {@link ILigand}
  */
 public static ILigand defineLigand(
     IAtomContainer container, VisitedAtoms visitedAtoms, int chiralAtom, int ligandAtom) {
   if (ligandAtom == HYDROGEN) {
     return new ImplicitHydrogenLigand(container, visitedAtoms, container.getAtom(chiralAtom));
   } else {
     return new Ligand(
         container, visitedAtoms, container.getAtom(chiralAtom), container.getAtom(ligandAtom));
   }
 }