/// <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); }
/// <summary> Adds a reactant to this reaction. /// /// </summary> /// <param name="reactant"> Molecule added as reactant to this reaction /// </param> /// <seealso cref="getReactants"> /// </seealso> public virtual void addReactant(IMolecule reactant) { addReactant(reactant, 1.0); /* notifyChanged() is called by * addReactant(Molecule reactant, double coefficient) */ }
/// <summary> Partitions the atoms in an AtomContainer into covalently connected components. /// /// </summary> /// <param name="atomContainer"> The AtomContainer to be partitioned into connected components, i.e. molecules /// </param> /// <returns> A SetOfMolecules. /// /// </returns> /// <cdk.dictref> blue-obelisk:graphPartitioning </cdk.dictref> public static ISetOfMolecules partitionIntoMolecules(IAtomContainer atomContainer) { IAtomContainer ac = atomContainer.Builder.newAtomContainer(); IAtom atom = null; IElectronContainer eContainer = null; IMolecule molecule = null; ISetOfMolecules molecules = atomContainer.Builder.newSetOfMolecules(); 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); atom.setFlag(CDKConstants.VISITED, false); ac.addAtom(atom); } IElectronContainer[] eContainers = atomContainer.ElectronContainers; for (int f = 0; f < eContainers.Length; f++) { eContainer = eContainers[f]; eContainer.setFlag(CDKConstants.VISITED, false); ac.addElectronContainer(eContainer); } while (ac.AtomCount > 0) { atom = ac.getAtomAt(0); molecule = atomContainer.Builder.newMolecule(); sphere.Clear(); sphere.Add(atom); atom.setFlag(CDKConstants.VISITED, true); PathTools.breadthFirstSearch(ac, sphere, molecule); molecules.addMolecule(molecule); ac.remove(molecule); } return(molecules); }
/// <summary> Adds a product to this reaction. /// /// </summary> /// <param name="product"> Molecule added as product to this reaction /// </param> /// <seealso cref="getProducts"> /// </seealso> public virtual void addProduct(IMolecule product) { this.addProduct(product, 1.0); /* notifyChanged() is called by * addProduct(Molecule product, double coefficient)*/ }
/// <summary> Adds a product to this reaction. /// /// </summary> /// <param name="product"> Molecule added as product to this reaction /// </param> /// <param name="coefficient">Stoichiometry coefficient for this molecule /// </param> /// <seealso cref="getProducts"> /// </seealso> public virtual void addProduct(IMolecule product, double coefficient) { products.addAtomContainer(product, coefficient); /* notifyChanged() is called by * addReactant(Molecule reactant, double coefficient) */ }
/// <summary> Writes a SetOfMolecules to an OutputStream for the reaction. /// /// </summary> /// <param name="som"> The SetOfMolecules that is written to an OutputStream /// </param> private void writeSetOfMolecules(ISetOfMolecules som) { for (int i = 0; i < som.MoleculeCount; i++) { IMolecule mol = som.getMolecule(i); for (int j = 0; j < som.getMultiplier(i); j++) { //MemoryStream ms = new MemoryStream(); //StreamWriter sw = new StreamWriter(ms); writer.Write("$MOL\n"); MDLWriter mdlwriter = null; try { mdlwriter = new MDLWriter(writer); } catch (System.Exception ex) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //logger.error(ex.Message); //logger.debug(ex); //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" throw new CDKException("Exception while creating MDLWriter: " + ex.Message, ex); } mdlwriter.write(mol); //writer.Write(sw.ToString()); } } }
/// <summary> Method that saturates a molecule by adding explicit hydrogens. /// In order to get coordinates for these Hydrogens, you need to /// remember the average bondlength of you molecule (coordinates for /// all atoms should be available) by using /// double bondLength = GeometryTools.getBondLengthAverage(atomContainer); /// and then use this method here and then use /// org.openscience.cdk.HydrogenPlacer(atomContainer, bondLength); /// /// </summary> /// <param name="molecule"> Molecule to saturate /// </param> /// <cdk.keyword> hydrogen, adding </cdk.keyword> /// <cdk.keyword> explicit hydrogen </cdk.keyword> public virtual IAtomContainer addHydrogensToSatisfyValency(IMolecule molecule) { //logger.debug("Start of addHydrogensToSatisfyValency"); IAtomContainer changedAtomsAndBonds = addExplicitHydrogensToSatisfyValency(molecule); //logger.debug("End of addHydrogensToSatisfyValency"); return(changedAtomsAndBonds); }
/// <summary> Writes a Molecule to an OutputStream in MDL sdf format. /// /// </summary> /// <param name="molecule"> Molecule that is written to an OutputStream /// </param> public virtual void writeMolecule(IMolecule molecule) { bool[] isVisible = new bool[molecule.AtomCount]; for (int i = 0; i < isVisible.Length; i++) { isVisible[i] = true; } writeMolecule(molecule, isVisible); }
private IMolecule readMolecule(IMolecule molecule) { JmolAdapter adapter = new SmarterJmolAdapter(); // note that it actually let's the adapter detect the format! System.Object model = adapter.openBufferedReader("", input); molecule.add(new Convertor(molecule.Builder).convert(model)); return(molecule); }
public MainWindow() { molecule = new Molecule(); InitializeComponent(); foreach(String s in molecule.FormulasList) { formulaCombo.Items.Add(s); } }
/// <summary> writes a single frame in XYZ format to the Writer.</summary> /// <param name="mol">the Molecule to write /// </param> public virtual void writeMolecule(IMolecule mol) { System.String st = ""; bool writecharge = true; try { System.String s1 = ((System.Int32)mol.AtomCount).ToString(); //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'" writer.Write(s1.ToCharArray(), 0, s1.Length); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); System.String s2 = null; // FIXME: add some interesting comment if (s2 != null) { //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'" writer.Write(s2.ToCharArray(), 0, s2.Length); } //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); // Loop through the atoms and write them out: IAtom[] atoms = mol.Atoms; for (int i = 0; i < atoms.Length; i++) { IAtom a = atoms[i]; st = a.Symbol; Point3d p3 = a.getPoint3d(); if (p3 != null) { st = st + "\t" + p3.x.ToString() + "\t" + p3.y.ToString() + "\t" + p3.z.ToString(); } if (writecharge) { double ct = a.getCharge(); st = st + "\t" + ct; } //UPGRADE_NOTE: Exceptions thrown by the equivalent in .NET of method 'java.io.BufferedWriter.write' may be different. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1099'" writer.Write(st.ToCharArray(), 0, st.Length); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } catch (System.IO.IOException e) { // throw e; //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //logger.error("Error while writing file: ", e.Message); //logger.debug(e); } }
public bool AreIsomers(IMolecule molecule) { if (!(molecule is ChemicalCompound)) { return(false); } var compound = molecule as ChemicalCompound; return(AreAtomsCountEqual(compound)); }
/// <summary> Description of the Method /// /// </summary> /// <param name="smiles"> Description of the Parameter /// </param> /// <returns> Description of the Return Value /// </returns> /// <exception cref="InvalidSmilesException"> Description of the Exception /// </exception> public virtual Reaction parseReactionSmiles(System.String smiles) { SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(smiles, ">"); System.String reactantSmiles = tokenizer.NextToken(); System.String agentSmiles = ""; System.String productSmiles = tokenizer.NextToken(); if (tokenizer.HasMoreTokens()) { agentSmiles = productSmiles; productSmiles = tokenizer.NextToken(); } Reaction reaction = new Reaction(); // add reactants IMolecule reactantContainer = parseSmiles(reactantSmiles); ISetOfMolecules reactantSet = ConnectivityChecker.partitionIntoMolecules(reactantContainer); IMolecule[] reactants = reactantSet.Molecules; for (int i = 0; i < reactants.Length; i++) { reaction.addReactant(reactants[i]); } // add reactants if (agentSmiles.Length > 0) { IMolecule agentContainer = parseSmiles(agentSmiles); ISetOfMolecules agentSet = ConnectivityChecker.partitionIntoMolecules(agentContainer); IMolecule[] agents = agentSet.Molecules; for (int i = 0; i < agents.Length; i++) { reaction.addAgent(agents[i]); } } // add products IMolecule productContainer = parseSmiles(productSmiles); ISetOfMolecules productSet = ConnectivityChecker.partitionIntoMolecules(productContainer); IMolecule[] products = productSet.Molecules; for (int i = 0; i < products.Length; i++) { reaction.addProduct(products[i]); } return(reaction); }
private IChemModel readChemModel(IChemModel chemModel) { ISetOfMolecules setOfMolecules = chemModel.SetOfMolecules; if (setOfMolecules == null) { setOfMolecules = chemModel.Builder.newSetOfMolecules(); } IMolecule m = readMolecule(chemModel.Builder.newMolecule()); if (m != null) { setOfMolecules.addMolecule(m); } chemModel.SetOfMolecules = setOfMolecules; return(chemModel); }
public static IAtomContainer createNewMolecule(IChemModel chemModel) { // Add a new molecule either the set of molecules IMolecule molecule = chemModel.Builder.newMolecule(); if (chemModel.SetOfMolecules != null) { ISetOfMolecules moleculeSet = chemModel.SetOfMolecules; moleculeSet.addMolecule(molecule); } else { ISetOfMolecules moleculeSet = chemModel.Builder.newSetOfMolecules(); moleculeSet.addMolecule(molecule); chemModel.SetOfMolecules = moleculeSet; } return(molecule); }
/// <summary> Method that saturates a molecule by adding implicit hydrogens. /// /// </summary> /// <param name="container"> Molecule to saturate /// </param> /// <cdk.keyword> hydrogen, adding </cdk.keyword> /// <cdk.keyword> implicit hydrogen </cdk.keyword> //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 virtual System.Collections.Hashtable addImplicitHydrogensToSatisfyValency(IAtomContainer container) { ISetOfMolecules moleculeSet = ConnectivityChecker.partitionIntoMolecules(container); IMolecule[] molecules = moleculeSet.Molecules; //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'" System.Collections.Hashtable hydrogenAtomMap = new System.Collections.Hashtable(); for (int k = 0; k < molecules.Length; k++) { IMolecule molPart = molecules[k]; IAtom[] atoms = molPart.Atoms; for (int f = 0; f < atoms.Length; f++) { int[] hydrogens = addImplicitHydrogensToSatisfyValency(molPart, atoms[f]); hydrogenAtomMap[atoms[f]] = hydrogens; } } return(hydrogenAtomMap); }
/// <summary> Reads partial atomic charges and add the to the given ChemModel. /// /// </summary> /// <param name="model">Description of the Parameter /// </param> /// <throws> CDKException Description of the Exception </throws> /// <throws> IOException Description of the Exception </throws> private void readPartialCharges(IChemModel model) { //logger.info("Reading partial atomic charges"); ISetOfMolecules moleculeSet = model.SetOfMolecules; IMolecule molecule = moleculeSet.getMolecule(0); System.String line = input.ReadLine(); // skip first line after "Total atomic charges" while (input.Peek() != -1) { line = input.ReadLine(); //logger.debug("Read charge block line: " + line); if ((line == null) || (line.IndexOf("Sum of Mulliken charges") >= 0)) { //logger.debug("End of charge block found"); break; } System.IO.StringReader sr = new System.IO.StringReader(line); SupportClass.StreamTokenizerSupport tokenizer = new SupportClass.StreamTokenizerSupport(sr); if (tokenizer.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'" int atomCounter = (int)tokenizer.nval; tokenizer.NextToken(); // ignore the symbol double charge; if (tokenizer.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER) { charge = tokenizer.nval; //logger.debug("Found charge for atom " + atomCounter + ": " + charge); } else { throw new CDKException("Error while reading charge: expected double."); } IAtom atom = molecule.getAtomAt(atomCounter - 1); atom.setCharge(charge); } } }
/// <summary> Returns the atoms which are closest to an atom in an AtomContainer by bonds. /// If number of atoms in or below sphere x<max andnumber of atoms in or below sphere x+1>max then atoms in or below sphere x+1 are returned. /// /// </summary> /// <param name="ac"> The AtomContainer to examine /// </param> /// <param name="a"> the atom to start from /// </param> /// <param name="max">the number of neighbours to return /// </param> /// <returns> the average bond length /// </returns> public static IAtom[] findClosestByBond(IAtomContainer ac, IAtom a, int max) { IMolecule mol = ac.Builder.newMolecule(); System.Collections.ArrayList v = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); v.Add(a); breadthFirstSearch(ac, v, mol, max); IAtom[] returnValue = new IAtom[mol.Atoms.Length - 1]; int k = 0; for (int i = 0; i < mol.Atoms.Length; i++) { if (mol.Atoms[i] != a) { returnValue[k] = mol.Atoms[i]; k++; } } return(returnValue); }
public static System.Collections.ArrayList getAllIDs(IReaction reaction) { System.Collections.ArrayList idList = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); if (reaction.ID != null) { idList.Add(reaction.ID); } IMolecule[] reactants = reaction.Reactants.Molecules; for (int i = 0; i < reactants.Length; i++) { IMolecule mol = reactants[i]; idList.AddRange(AtomContainerManipulator.getAllIDs(mol)); } IMolecule[] products = reaction.Products.Molecules; for (int i = 0; i < products.Length; i++) { IMolecule mol = products[i]; idList.AddRange(AtomContainerManipulator.getAllIDs(mol)); } return(idList); }
public static void removeAtomAndConnectedElectronContainers(IReaction reaction, IAtom atom) { IMolecule[] reactants = reaction.Reactants.Molecules; for (int i = 0; i < reactants.Length; i++) { IMolecule mol = reactants[i]; if (mol.contains(atom)) { mol.removeAtomAndConnectedElectronContainers(atom); } } IMolecule[] products = reaction.Products.Molecules; for (int i = 0; i < products.Length; i++) { IMolecule mol = products[i]; if (mol.contains(atom)) { mol.removeAtomAndConnectedElectronContainers(atom); } } }
public static void removeElectronContainer(IReaction reaction, IElectronContainer electrons) { IMolecule[] reactants = reaction.Reactants.Molecules; for (int i = 0; i < reactants.Length; i++) { IMolecule mol = reactants[i]; if (mol.contains(electrons)) { mol.removeElectronContainer(electrons); } } IMolecule[] products = reaction.Products.Molecules; for (int i = 0; i < products.Length; i++) { IMolecule mol = products[i]; if (mol.contains(electrons)) { mol.removeElectronContainer(electrons); } } }
/// <summary> Writes the content from molecule to output. /// /// </summary> /// <param name="molecule"> Molecule of which the data is outputted. /// </param> public virtual void writeMolecule(IMolecule molecule) { SmilesGenerator sg = new SmilesGenerator(molecule.Builder); System.String smiles = ""; try { smiles = sg.createSMILES(molecule); //logger.debug("Generated SMILES: " + smiles); writer.Write(smiles); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); writer.Flush(); //logger.debug("file flushed..."); } catch (System.Exception exc) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //logger.error("Error while writing Molecule: ", exc.Message); //logger.debug(exc); } }
/// <deprecated> This method has a serious performace impact. Try to use /// other methods. /// </deprecated> public static IAtomContainer getAllInOneContainer(IReaction reaction) { IAtomContainer container = reaction.Builder.newAtomContainer(); if (reaction == null) { return(container); } IMolecule[] reactants = reaction.Reactants.Molecules; for (int i = 0; i < reactants.Length; i++) { IMolecule molecule = reactants[i]; container.add(molecule); } IMolecule[] products = reaction.Products.Molecules; for (int i = 0; i < products.Length; i++) { IMolecule molecule = products[i]; container.add(molecule); } return(container); }
/// <summary> Method that saturates a molecule by adding explicit hydrogens. /// In order to get coordinates for these Hydrogens, you need to /// remember the average bondlength of you molecule (coordinates for /// all atoms should be available) by using /// double bondLength = GeometryTools.getBondLengthAverage(atomContainer); /// and then use this method here and then use /// org.openscience.cdk.HydrogenPlacer(atomContainer, bondLength); /// /// </summary> /// <param name="molecule"> Molecule to saturate /// </param> /// <cdk.keyword> hydrogen, adding </cdk.keyword> /// <cdk.keyword> explicit hydrogen </cdk.keyword> public virtual IAtomContainer addExplicitHydrogensToSatisfyValency(IMolecule molecule) { //logger.debug("Start of addExplicitHydrogensToSatisfyValency"); ISetOfMolecules moleculeSet = ConnectivityChecker.partitionIntoMolecules(molecule); IMolecule[] molecules = moleculeSet.Molecules; IAtomContainer changedAtomsAndBonds = molecule.Builder.newAtomContainer(); IAtomContainer intermediateContainer = null; for (int k = 0; k < molecules.Length; k++) { IMolecule molPart = molecules[k]; IAtom[] atoms = molPart.Atoms; for (int i = 0; i < atoms.Length; i++) { intermediateContainer = addHydrogensToSatisfyValency(molPart, atoms[i], molecule); changedAtomsAndBonds.add(intermediateContainer); } } //logger.debug("End of addExplicitHydrogensToSatisfyValency"); return(changedAtomsAndBonds); }
public virtual void writeMolecule(IMolecule molecule) { writer.Write("{\n"); writer.Write(" Molecule mol = new Molecule();\n"); IDCreator idCreator = new IDCreator(); idCreator.createIDs(molecule); IAtom[] atoms = molecule.Atoms; for (int i = 0; i < atoms.Length; i++) { IAtom atom = atoms[i]; writeAtom(atom); writer.Write(" mol.addAtom(" + atom.ID + ");\n"); } IBond[] bonds = molecule.Bonds; for (int i = 0; i < bonds.Length; i++) { IBond bond = bonds[i]; writeBond(bond); writer.Write(" mol.addBond(" + bond.ID + ");\n"); } writer.Write("}\n"); }
/// <summary> Method that saturates a molecule by adding explicit hydrogens. /// In order to get coordinates for these Hydrogens, you need to /// remember the average bondlength of you molecule (coordinates for /// all atoms should be available) by using /// double bondLength = GeometryTools.getBondLengthAverage(atomContainer); /// and then use this method here and then use /// org.openscience.cdk.HydrogenPlacer(atomContainer, bondLength); /// /// </summary> /// <param name="molecule"> Molecule to saturate /// </param> /// <cdk.keyword> hydrogen, adding </cdk.keyword> /// <cdk.keyword> explicit hydrogen </cdk.keyword> public virtual IAtomContainer addHydrogensToSatisfyValency(IMolecule molecule) { //logger.debug("Start of addHydrogensToSatisfyValency"); IAtomContainer changedAtomsAndBonds = addExplicitHydrogensToSatisfyValency(molecule); //logger.debug("End of addHydrogensToSatisfyValency"); return changedAtomsAndBonds; }
/// <summary> Read a Reaction from a file in MDL RXN format /// /// </summary> /// <returns> The Reaction that was read from the MDL file. /// </returns> private IMolecule readMolecule(IMolecule molecule) { AtomTypeFactory atFactory = null; try { atFactory = AtomTypeFactory.getInstance("mol2_atomtypes.xml", molecule.Builder); } catch (System.Exception exception) { System.String error = "Could not instantiate an AtomTypeFactory"; //logger.error(error); //logger.debug(exception); throw new CDKException(error, exception); } try { System.String line = input.ReadLine(); int atomCount = 0; int bondCount = 0; while (line != null) { if (line.StartsWith("@<TRIPOS>MOLECULE")) { //logger.info("Reading molecule block"); // second line has atom/bond counts? input.ReadLine(); // disregard the name line System.String counts = input.ReadLine(); SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(counts); try { atomCount = System.Int32.Parse(tokenizer.NextToken()); } catch (System.FormatException nfExc) { System.String error = "Error while reading atom count from MOLECULE block"; //logger.error(error); //logger.debug(nfExc); throw new CDKException(error, nfExc); } if (tokenizer.HasMoreTokens()) { try { bondCount = System.Int32.Parse(tokenizer.NextToken()); } catch (System.FormatException nfExc) { System.String error = "Error while reading atom and bond counts"; //logger.error(error); //logger.debug(nfExc); throw new CDKException(error, nfExc); } } else { bondCount = 0; } //logger.info("Reading #atoms: ", atomCount); //logger.info("Reading #bonds: ", bondCount); //logger.warn("Not reading molecule qualifiers"); } else if (line.StartsWith("@<TRIPOS>ATOM")) { //logger.info("Reading atom block"); for (int i = 0; i < atomCount; i++) { line = input.ReadLine().Trim(); SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(line); tokenizer.NextToken(); // disregard the id token System.String nameStr = tokenizer.NextToken(); System.String xStr = tokenizer.NextToken(); System.String yStr = tokenizer.NextToken(); System.String zStr = tokenizer.NextToken(); System.String atomTypeStr = tokenizer.NextToken(); IAtomType atomType = atFactory.getAtomType(atomTypeStr); if (atomType == null) { atomType = atFactory.getAtomType("X"); //logger.error("Could not find specified atom type: ", atomTypeStr); } IAtom atom = molecule.Builder.newAtom("X"); atom.ID = nameStr; atom.AtomTypeName = atomTypeStr; atFactory.configure(atom); try { double x = System.Double.Parse(xStr); double y = System.Double.Parse(yStr); double z = System.Double.Parse(zStr); atom.setPoint3d(new Point3d(x, y, z)); } catch (System.FormatException nfExc) { System.String error = "Error while reading atom coordinates"; //logger.error(error); //logger.debug(nfExc); throw new CDKException(error, nfExc); } molecule.addAtom(atom); } } else if (line.StartsWith("@<TRIPOS>BOND")) { //logger.info("Reading bond block"); for (int i = 0; i < bondCount; i++) { line = input.ReadLine(); SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(line); tokenizer.NextToken(); // disregard the id token System.String atom1Str = tokenizer.NextToken(); System.String atom2Str = tokenizer.NextToken(); System.String orderStr = tokenizer.NextToken(); try { int atom1 = System.Int32.Parse(atom1Str); int atom2 = System.Int32.Parse(atom2Str); double order = 0; if ("1".Equals(orderStr)) { order = CDKConstants.BONDORDER_AROMATIC; } else if ("2".Equals(orderStr)) { order = CDKConstants.BONDORDER_DOUBLE; } else if ("3".Equals(orderStr)) { order = CDKConstants.BONDORDER_TRIPLE; } else if ("am".Equals(orderStr)) { order = CDKConstants.BONDORDER_SINGLE; } else if ("ar".Equals(orderStr)) { order = CDKConstants.BONDORDER_AROMATIC; } else if ("du".Equals(orderStr)) { order = CDKConstants.BONDORDER_SINGLE; } else if ("un".Equals(orderStr)) { order = CDKConstants.BONDORDER_SINGLE; } else if ("nc".Equals(orderStr)) { // not connected order = 0; } if (order != 0) { molecule.addBond(atom1 - 1, atom2 - 1, order); } } catch (System.FormatException nfExc) { System.String error = "Error while reading bond information"; //logger.error(error); //logger.debug(nfExc); throw new CDKException(error, nfExc); } } } line = input.ReadLine(); } } catch (System.IO.IOException exception) { System.String error = "Error while reading general structure"; //logger.error(error); //logger.debug(exception); throw new CDKException(error, exception); } return(molecule); }
/// <summary> Performs a breadthFirstSearch in an AtomContainer starting with a /// particular sphere, which usually consists of one start atom. While /// searching the graph, the method marks each visited atom. It then puts all /// the atoms connected to the atoms in the given sphere into a new vector /// which forms the sphere to search for the next recursive method call. All /// atoms that have been visited are put into a molecule container. This /// breadthFirstSearch does thus find the connected graph for a given start /// atom. /// /// </summary> /// <param name="ac"> The AtomContainer to be searched /// </param> /// <param name="sphere"> A sphere of atoms to start the search with /// </param> /// <param name="molecule">A molecule into which all the atoms and bonds are stored /// that are found during search /// </param> public static void breadthFirstSearch(IAtomContainer ac, System.Collections.ArrayList sphere, IMolecule molecule) { // System.out.println("Staring partitioning with this ac: " + ac); breadthFirstSearch(ac, sphere, molecule, -1); }
public void ExportMolecule(IMolecule molecule) { }
// private procedures /// <summary> Private method that actually parses the input to read a ChemFile /// object. /// /// </summary> /// <returns> A ChemFile containing the data parsed from input. /// </returns> private IChemFile readChemFile(IChemFile file) { IChemSequence chemSequence = file.Builder.newChemSequence(); int number_of_atoms = 0; SupportClass.Tokenizer tokenizer; try { System.String line = input.ReadLine(); while (input.Peek() != -1 && line != null) { // parse frame by frame tokenizer = new SupportClass.Tokenizer(line, "\t ,;"); System.String token = tokenizer.NextToken(); number_of_atoms = System.Int32.Parse(token); System.String info = input.ReadLine(); IChemModel chemModel = file.Builder.newChemModel(); ISetOfMolecules setOfMolecules = file.Builder.newSetOfMolecules(); IMolecule m = file.Builder.newMolecule(); m.setProperty(CDKConstants.TITLE, info); for (int i = 0; i < number_of_atoms; i++) { line = input.ReadLine(); if (line == null) { break; } if (line.StartsWith("#") && line.Length > 1) { System.Object comment = m.getProperty(CDKConstants.COMMENT); if (comment == null) { comment = ""; } //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" comment = comment.ToString() + line.Substring(1).Trim(); m.setProperty(CDKConstants.COMMENT, comment); //logger.debug("Found and set comment: ", comment); } else { double x = 0.0f, y = 0.0f, z = 0.0f; double charge = 0.0f; tokenizer = new SupportClass.Tokenizer(line, "\t ,;"); int fields = tokenizer.Count; if (fields < 4) { // this is an error but cannot throw exception } else { System.String atomtype = tokenizer.NextToken(); //UPGRADE_TODO: The differences in the format of parameters for constructor 'java.lang.Double.Double' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" x = (System.Double.Parse(tokenizer.NextToken())); //UPGRADE_TODO: The differences in the format of parameters for constructor 'java.lang.Double.Double' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" y = (System.Double.Parse(tokenizer.NextToken())); //UPGRADE_TODO: The differences in the format of parameters for constructor 'java.lang.Double.Double' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" z = (System.Double.Parse(tokenizer.NextToken())); if (fields == 8) { //UPGRADE_TODO: The differences in the format of parameters for constructor 'java.lang.Double.Double' may cause compilation errors. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'" charge = (System.Double.Parse(tokenizer.NextToken())); } IAtom atom = file.Builder.newAtom(atomtype, new Point3d(x, y, z)); atom.setCharge(charge); m.addAtom(atom); } } } setOfMolecules.addMolecule(m); chemModel.SetOfMolecules = setOfMolecules; chemSequence.addChemModel(chemModel); line = input.ReadLine(); } file.addChemSequence(chemSequence); } catch (System.IO.IOException e) { // should make some noise now file = null; //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //logger.error("Error while reading file: ", e.Message); //logger.debug(e); } return(file); }
/// <summary> Writes a single frame in XYZ format to the Writer. /// /// </summary> /// <param name="mol">the Molecule to write /// </param> public virtual void writeMolecule(IMolecule mol) { try { /* # Name: benzene # Creating user name: tom # Creation time: Wed Dec 28 00:18:30 1988 # Modifying user name: tom # Modification time: Wed Dec 28 00:18:30 1988*/ //logger.debug("Writing header..."); if (mol.getProperty(CDKConstants.TITLE) != null) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" writer.Write("# Name: " + mol.getProperty(CDKConstants.TITLE) + "\n"); } // FIXME: add other types of meta data //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); /* @<TRIPOS>MOLECULE benzene 12 12 1 0 0 SMALL NO_CHARGES */ //logger.debug("Writing molecule block..."); writer.Write("@<TRIPOS>MOLECULE\n"); writer.Write(mol.ID + "\n"); writer.Write(mol.AtomCount + " " + mol.getBondCount() + "\n"); // that's the minimum amount of info required the format writer.Write("SMALL\n"); // no biopolymer writer.Write("NO CHARGES\n"); // other options include Gasteiger charges /* @<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 //logger.debug("Writing atom block..."); writer.Write("@<TRIPOS>ATOM\n"); IAtom[] atoms = mol.Atoms; for (int i = 0; i < atoms.Length; i++) { writer.Write(i + " " + atoms[i].ID + " "); if (atoms[i].getPoint3d() != null) { writer.Write(atoms[i].X3d + " "); writer.Write(atoms[i].Y3d + " "); writer.Write(atoms[i].Z3d + " "); } else if (atoms[i].getPoint2d() != null) { writer.Write(atoms[i].X2d + " "); writer.Write(atoms[i].Y2d + " "); writer.Write(" 0.000 "); } else { writer.Write("0.000 0.000 0.000 "); } writer.Write(atoms[i].Symbol + "\n"); // FIXME: should use perceived Mol2 Atom Types! } /* @<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 //logger.debug("Writing bond block..."); writer.Write("@<TRIPOS>BOND\n"); IBond[] bonds = mol.Bonds; for (int i = 0; i < bonds.Length; i++) { //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'" writer.Write(i + " " + mol.getAtomNumber(bonds[i].getAtomAt(0)) + " " + mol.getAtomNumber(bonds[i].getAtomAt(1)) + " " + ((int)bonds[i].Order) + "\n"); } } catch (System.IO.IOException e) { throw e; } }
/// <summary> Generate canonical SMILES from the <code>molecule</code>. This method /// canonicaly lables the molecule but dose not perform any checks on the /// chemical validity of the molecule. Does not care about multiple molecules. /// IMPORTANT: A precomputed Set of All Rings (SAR) can be passed to this /// SmilesGenerator in order to avoid recomputing it. Use setRings() to /// assign the SAR. /// /// </summary> /// <param name="molecule"> The molecule to evaluate /// </param> /// <param name="chiral"> true=SMILES will be chiral, false=SMILES /// will not be chiral. /// </param> /// <param name="doubleBondConfiguration"> Description of Parameter /// </param> /// <returns> Description of the Returned Value /// </returns> /// <exception cref="CDKException"> At least one atom has no Point2D; /// coordinates are needed for creating the chiral smiles. This excpetion /// can only be thrown if chiral smiles is created, ignore it if you want a /// non-chiral smiles (createSMILES(AtomContainer) does not throw an /// exception). /// </exception> /// <seealso cref="org.openscience.cdk.graph.invariant.CanonicalLabeler.canonLabel(IAtomContainer)"> /// </seealso> //UPGRADE_NOTE: Synchronized keyword was removed from method 'createSMILESWithoutCheckForMultipleMolecules'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'" public virtual System.String createSMILESWithoutCheckForMultipleMolecules(IMolecule molecule, bool chiral, bool[] doubleBondConfiguration) { lock (this) { if (molecule.AtomCount == 0) { return ""; } canLabler.canonLabel(molecule); brokenBonds.Clear(); ringMarker = 0; IAtom[] all = molecule.Atoms; IAtom start = null; for (int i = 0; i < all.Length; i++) { IAtom atom = all[i]; if (chiral && atom.getPoint2d() == null) { throw new CDKException("Atom number " + i + " has no 2D coordinates, but 2D coordinates are needed for creating chiral smiles"); } //System.out.println("Setting all VISITED flags to false"); atom.setFlag(CDKConstants.VISITED, false); if ((long)((System.Int64)atom.getProperty("CanonicalLable")) == 1) { start = atom; } } //detect aromaticity if (rings == null) { if (ringFinder == null) { ringFinder = new AllRingsFinder(); } rings = ringFinder.findAllRings(molecule); } HueckelAromaticityDetector.detectAromaticity(molecule, rings, false); if (chiral && rings.AtomContainerCount > 0) { System.Collections.ArrayList v = RingPartitioner.partitionRings(rings); //System.out.println("RingSystems: " + v.size()); for (int i = 0; i < v.Count; i++) { int counter = 0; IAtomContainer allrings = RingSetManipulator.getAllInOneContainer((IRingSet)v[i]); for (int k = 0; k < allrings.AtomCount; k++) { if (!BondTools.isStereo(molecule, allrings.getAtomAt(k)) && hasWedges(molecule, allrings.getAtomAt(k)) != null) { IBond bond = molecule.getBond(allrings.getAtomAt(k), hasWedges(molecule, allrings.getAtomAt(k))); if (bond.Stereo == CDKConstants.STEREO_BOND_UP) { allrings.getAtomAt(k).setProperty(RING_CONFIG, UP); } else { allrings.getAtomAt(k).setProperty(RING_CONFIG, DOWN); } counter++; } } if (counter == 1) { for (int k = 0; k < allrings.AtomCount; k++) { allrings.getAtomAt(k).setProperty(RING_CONFIG, UP); } } } } System.Text.StringBuilder l = new System.Text.StringBuilder(); createSMILES(start, l, molecule, chiral, doubleBondConfiguration); rings = null; return l.ToString(); } }
/// <summary> Sets the coefficient of a a product to a given value. /// /// </summary> /// <param name="product"> Product for which the coefficient is set /// </param> /// <param name="coefficient">The new coefficient for the given product /// </param> /// <returns> true if Molecule has been found and stoichiometry has been set. /// </returns> /// <seealso cref="getProductCoefficient"> /// </seealso> public virtual bool setProductCoefficient(IMolecule product, double coefficient) { notifyChanged(); return products.setMultiplier(product, coefficient); }
/// <summary> Adds an agent to this reaction. /// /// </summary> /// <param name="agent"> Molecule added as agent to this reaction /// </param> /// <seealso cref="getAgents"> /// </seealso> public virtual void addAgent(IMolecule agent) { agents.addAtomContainer(agent); notifyChanged(); }
/// <summary> Adds a reactant to this reaction with a stoichiometry coefficient. /// /// </summary> /// <param name="reactant"> Molecule added as reactant to this reaction /// </param> /// <param name="coefficient">Stoichiometry coefficient for this molecule /// </param> /// <seealso cref="getReactants"> /// </seealso> public virtual void addReactant(IMolecule reactant, double coefficient) { reactants.addAtomContainer(reactant, coefficient); notifyChanged(); }
/// <summary> Returns the stoichiometry coefficient of the given reactant. /// /// </summary> /// <param name="reactant">Reactant for which the coefficient is returned. /// </param> /// <returns> -1, if the given molecule is not a product in this Reaction /// </returns> /// <seealso cref="setReactantCoefficient"> /// </seealso> public virtual double getReactantCoefficient(IMolecule reactant) { return reactants.getMultiplier(reactant); }
/// <summary> Adds a product to this reaction. /// /// </summary> /// <param name="product"> Molecule added as product to this reaction /// </param> /// <param name="coefficient">Stoichiometry coefficient for this molecule /// </param> /// <seealso cref="getProducts"> /// </seealso> public virtual void addProduct(IMolecule product, double coefficient) { products.addAtomContainer(product, coefficient); /* notifyChanged() is called by addReactant(Molecule reactant, double coefficient) */ }
/// <summary> Generate canonical SMILES from the <code>molecule</code>. This method /// canonicaly lables the molecule but dose not perform any checks on the /// chemical validity of the molecule. This method also takes care of multiple /// molecules. /// IMPORTANT: A precomputed Set of All Rings (SAR) can be passed to this /// SmilesGenerator in order to avoid recomputing it. Use setRings() to /// assign the SAR. /// /// </summary> /// <param name="molecule"> The molecule to evaluate /// </param> /// <param name="chiral"> true=SMILES will be chiral, false=SMILES /// will not be chiral. /// </param> /// <param name="doubleBondConfiguration"> Description of Parameter /// </param> /// <returns> Description of the Returned Value /// </returns> /// <exception cref="CDKException"> At least one atom has no Point2D; /// coordinates are needed for crating the chiral smiles. This excpetion /// can only be thrown if chiral smiles is created, ignore it if you want a /// non-chiral smiles (createSMILES(AtomContainer) does not throw an /// exception). /// </exception> /// <seealso cref="org.openscience.cdk.graph.invariant.CanonicalLabeler.canonLabel(IAtomContainer)"> /// </seealso> //UPGRADE_NOTE: Synchronized keyword was removed from method 'createSMILES'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'" public virtual System.String createSMILES(IMolecule molecule, bool chiral, bool[] doubleBondConfiguration) { lock (this) { ISetOfMolecules moleculeSet = ConnectivityChecker.partitionIntoMolecules(molecule); if (moleculeSet.MoleculeCount > 1) { System.Text.StringBuilder fullSMILES = new System.Text.StringBuilder(); IMolecule[] molecules = moleculeSet.Molecules; for (int i = 0; i < molecules.Length; i++) { IMolecule molPart = molecules[i]; fullSMILES.Append(createSMILESWithoutCheckForMultipleMolecules(molPart, chiral, doubleBondConfiguration)); if (i < (molecules.Length - 1)) { // are there more molecules? fullSMILES.Append('.'); } } return fullSMILES.ToString(); } else { return (createSMILESWithoutCheckForMultipleMolecules(molecule, chiral, doubleBondConfiguration)); } } }
/// <summary> Adds a reactant to this reaction. /// /// </summary> /// <param name="reactant"> Molecule added as reactant to this reaction /// </param> /// <seealso cref="getReactants"> /// </seealso> public virtual void addReactant(IMolecule reactant) { addReactant(reactant, 1.0); /* notifyChanged() is called by addReactant(Molecule reactant, double coefficient) */ }
/// <summary> Reads a set of coordinates from the "file system" file through the use of /// the "input" field, scales coordinate to angstr???m unit, builds each atom with /// the right associated coordinates, builds a new molecule with these atoms /// and returns the complete molecule. /// /// <p><b>Implementation</b>: /// <br>Dummy atoms are ignored. /// /// </summary> /// <param name="coordinatesUnits The">unit in which coordinates are given. /// /// </param> /// <throws IOException may> be thrown by the "input" object. </throws IOException may> /// <summary> /// </summary> /// <seealso cref="org.openscience.cdk.io.GamessReader.input"> /// </seealso> //TODO Update method comments with appropriate information. private IMolecule readCoordinates(IMolecule molecule, bool coordinatesUnits) { /* * Coordinates must all be given in angstr???ms. */ double unitScaling = GamessReader.scalesCoordinatesUnits(coordinatesUnits); System.String retrievedLineFromFile; while (this.input.Peek() != -1 == true) { retrievedLineFromFile = this.input.ReadLine(); /* * A coordinate set is followed by an empty line, so when this line * is reached, there are no more coordinates to add to the current set. */ if ((retrievedLineFromFile == null) || (retrievedLineFromFile.Trim().Length == 0)) { break; } int atomicNumber; System.String atomicSymbol; //StringReader sr = new StringReader(retrievedLineFromFile); SupportClass.StreamTokenizerSupport token = new SupportClass.StreamTokenizerSupport(new System.IO.StringReader(retrievedLineFromFile)); /* * The first token is ignored. It contains the atomic symbol and may * be concatenated with a number. */ token.NextToken(); 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; atomicSymbol = this.identifyAtomicSymbol(atomicNumber); /* * Dummy atoms are assumed to be given with an atomic number set * to zero. We will do not add them to the molecule. */ if (atomicNumber == 0) { continue; } } else { throw new System.IO.IOException("Error reading coordinates"); } /* * Atom's coordinates are stored in an array. */ double[] coordinates = new double[3]; for (int i = 0; i < coordinates.Length; i++) { if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER) { coordinates[i] = token.nval * unitScaling; } else { throw new System.IO.IOException("Error reading coordinates"); } } IAtom atom = molecule.Builder.newAtom(atomicSymbol, new Point3d(coordinates[0], coordinates[1], coordinates[2])); molecule.addAtom(atom); } return molecule; }
/// <summary> Adds an molecule to this container. /// /// </summary> /// <param name="molecule"> The molecule to be added to this container /// </param> public virtual void addMolecule(IMolecule molecule) { base.addAtomContainer(molecule); /* notifyChanged() called in super.addAtomContainer() */ }
/// <summary> Read a Reaction from a file in MDL RXN format /// /// </summary> /// <returns> The Reaction that was read from the MDL file. /// </returns> private IMolecule readMolecule(IMolecule molecule) { AtomTypeFactory atFactory = null; try { atFactory = AtomTypeFactory.getInstance("mol2_atomtypes.xml", molecule.Builder); } catch (System.Exception exception) { System.String error = "Could not instantiate an AtomTypeFactory"; //logger.error(error); //logger.debug(exception); throw new CDKException(error, exception); } try { System.String line = input.ReadLine(); int atomCount = 0; int bondCount = 0; while (line != null) { if (line.StartsWith("@<TRIPOS>MOLECULE")) { //logger.info("Reading molecule block"); // second line has atom/bond counts? input.ReadLine(); // disregard the name line System.String counts = input.ReadLine(); SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(counts); try { atomCount = System.Int32.Parse(tokenizer.NextToken()); } catch (System.FormatException nfExc) { System.String error = "Error while reading atom count from MOLECULE block"; //logger.error(error); //logger.debug(nfExc); throw new CDKException(error, nfExc); } if (tokenizer.HasMoreTokens()) { try { bondCount = System.Int32.Parse(tokenizer.NextToken()); } catch (System.FormatException nfExc) { System.String error = "Error while reading atom and bond counts"; //logger.error(error); //logger.debug(nfExc); throw new CDKException(error, nfExc); } } else { bondCount = 0; } //logger.info("Reading #atoms: ", atomCount); //logger.info("Reading #bonds: ", bondCount); //logger.warn("Not reading molecule qualifiers"); } else if (line.StartsWith("@<TRIPOS>ATOM")) { //logger.info("Reading atom block"); for (int i = 0; i < atomCount; i++) { line = input.ReadLine().Trim(); SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(line); tokenizer.NextToken(); // disregard the id token System.String nameStr = tokenizer.NextToken(); System.String xStr = tokenizer.NextToken(); System.String yStr = tokenizer.NextToken(); System.String zStr = tokenizer.NextToken(); System.String atomTypeStr = tokenizer.NextToken(); IAtomType atomType = atFactory.getAtomType(atomTypeStr); if (atomType == null) { atomType = atFactory.getAtomType("X"); //logger.error("Could not find specified atom type: ", atomTypeStr); } IAtom atom = molecule.Builder.newAtom("X"); atom.ID = nameStr; atom.AtomTypeName = atomTypeStr; atFactory.configure(atom); try { double x = System.Double.Parse(xStr); double y = System.Double.Parse(yStr); double z = System.Double.Parse(zStr); atom.setPoint3d(new Point3d(x, y, z)); } catch (System.FormatException nfExc) { System.String error = "Error while reading atom coordinates"; //logger.error(error); //logger.debug(nfExc); throw new CDKException(error, nfExc); } molecule.addAtom(atom); } } else if (line.StartsWith("@<TRIPOS>BOND")) { //logger.info("Reading bond block"); for (int i = 0; i < bondCount; i++) { line = input.ReadLine(); SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(line); tokenizer.NextToken(); // disregard the id token System.String atom1Str = tokenizer.NextToken(); System.String atom2Str = tokenizer.NextToken(); System.String orderStr = tokenizer.NextToken(); try { int atom1 = System.Int32.Parse(atom1Str); int atom2 = System.Int32.Parse(atom2Str); double order = 0; if ("1".Equals(orderStr)) { order = CDKConstants.BONDORDER_AROMATIC; } else if ("2".Equals(orderStr)) { order = CDKConstants.BONDORDER_DOUBLE; } else if ("3".Equals(orderStr)) { order = CDKConstants.BONDORDER_TRIPLE; } else if ("am".Equals(orderStr)) { order = CDKConstants.BONDORDER_SINGLE; } else if ("ar".Equals(orderStr)) { order = CDKConstants.BONDORDER_AROMATIC; } else if ("du".Equals(orderStr)) { order = CDKConstants.BONDORDER_SINGLE; } else if ("un".Equals(orderStr)) { order = CDKConstants.BONDORDER_SINGLE; } else if ("nc".Equals(orderStr)) { // not connected order = 0; } if (order != 0) { molecule.addBond(atom1 - 1, atom2 - 1, order); } } catch (System.FormatException nfExc) { System.String error = "Error while reading bond information"; //logger.error(error); //logger.debug(nfExc); throw new CDKException(error, nfExc); } } } line = input.ReadLine(); } } catch (System.IO.IOException exception) { System.String error = "Error while reading general structure"; //logger.error(error); //logger.debug(exception); throw new CDKException(error, exception); } return molecule; }
private static void ProcessChemModel(IChemModel chemModel, ISettings settings, FileUsage usage, MoleculeLoadingResults results, MoleculeProcessingProgress progress, float sectionSz) { //if (ChemModelManipulator.getAllInOneContainer(chemModel).getBondCount() == 0) //{ // return; //} // check for coordinates if ((GeometryTools.has2DCoordinatesNew(ChemModelManipulator.getAllInOneContainer(chemModel)) != 0))// { results.Num2DCoords++; } // usage == FileUsage.TwoD) //{ // throw new UserLevelException("File has no 2D coords", UserLevelException.ExceptionType.FileLoading, // typeof(MoleculeLoader), null); //} if ((GeometryTools.has2DCoordinatesNew(ChemModelManipulator.getAllInOneContainer(chemModel)) != 0))// && { results.Num3DCoords++; } // usage == FileUsage.ThreeD) //{ // throw new UserLevelException("File has no 3D coords", UserLevelException.ExceptionType.FileLoading, // typeof(MoleculeLoader), null); //} ElementPTFactory elements = ElementPTFactory.Instance; // calc item sz int numItems = 0; if (chemModel.SetOfMolecules != null) { results.NumMolecules += chemModel.SetOfMolecules.MoleculeCount; for (int mol = 0; mol < chemModel.SetOfMolecules.MoleculeCount; mol++) { numItems += chemModel.SetOfMolecules.Molecules[mol].Atoms.Length; //numItems += chemModel.SetOfMolecules.Molecules[mol].Bonds.Length; } } float itemSz = sectionSz / (float)numItems; if (chemModel.SetOfMolecules != null) { results.NumMolecules += chemModel.SetOfMolecules.MoleculeCount; for (int mol = 0; mol < chemModel.SetOfMolecules.MoleculeCount; mol++) { IMolecule molecule = chemModel.SetOfMolecules.Molecules[mol]; results.NumAtoms += molecule.Atoms.Length; results.NumBonds += molecule.Bonds.Length; foreach (IAtom atom in molecule.Atoms) { PeriodicTableElement pe = elements.getElement(atom.Symbol); if (pe != null) { atom.AtomicNumber = pe.AtomicNumber; atom.Properties["PeriodicTableElement"] = pe; atom.Properties["Period"] = int.Parse(pe.Period); } else { progress.Log(string.Format("Failed to find periodic element: {0}", atom.Symbol), LogItem.ItemLevel.Failure); } progress.UpdateProgress(itemSz); } progress.Log(string.Format("Processed {0} atoms", molecule.Atoms.Length), LogItem.ItemLevel.Info); } } progress.Log("Processed Model", LogItem.ItemLevel.Success); }
/// <summary> Performs a breadthFirstSearch in an AtomContainer starting with a /// particular sphere, which usually consists of one start atom. While /// searching the graph, the method marks each visited atom. It then puts all /// the atoms connected to the atoms in the given sphere into a new vector /// which forms the sphere to search for the next recursive method call. All /// atoms that have been visited are put into a molecule container. This /// breadthFirstSearch does thus find the connected graph for a given start /// atom. /// /// </summary> /// <param name="ac"> The AtomContainer to be searched /// </param> /// <param name="sphere"> A sphere of atoms to start the search with /// </param> /// <param name="molecule">A molecule into which all the atoms and bonds are stored /// that are found during search /// </param> public static void breadthFirstSearch(IAtomContainer ac, System.Collections.ArrayList sphere, IMolecule molecule, int max) { IAtom atom; IAtom nextAtom; System.Collections.ArrayList newSphere = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10)); for (int f = 0; f < sphere.Count; f++) { atom = (IAtom)sphere[f]; //System.out.println("atoms "+ atom + f); //System.out.println("sphere size "+ sphere.size()); molecule.addAtom(atom); // first copy LonePair's and SingleElectron's of this Atom as they need // to be copied too IElectronContainer[] eContainers = ac.getConnectedElectronContainers(atom); //System.out.println("found #ec's: " + eContainers.length); for (int i = 0; i < eContainers.Length; i++) { if (!(eContainers[i] is IBond)) { // ok, no bond, thus LonePair or SingleElectron // System.out.println("adding non bond " + eContainers[i]); molecule.addElectronContainer(eContainers[i]); } } // now look at bonds IBond[] bonds = ac.getConnectedBonds(atom); for (int g = 0; g < bonds.Length; g++) { if (!bonds[g].getFlag(CDKConstants.VISITED)) { molecule.addBond(bonds[g]); bonds[g].setFlag(CDKConstants.VISITED, true); } nextAtom = bonds[g].getConnectedAtom(atom); if (!nextAtom.getFlag(CDKConstants.VISITED)) { // System.out.println("wie oft???"); newSphere.Add(nextAtom); nextAtom.setFlag(CDKConstants.VISITED, true); } } if (max > -1 && molecule.AtomCount > max) return; } if (newSphere.Count > 0) { breadthFirstSearch(ac, newSphere, molecule, max); } }
/// <summary> Reads a set of coordinates into ChemFrame. /// /// </summary> /// <param name="model">Description of the Parameter /// </param> /// <throws> IOException if an I/O error occurs </throws> /// <throws> CDKException Description of the Exception </throws> private void readCoordinates(IChemModel model) { ISetOfMolecules moleculeSet = model.Builder.newSetOfMolecules(); IMolecule molecule = model.Builder.newMolecule(); 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; 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 CDKException("Error while reading coordinates: expected integer."); } token.NextToken(); // ignore third token double x; double y; double z; if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER) { x = token.nval; } else { throw new System.IO.IOException("Error reading x coordinate"); } if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER) { y = token.nval; } else { throw new System.IO.IOException("Error reading y coordinate"); } if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER) { z = token.nval; } else { throw new System.IO.IOException("Error reading z coordinate"); } 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)); molecule.addAtom(atom); } /* * this is the place where we store the atomcount to * be used as a counter in the nmr reading */ atomCount = molecule.AtomCount; moleculeSet.addMolecule(molecule); model.SetOfMolecules = moleculeSet; }
/// <summary> Writes a Molecule to an OutputStream in MDL sdf format. /// /// </summary> /// <param name="container"> Molecule that is written to an OutputStream /// </param> /// <param name="isVisible">Should a certain atom be written to mdl? /// </param> public virtual void writeMolecule(IMolecule container, bool[] isVisible) { System.String line = ""; // taking care of the $$$$ signs: // we do not write such a sign at the end of the first molecule, thus we have to write on BEFORE the second molecule if (moleculeNumber == 2) { writer.Write("$$$$"); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } // write header block // lines get shortened to 80 chars, that's in the spec System.String title = (System.String)container.getProperty(CDKConstants.TITLE); if (title == null) { title = ""; } if (title.Length > 80) { title = title.Substring(0, (80) - (0)); } writer.Write(title + "\n"); /* From CTX spec * This line has the format: * IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR * (FORTRAN: A2<--A8--><---A10-->A2I2<--F10.5-><---F12.5--><-I6-> ) * User's first and last initials (l), program name (P), * date/time (M/D/Y,H:m), dimensional codes (d), scaling factors (S, s), * energy (E) if modeling program input, internal registry number (R) * if input through MDL form. * A blank line can be substituted for line 2. */ writer.Write(" CDK "); //UPGRADE_ISSUE: Constructor 'java.text.SimpleDateFormat.SimpleDateFormat' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javatextSimpleDateFormat'" //UPGRADE_TODO: The equivalent in .NET for method 'java.util.Calendar.getTime' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" System.TimeZone generatedAux3 = System.TimeZone.CurrentTimeZone; //writer.Write(SupportClass.FormatDateTime(new SimpleDateFormat("M/d/y,H:m", new System.Globalization.CultureInfo("en-US")), SupportClass.CalendarManager.manager.GetDateTime(new System.Globalization.GregorianCalendar()))); writer.Write('\n'); System.String comment = (System.String)container.getProperty(CDKConstants.REMARK); if (comment == null) { comment = ""; } if (comment.Length > 80) { comment = comment.Substring(0, (80) - (0)); } writer.Write(comment + "\n"); // write Counts line int upToWhichAtom = 0; for (int i = 0; i < isVisible.Length; i++) { if (isVisible[i]) { upToWhichAtom++; } } line += formatMDLInt(upToWhichAtom, 3); int numberOfBonds = 0; if (upToWhichAtom < container.AtomCount) { for (int i = 0; i < container.getBondCount(); i++) { if (isVisible[container.getAtomNumber(container.getBondAt(i).getAtoms()[0])] && isVisible[container.getAtomNumber(container.getBondAt(i).getAtoms()[1])]) { numberOfBonds++; } } } else { numberOfBonds = container.getBondCount(); } line += formatMDLInt(numberOfBonds, 3); line += " 0 0 0 0 0 0 0 0999 V2000\n"; writer.Write(line); // write Atom block IAtom[] atoms = container.Atoms; for (int f = 0; f < atoms.Length; f++) { if (isVisible[f]) { IAtom atom = atoms[f]; line = ""; if (atom.getPoint3d() != null) { //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'" line += formatMDLFloat((float)atom.X3d); //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'" line += formatMDLFloat((float)atom.Y3d); //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'" line += (formatMDLFloat((float)atom.Z3d) + " "); } else if (atom.getPoint2d() != null) { //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'" line += formatMDLFloat((float)atom.X2d); //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'" line += formatMDLFloat((float)atom.Y2d); line += " 0.0000 "; } else { // if no coordinates available, then output a number // of zeros line += formatMDLFloat((float)0.0); line += formatMDLFloat((float)0.0); line += (formatMDLFloat((float)0.0) + " "); } if (container.getAtomAt(f) is IPseudoAtom) { line += formatMDLString(((IPseudoAtom)container.getAtomAt(f)).Label, 3); } else { line += formatMDLString(container.getAtomAt(f).Symbol, 3); } line += " 0 0 0 0 0 0 0 0 0 0 0 0"; writer.Write(line); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } // write Bond block IBond[] bonds = container.Bonds; for (int g = 0; g < bonds.Length; g++) { if (upToWhichAtom == container.AtomCount || (isVisible[container.getAtomNumber(container.getBondAt(g).getAtoms()[0])] && isVisible[container.getAtomNumber(container.getBondAt(g).getAtoms()[1])])) { IBond bond = bonds[g]; if (bond.getAtoms().Length != 2) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //logger.warn("Skipping bond with more/less than two atoms: " + bond); } else { if (bond.Stereo == CDKConstants.STEREO_BOND_UP_INV || bond.Stereo == CDKConstants.STEREO_BOND_DOWN_INV) { // turn around atom coding to correct for inv stereo line = formatMDLInt(container.getAtomNumber(bond.getAtomAt(1)) + 1, 3); line += formatMDLInt(container.getAtomNumber(bond.getAtomAt(0)) + 1, 3); } else { line = formatMDLInt(container.getAtomNumber(bond.getAtomAt(0)) + 1, 3); line += formatMDLInt(container.getAtomNumber(bond.getAtomAt(1)) + 1, 3); } //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'" line += formatMDLInt((int)bond.Order, 3); line += " "; switch (bond.Stereo) { case CDKConstants.STEREO_BOND_UP: line += "1"; break; case CDKConstants.STEREO_BOND_UP_INV: line += "1"; break; case CDKConstants.STEREO_BOND_DOWN: line += "6"; break; case CDKConstants.STEREO_BOND_DOWN_INV: line += "6"; break; default: line += "0"; break; } line += " 0 0 0 "; writer.Write(line); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } } // write formal atomic charges for (int i = 0; i < atoms.Length; i++) { IAtom atom = atoms[i]; int charge = atom.getFormalCharge(); if (charge != 0) { writer.Write("M CHG 1 "); writer.Write(formatMDLInt(i + 1, 3)); writer.Write(" "); writer.Write(formatMDLInt(charge, 3)); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } // write formal isotope information for (int i = 0; i < atoms.Length; i++) { IAtom atom = atoms[i]; if (!(atom is IPseudoAtom)) { int atomicMass = atom.MassNumber; int majorMass = IsotopeFactory.getInstance(atom.Builder).getMajorIsotope(atom.Symbol).MassNumber; if (atomicMass != 0 && atomicMass != majorMass) { writer.Write("M ISO 1 "); writer.Write(formatMDLInt(i + 1, 3)); writer.Write(" "); writer.Write(formatMDLInt(atomicMass, 3)); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } } // close molecule writer.Write("M END"); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); //write sdfields, if any if (sdFields != null) { //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'CSGraphT.SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" CSGraphT.SupportClass.SetSupport set_Renamed = new CSGraphT.SupportClass.HashSetSupport(sdFields.Keys); System.Collections.IEnumerator iterator = set_Renamed.GetEnumerator(); //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' 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_javautilIteratorhasNext'" while (iterator.MoveNext()) { //UPGRADE_TODO: Method 'java.util.Iterator.next' 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_javautilIteratornext'" System.Object element = iterator.Current; writer.Write("> <" + ((System.String)element) + ">"); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" writer.Write(sdFields[element].ToString()); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } // taking care of the $$$$ signs: // we write such a sign at the end of all except the first molecule if (moleculeNumber != 1) { writer.Write("$$$$"); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } moleculeNumber++; writer.Flush(); }
/// <summary> Writes a Molecule to an OutputStream in MDL sdf format. /// /// </summary> /// <param name="container"> Molecule that is written to an OutputStream /// </param> /// <param name="isVisible">Should a certain atom be written to mdl? /// </param> public virtual void writeMolecule(IMolecule container, bool[] isVisible) { System.String line = ""; // taking care of the $$$$ signs: // we do not write such a sign at the end of the first molecule, thus we have to write on BEFORE the second molecule if (moleculeNumber == 2) { writer.Write("$$$$"); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } // write header block // lines get shortened to 80 chars, that's in the spec System.String title = (System.String)container.getProperty(CDKConstants.TITLE); if (title == null) title = ""; if (title.Length > 80) title = title.Substring(0, (80) - (0)); writer.Write(title + "\n"); /* From CTX spec * This line has the format: * IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR * (FORTRAN: A2<--A8--><---A10-->A2I2<--F10.5-><---F12.5--><-I6-> ) * User's first and last initials (l), program name (P), * date/time (M/D/Y,H:m), dimensional codes (d), scaling factors (S, s), * energy (E) if modeling program input, internal registry number (R) * if input through MDL form. * A blank line can be substituted for line 2. */ writer.Write(" CDK "); //UPGRADE_ISSUE: Constructor 'java.text.SimpleDateFormat.SimpleDateFormat' was not converted. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1000_javatextSimpleDateFormat'" //UPGRADE_TODO: The equivalent in .NET for method 'java.util.Calendar.getTime' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" System.TimeZone generatedAux3 = System.TimeZone.CurrentTimeZone; //writer.Write(SupportClass.FormatDateTime(new SimpleDateFormat("M/d/y,H:m", new System.Globalization.CultureInfo("en-US")), SupportClass.CalendarManager.manager.GetDateTime(new System.Globalization.GregorianCalendar()))); writer.Write('\n'); System.String comment = (System.String)container.getProperty(CDKConstants.REMARK); if (comment == null) comment = ""; if (comment.Length > 80) comment = comment.Substring(0, (80) - (0)); writer.Write(comment + "\n"); // write Counts line int upToWhichAtom = 0; for (int i = 0; i < isVisible.Length; i++) { if (isVisible[i]) upToWhichAtom++; } line += formatMDLInt(upToWhichAtom, 3); int numberOfBonds = 0; if (upToWhichAtom < container.AtomCount) { for (int i = 0; i < container.getBondCount(); i++) { if (isVisible[container.getAtomNumber(container.getBondAt(i).getAtoms()[0])] && isVisible[container.getAtomNumber(container.getBondAt(i).getAtoms()[1])]) numberOfBonds++; } } else { numberOfBonds = container.getBondCount(); } line += formatMDLInt(numberOfBonds, 3); line += " 0 0 0 0 0 0 0 0999 V2000\n"; writer.Write(line); // write Atom block IAtom[] atoms = container.Atoms; for (int f = 0; f < atoms.Length; f++) { if (isVisible[f]) { IAtom atom = atoms[f]; line = ""; if (atom.getPoint3d() != null) { //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'" line += formatMDLFloat((float)atom.X3d); //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'" line += formatMDLFloat((float)atom.Y3d); //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'" line += (formatMDLFloat((float)atom.Z3d) + " "); } else if (atom.getPoint2d() != null) { //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'" line += formatMDLFloat((float)atom.X2d); //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'" line += formatMDLFloat((float)atom.Y2d); line += " 0.0000 "; } else { // if no coordinates available, then output a number // of zeros line += formatMDLFloat((float)0.0); line += formatMDLFloat((float)0.0); line += (formatMDLFloat((float)0.0) + " "); } if (container.getAtomAt(f) is IPseudoAtom) line += formatMDLString(((IPseudoAtom)container.getAtomAt(f)).Label, 3); else line += formatMDLString(container.getAtomAt(f).Symbol, 3); line += " 0 0 0 0 0 0 0 0 0 0 0 0"; writer.Write(line); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } // write Bond block IBond[] bonds = container.Bonds; for (int g = 0; g < bonds.Length; g++) { if (upToWhichAtom == container.AtomCount || (isVisible[container.getAtomNumber(container.getBondAt(g).getAtoms()[0])] && isVisible[container.getAtomNumber(container.getBondAt(g).getAtoms()[1])])) { IBond bond = bonds[g]; if (bond.getAtoms().Length != 2) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //logger.warn("Skipping bond with more/less than two atoms: " + bond); } else { if (bond.Stereo == CDKConstants.STEREO_BOND_UP_INV || bond.Stereo == CDKConstants.STEREO_BOND_DOWN_INV) { // turn around atom coding to correct for inv stereo line = formatMDLInt(container.getAtomNumber(bond.getAtomAt(1)) + 1, 3); line += formatMDLInt(container.getAtomNumber(bond.getAtomAt(0)) + 1, 3); } else { line = formatMDLInt(container.getAtomNumber(bond.getAtomAt(0)) + 1, 3); line += formatMDLInt(container.getAtomNumber(bond.getAtomAt(1)) + 1, 3); } //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'" line += formatMDLInt((int)bond.Order, 3); line += " "; switch (bond.Stereo) { case CDKConstants.STEREO_BOND_UP: line += "1"; break; case CDKConstants.STEREO_BOND_UP_INV: line += "1"; break; case CDKConstants.STEREO_BOND_DOWN: line += "6"; break; case CDKConstants.STEREO_BOND_DOWN_INV: line += "6"; break; default: line += "0"; break; } line += " 0 0 0 "; writer.Write(line); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } } // write formal atomic charges for (int i = 0; i < atoms.Length; i++) { IAtom atom = atoms[i]; int charge = atom.getFormalCharge(); if (charge != 0) { writer.Write("M CHG 1 "); writer.Write(formatMDLInt(i + 1, 3)); writer.Write(" "); writer.Write(formatMDLInt(charge, 3)); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } // write formal isotope information for (int i = 0; i < atoms.Length; i++) { IAtom atom = atoms[i]; if (!(atom is IPseudoAtom)) { int atomicMass = atom.MassNumber; int majorMass = IsotopeFactory.getInstance(atom.Builder).getMajorIsotope(atom.Symbol).MassNumber; if (atomicMass != 0 && atomicMass != majorMass) { writer.Write("M ISO 1 "); writer.Write(formatMDLInt(i + 1, 3)); writer.Write(" "); writer.Write(formatMDLInt(atomicMass, 3)); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } } // close molecule writer.Write("M END"); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); //write sdfields, if any if (sdFields != null) { //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'CSGraphT.SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" CSGraphT.SupportClass.SetSupport set_Renamed = new CSGraphT.SupportClass.HashSetSupport(sdFields.Keys); System.Collections.IEnumerator iterator = set_Renamed.GetEnumerator(); //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' 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_javautilIteratorhasNext'" while (iterator.MoveNext()) { //UPGRADE_TODO: Method 'java.util.Iterator.next' 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_javautilIteratornext'" System.Object element = iterator.Current; writer.Write("> <" + ((System.String)element) + ">"); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" writer.Write(sdFields[element].ToString()); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } } // taking care of the $$$$ signs: // we write such a sign at the end of all except the first molecule if (moleculeNumber != 1) { writer.Write("$$$$"); //UPGRADE_TODO: Method 'java.io.BufferedWriter.newLine' was converted to 'System.IO.TextWriter.WriteLine' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'" writer.WriteLine(); } moleculeNumber++; writer.Flush(); }
/// <summary> Generate canonical SMILES from the <code>molecule</code>. This method /// canonicaly lables the molecule but does not perform any checks on the /// chemical validity of the molecule. /// IMPORTANT: A precomputed Set of All Rings (SAR) can be passed to this /// SmilesGenerator in order to avoid recomputing it. Use setRings() to /// assign the SAR. /// /// </summary> /// <param name="molecule"> The molecule to evaluate /// </param> /// <returns> Description of the Returned Value /// </returns> /// <seealso cref="org.openscience.cdk.graph.invariant.CanonicalLabeler.canonLabel(IAtomContainer)"> /// </seealso> //UPGRADE_NOTE: Synchronized keyword was removed from method 'createSMILES'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'" public virtual System.String createSMILES(IMolecule molecule) { lock (this) { try { return (createSMILES(molecule, false, new bool[molecule.getBondCount()])); } catch (CDKException exception) { // This exception can only happen if a chiral smiles is requested return (""); } } }
/// <summary> Method that saturates a molecule by adding explicit hydrogens. /// In order to get coordinates for these Hydrogens, you need to /// remember the average bondlength of you molecule (coordinates for /// all atoms should be available) by using /// double bondLength = GeometryTools.getBondLengthAverage(atomContainer); /// and then use this method here and then use /// org.openscience.cdk.HydrogenPlacer(atomContainer, bondLength); /// /// </summary> /// <param name="molecule"> Molecule to saturate /// </param> /// <cdk.keyword> hydrogen, adding </cdk.keyword> /// <cdk.keyword> explicit hydrogen </cdk.keyword> public virtual IAtomContainer addExplicitHydrogensToSatisfyValency(IMolecule molecule) { //logger.debug("Start of addExplicitHydrogensToSatisfyValency"); ISetOfMolecules moleculeSet = ConnectivityChecker.partitionIntoMolecules(molecule); IMolecule[] molecules = moleculeSet.Molecules; IAtomContainer changedAtomsAndBonds = molecule.Builder.newAtomContainer(); IAtomContainer intermediateContainer = null; for (int k = 0; k < molecules.Length; k++) { IMolecule molPart = molecules[k]; IAtom[] atoms = molPart.Atoms; for (int i = 0; i < atoms.Length; i++) { intermediateContainer = addHydrogensToSatisfyValency(molPart, atoms[i], molecule); changedAtomsAndBonds.add(intermediateContainer); } } //logger.debug("End of addExplicitHydrogensToSatisfyValency"); return changedAtomsAndBonds; }
/// <summary> Generate canonical and chiral SMILES from the <code>molecule</code>. This /// method canonicaly lables the molecule but dose not perform any checks on /// the chemical validity of the molecule. The chiral smiles is done like in /// the <a href="http://www.daylight.com/dayhtml/doc/theory/theory.smiles.html"> /// daylight theory manual</a> . I did not find rules for canonical and chiral /// smiles, therefore there is no guarantee that the smiles complies to any /// externeal rules, but it is canonical compared to other smiles produced by /// this method. The method checks if there are 2D coordinates but does not /// check if coordinates make sense. Invalid stereo configurations are ignored; /// if there are no valid stereo configuration the smiles will be the same as /// the non-chiral one. Note that often stereo configurations are only complete /// and can be converted to a smiles if explicit Hs are given. /// IMPORTANT: A precomputed Set of All Rings (SAR) can be passed to this /// SmilesGenerator in order to avoid recomputing it. Use setRings() to /// assign the SAR. /// /// </summary> /// <param name="molecule"> The molecule to evaluate /// </param> /// <param name="doubleBondConfiguration"> Description of Parameter /// </param> /// <returns> Description of the Returned Value /// </returns> /// <exception cref="CDKException"> At least one atom has no Point2D; /// coordinates are needed for creating the chiral smiles. /// </exception> /// <seealso cref="org.openscience.cdk.graph.invariant.CanonicalLabeler.canonLabel(IAtomContainer)"> /// </seealso> //UPGRADE_NOTE: Synchronized keyword was removed from method 'createChiralSMILES'. Lock expression was added. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1027'" public virtual System.String createChiralSMILES(IMolecule molecule, bool[] doubleBondConfiguration) { lock (this) { return (createSMILES(molecule, true, doubleBondConfiguration)); } }
/// <summary> Returns the stoichiometry coefficient of the given product. /// /// </summary> /// <param name="product">Product for which the coefficient is returned. /// </param> /// <returns> -1, if the given molecule is not a product in this Reaction /// </returns> /// <seealso cref="setProductCoefficient"> /// </seealso> public virtual double getProductCoefficient(IMolecule product) { return products.getMultiplier(product); }
/// <summary> Adds a product to this reaction. /// /// </summary> /// <param name="product"> Molecule added as product to this reaction /// </param> /// <seealso cref="getProducts"> /// </seealso> public virtual void addProduct(IMolecule product) { this.addProduct(product, 1.0); /* notifyChanged() is called by addProduct(Molecule product, double coefficient)*/ }
/// <summary> Sets the coefficient of a a reactant to a given value. /// /// </summary> /// <param name="reactant"> Reactant for which the coefficient is set /// </param> /// <param name="coefficient">The new coefficient for the given reactant /// </param> /// <returns> true if Molecule has been found and stoichiometry has been set. /// </returns> /// <seealso cref="getReactantCoefficient"> /// </seealso> public virtual bool setReactantCoefficient(IMolecule reactant, double coefficient) { notifyChanged(); return reactants.setMultiplier(reactant, coefficient); }
private IMolecule readMolecule(IMolecule molecule) { JmolAdapter adapter = new SmarterJmolAdapter(); // note that it actually let's the adapter detect the format! System.Object model = adapter.openBufferedReader("", input); molecule.add(new Convertor(molecule.Builder).convert(model)); return molecule; }