Esempio n. 1
0
  /**
   * @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);
    }
  }
  /**
   * 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;
  }
  /**
   * Fill the {@literal coordinates} and {@literal elevation} from the given offset index. If there
   * is only one connection then the second entry (from the offset) will use the coordinates of
   * <i>a</i>. The permutation parity is also built and returned.
   *
   * @param container atom container
   * @param a the central atom
   * @param connected bonds connected to the central atom
   * @param coordinates the coordinates array to fill
   * @param elevations the elevations of the connected atoms
   * @param offset current location in the offset array
   * @return the permutation parity
   */
  private static PermutationParity fill2DCoordinates(
      IAtomContainer container,
      IAtom a,
      List<IBond> connected,
      Point2d[] coordinates,
      int[] elevations,
      int offset) {

    int i = 0;
    coordinates[offset + 1] = a.getPoint2d();
    elevations[offset + 1] = 0;
    int[] indices = new int[2];

    for (IBond bond : connected) {
      if (!isDoubleBond(bond)) {
        IAtom other = bond.getConnectedAtom(a);
        coordinates[i + offset] = other.getPoint2d();
        elevations[i + offset] = elevation(bond, a);
        indices[i] = container.getAtomNumber(other);
        i++;
      }
    }

    if (i == 1) {
      return PermutationParity.IDENTITY;
    } else {
      return new BasicPermutationParity(indices);
    }
  }
Esempio n. 4
0
File: Misc.java Progetto: egonw/cdkr
  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;
  }
Esempio n. 5
0
 /**
  * Convenience method for giving a string representation of this ring based on the number of the
  * atom in a given molecule.
  *
  * @param molecule A molecule to determine an atom number for each ring atom
  * @return string representation of this ring
  */
 private String toString(IRing ring, IAtomContainer molecule) throws Exception {
   String str = "";
   for (int f = 0; f < ring.getAtomCount(); f++) {
     str += molecule.getAtomNumber(ring.getAtom(f)) + " - ";
   }
   return str;
 }
Esempio n. 6
0
 @Override
 public int seed(IAtomContainer molecule, IAtom atom, BitSet mask) {
   double sum = 0;
   for (IBond bond : molecule.getConnectedBondsList(atom)) {
     if (mask.get(molecule.getAtomNumber(bond.getConnectedAtom(atom))))
       sum += order(bond.getOrder());
   }
   return ((Double) sum).hashCode();
 }
  /**
   * Create an encoder for axial 3D stereochemistry for the given start and end atoms.
   *
   * @param container the molecule
   * @param start start of the cumulated system
   * @param startBonds bonds connected to the start
   * @param end end of the cumulated system
   * @param endBonds bonds connected to the end
   * @return an encoder
   */
  private static StereoEncoder axial3DEncoder(
      IAtomContainer container,
      IAtom start,
      List<IBond> startBonds,
      IAtom end,
      List<IBond> endBonds) {

    Point3d[] coordinates = new Point3d[4];

    PermutationParity perm =
        new CombinedPermutationParity(
            fill3DCoordinates(container, start, startBonds, coordinates, 0),
            fill3DCoordinates(container, end, endBonds, coordinates, 2));

    GeometricParity geom = new Tetrahedral3DParity(coordinates);

    int u = container.getAtomNumber(start);
    int v = container.getAtomNumber(end);

    return new GeometryEncoder(new int[] {u, v}, perm, geom);
  }
Esempio n. 8
0
  protected void process(
      IAtomContainer target,
      List<Integer> unmapped_atoms_molB,
      int mappingSize,
      List<Integer> i_bond_setB,
      List<String> c_bond_setB,
      List<Integer> mapped_atoms,
      int counter) {

    int unmapped_numB = unmapped_atoms_molB.size();
    boolean bond_considered = false;
    boolean normal_bond = true;

    for (int atomIndex = 0; atomIndex < target.getBondCount(); atomIndex++) {

      Integer indexI = target.getAtomNumber(target.getBond(atomIndex).getAtom(0));
      Integer indexJ = target.getAtomNumber(target.getBond(atomIndex).getAtom(1));
      IBond bond = target.getBond(atomIndex);
      Integer order = (bond.getOrder().ordinal() + 1);

      for (int b = 0; b < unmapped_numB; b++) {
        if (unmapped_atoms_molB.get(b).equals(indexI)) {
          normal_bond =
              unMappedAtomsEqualsIndexI(
                  target, mappingSize, atomIndex, counter, mapped_atoms, indexI, indexJ, order);
          bond_considered = true;
        } else if (unmapped_atoms_molB.get(b) == indexJ) {
          normal_bond =
              unMappedAtomsEqualsIndexJ(
                  target, mappingSize, atomIndex, counter, mapped_atoms, indexI, indexJ, order);
          bond_considered = true;
        }

        if (normal_bond && bond_considered) {
          markNormalBonds(atomIndex, i_bond_setB, c_bond_setB, indexI, indexJ, order);
          normal_bond = true;
          break;
        }
      }
      bond_considered = false;
    }
  }
Esempio n. 9
0
  /**
   * Positions the aliphatic substituents of a ring system
   *
   * @param rs The RingSystem for which the substituents are to be laid out
   * @return A list of atoms that where laid out
   */
  public IAtomContainer placeRingSubstituents(IRingSet rs, double bondLength) {
    logger.debug("RingPlacer.placeRingSubstituents() start");
    IRing ring = null;
    IAtom atom = null;
    IRingSet rings = null;
    IAtomContainer unplacedPartners = rs.getBuilder().newInstance(IAtomContainer.class);
    IAtomContainer sharedAtoms = rs.getBuilder().newInstance(IAtomContainer.class);
    IAtomContainer primaryAtoms = rs.getBuilder().newInstance(IAtomContainer.class);
    IAtomContainer treatedAtoms = rs.getBuilder().newInstance(IAtomContainer.class);
    Point2d centerOfRingGravity = null;
    for (int j = 0; j < rs.getAtomContainerCount(); j++) {
      ring = (IRing) rs.getAtomContainer(j); /* Get the j-th Ring in RingSet rs */
      for (int k = 0; k < ring.getAtomCount(); k++) {
        unplacedPartners.removeAllElements();
        sharedAtoms.removeAllElements();
        primaryAtoms.removeAllElements();
        atom = ring.getAtom(k);
        rings = rs.getRings(atom);
        centerOfRingGravity = GeometryTools.get2DCenter(rings);
        atomPlacer.partitionPartners(atom, unplacedPartners, sharedAtoms);
        atomPlacer.markNotPlaced(unplacedPartners);
        try {
          for (int f = 0; f < unplacedPartners.getAtomCount(); f++) {
            logger.debug(
                "placeRingSubstituents->unplacedPartners: "
                    + (molecule.getAtomNumber(unplacedPartners.getAtom(f)) + 1));
          }
        } catch (Exception exc) {
        }

        treatedAtoms.add(unplacedPartners);
        if (unplacedPartners.getAtomCount() > 0) {
          atomPlacer.distributePartners(
              atom, sharedAtoms, centerOfRingGravity, unplacedPartners, bondLength);
        }
      }
    }
    logger.debug("RingPlacer.placeRingSubstituents() end");
    return treatedAtoms;
  }
  /**
   * The method calculates the sigma electronegativity of a given atom It is needed to call the
   * addExplicitHydrogensToSatisfyValency method from the class tools.HydrogenAdder.
   *
   * @param atom The IAtom for which the DescriptorValue is requested
   * @param ac AtomContainer
   * @return return the sigma electronegativity
   */
  @TestMethod(value = "testCalculate_IAtomContainer")
  public DescriptorValue calculate(IAtom atom, IAtomContainer ac) {

    IAtomContainer clone;
    IAtom localAtom;
    try {
      clone = (IAtomContainer) ac.clone();
      localAtom = clone.getAtom(ac.getAtomNumber(atom));
      AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(clone);
    } catch (CDKException e) {
      return new DescriptorValue(
          getSpecification(),
          getParameterNames(),
          getParameters(),
          new DoubleResult(Double.NaN),
          descriptorNames,
          e);
    } catch (CloneNotSupportedException e) {
      return new DescriptorValue(
          getSpecification(),
          getParameterNames(),
          getParameters(),
          new DoubleResult(Double.NaN),
          descriptorNames,
          e);
    }

    if (maxIterations != -1 && maxIterations != 0)
      electronegativity.setMaxIterations(maxIterations);

    double result = electronegativity.calculateSigmaElectronegativity(clone, localAtom);

    return new DescriptorValue(
        getSpecification(),
        getParameterNames(),
        getParameters(),
        new DoubleResult(result),
        descriptorNames);
  }
Esempio n. 11
0
  private List<List<Integer>> getAtomMappings(List bondMapping, IAtomContainer atomContainer) {
    List<List<Integer>> atomMapping = new ArrayList<List<Integer>>();

    // loop over each mapping
    for (Object aBondMapping : bondMapping) {
      List list = (List) aBondMapping;

      List<Integer> tmp = new ArrayList<Integer>();
      IAtom atom1 = null;
      IAtom atom2 = null;
      // loop over this mapping
      for (Object aList : list) {
        RMap map = (RMap) aList;
        int bondID = map.getId1();

        // get the atoms in this bond
        IBond bond = atomContainer.getBond(bondID);
        atom1 = bond.getAtom(0);
        atom2 = bond.getAtom(1);

        Integer idx1 = atomContainer.getAtomNumber(atom1);
        Integer idx2 = atomContainer.getAtomNumber(atom2);

        if (!tmp.contains(idx1)) tmp.add(idx1);
        if (!tmp.contains(idx2)) tmp.add(idx2);
      }
      if (tmp.size() > 0) atomMapping.add(tmp);

      // If there is only one bond, check if it matches both ways.
      if (list.size() == 1 && atom1.getAtomicNumber() == atom2.getAtomicNumber()) {
        List<Integer> tmp2 = new ArrayList<Integer>();
        tmp2.add(tmp.get(0));
        tmp2.add(tmp.get(1));
        atomMapping.add(tmp2);
      }
    }

    return atomMapping;
  }
  /**
   * 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;
  }
Esempio n. 13
0
 /**
  * This makes sourceAtom map1 of matching atoms out of sourceAtom map1 of matching bonds as
  * produced by the get(Subgraph|Ismorphism)Map methods.
  *
  * @param rMapList The list produced by the getMap method.
  * @param graph1 first molecule. Must not be an IQueryAtomContainer.
  * @param graph2 second molecule. May be an IQueryAtomContainer.
  * @return The mapping found projected on graph1. This is sourceAtom List of CDKRMap objects
  *     containing Ids of matching atoms.
  */
 private synchronized List<List<CDKRMap>> makeAtomsMapOfBondsMap(
     List<CDKRMap> rMapList, IAtomContainer graph1, IAtomContainer graph2) {
   if (rMapList == null) {
     return (null);
   }
   List<List<CDKRMap>> result;
   if (rMapList.size() == 1) {
     result = makeAtomsMapOfBondsMapSingleBond(rMapList, graph1, graph2);
   } else {
     List<CDKRMap> resultLocal = new ArrayList<CDKRMap>();
     for (CDKRMap rMapList2 : rMapList) {
       IBond qBond = graph1.getBond(rMapList2.getId1());
       IBond tBond = graph2.getBond(rMapList2.getId2());
       IAtom[] qAtoms = BondManipulator.getAtomArray(qBond);
       IAtom[] tAtoms = BondManipulator.getAtomArray(tBond);
       for (int j = 0; j < 2; j++) {
         List<IBond> bondsConnectedToAtom1j = graph1.getConnectedBondsList(qAtoms[j]);
         for (IBond bondsConnectedToAtom1j1 : bondsConnectedToAtom1j) {
           if (bondsConnectedToAtom1j1 != qBond) {
             IBond testBond = bondsConnectedToAtom1j1;
             for (CDKRMap rMapList1 : rMapList) {
               IBond testBond2;
               if ((rMapList1).getId1() == graph1.getBondNumber(testBond)) {
                 testBond2 = graph2.getBond((rMapList1).getId2());
                 for (int n = 0; n < 2; n++) {
                   List<IBond> bondsToTest = graph2.getConnectedBondsList(tAtoms[n]);
                   if (bondsToTest.contains(testBond2)) {
                     CDKRMap map1;
                     if (j == n) {
                       map1 =
                           new CDKRMap(
                               graph1.getAtomNumber(qAtoms[0]), graph2.getAtomNumber(tAtoms[0]));
                     } else {
                       map1 =
                           new CDKRMap(
                               graph1.getAtomNumber(qAtoms[1]), graph2.getAtomNumber(tAtoms[0]));
                     }
                     if (!resultLocal.contains(map1)) {
                       resultLocal.add(map1);
                     }
                     CDKRMap map2;
                     if (j == n) {
                       map2 =
                           new CDKRMap(
                               graph1.getAtomNumber(qAtoms[1]), graph2.getAtomNumber(tAtoms[1]));
                     } else {
                       map2 =
                           new CDKRMap(
                               graph1.getAtomNumber(qAtoms[0]), graph2.getAtomNumber(tAtoms[1]));
                     }
                     if (!resultLocal.contains(map2)) {
                       resultLocal.add(map2);
                     }
                   }
                 }
               }
             }
           }
         }
       }
     }
     result = new ArrayList<>();
     result.add(resultLocal);
   }
   return result;
 }
Esempio n. 14
0
  /**
   * Generated coordinates for a given ring, which is fused to another ring. The rings share exactly
   * one bond.
   *
   * @param ring The ring to be placed
   * @param sharedAtoms The atoms of this ring, also members of another ring, which are already
   *     placed
   * @param sharedAtomsCenter The geometric center of these atoms
   * @param ringCenterVector A vector pointing the the center of the new ring
   * @param bondLength The standard bondlength
   */
  public void placeFusedRing(
      IRing ring,
      IAtomContainer sharedAtoms,
      Point2d sharedAtomsCenter,
      Vector2d ringCenterVector,
      double bondLength) {
    logger.debug("RingPlacer.placeFusedRing() start");
    Point2d ringCenter = new Point2d(sharedAtomsCenter);
    double radius = getNativeRingRadius(ring, bondLength);
    double newRingPerpendicular = Math.sqrt(Math.pow(radius, 2) - Math.pow(bondLength / 2, 2));
    ringCenterVector.normalize();
    logger.debug("placeFusedRing->: ringCenterVector.length()" + ringCenterVector.length());
    ringCenterVector.scale(newRingPerpendicular);
    ringCenter.add(ringCenterVector);

    IAtom bondAtom1 = sharedAtoms.getAtom(0);
    IAtom bondAtom2 = sharedAtoms.getAtom(1);

    Vector2d bondAtom1Vector = new Vector2d(bondAtom1.getPoint2d());
    Vector2d bondAtom2Vector = new Vector2d(bondAtom2.getPoint2d());
    Vector2d originRingCenterVector = new Vector2d(ringCenter);

    bondAtom1Vector.sub(originRingCenterVector);
    bondAtom2Vector.sub(originRingCenterVector);

    double occupiedAngle = bondAtom1Vector.angle(bondAtom2Vector);

    double remainingAngle = (2 * Math.PI) - occupiedAngle;
    double addAngle = remainingAngle / (ring.getRingSize() - 1);

    logger.debug("placeFusedRing->occupiedAngle: " + Math.toDegrees(occupiedAngle));
    logger.debug("placeFusedRing->remainingAngle: " + Math.toDegrees(remainingAngle));
    logger.debug("placeFusedRing->addAngle: " + Math.toDegrees(addAngle));

    IAtom startAtom;

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

    double xDiff = bondAtom1.getPoint2d().x - bondAtom2.getPoint2d().x;
    double yDiff = bondAtom1.getPoint2d().y - bondAtom2.getPoint2d().y;

    double startAngle;
    ;

    int direction = 1;
    // if bond is vertical
    if (xDiff == 0) {
      logger.debug("placeFusedRing->Bond is vertical");
      // starts with the lower Atom
      if (bondAtom1.getPoint2d().y > bondAtom2.getPoint2d().y) {
        startAtom = bondAtom1;
      } else {
        startAtom = bondAtom2;
      }

      // changes the drawing direction
      if (centerX < bondAtom1.getPoint2d().x) {
        direction = 1;
      } else {
        direction = -1;
      }
    }

    // if bond is not vertical
    else {
      // starts with the left Atom
      if (bondAtom1.getPoint2d().x > bondAtom2.getPoint2d().x) {
        startAtom = bondAtom1;
      } else {
        startAtom = bondAtom2;
      }

      // changes the drawing direction
      if (centerY - bondAtom1.getPoint2d().y
          > (centerX - bondAtom1.getPoint2d().x) * yDiff / xDiff) {
        direction = 1;
      } else {
        direction = -1;
      }
    }
    startAngle =
        GeometryTools.getAngle(
            startAtom.getPoint2d().x - ringCenter.x, startAtom.getPoint2d().y - ringCenter.y);

    IAtom currentAtom = startAtom;
    // determine first bond in Ring
    //        int k = 0;
    //        for (k = 0; k < ring.getElectronContainerCount(); k++) {
    //            if (ring.getElectronContainer(k) instanceof IBond) break;
    //        }
    IBond currentBond = sharedAtoms.getBond(0);
    Vector atomsToDraw = new Vector();
    for (int i = 0; i < ring.getBondCount() - 2; i++) {
      currentBond = ring.getNextBond(currentBond, currentAtom);
      currentAtom = currentBond.getConnectedAtom(currentAtom);
      atomsToDraw.addElement(currentAtom);
    }
    addAngle = addAngle * direction;
    try {
      logger.debug("placeFusedRing->startAngle: " + Math.toDegrees(startAngle));
      logger.debug("placeFusedRing->addAngle: " + Math.toDegrees(addAngle));
      logger.debug("placeFusedRing->startAtom is: " + (molecule.getAtomNumber(startAtom) + 1));
      logger.debug("AtomsToDraw: " + atomPlacer.listNumbers(molecule, atomsToDraw));
    } catch (Exception exc) {
      logger.debug("Caught an exception while logging in RingPlacer");
    }
    atomPlacer.populatePolygonCorners(atomsToDraw, ringCenter, startAngle, addAngle, radius);
  }
Esempio n. 15
0
 /**
  * @param atom1
  * @param atom2
  */
 public synchronized void put(IAtom atom1, IAtom atom2) {
   mapping.put(atom1, atom2);
   mappingIndex.put(query.getAtomNumber(atom1), target.getAtomNumber(atom2));
 }
Esempio n. 16
0
  /**
   * This makes atom map1 of matching atoms out of atom map1 of matching bonds as produced by the
   * get(Subgraph|Ismorphism)Map methods. Added by Asad since CDK one doesn't pick up the correct
   * changes
   *
   * @param list The list produced by the getMap method.
   * @param sourceGraph first molecule. Must not be an IQueryAtomContainer.
   * @param targetGraph second molecule. May be an IQueryAtomContainer.
   * @return The mapping found projected on sourceGraph. This is atom List of CDKRMap objects
   *     containing Ids of matching atoms.
   */
  private synchronized List<List<CDKRMap>> makeAtomsMapOfBondsMapSingleBond(
      List<CDKRMap> list, IAtomContainer sourceGraph, IAtomContainer targetGraph) {
    if (list == null) {
      return null;
    }
    Map<IBond, IBond> bondMap = new HashMap<IBond, IBond>(list.size());
    for (CDKRMap solBondMap : list) {
      int id1 = solBondMap.getId1();
      int id2 = solBondMap.getId2();
      IBond qBond = sourceGraph.getBond(id1);
      IBond tBond = targetGraph.getBond(id2);
      bondMap.put(qBond, tBond);
    }
    List<CDKRMap> result1 = new ArrayList<CDKRMap>();
    List<CDKRMap> result2 = new ArrayList<CDKRMap>();
    for (IBond qbond : sourceGraph.bonds()) {
      if (bondMap.containsKey(qbond)) {
        IBond tbond = bondMap.get(qbond);
        CDKRMap map00 = null;
        CDKRMap map01 = null;
        CDKRMap map10 = null;
        CDKRMap map11 = null;

        if ((qbond.getAtom(0).getSymbol().equals(tbond.getAtom(0).getSymbol()))
            && (qbond.getAtom(1).getSymbol().equals(tbond.getAtom(1).getSymbol()))) {
          map00 =
              new CDKRMap(
                  sourceGraph.getAtomNumber(qbond.getAtom(0)),
                  targetGraph.getAtomNumber(tbond.getAtom(0)));
          map11 =
              new CDKRMap(
                  sourceGraph.getAtomNumber(qbond.getAtom(1)),
                  targetGraph.getAtomNumber(tbond.getAtom(1)));
          if (!result1.contains(map00)) {
            result1.add(map00);
          }
          if (!result1.contains(map11)) {
            result1.add(map11);
          }
        }
        if ((qbond.getAtom(0).getSymbol().equals(tbond.getAtom(1).getSymbol()))
            && (qbond.getAtom(1).getSymbol().equals(tbond.getAtom(0).getSymbol()))) {
          map01 =
              new CDKRMap(
                  sourceGraph.getAtomNumber(qbond.getAtom(0)),
                  targetGraph.getAtomNumber(tbond.getAtom(1)));
          map10 =
              new CDKRMap(
                  sourceGraph.getAtomNumber(qbond.getAtom(1)),
                  targetGraph.getAtomNumber(tbond.getAtom(0)));
          if (!result2.contains(map01)) {
            result2.add(map01);
          }
          if (!result2.contains(map10)) {
            result2.add(map10);
          }
        }
      }
    }
    List<List<CDKRMap>> result = new ArrayList<List<CDKRMap>>();
    if (result1.size() == result2.size()) {
      result.add(result1);
      result.add(result2);
    } else if (result1.size() > result2.size()) {
      result.add(result1);
    } else {
      result.add(result2);
    }
    return result;
  }
Esempio n. 17
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());
  }
  /**
   * Initiates the process for the given mechanism. The atoms to apply are mapped between reactants
   * and products.
   *
   * @param atomContainerSet
   * @param atomList The list of atoms taking part in the mechanism. Only allowed two atoms. The
   *     first atom is the atom which contains the ISingleElectron and the second third is the atom
   *     which will be removed the first atom
   * @param bondList The list of bonds taking part in the mechanism. Only allowed one bond. It is
   *     the bond which is moved
   * @return The Reaction mechanism
   */
  @TestMethod(value = "testInitiate_IAtomContainerSet_ArrayList_ArrayList")
  public IReaction initiate(
      IAtomContainerSet atomContainerSet, ArrayList<IAtom> atomList, ArrayList<IBond> bondList)
      throws CDKException {
    CDKAtomTypeMatcher atMatcher = CDKAtomTypeMatcher.getInstance(atomContainerSet.getBuilder());
    if (atomContainerSet.getAtomContainerCount() != 1) {
      throw new CDKException("RadicalSiteIonizationMechanism only expects one IMolecule");
    }
    if (atomList.size() != 3) {
      throw new CDKException("RadicalSiteIonizationMechanism expects three atoms in the ArrayList");
    }
    if (bondList.size() != 2) {
      throw new CDKException(
          "RadicalSiteIonizationMechanism only expect one bond in the ArrayList");
    }
    IAtomContainer molecule = atomContainerSet.getAtomContainer(0);
    IAtomContainer reactantCloned;
    try {
      reactantCloned = (IAtomContainer) molecule.clone();
    } catch (CloneNotSupportedException e) {
      throw new CDKException("Could not clone IMolecule!", e);
    }
    IAtom atom1 = atomList.get(0); // Atom containing the ISingleElectron
    IAtom atom1C = reactantCloned.getAtom(molecule.getAtomNumber(atom1));
    IAtom atom2 = atomList.get(1); // Atom
    IAtom atom2C = reactantCloned.getAtom(molecule.getAtomNumber(atom2));
    IAtom atom3 = atomList.get(2); // Atom to be saved
    IAtom atom3C = reactantCloned.getAtom(molecule.getAtomNumber(atom3));
    IBond bond1 = bondList.get(0); // Bond to increase the order
    int posBond1 = molecule.getBondNumber(bond1);
    IBond bond2 = bondList.get(1); // Bond to remove
    int posBond2 = molecule.getBondNumber(bond2);

    BondManipulator.increaseBondOrder(reactantCloned.getBond(posBond1));
    reactantCloned.removeBond(reactantCloned.getBond(posBond2));

    List<ISingleElectron> selectron = reactantCloned.getConnectedSingleElectronsList(atom1C);
    reactantCloned.removeSingleElectron(selectron.get(selectron.size() - 1));
    atom1C.setHybridization(null);
    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(reactantCloned);
    IAtomType type = atMatcher.findMatchingAtomType(reactantCloned, atom1C);
    if (type == null) return null;

    atom2C.setHybridization(null);
    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(reactantCloned);
    type = atMatcher.findMatchingAtomType(reactantCloned, atom2C);
    if (type == null) return null;

    reactantCloned.addSingleElectron(new SingleElectron(atom3C));
    atom3C.setHybridization(null);
    AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(reactantCloned);
    type = atMatcher.findMatchingAtomType(reactantCloned, atom3C);
    if (type == null) return null;

    IReaction reaction = DefaultChemObjectBuilder.getInstance().newInstance(IReaction.class);
    reaction.addReactant(molecule);

    /* mapping */
    for (IAtom atom : molecule.atoms()) {
      IMapping mapping =
          DefaultChemObjectBuilder.getInstance()
              .newInstance(
                  IMapping.class, atom, reactantCloned.getAtom(molecule.getAtomNumber(atom)));
      reaction.addMapping(mapping);
    }

    IAtomContainerSet moleculeSetP = ConnectivityChecker.partitionIntoMolecules(reactantCloned);
    for (int z = 0; z < moleculeSetP.getAtomContainerCount(); z++)
      reaction.addProduct((IAtomContainer) moleculeSetP.getAtomContainer(z));

    return reaction;
  }