/// <summary> /// Tells if a certain bond is center of a valid double bond configuration. /// </summary> /// <param name="container"> The atomcontainer. /// </param> /// <param name="bond"> The bond. /// </param> /// <returns> true=is a potential configuration, false=is not. /// </returns> public static bool isValidDoubleBondConfiguration(IAtomContainer container, IBond bond) { IAtom[] atoms = bond.getAtoms(); IAtom[] connectedAtoms = container.getConnectedAtoms(atoms[0]); IAtom from = null; for (int i = 0; i < connectedAtoms.Length; i++) { if (connectedAtoms[i] != atoms[1]) { from = connectedAtoms[i]; } } bool[] array = new bool[container.Bonds.Length]; for (int i = 0; i < array.Length; i++) { array[i] = true; } if (isStartOfDoubleBond(container, atoms[0], from, array) && isEndOfDoubleBond(container, atoms[1], atoms[0], array) && !bond.getFlag(CDKConstants.ISAROMATIC)) { return (true); } else { return (false); } }
public IEnumerable<IAtomContainer> GenerateFragments(IAtomContainer compound, string compoundId, CancellationToken isCancelled) { var fragmenter = new Fragmenter(spectrum.Peaks.ToList(), config); // This might throw an OutOfMemoryException, but I want it to be thrown not silently fail return fragmenter.GenerateFragmentsEfficient(compound, true, config.TreeDepth, compoundId, isCancelled); }
/// <summary> Makes an array containing the morgan numbers of the atoms of atomContainer. /// /// </summary> /// <param name="atomContainer"> The atomContainer to analyse. /// </param> /// <returns> The morgan numbers value. /// </returns> public static int[] getMorganNumbers(IAtomContainer atomContainer) { int[] morganMatrix; int[] tempMorganMatrix; int N = atomContainer.AtomCount; morganMatrix = new int[N]; tempMorganMatrix = new int[N]; IAtom[] atoms = null; for (int f = 0; f < N; f++) { morganMatrix[f] = atomContainer.getBondCount(f); tempMorganMatrix[f] = atomContainer.getBondCount(f); } for (int e = 0; e < N; e++) { for (int f = 0; f < N; f++) { morganMatrix[f] = 0; atoms = atomContainer.getConnectedAtoms(atomContainer.getAtomAt(f)); for (int g = 0; g < atoms.Length; g++) { morganMatrix[f] += tempMorganMatrix[atomContainer.getAtomNumber(atoms[g])]; } } Array.Copy(morganMatrix, 0, tempMorganMatrix, 0, N); } return tempMorganMatrix; }
//UPGRADE_NOTE: The initialization of '//logger' was moved to static method 'org.openscience.cdk.geometry.GeometryTools'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" //private static LoggingTool //logger; /// <summary> Adds an automatically calculated offset to the coordinates of all atoms /// such that all coordinates are positive and the smallest x or y coordinate /// is exactly zero, using an external set of coordinates. /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets /// /// </summary> /// <param name="atomCon"> AtomContainer for which all the atoms are translated to /// positive coordinates /// </param> /// <param name="renderingCoordinates"> The set of coordinates to use coming from RendererModel2D /// </param> //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'" public static void translateAllPositive(IAtomContainer atomCon, System.Collections.Hashtable renderingCoordinates) { //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" double minX = System.Double.MaxValue; //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" double minY = System.Double.MaxValue; IAtom[] atoms = atomCon.Atoms; for (int i = 0; i < atoms.Length; i++) { //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'" if (renderingCoordinates[atoms[i]] == null && atoms[i].getPoint2d() != null) { renderingCoordinates[atoms[i]] = new Point2d(atoms[i].getPoint2d().x, atoms[i].getPoint2d().y); } //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'" if (renderingCoordinates[atoms[i]] != null) { //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'" if (((Point2d)renderingCoordinates[atoms[i]]).x < minX) { //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'" minX = ((Point2d)renderingCoordinates[atoms[i]]).x; } //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'" if (((Point2d)renderingCoordinates[atoms[i]]).y < minY) { //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'" minY = ((Point2d)renderingCoordinates[atoms[i]]).y; } } } //logger.debug("Translating: minx=" + minX + ", minY=" + minY); translate2D(atomCon, minX * (-1), minY * (-1), renderingCoordinates); }
public bool AddImplicitHydrogens(IAtomContainer molecule) { try { var builder = molecule.getBuilder(); var matcher = CDKAtomTypeMatcher.getInstance(builder); foreach (var atom in molecule.atoms().ToWindowsEnumerable<IAtom>()) { var type = matcher.findMatchingAtomType(molecule, atom); AtomTypeManipulator.configure(atom, type); } var hAdder = CDKHydrogenAdder.getInstance(builder); hAdder.addImplicitHydrogens(molecule); AtomContainerManipulator.convertImplicitToExplicitHydrogens(molecule); } //there is a bug in cdk?? error happens when there is a S or Ti in the molecule catch (IllegalArgumentException) { return false; } return true; }
/// <summary> Rebonding using a Binary Space Partition Tree. Note, that any bonds /// defined will be deleted first. It assumes the unit of 3D space to /// be 1 Âle;ngstrom. /// </summary> public virtual void rebond(IAtomContainer container) { container.removeAllBonds(); maxCovalentRadius = 0.0; // construct a new binary space partition tree bspt = new Bspt(3); IAtom[] atoms = container.Atoms; for (int i = atoms.Length; --i >= 0; ) { IAtom atom = atoms[i]; double myCovalentRadius = atom.CovalentRadius; if (myCovalentRadius == 0.0) { //throw new CDKException("Atom(s) does not have covalentRadius defined."); } else { if (myCovalentRadius > maxCovalentRadius) maxCovalentRadius = myCovalentRadius; TupleAtom tupleAtom = new TupleAtom(atom); bspt.addTuple(tupleAtom); } } // rebond all atoms for (int i = atoms.Length; --i >= 0; ) { bondAtom(container, atoms[i]); } }
/// <summary> Check whether a set of atoms in an atomcontainer is connected /// /// </summary> /// <param name="atomContainer"> The AtomContainer to be check for connectedness /// </param> /// <returns> true if the AtomContainer is connected /// </returns> public static bool isConnected(IAtomContainer atomContainer) { IAtomContainer ac = atomContainer.Builder.newAtomContainer(); IAtom atom = null; IMolecule molecule = atomContainer.Builder.newMolecule(); System.Collections.ArrayList sphere = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); for (int f = 0; f < atomContainer.AtomCount; f++) { atom = atomContainer.getAtomAt(f); atomContainer.getAtomAt(f).setFlag(CDKConstants.VISITED, false); ac.addAtom(atomContainer.getAtomAt(f)); } IBond[] bonds = atomContainer.Bonds; for (int f = 0; f < bonds.Length; f++) { bonds[f].setFlag(CDKConstants.VISITED, false); ac.addBond(bonds[f]); } atom = ac.getAtomAt(0); sphere.Add(atom); atom.setFlag(CDKConstants.VISITED, true); PathTools.breadthFirstSearch(ac, sphere, molecule); if (molecule.AtomCount == atomContainer.AtomCount) { return true; } return false; }
public ResultRow GetResultRow(IAtomContainer originalCompound, IEnumerable<IAtomContainer> fragments, string compoundId) { var assignFragmentHits = AssignHits(fragments); var fragsPics = assignFragmentHits.AllHits.Reverse(); return new ResultRow(compoundId, originalCompound, fragsPics); }
/// <summary> Returna an atom in an atomcontainer identified by id /// /// </summary> /// <param name="ac">The AtomContainer to search in /// </param> /// <param name="id">The id to search for /// </param> /// <returns> An atom having id id /// </returns> /// <throws> CDKException There is no such atom </throws> public static IAtom getAtomById(IAtomContainer ac, System.String id) { for (int i = 0; i < ac.AtomCount; i++) { if (ac.getAtomAt(i).ID != null && ac.getAtomAt(i).ID.Equals(id)) return ac.getAtomAt(i); } throw new CDKException("no suc atom"); }
public ResultRow( string id, IAtomContainer originalCompound, IEnumerable<PeakMolPair> fragmentPics) { this.id = id; this.fragmentPics = fragmentPics; bondEnergy = new BondEnergyCalculator(originalCompound).TotalBondEnergy(); }
public ResultRow GenerateFragments(IAtomContainer compound, string compoundId, CancellationToken isCancelled) { if (!hydrogenAdder.AddImplicitHydrogens(compound)) { return null; } var fragments = fragmentGenerator.GenerateFragments(compound, compoundId, isCancelled); return hitsMatcher.GetResultRow(compound, fragments, compoundId); }
public PeakMolPair(IAtomContainer ac, Peak peak, double matchedMass, string molecularFormula, double hydrogenPenalty, double bondDissociationEnergy, string neutralChange) { this.ac = ac; this.peak = peak; MatchedMass = matchedMass; MolecularFormula = molecularFormula; HydrogenPenalty = hydrogenPenalty; BondDissociationEnergy = bondDissociationEnergy; NeutralChange = neutralChange; }
private bool MatchByMass(IAtomContainer ac, double peak, double mzabs, double mzppm, out double matchedMass, out double hydrogenPenalty, out int hydrogensAdded) { matchedMass = 0; hydrogenPenalty = 0; hydrogensAdded = 0; double mass; //speed up and neutral loss matching! if (ac.getProperty("FragmentMass") != null && (string)ac.getProperty("FragmentMass") != "") { mass = double.Parse(ac.getProperty("FragmentMass").ToString(), CultureInfo.InvariantCulture); } else { mass = MolecularFormulaTools.GetMonoisotopicMass(GetMolecularFormula(ac)); } var peakLow = peak - mzabs - PpmTool.GetPPMDeviation(peak, mzppm); var peakHigh = peak + mzabs + PpmTool.GetPPMDeviation(peak, mzppm); //now try to add/remove neutral hydrogens ...at most the treedepth var treeDepth = int.Parse((String)ac.getProperty("TreeDepth")); for (var i = 0; i <= treeDepth; i++) { var hMass = i * hydrogenMass; if ((mass + hMass) >= peakLow && (mass + hMass) <= peakHigh) { matchedMass = Math.Round(mass + hMass, 4); //now add a bond energy equivalent to a H-C bond hydrogenPenalty = (i * 1000); hydrogensAdded = i; return true; } if ((mass - hMass) >= peakLow && (mass - hMass) <= peakHigh) { matchedMass = Math.Round(mass - hMass, 4); //now add a bond energy equivalent to a H-C bond hydrogenPenalty = (i * 1000); hydrogensAdded = -i; return true; } } return false; }
/// <summary> Saturates a molecule by setting appropriate bond orders. /// /// </summary> /// <cdk.keyword> bond order, calculation </cdk.keyword> /// <summary> /// </summary> /// <cdk.created> 2003-10-03 </cdk.created> public virtual void saturate(IAtomContainer atomContainer) { //logger.info("Saturating atomContainer by adjusting bond orders..."); bool allSaturated = this.allSaturated(atomContainer); if (!allSaturated) { //logger.info("Saturating bond orders is needed..."); bool succeeded = saturate(atomContainer.Bonds, atomContainer); if (!succeeded) { throw new CDKException("Could not saturate this atomContainer!"); } } }
/// <summary> Processes the content from the formula field of the INChI. /// Typical values look like C6H6, from INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H. /// </summary> public virtual IAtomContainer processFormula(IAtomContainer parsedContent, System.String atomsEncoding) { //logger.debug("Parsing atom data: ", atomsEncoding); Regex pattern = new Regex("([A-Z][a-z]?)(\\d+)?(.*)"); //Pattern pattern = Pattern.compile("([A-Z][a-z]?)(\\d+)?(.*)"); System.String remainder = atomsEncoding; while (remainder.Length > 0) { //logger.debug("Remaining: ", remainder); Match matcher = pattern.Match(remainder); //Matcher matcher = pattern.matcher(remainder); //if (matcher.matches()) if (matcher != null && matcher.Success) { System.String symbol = matcher.Groups[1].Value; //logger.debug("Atom symbol: ", symbol); if (symbol.Equals("H")) { // don't add explicit hydrogens } else { System.String occurenceStr = matcher.Groups[2].Value; int occurence = 1; if (occurenceStr != null) { occurence = System.Int32.Parse(occurenceStr); } //logger.debug(" occurence: ", occurence); for (int i = 1; i <= occurence; i++) { parsedContent.addAtom(parsedContent.Builder.newAtom(symbol)); } } remainder = matcher.Groups[3].Value; if (remainder == null) remainder = ""; //logger.debug(" Remaining: ", remainder); } else { //logger.error("No match found!"); remainder = ""; } //logger.debug("NO atoms: ", parsedContent.AtomCount); } return parsedContent; }
private bool preprocessMolecule(IAtomContainer original) { //prepare atom weights var atomWeightCanBeCalculated = prepareAtomWeights(original); // If the SDF contains an "R" or something, we don't know its mass, so this whole endevour is fruitless // (since we won't be able to match the fragment masses to the peaks). if (!atomWeightCanBeCalculated) { return false; } //mark all the bonds and atoms with numbers --> identify them later on originalMolecule = markAllBonds(original); //do ring detection with the original molecule var allRingsFinder = new AllRingsFinder(); // Steve: Set a really large timeout, because we don't want to crash just because it took a long time. // The size limit of 7 below should stop it looping forever. allRingsFinder.setTimeout(int.MaxValue); // TODO: Steve: The 7 is a max ring size - I added this to prevent it getting in to infinite loops (7 comes from MetFrag // where it is used in some other random class). Don't know if we need to change this?? allRings = allRingsFinder.findAllRings(originalMolecule, Integer.valueOf(7)); aromaticBonds = new List<IBond>(); CDKHueckelAromaticityDetector.detectAromaticity(originalMolecule); foreach (var bond in originalMolecule.bonds().ToWindowsEnumerable<IBond>()) { //lets see if it is a ring and aromatic var rings = allRings.getRings(bond); //don't split up aromatic rings...see constructor for option for (var i = 0; i < rings.getAtomContainerCount(); i++) { var aromatic = AromaticityCalculator.isAromatic((IRing)rings.getAtomContainer(i), originalMolecule); if (aromatic) { aromaticBonds.Add(bond); break; } } } return true; }
/// <summary> /// Creates a molecule graph for use with jgrapht. /// Bond orders are not respected. /// </summary> /// <param name="molecule">the specified molecule</param> /// <returns>a graph representing the molecule</returns> static public SimpleGraph getMoleculeGraph(IAtomContainer molecule) { SimpleGraph graph = new SimpleGraph(); for (int i=0; i<molecule.AtomCount; i++ ) { IAtom atom = molecule.Atoms[i]; graph.addVertex(atom); } for (int i=0; i<molecule.getBondCount(); i++ ) { IBond bond = molecule.Bonds[i]; /* int order = (int) bond.getOrder(); for (int j=0; j<order; j++) { graph.addEdge(bond.getAtoms()[0], bond.getAtoms()[1]); } */ graph.addEdge(bond.getAtoms()[0], bond.getAtoms()[1]); } return graph; }
/// <summary> Returns a ringset containing all rings in the given AtomContainer /// /// </summary> /// <param name="atomContainer"> The AtomContainer to be searched for rings /// </param> /// <returns> A RingSet with all rings in the AtomContainer /// </returns> /// <exception cref="CDKException"> An exception thrown if something goes wrong or if the timeout limit is reached /// </exception> public virtual IRingSet findAllRings(IAtomContainer atomContainer) { startTime = (System.DateTime.Now.Ticks - 621355968000000000) / 10000; SpanningTree spanningTree; try { spanningTree = new SpanningTree((IAtomContainer)atomContainer.Clone()); } //UPGRADE_NOTE: Exception 'java.lang.CloneNotSupportedException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'" catch (System.Exception e) { throw new CDKException("Could not clone IAtomContainer!", e); } spanningTree.identifyBonds(); if (spanningTree.BondsCyclicCount < 37) { findAllRings(atomContainer, false); } return findAllRings(atomContainer, true); }
public static bool replaceAtomByAtom(IAtomContainer container, IAtom atom, IAtom newAtom) { if (!container.contains(atom)) { // it should complain return false; } else { container.setAtomAt(container.getAtomNumber(atom), newAtom); IElectronContainer[] electronContainers = container.ElectronContainers; for (int i = 0; i < electronContainers.Length; i++) { if (electronContainers[i] is IBond) { IBond bond = (IBond)electronContainers[i]; if (bond.contains(atom)) { for (int j = 0; j < bond.AtomCount; j++) { if (atom.Equals(bond.getAtomAt(j))) { bond.setAtomAt(newAtom, j); } } } } else if (electronContainers[i] is ILonePair) { ILonePair lonePair = (ILonePair)electronContainers[i]; if (atom.Equals(lonePair.Atom)) { lonePair.Atom = newAtom; } } } return true; } }
/// <summary> Labels the Atom's and Bond's in the AtomContainer using the a1, a2, b1, b2 /// scheme often used in CML. /// /// </summary> /// <seealso cref="createIDs(ISetOfAtomContainers)"> /// </seealso> public virtual void createIDs(IAtomContainer container) { if (tabuList == null) tabuList = AtomContainerManipulator.getAllIDs(container); if (container.ID == null) { moleculeCount++; while (tabuList.Contains("m" + moleculeCount)) moleculeCount++; container.ID = "m" + moleculeCount; } IAtom[] atoms = container.Atoms; for (int i = 0; i < atoms.Length; i++) { IAtom atom = atoms[i]; if (atom.ID == null) { atomCount++; while (tabuList.Contains("a" + atomCount)) atomCount++; atoms[i].ID = "a" + atomCount; } } IBond[] bonds = container.Bonds; for (int i = 0; i < bonds.Length; i++) { IBond bond = bonds[i]; if (bond.ID == null) { bondCount++; while (tabuList.Contains("b" + bondCount)) bondCount++; bonds[i].ID = "b" + bondCount; } } }
public static IAtomContainer MoleculeNumbering(IAtomContainer mol) { var count = 0; var countBond = 0; var alreadyDone = new List<IAtom>(); foreach (var bond in mol.bonds().ToWindowsEnumerable<IBond>()) { bond.setID(countBond.ToString(CultureInfo.InvariantCulture)); countBond++; foreach (var atom in bond.atoms().ToWindowsEnumerable<IAtom>()) { if (!alreadyDone.Contains(atom)) { atom.setID(count.ToString(CultureInfo.InvariantCulture)); count++; alreadyDone.Add(atom); } } } return mol; }
/// <summary> Returns the adjacency matrix for the given AtomContainer. /// /// </summary> /// <param name="container">The AtomContainer for which the matrix is calculated /// </param> /// <returns> A adjacency matrix representating this AtomContainer /// </returns> public static int[][] getMatrix(IAtomContainer container) { IElectronContainer electronContainer = null; int indexAtom1; int indexAtom2; int[][] conMat = new int[container.AtomCount][]; for (int i = 0; i < container.AtomCount; i++) { conMat[i] = new int[container.AtomCount]; } for (int f = 0; f < container.ElectronContainerCount; f++) { electronContainer = container.getElectronContainerAt(f); if (electronContainer is IBond) { IBond bond = (IBond)electronContainer; indexAtom1 = container.getAtomNumber(bond.getAtomAt(0)); indexAtom2 = container.getAtomNumber(bond.getAtomAt(1)); conMat[indexAtom1][indexAtom2] = 1; conMat[indexAtom2][indexAtom1] = 1; } } return conMat; }
/// <summary> Returns the geometric center of all the atoms in the atomContainer. /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets /// /// </summary> /// <param name="container"> Description of the Parameter /// </param> /// <param name="renderingCoordinates"> The set of coordinates to use coming from RendererModel2D /// </param> /// <returns> the geometric center of the atoms in this atomContainer /// </returns> //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'" public static Point2d get2DCenter(IAtomContainer container, System.Collections.Hashtable renderingCoordinates) { double centerX = 0; double centerY = 0; double counter = 0; IAtom[] atoms = container.Atoms; for (int i = 0; i < atoms.Length; i++) { if (atoms[i].getPoint2d() != null) { //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'" centerX += ((Point2d)renderingCoordinates[atoms[i]]).x; //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'" centerY += ((Point2d)renderingCoordinates[atoms[i]]).y; counter++; } } Point2d point = new Point2d(centerX / (counter), centerY / (counter)); return point; }
public void FavorCarbonyl() { IAtomContainer container = CDK.SmilesParser.ParseSmiles("P([O-])=O"); Assert.IsTrue(Compares.AreEqual(new long[] { 3, 2, 1 }, InChINumbersTools.GetUSmilesNumbers(container))); }
/// <summary> /// Initiates the process for the given mechanism. The atoms to apply are mapped between /// reactants and products. /// </summary> /// <param name="atomContainerSet"></param> /// <param name="atomList"> /// The list of atoms taking part in the mechanism. Only allowed two atoms. /// The first atom is the atom which must be moved and the second /// is the atom which receives the atom1 and the third is the atom which loss /// the first atom</param> /// <param name="bondList">The list of bonds taking part in the mechanism. Only allowed one bond. /// It is the bond which is moved</param> /// <returns>The Reaction mechanism</returns> public IReaction Initiate(IChemObjectSet <IAtomContainer> atomContainerSet, IList <IAtom> atomList, IList <IBond> bondList) { var atMatcher = CDK.AtomTypeMatcher; if (atomContainerSet.Count != 1) { throw new CDKException("RadicalSiteRearrangementMechanism only expects one IAtomContainer"); } if (atomList.Count != 3) { throw new CDKException("RadicalSiteRearrangementMechanism expects three atoms in the List"); } if (bondList.Count != 1) { throw new CDKException("RadicalSiteRearrangementMechanism only expect one bond in the List"); } IAtomContainer molecule = atomContainerSet[0]; IAtomContainer reactantCloned; reactantCloned = (IAtomContainer)molecule.Clone(); IAtom atom1 = atomList[0]; // Atom to be moved IAtom atom1C = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom1)]; IAtom atom2 = atomList[1]; // Atom to receive the new bonding with a ISingleElectron IAtom atom2C = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom2)]; IAtom atom3 = atomList[2]; // Atom which loss the atom IAtom atom3C = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom3)]; IBond bond1 = bondList[0]; // Bond to move int posBond1 = molecule.Bonds.IndexOf(bond1); reactantCloned.Bonds.Remove(reactantCloned.Bonds[posBond1]); IBond newBond = atom1.Builder.NewBond(atom1C, atom2C, BondOrder.Single); reactantCloned.Bonds.Add(newBond); var selectron = reactantCloned.GetConnectedSingleElectrons(atom2C); reactantCloned.SingleElectrons.Remove(selectron.Last()); atom2C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C); if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) { return(null); } reactantCloned.SingleElectrons.Add(atom2C.Builder.NewSingleElectron(atom3C)); atom3C.Hybridization = Hybridization.Unset; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned); type = atMatcher.FindMatchingAtomType(reactantCloned, atom3C); if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal)) { return(null); } IReaction reaction = atom2C.Builder.NewReaction(); reaction.Reactants.Add(molecule); /* mapping */ foreach (var atom in molecule.Atoms) { IMapping mapping = atom2C.Builder.NewMapping(atom, reactantCloned.Atoms[molecule.Atoms.IndexOf(atom)]); reaction.Mappings.Add(mapping); } reaction.Products.Add(reactantCloned); return(reaction); }
/// <summary> Reads a set of coordinates into ChemModel. /// /// </summary> /// <param name="model">the destination ChemModel /// </param> /// <throws> IOException if an I/O error occurs </throws> private void readCoordinates(IChemModel model) { IAtomContainer container = model.Builder.newAtomContainer(); System.String line = input.ReadLine(); line = input.ReadLine(); line = input.ReadLine(); line = input.ReadLine(); while (input.Peek() != -1) { line = input.ReadLine(); if ((line == null) || (line.IndexOf("-----") >= 0)) { break; } int atomicNumber = 0; System.IO.StringReader sr = new System.IO.StringReader(line); SupportClass.StreamTokenizerSupport token = new SupportClass.StreamTokenizerSupport(sr); token.NextToken(); // ignore first token if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER) { //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" atomicNumber = (int)token.nval; if (atomicNumber == 0) { // Skip dummy atoms. Dummy atoms must be skipped // if frequencies are to be read because Gaussian // does not report dummy atoms in frequencies, and // the number of atoms is used for reading frequencies. continue; } } else { throw new System.IO.IOException("Error reading coordinates"); } token.NextToken(); // ignore third token double x = 0.0; double y = 0.0; double z = 0.0; if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER) { x = token.nval; } else { throw new System.IO.IOException("Error reading coordinates"); } if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER) { y = token.nval; } else { throw new System.IO.IOException("Error reading coordinates"); } if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER) { z = token.nval; } else { throw new System.IO.IOException("Error reading coordinates"); } System.String symbol = "Du"; try { symbol = IsotopeFactory.getInstance(model.Builder).getElementSymbol(atomicNumber); } catch (System.Exception exception) { throw new CDKException("Could not determine element symbol!", exception); } IAtom atom = model.Builder.newAtom(symbol); atom.setPoint3d(new Point3d(x, y, z)); container.addAtom(atom); } ISetOfMolecules moleculeSet = model.Builder.newSetOfMolecules(); moleculeSet.addMolecule(model.Builder.newMolecule(container)); model.SetOfMolecules = moleculeSet; }
public void Remove(IAtomContainer atomContainer) { }
public IAtomType FindMatchingAtomType(IAtomContainer atomContainer, IAtom atom) { IAtomType atomType = null; try { string fragment = ""; int NumHAtoms = 0; int NumSingleBonds2 = 0; int NumDoubleBonds2 = 0; int NumTripleBonds2 = 0; int NumAromaticBonds2 = 0; int NumAromaticBondsTotal2 = 0; string element = atom.Symbol; var n = atom.AtomicNumber; var attachedAtoms = atomContainer.GetConnectedAtoms(atom); foreach (var attached in attachedAtoms) { var b = atomContainer.GetBond(atom, attached); if (attached.AtomicNumber.Equals(AtomicNumbers.H)) { NumHAtoms++; } if (atom.IsAromatic && attached.IsAromatic) { bool SameRing = InSameAromaticRing(atomContainer, atom, attached, ringSet); if (SameRing) { NumAromaticBonds2++; if (n.Equals(AtomicNumbers.N)) { if (b.Order == BondOrder.Single) { NumAromaticBondsTotal2++; } if (b.Order == BondOrder.Double) { NumAromaticBondsTotal2 = NumAromaticBondsTotal2 + 2; } } } else { if (b.Order == BondOrder.Single) { NumSingleBonds2++; } if (b.Order == BondOrder.Double) { NumDoubleBonds2++; } if (b.Order == BondOrder.Triple) { NumTripleBonds2++; } } } else { if (b.Order == BondOrder.Single) { NumSingleBonds2++; } if (b.Order == BondOrder.Double) { NumDoubleBonds2++; } if (b.Order == BondOrder.Triple) { NumTripleBonds2++; } } } NumSingleBonds2 = NumSingleBonds2 - NumHAtoms; // assign frag here fragment = "S"; for (int j = 0; j <= NumTripleBonds2 - 1; j++) { fragment += "t"; } for (int j = 0; j <= NumDoubleBonds2 - 1; j++) { fragment += "d"; } for (int j = 0; j <= NumSingleBonds2 - 1; j++) { fragment += "s"; } for (int j = 0; j <= NumAromaticBonds2 - 1; j++) { fragment += "a"; } fragment += element; if (atom.FormalCharge == 1) { fragment += "p"; } else if (atom.FormalCharge == -1) { fragment += "m"; } if (NumHAtoms == 1) { fragment += "H"; } else if (NumHAtoms > 1) { fragment += ("H" + NumHAtoms); } atomType = atom.Builder.NewAtomType(fragment, atom.Symbol); atomType.FormalCharge = atom.FormalCharge; if (atom.IsAromatic) { atomType.IsAromatic = true; } } catch (Exception e) { Console.Error.WriteLine(e.StackTrace); } return(atomType); }
IDescriptorResult IMolecularDescriptor.Calculate(IAtomContainer mol) => Calculate(mol);
/// <summary> Retrieves the set of all rings and performs an aromaticity detection based /// on Hueckels 4n + 2 rule. /// /// </summary> /// <param name="removeAromatictyFlags"> When true, we leaves ChemObjects that /// are already marked as aromatic as they are /// </param> /// <param name="atomContainer"> AtomContainer to be searched for /// rings /// </param> /// <returns> True, if molecule has aromatic features /// </returns> /// <exception cref="CDKException"> Thrown in case of errors or an /// AllRingsFinder timeout /// </exception> public static bool detectAromaticity(IAtomContainer atomContainer, bool removeAromatictyFlags) { return(detectAromaticity(atomContainer, removeAromatictyFlags, null)); }
/// <summary> Uses precomputed set of ALL rings and performs an aromaticity detection /// based on Hueckels 4n+2 rule. /// /// </summary> /// <param name="ringSet "> set of ALL rings /// </param> /// <param name="atomContainer"> The AtomContainer to detect rings in /// </param> /// <returns> True if molecule has aromatic features /// </returns> /// <exception cref="org.openscience.cdk.exception.CDKException"> /// </exception> public static bool detectAromaticity(IAtomContainer atomContainer, IRingSet ringSet) { return(detectAromaticity(atomContainer, ringSet, true)); }
/// <summary> Retrieves the set of all rings and performs an aromaticity detection based /// on Hueckels 4n+2 rule. /// /// </summary> /// <param name="atomContainer AtomContainer">to detect rings in /// </param> /// <returns> True if the molecule has aromatic features /// </returns> /// <exception cref="CDKException"> Thrown if something goes wrong or in /// case of a AllRingsFinder timeout /// </exception> public static bool detectAromaticity(IAtomContainer atomContainer) { return(detectAromaticity(atomContainer, true)); }
/// <summary> /// Writes a molecule for input for Gaussian. /// </summary> /// <param name="mol"></param> public void WriteMolecule(IAtomContainer mol) { CustomizeJob(); // write extra statements if (proccount.GetSettingValue() > 1) { writer.Write("%nprocl=" + proccount.GetSettingValue()); writer.Write('\n'); } if (!string.Equals(memory.Setting, "unset", StringComparison.Ordinal)) { writer.Write("%Mem=" + memory.Setting); writer.Write('\n'); } if (usecheckpoint.IsSet) { if (mol.Id != null && mol.Id.Length > 0) { writer.Write($"%chk={mol.Id}.chk"); } else { // force different file names writer.Write($"%chk={DateTime.Now.Ticks}.chk"); // TODO: Better to use Guid? } writer.Write('\n'); } // write the command line writer.Write("# " + method.Setting + "/" + basis.Setting + " "); string commandString = command.Setting; if (string.Equals(commandString, "energy calculation", StringComparison.Ordinal)) { // ok, no special command needed } else if (string.Equals(commandString, "geometry optimization", StringComparison.Ordinal)) { writer.Write("opt"); } else if (string.Equals(commandString, "IR frequency calculation", StringComparison.Ordinal)) { writer.Write("freq"); } else if (string.Equals(commandString, "IR frequency calculation (with Raman)", StringComparison.Ordinal)) { writer.Write("freq=noraman"); } else { // assume that user knows what he's doing writer.Write(commandString); } writer.Write('\n'); // next line is empty writer.Write('\n'); // next line is comment writer.Write(comment.Setting); writer.Write('\n'); // next line is empty writer.Write('\n'); // next line contains two digits the first is the total charge the // second is bool indicating: 0 = open shell 1 = closed shell writer.Write("0 "); // FIXME: should write total charge of molecule if (shell.IsSet) { writer.Write("0"); } else { writer.Write("1"); } writer.Write('\n'); // then come all the atoms. // Loop through the atoms and write them out: foreach (var a in mol.Atoms) { var sb = new StringBuilder(a.Symbol); // export Eucledian coordinates (indicated by the 0) sb.Append(" 0 "); // export the 3D coordinates var p3 = a.Point3D; if (p3 != null) { sb.Append(p3.Value.X.ToString(NumberFormatInfo.InvariantInfo)).Append(" ") .Append(p3.Value.Y.ToString(NumberFormatInfo.InvariantInfo)).Append(" ") .Append(p3.Value.Z.ToString(NumberFormatInfo.InvariantInfo)); } var st = sb.ToString(); writer.Write(st, 0, st.Length); writer.Write('\n'); } // G98 expects an empty line at the end writer.Write('\n'); }
/// <inheritdoc/> public override int[] Match(IAtomContainer container) { return(MatchAll(container).First()); }
/// <summary> /// Read a Reaction from a file in MDL RXN format /// </summary> /// <returns>The Reaction that was read from the MDL file.</returns> private IAtomContainer ReadMolecule(IAtomContainer molecule) { try { int atomCount = 0; int bondCount = 0; string line; while (true) { line = input.ReadLine(); if (line == null) { return(null); } if (line.StartsWith("@<TRIPOS>MOLECULE", StringComparison.Ordinal)) { break; } if (!line.StartsWithChar('#') && line.Trim().Length > 0) { break; } } // ok, if we're coming from the chemfile function, we've already read the molecule RTI if (firstLineisMolecule) { molecule.Title = line; } else { line = input.ReadLine(); molecule.Title = line; } // get atom and bond counts var counts = input.ReadLine(); var tokenizer = Strings.Tokenize(counts); try { atomCount = int.Parse(tokenizer[0], NumberFormatInfo.InvariantInfo); } catch (FormatException nfExc) { string error = "Error while reading atom count from MOLECULE block"; Trace.TraceError(error); Debug.WriteLine(nfExc); throw new CDKException(error, nfExc); } if (tokenizer.Count > 1) { try { bondCount = int.Parse(tokenizer[1], NumberFormatInfo.InvariantInfo); } catch (FormatException nfExc) { string error = "Error while reading atom and bond counts"; Trace.TraceError(error); Debug.WriteLine(nfExc); throw new CDKException(error, nfExc); } } else { bondCount = 0; } Trace.TraceInformation("Reading #atoms: ", atomCount); Trace.TraceInformation("Reading #bonds: ", bondCount); // we skip mol type, charge type and status bit lines Trace.TraceWarning("Not reading molecule qualifiers"); line = input.ReadLine(); bool molend = false; while (line != null) { if (line.StartsWith("@<TRIPOS>MOLECULE", StringComparison.Ordinal)) { molend = true; break; } else if (line.StartsWith("@<TRIPOS>ATOM", StringComparison.Ordinal)) { Trace.TraceInformation("Reading atom block"); for (int i = 0; i < atomCount; i++) { line = input.ReadLine().Trim(); if (line.StartsWith("@<TRIPOS>MOLECULE", StringComparison.Ordinal)) { molend = true; break; } tokenizer = Strings.Tokenize(line); // disregard the id token var nameStr = tokenizer[1]; var xStr = tokenizer[2]; var yStr = tokenizer[3]; var zStr = tokenizer[4]; var atomTypeStr = tokenizer[5]; // replace unrecognised atom type if (ATOM_TYPE_ALIASES.ContainsKey(atomTypeStr)) { atomTypeStr = ATOM_TYPE_ALIASES[atomTypeStr]; } var atom = molecule.Builder.NewAtom(); IAtomType atomType; try { atomType = atFactory.GetAtomType(atomTypeStr); } catch (Exception) { // ok, *not* an mol2 atom type atomType = null; } // Maybe it is just an element if (atomType == null && IsElementSymbol(atomTypeStr)) { atom.Symbol = atomTypeStr; } else { if (atomType == null) { atomType = atFactory.GetAtomType("X"); Trace.TraceError($"Could not find specified atom type: {atomTypeStr}"); } AtomTypeManipulator.Configure(atom, atomType); } atom.AtomicNumber = ChemicalElement.OfSymbol(atom.Symbol).AtomicNumber; atom.Id = nameStr; atom.AtomTypeName = atomTypeStr; try { var x = double.Parse(xStr, NumberFormatInfo.InvariantInfo); var y = double.Parse(yStr, NumberFormatInfo.InvariantInfo); var z = double.Parse(zStr, NumberFormatInfo.InvariantInfo); atom.Point3D = new Vector3(x, y, z); } catch (FormatException nfExc) { string error = "Error while reading atom coordinates"; Trace.TraceError(error); Debug.WriteLine(nfExc); throw new CDKException(error, nfExc); } molecule.Atoms.Add(atom); } } else if (line.StartsWith("@<TRIPOS>BOND", StringComparison.Ordinal)) { Trace.TraceInformation("Reading bond block"); for (int i = 0; i < bondCount; i++) { line = input.ReadLine(); if (line.StartsWith("@<TRIPOS>MOLECULE", StringComparison.Ordinal)) { molend = true; break; } tokenizer = Strings.Tokenize(line); // disregard the id token var atom1Str = tokenizer[1]; var atom2Str = tokenizer[2]; var orderStr = tokenizer[3]; try { var atom1 = int.Parse(atom1Str, NumberFormatInfo.InvariantInfo); var atom2 = int.Parse(atom2Str, NumberFormatInfo.InvariantInfo); if (string.Equals("nc", orderStr, StringComparison.Ordinal)) { // do not connect the atoms } else { var bond = molecule.Builder.NewBond(molecule.Atoms[atom1 - 1], molecule.Atoms[atom2 - 1]); switch (orderStr) { case "1": bond.Order = BondOrder.Single; break; case "2": bond.Order = BondOrder.Double; break; case "3": bond.Order = BondOrder.Triple; break; case "am": case "ar": bond.Order = BondOrder.Single; bond.IsAromatic = true; bond.Begin.IsAromatic = true; bond.End.IsAromatic = true; break; case "du": bond.Order = BondOrder.Single; break; case "un": bond.Order = BondOrder.Single; break; default: break; } molecule.Bonds.Add(bond); } } catch (FormatException nfExc) { var error = "Error while reading bond information"; Trace.TraceError(error); Debug.WriteLine(nfExc); throw new CDKException(error, nfExc); } } } if (molend) { return(molecule); } line = input.ReadLine(); } } catch (IOException exception) { var error = "Error while reading general structure"; Trace.TraceError(error); Debug.WriteLine(exception); throw new CDKException(error, exception); } return(molecule); }
/// <summary> Calculates the center of mass for the <code>Atom</code>s in the /// AtomContainer for the 2D coordinates. /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets /// /// </summary> /// <param name="ac"> AtomContainer for which the center of mass is calculated /// </param> /// <returns> Description of the Return Value /// </returns> /// <cdk.keyword> center of mass </cdk.keyword> /// <cdk.dictref> blue-obelisk:calculate3DCenterOfMass </cdk.dictref> public static Point3d get3DCentreOfMass(IAtomContainer ac) { double x = 0.0; double y = 0.0; double z = 0.0; double totalmass = 0.0; System.Collections.IEnumerator atoms = ac.atoms(); //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" while (atoms.MoveNext()) { //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" IAtom a = (IAtom)atoms.Current; double mass = a.getExactMass(); totalmass += mass; x += mass * a.X3d; y += mass * a.Y3d; z += mass * a.Z3d; } return new Point3d(x / totalmass, y / totalmass, z / totalmass); }
/// <summary> /// Calculates the kier shape indices for an atom container /// </summary> /// <returns>kier1, kier2 and kier3 are returned as arrayList of doubles</returns> public Result Calculate(IAtomContainer container) { container = (IAtomContainer)container.Clone(); container = AtomContainerManipulator.RemoveHydrogens(container); var singlePaths = new List <double>(); var doublePaths = new List <string>(); var triplePaths = new List <string>(); foreach (var atom1 in container.Atoms) { var firstAtomNeighboors = container.GetConnectedAtoms(atom1); foreach (var firstAtomNeighboor in firstAtomNeighboors) { var bond1 = container.Bonds.IndexOf(container.GetBond(atom1, firstAtomNeighboor)); if (!singlePaths.Contains(bond1)) { singlePaths.Add(bond1); singlePaths.Sort(); } var secondAtomNeighboors = container.GetConnectedAtoms(firstAtomNeighboor); foreach (var secondAtomNeighboor in secondAtomNeighboors) { var bond2 = container.Bonds.IndexOf(container.GetBond(firstAtomNeighboor, secondAtomNeighboor)); if (!singlePaths.Contains(bond2)) { singlePaths.Add(bond2); } var sorterFirst = new double[] { bond1, bond2 }; Array.Sort(sorterFirst); var tmpbond2 = sorterFirst[0] + "+" + sorterFirst[1]; if (!doublePaths.Contains(tmpbond2) && (bond1 != bond2)) { doublePaths.Add(tmpbond2); } var thirdAtomNeighboors = container.GetConnectedAtoms(secondAtomNeighboor); foreach (var thirdAtomNeighboor in thirdAtomNeighboors) { var bond3 = container.Bonds.IndexOf(container.GetBond(secondAtomNeighboor, thirdAtomNeighboor)); if (!singlePaths.Contains(bond3)) { singlePaths.Add(bond3); } var sorterSecond = new double[] { bond1, bond2, bond3 }; Array.Sort(sorterSecond); var tmpbond3 = sorterSecond[0] + "+" + sorterSecond[1] + "+" + sorterSecond[2]; if (!triplePaths.Contains(tmpbond3)) { if ((bond1 != bond2) && (bond1 != bond3) && (bond2 != bond3)) { triplePaths.Add(tmpbond3); } } } } } } var kier = new double[] { 0, 0, 0, }; do { if (container.Atoms.Count == 1) { break; } kier[0] = (double)(container.Atoms.Count * (container.Atoms.Count - 1) * (container.Atoms.Count - 1)) / (singlePaths.Count * singlePaths.Count); if (container.Atoms.Count == 2) { break; } kier[1] = doublePaths.Count == 0 ? double.NaN : (double)((container.Atoms.Count - 1) * (container.Atoms.Count - 2) * (container.Atoms.Count - 2)) / (doublePaths.Count * doublePaths.Count); if (container.Atoms.Count == 3) { break; } kier[2] = triplePaths.Count == 0 ? double.NaN : ( container.Atoms.Count % 2 != 0 ? (double)((container.Atoms.Count - 1) * (container.Atoms.Count - 3) * (container.Atoms.Count - 3)) / (triplePaths.Count * triplePaths.Count) : (double)((container.Atoms.Count - 3) * (container.Atoms.Count - 2) * (container.Atoms.Count - 2)) / (triplePaths.Count * triplePaths.Count) ); } while (false); return(new Result(kier)); }
/// <summary> /// Returns a new instance indicating which atoms are suppressed for this /// suppression method. /// </summary> /// <param name="container">molecule with 0 or more atoms</param> /// <returns>the vertices (atom index) which should be suppressed</returns> public abstract Suppressed Suppress(IAtomContainer container);
/// <summary> Returns all the AtomContainer's of a ChemFile.</summary> public static IAtomContainer[] getAllAtomContainers(IChemFile file) { IChemSequence[] sequences = file.ChemSequences; int acCount = 0; System.Collections.ArrayList acArrays = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); for (int i = 0; i < sequences.Length; i++) { IAtomContainer[] sequenceContainers = ChemSequenceManipulator.getAllAtomContainers(sequences[i]); acArrays.Add(sequenceContainers); acCount += sequenceContainers.Length; } IAtomContainer[] containers = new IAtomContainer[acCount]; int arrayOffset = 0; //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" for (System.Collections.IEnumerator acArraysElements = acArrays.GetEnumerator(); acArraysElements.MoveNext(); ) { //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" IAtomContainer[] modelContainers = (IAtomContainer[])acArraysElements.Current; Array.Copy(modelContainers, 0, containers, arrayOffset, modelContainers.Length); arrayOffset += modelContainers.Length; } return containers; }
private IChemFile ReadChemFile() { IChemSequence seq = file.Builder.NewChemSequence(); IChemModel model = file.Builder.NewChemModel(); var containerSet = file.Builder.NewAtomContainerSet(); IAtomContainer container = file.Builder.NewAtomContainer(); int lineNumber = 0; try { string line = input.ReadLine(); while (line != null) { Debug.WriteLine((lineNumber++) + ": ", line); string command = null; if (IsCommand(line)) { command = GetCommand(line); int lineCount = GetContentLinesCount(line); if (string.Equals("ATOMS", command, StringComparison.Ordinal)) { ProcessAtomsBlock(lineCount, container); } else if (string.Equals("BONDS", command, StringComparison.Ordinal)) { ProcessBondsBlock(lineCount, container); } else if (string.Equals("IDENT", command, StringComparison.Ordinal)) { ProcessIdentBlock(lineCount, container); } else if (string.Equals("NAME", command, StringComparison.Ordinal)) { ProcessNameBlock(lineCount, container); } else { // skip lines Trace.TraceWarning("Dropping block: ", command); for (int i = 0; i < lineCount; i++) { input.ReadLine(); } } } else { Trace.TraceWarning("Unexpected content at line: ", lineNumber); } line = input.ReadLine(); } containerSet.Add(container); model.MoleculeSet = containerSet; seq.Add(model); file.Add(seq); } catch (Exception exception) { string message = "Error while parsing CTX file: " + exception.Message; Trace.TraceError(message); Debug.WriteLine(exception); throw new CDKException(message, exception); } return(file); }
/// <summary> /// Writes a single frame in XYZ format to the Writer. /// </summary> /// <param name="mol">the Molecule to write</param> /// <exception cref="IOException">if there is an error during writing</exception> public void WriteMolecule(IAtomContainer mol) { matcher = SybylAtomTypeMatcher.GetInstance(); try { Debug.WriteLine("Writing header..."); if (mol.Title != null) { writer.Write("# Name: " + mol.Title); writer.Write('\n'); } // FIXME: add other types of meta data writer.Write('\n'); // @<TRIPOS>MOLECULE benzene 12 12 1 0 0 SMALL NO_CHARGES Debug.WriteLine("Writing molecule block..."); writer.Write("@<TRIPOS>MOLECULE"); writer.Write('\n'); if (mol.Id == null) { writer.Write("CDKMolecule"); } else { writer.Write(mol.Id); } writer.Write('\n'); writer.Write(mol.Atoms.Count + " " + mol.Bonds.Count); // that's the minimum amount of info required the format writer.Write('\n'); writer.Write("SMALL"); // no biopolymer writer.Write('\n'); writer.Write("NO CHARGES"); // other options include Gasteiger charges writer.Write('\n'); // @<TRIPOS>ATOM 1 C1 1.207 2.091 0.000 C.ar 1 BENZENE 0.000 2 C2 // 2.414 1.394 0.000 C.ar 1 BENZENE 0.000 3 C3 2.414 0.000 0.000 // C.ar 1 BENZENE 0.000 4 C4 1.207 -0.697 0.000 C.ar 1 BENZENE 0.000 // 5 C5 0.000 0.000 0.000 C.ar 1 BENZENE 0.000 6 C6 0.000 1.394 // 0.000 C.ar 1 BENZENE 0.000 7 H1 1.207 3.175 0.000 H 1 BENZENE // 0.000 8 H2 3.353 1.936 0.000 H 1 BENZENE 0.000 9 H3 3.353 -0.542 // 0.000 H 1 BENZENE 0.000 10 H4 1.207 -1.781 0.000 H 1 BENZENE // 0.000 11 H5 -0.939 -0.542 0.000 H 1 BENZENE 0.000 12 H6 -0.939 // 1.936 0.000 H 1 BENZENE 0.000 // write atom block Debug.WriteLine("Writing atom block..."); writer.Write("@<TRIPOS>ATOM"); writer.Write('\n'); for (int i = 0; i < mol.Atoms.Count; i++) { IAtom atom = mol.Atoms[i]; writer.Write((i + 1) + " " + atom.Symbol + (mol.Atoms.IndexOf(atom) + 1) + " "); if (atom.Point3D != null) { writer.Write(atom.Point3D.Value.X.ToString("F3", NumberFormatInfo.InvariantInfo) + " "); writer.Write(atom.Point3D.Value.Y.ToString("F3", NumberFormatInfo.InvariantInfo) + " "); writer.Write(atom.Point3D.Value.Z.ToString("F3", NumberFormatInfo.InvariantInfo) + " "); } else if (atom.Point2D != null) { writer.Write(atom.Point2D.Value.X.ToString("F3", NumberFormatInfo.InvariantInfo) + " "); writer.Write(atom.Point2D.Value.Y.ToString("F3", NumberFormatInfo.InvariantInfo) + " "); writer.Write(" 0.000 "); } else { writer.Write("0.000 0.000 0.000 "); } IAtomType sybylType = null; try { sybylType = matcher.FindMatchingAtomType(mol, atom); } catch (CDKException e) { Console.Error.WriteLine(e.StackTrace); } if (sybylType != null) { writer.Write(sybylType.AtomTypeName); } else { writer.Write(atom.Symbol); } writer.Write('\n'); } // @<TRIPOS>BOND 1 1 2 ar 2 1 6 ar 3 2 3 ar 4 3 4 ar 5 4 5 ar 6 5 6 // ar 7 1 7 1 8 2 8 1 9 3 9 1 10 4 10 1 11 5 11 1 12 6 12 1 // write bond block Debug.WriteLine("Writing bond block..."); writer.Write("@<TRIPOS>BOND"); writer.Write('\n'); int counter = 0; foreach (var bond in mol.Bonds) { string sybylBondOrder = "-1"; switch (bond.Order) { case BondOrder.Single: sybylBondOrder = "1"; break; case BondOrder.Double: sybylBondOrder = "2"; break; case BondOrder.Triple: sybylBondOrder = "3"; break; } if (bond.IsAromatic) { sybylBondOrder = "ar"; } // we need to check the atom types to see if we have an amide bond // and we're assuming a 2-centered bond IAtom bondAtom1 = bond.Begin; IAtom bondAtom2 = bond.End; try { IAtomType bondAtom1Type = matcher.FindMatchingAtomType(mol, bondAtom1); IAtomType bondAtom2Type = matcher.FindMatchingAtomType(mol, bondAtom2); if (bondAtom1Type != null && bondAtom2Type != null && ((bondAtom1Type.AtomTypeName.Equals("N.am", StringComparison.Ordinal) && bondAtom2Type.AtomTypeName.Equals("C.2", StringComparison.Ordinal)) || (bondAtom2Type.AtomTypeName.Equals("N.am", StringComparison.Ordinal) && bondAtom1Type.AtomTypeName.Equals("C.2", StringComparison.Ordinal)))) { sybylBondOrder = "am"; } } catch (CDKException e) { Console.Error.WriteLine(e.StackTrace); } writer.Write($"{counter + 1} {mol.Atoms.IndexOf(bond.Begin) + 1} {mol.Atoms.IndexOf(bond.End) + 1} {sybylBondOrder}"); writer.Write('\n'); counter++; } } catch (IOException) { throw; } }
public static void Main(string[] args) { { var molecules = new Silent.AtomContainerSet(); #region ElectronDonation model = ElectronDonation.DaylightModel; ICycleFinder cycles = Cycles.Or(Cycles.AllSimpleFinder, Cycles.GetAllFinder(6)); Aromaticity aromaticity = new Aromaticity(model, cycles); // apply our configured model to each molecule foreach (IAtomContainer molecule in molecules) { aromaticity.Apply(molecule); } #endregion } { #region ctor // mimics the CDKHuckelAromaticityDetector Aromaticity aromaticity_cdk = new Aromaticity(ElectronDonation.CDKModel, Cycles.CDKAromaticSetFinder); // mimics the DoubleBondAcceptingAromaticityDetector Aromaticity aromaticity_exo = new Aromaticity(ElectronDonation.CDKAllowingExocyclicModel, Cycles.CDKAromaticSetFinder); // a good model for writing SMILES Aromaticity aromaticity_smi = new Aromaticity(ElectronDonation.DaylightModel, Cycles.AllSimpleFinder); // a good model for writing MDL/Mol2 Aromaticity aromaticity_mdl = new Aromaticity(ElectronDonation.PiBondsModel, Cycles.AllSimpleFinder); #endregion } { #region FindBonds Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllSimpleFinder); IAtomContainer container = TestMoleculeFactory.MakeAnthracene(); AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container); try { var bonds = aromaticity.FindBonds(container); int nAromaticBonds = bonds.Count(); } catch (CDKException) { // cycle computation was intractable } #endregion } { #region Apply Aromaticity aromaticity = new Aromaticity(ElectronDonation.CDKModel, Cycles.AllSimpleFinder); IAtomContainer container = TestMoleculeFactory.MakeAnthracene(); try { if (aromaticity.Apply(container)) { // } } catch (CDKException) { // cycle computation was intractable } #endregion } { #region CDKLegacy_CDKAromaticSetFinder new Aromaticity(ElectronDonation.CDKModel, Cycles.CDKAromaticSetFinder); #endregion } { #region CDKLegacy_AllFinder_RelevantFinder new Aromaticity(ElectronDonation.CDKModel, Cycles.Or(Cycles.AllSimpleFinder, Cycles.RelevantFinder)); #endregion } }
/// <summary> /// Produces a HOSE code for Atom <paramref name="root"/> in the <see cref="IAtomContainer"/> <paramref name="ac"/>. The HOSE /// code is produced for the number of spheres given by <paramref name="noOfSpheres"/>. /// IMPORTANT: if you want aromaticity to be included in the code, you need /// to apply <see cref="Aromaticities.Aromaticity.Apply(IAtomContainer)"/> <paramref name="ac"/> prior to /// using <see cref="GetHOSECode(IAtomContainer, IAtom, int)"/>. This method only gives proper results if the molecule is /// fully saturated (if not, the order of the HOSE code might depend on atoms in higher spheres). /// This method is known to fail for protons sometimes. /// </summary> /// <remarks> /// <note type="important"> /// Your molecule must contain implicit or explicit hydrogens /// for this method to work properly. /// </note> /// </remarks> /// <param name="ac">The <see cref="IAtomContainer"/> with the molecular skeleton in which the root atom resides</param> /// <param name="root">The root atom for which to produce the HOSE code</param> /// <param name="noOfSpheres">The number of spheres to look at</param> /// <returns>The HOSECode value</returns> /// <exception cref="CDKException"> Thrown if something is wrong</exception> public string GetHOSECode(IAtomContainer ac, IAtom root, int noOfSpheres) { return(GetHOSECode(ac, root, noOfSpheres, false)); }
/// <summary> /// This makes sourceAtom map of matching atoms out of sourceAtom map of matching bonds as produced by the Get(Subgraph|Ismorphism)Map methods. /// </summary> /// <param name="rMapList">The list produced by the getMap method.</param> /// <param name="graph1">first molecule. Must not be an IQueryAtomContainer.</param> /// <param name="graph2">second molecule. May be an IQueryAtomContainer.</param> /// <returns>The mapping found projected on graph1. This is sourceAtom List of CDKRMap objects containing Ids of matching atoms.</returns> private static IReadOnlyList <IReadOnlyList <CDKRMap> > MakeAtomsMapOfBondsMap(IReadOnlyList <CDKRMap> rMapList, IAtomContainer graph1, IAtomContainer graph2) { if (rMapList == null) { return(null); } IReadOnlyList <IReadOnlyList <CDKRMap> > result = null; if (rMapList.Count == 1) { result = MakeAtomsMapOfBondsMapSingleBond(rMapList, graph1, graph2); } else { List <CDKRMap> resultLocal = new List <CDKRMap>(); for (int i = 0; i < rMapList.Count; i++) { IBond qBond = graph1.Bonds[rMapList[i].Id1]; IBond tBond = graph2.Bonds[rMapList[i].Id2]; IAtom[] qAtoms = BondManipulator.GetAtomArray(qBond); IAtom[] tAtoms = BondManipulator.GetAtomArray(tBond); for (int j = 0; j < 2; j++) { var bondsConnectedToAtom1j = graph1.GetConnectedBonds(qAtoms[j]); foreach (var bondConnectedToAtom1j in bondsConnectedToAtom1j) { if (bondConnectedToAtom1j != qBond) { IBond testBond = bondConnectedToAtom1j; foreach (var rMap in rMapList) { IBond testBond2; if ((rMap).Id1 == graph1.Bonds.IndexOf(testBond)) { testBond2 = graph2.Bonds[(rMap).Id2]; for (int n = 0; n < 2; n++) { var bondsToTest = graph2.GetConnectedBonds(tAtoms[n]); if (bondsToTest.Contains(testBond2)) { CDKRMap map; if (j == n) { map = new CDKRMap(graph1.Atoms.IndexOf(qAtoms[0]), graph2.Atoms.IndexOf(tAtoms[0])); } else { map = new CDKRMap(graph1.Atoms.IndexOf(qAtoms[1]), graph2.Atoms.IndexOf(tAtoms[0])); } if (!resultLocal.Contains(map)) { resultLocal.Add(map); } CDKRMap map2; if (j == n) { map2 = new CDKRMap(graph1.Atoms.IndexOf(qAtoms[1]), graph2.Atoms.IndexOf(tAtoms[1])); } else { map2 = new CDKRMap(graph1.Atoms.IndexOf(qAtoms[0]), graph2.Atoms.IndexOf(tAtoms[1])); } if (!resultLocal.Contains(map2)) { resultLocal.Add(map2); } } } } } } } } } result = new List <IReadOnlyList <CDKRMap> > { resultLocal }; } return(result); }
public override Pattern Create(IAtomContainer container) { return(DfPattern.FindSubstructure(container)); }
/// <summary> /// This makes atom map of matching atoms out of atom map 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 /// </summary> /// <param name="list">The list produced by the getMap method.</param> /// <param name="sourceGraph">first molecule. Must not be an IQueryAtomContainer.</param> /// <param name="targetGraph">second molecule. May be an IQueryAtomContainer.</param> /// <returns>The mapping found projected on sourceGraph. This is atom List of CDKRMap objects containing Ids of matching atoms.</returns> private static IReadOnlyList <IReadOnlyList <CDKRMap> > MakeAtomsMapOfBondsMapSingleBond(IReadOnlyList <CDKRMap> list, IAtomContainer sourceGraph, IAtomContainer targetGraph) { if (list == null) { return(null); } var bondMap = new Dictionary <IBond, IBond>(list.Count); foreach (var solBondMap in list) { var id1 = solBondMap.Id1; var id2 = solBondMap.Id2; var qBond = sourceGraph.Bonds[id1]; var tBond = targetGraph.Bonds[id2]; bondMap[qBond] = tBond; } var result1 = new List <CDKRMap>(); var result2 = new List <CDKRMap>(); foreach (var qbond in sourceGraph.Bonds) { if (bondMap.ContainsKey(qbond)) { var tbond = bondMap[qbond]; CDKRMap map00 = null; CDKRMap map01 = null; CDKRMap map10 = null; CDKRMap map11 = null; if (string.Equals(qbond.Atoms[0].Symbol, tbond.Atoms[0].Symbol, StringComparison.Ordinal) && string.Equals(qbond.Atoms[1].Symbol, tbond.Atoms[1].Symbol, StringComparison.Ordinal)) { map00 = new CDKRMap(sourceGraph.Atoms.IndexOf(qbond.Atoms[0]), targetGraph.Atoms.IndexOf(tbond.Atoms[0])); map11 = new CDKRMap(sourceGraph.Atoms.IndexOf(qbond.Atoms[1]), targetGraph.Atoms.IndexOf(tbond.Atoms[1])); if (!result1.Contains(map00)) { result1.Add(map00); } if (!result1.Contains(map11)) { result1.Add(map11); } } if (string.Equals(qbond.Atoms[0].Symbol, tbond.Atoms[1].Symbol, StringComparison.Ordinal) && string.Equals(qbond.Atoms[1].Symbol, tbond.Atoms[0].Symbol, StringComparison.Ordinal)) { map01 = new CDKRMap(sourceGraph.Atoms.IndexOf(qbond.Atoms[0]), targetGraph.Atoms.IndexOf(tbond.Atoms[1])); map10 = new CDKRMap(sourceGraph.Atoms.IndexOf(qbond.Atoms[1]), targetGraph.Atoms.IndexOf(tbond.Atoms[0])); if (!result2.Contains(map01)) { result2.Add(map01); } if (!result2.Contains(map10)) { result2.Add(map10); } } } } var result = new List <IReadOnlyList <CDKRMap> >(); if (result1.Count == result2.Count) { result.Add(result1); result.Add(result2); } else if (result1.Count > result2.Count) { result.Add(result1); } else { result.Add(result2); } return(result); }
public override Pattern Create(IAtomContainer container) { return(Ullmann.CreateSubstructureFinder(container)); }
/// <summary> /// Create an atom signature for the atom <paramref name="atom"/>. /// </summary> /// <param name="atom">the atom to make the signature for</param> /// <param name="molecule">the molecule to create the signature from</param> public AtomSignature(IAtom atom, IAtomContainer molecule) : this(molecule.Atoms.IndexOf(atom), molecule) { }
/// <summary> Returns the geometric center of all the atoms in the atomContainer. /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets /// /// </summary> /// <param name="container"> Description of the Parameter /// </param> /// <returns> the geometric center of the atoms in this atomContainer /// </returns> public static Point2d get2DCenter(IAtomContainer container) { double centerX = 0; double centerY = 0; double counter = 0; IAtom[] atoms = container.Atoms; for (int i = 0; i < atoms.Length; i++) { if (atoms[i].getPoint2d() != null) { centerX += atoms[i].getPoint2d().x; centerY += atoms[i].getPoint2d().y; counter++; } } Point2d point = new Point2d(centerX / (counter), centerY / (counter)); return point; }
/// <summary> /// Create an atom signature starting at <paramref name="atomIndex"/>. /// </summary> /// <param name="atomIndex">the index of the atom that roots this signature</param> /// <param name="molecule">the molecule to create the signature from</param> public AtomSignature(int atomIndex, IAtomContainer molecule) : base() { this.molecule = molecule; base.CreateMaximumHeight(atomIndex, molecule.Atoms.Count); }
/// <summary> Translates the geometric 2DCenter of the given /// AtomContainer container to the specified Point2d p. /// /// </summary> /// <param name="container"> AtomContainer which should be translated. /// </param> /// <param name="p"> New Location of the geometric 2D Center. /// </param> /// <seealso cref="get2DCenter"> /// </seealso> /// <seealso cref="translate2DCentreOfMassTo"> /// </seealso> public static void translate2DCenterTo(IAtomContainer container, Point2d p) { Point2d com = get2DCenter(container); Vector2d translation = new Vector2d(p.x - com.x, p.y - com.y); IAtom[] atoms = container.Atoms; for (int i = 0; i < atoms.Length; i++) { if (atoms[i].getPoint2d() != null) { atoms[i].getPoint2d().add(translation); } } }
/// <summary> /// Create an atom signature for the atom <paramref name="atom"/>, with maximum /// height of <paramref name="height"/>, and using a particular invariant type. /// </summary> /// <param name="atom">the index of the atom that roots this signature</param> /// <param name="height">the maximum height of the signature</param> /// <param name="invariantType">the type of invariant (int, string, ...)</param> /// <param name="molecule">the molecule to create the signature from</param> public AtomSignature(IAtom atom, int height, InvariantType invariantType, IAtomContainer molecule) : this(molecule.Atoms.IndexOf(atom), height, invariantType, molecule) { }
/// <summary> Processes the content from the connections field of the INChI. /// Typical values look like 1-2-4-6-5-3-1, from INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H. /// /// </summary> /// <param name="bondsEncoding">the content of the INChI connections field /// </param> /// <param name="container"> the atomContainer parsed from the formula field /// </param> /// <param name="source"> the atom to build the path upon. If -1, then start new path /// /// </param> /// <seealso cref="processFormula"> /// </seealso> public virtual void processConnections(System.String bondsEncoding, IAtomContainer container, int source) { //logger.debug("Parsing bond data: ", bondsEncoding); IBond bondToAdd = null; /* Fixme: treatment of branching is too limited! */ System.String remainder = bondsEncoding; while (remainder.Length > 0) { //logger.debug("Bond part: ", remainder); if (remainder[0] == '(') { System.String branch = chopBranch(remainder); processConnections(branch, container, source); if (branch.Length + 2 <= remainder.Length) { remainder = remainder.Substring(branch.Length + 2); } else { remainder = ""; } } else { Regex pattern = new Regex("^(\\d+)-?(.*)"); //Pattern pattern = Pattern.compile("^(\\d+)-?(.*)"); //Matcher matcher = pattern.matcher(remainder); Match matcher = pattern.Match(remainder); //if (matcher.matches()) if (matcher != null && matcher.Success) { System.String targetStr = matcher.Groups[1].Value; int target = System.Int32.Parse(targetStr); //logger.debug("Source atom: ", source); //logger.debug("Target atom: ", targetStr); IAtom targetAtom = container.getAtomAt(target - 1); if (source != -1) { IAtom sourceAtom = container.getAtomAt(source - 1); bondToAdd = container.Builder.newBond(sourceAtom, targetAtom, 1.0); container.addBond(bondToAdd); } remainder = matcher.Groups[2].Value; source = target; //logger.debug(" remainder: ", remainder); } else { //logger.error("Could not get next bond info part"); return; } } } }
/// <summary> /// Create an atom signature starting at <paramref name="atomIndex"/>, with maximum /// height of <paramref name="height"/>, and using a particular invariant type. /// </summary> /// <param name="atomIndex">the index of the atom that roots this signature</param> /// <param name="height">the maximum height of the signature</param> /// <param name="invariantType">the type of invariant (int, string, ...)</param> /// <param name="molecule">the molecule to create the signature from</param> public AtomSignature(int atomIndex, int height, InvariantType invariantType, IAtomContainer molecule) : base(invariantType) { this.molecule = molecule; base.Create(atomIndex, molecule.Atoms.Count, height); }
/// <summary> /// Rebonds one atom by looking up nearby atom using the binary space partition tree. /// </summary> private void bondAtom(IAtomContainer container, IAtom atom) { double myCovalentRadius = atom.CovalentRadius; double searchRadius = myCovalentRadius + maxCovalentRadius + bondTolerance; Point tupleAtom = new Point(atom.X3d, atom.Y3d, atom.Z3d); Bspt.EnumerateSphere e = bspt.enumHemiSphere(tupleAtom, searchRadius); while (e.MoveNext()) { IAtom atomNear = ((TupleAtom)e.Current).Atom; if (atomNear != atom && container.getBond(atom, atomNear) == null) { bool isBonded_ = isBonded(myCovalentRadius, atomNear.CovalentRadius, e.foundDistance2()); if (isBonded_) { IBond bond = atom.Builder.newBond(atom, atomNear, 1.0); container.addBond(bond); } } } }
/// <summary>Check the electron contribution is the same as expected.</summary> static void Test(IAtomContainer m, params int[] expected) { AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(m); Assert.IsTrue(Compares.AreDeepEqual(expected, model.Contribution(m, new RingSearch(m)))); }
public static IMolecularFormula GetMolecularFormula(IAtomContainer atomContainer) { var formula = new MolecularFormula(); var charge = 0; var hydrogen = new Atom("H"); foreach (var iAtom in atomContainer.atoms().ToWindowsEnumerable<IAtom>()) { formula.addIsotope(iAtom); charge += iAtom.getFormalCharge().intValue(); var implicitHydrogenCount = iAtom.getImplicitHydrogenCount(); var implicitHydrogenCountValue = implicitHydrogenCount != null ? implicitHydrogenCount.intValue() : (int?) null; if (implicitHydrogenCountValue.HasValue && implicitHydrogenCountValue.Value > 0) { formula.addIsotope(hydrogen, implicitHydrogenCountValue.Value); } } formula.setCharge(new Integer(charge)); return formula; }
/// <summary> /// Calculates the 3 MI's, 3 ration and the R_gyr value. /// The molecule should have hydrogens. /// </summary> /// <returns>An <see cref="Result"/> containing 7 elements in the order described above</returns> public Result Calculate(IAtomContainer container) { container = (IAtomContainer)container.Clone(); var factory = CDK.IsotopeFactory; factory.ConfigureAtoms(container); if (!GeometryUtil.Has3DCoordinates(container)) { throw new ThreeDRequiredException("Molecule must have 3D coordinates"); } var retval = new List <double>(7); double ccf = 1.000138; double eps = 1e-5; var imat = Arrays.CreateJagged <double>(3, 3); var centerOfMass = GeometryUtil.Get3DCentreOfMass(container).Value; double xdif; double ydif; double zdif; double xsq; double ysq; double zsq; for (int i = 0; i < container.Atoms.Count; i++) { var currentAtom = container.Atoms[i]; var _mass = factory.GetMajorIsotope(currentAtom.Symbol).ExactMass; var mass = _mass == null?factory.GetNaturalMass(currentAtom.Element) : _mass.Value; var p = currentAtom.Point3D.Value; xdif = p.X - centerOfMass.X; ydif = p.Y - centerOfMass.Y; zdif = p.Z - centerOfMass.Z; xsq = xdif * xdif; ysq = ydif * ydif; zsq = zdif * zdif; imat[0][0] += mass * (ysq + zsq); imat[1][1] += mass * (xsq + zsq); imat[2][2] += mass * (xsq + ysq); imat[1][0] += -1 * mass * ydif * xdif; imat[0][1] = imat[1][0]; imat[2][0] += -1 * mass * xdif * zdif; imat[0][2] = imat[2][0]; imat[2][1] += -1 * mass * ydif * zdif; imat[1][2] = imat[2][1]; } // diagonalize the MI tensor var tmp = Matrix <double> .Build.DenseOfColumnArrays(imat); var eigenDecomp = tmp.Evd(); var eval = eigenDecomp.EigenValues.Select(n => n.Real).ToArray(); retval.Add(eval[2]); retval.Add(eval[1]); retval.Add(eval[0]); var etmp = eval[0]; eval[0] = eval[2]; eval[2] = etmp; if (Math.Abs(eval[1]) > 1e-3) { retval.Add(eval[0] / eval[1]); } else { retval.Add(1000); } if (Math.Abs(eval[2]) > 1e-3) { retval.Add(eval[0] / eval[2]); retval.Add(eval[1] / eval[2]); } else { retval.Add(1000); retval.Add(1000); } // finally get the radius of gyration var formula = MolecularFormulaManipulator.GetMolecularFormula(container); var pri = Math.Abs(eval[2]) > eps ? Math.Pow(eval[0] *eval[1] *eval[2], 1.0 / 3.0) : Math.Sqrt(eval[0] * ccf / MolecularFormulaManipulator.GetTotalExactMass(formula)); retval.Add(Math.Sqrt(Math.PI * 2 * pri * ccf / MolecularFormulaManipulator.GetTotalExactMass(formula))); return(new Result(retval)); }
public override Suppressed Suppress(IAtomContainer container) { return(Suppressed.None); }
public void Add(IAtomContainer atomContainer) { throw new InvalidOperationException("not supported"); }