/// <summary> /// Method will return an appropriate reader for the provided format. Each reader is stored /// in a map, if no reader is available for the specified format a new reader is created. The /// <see cref="IChemObjectReader.ErrorHandler"/> and /// <see cref="IChemObjectReader.ReaderMode"/> are set. /// </summary> /// <param name="format">The format to obtain a reader for</param> /// <returns>instance of a reader appropriate for the provided format</returns> private ISimpleChemObjectReader GetReader(IChemFormat format, TextReader input) { ISimpleChemObjectReader reader; if (format is MDLV2000Format) { reader = new MDLV2000Reader(input); } else if (format is MDLV3000Format) { reader = new MDLV3000Reader(input); } else if (format is MDLFormat) { reader = new MDLReader(input); } else { throw new ArgumentException("Unexpected format: " + format); } reader.ErrorHandler = this.ErrorHandler; reader.ReaderMode = this.ReaderMode; if (currentFormat is MDLV2000Format) { reader.AddSettings(IOSettings.Settings); } return(reader); }
public void TestStabilityAfterRoundtrip() { var filename = "NCDK.Data.MDL.bug1014344-1.mol"; var ins = ResourceLoader.GetAsStream(filename); var reader = new MDLReader(ins, ChemObjectReaderMode.Strict); var mol1 = reader.Read(builder.NewAtomContainer()); AddImplicitHydrogens(mol1); var output = new StringWriter(); var cmlWriter = new CMLWriter(output); cmlWriter.Write(mol1); var cmlreader = new CMLReader(new MemoryStream(Encoding.UTF8.GetBytes(output.ToString()))); var mol2 = ((IChemFile)cmlreader.Read(builder.NewChemFile()))[0][0].MoleculeSet[0]; AddImplicitHydrogens(mol2); labeler.CanonLabel(mol1); labeler.CanonLabel(mol2); var atoms1 = mol1.Atoms.GetEnumerator(); var atoms2 = mol2.Atoms.GetEnumerator(); while (atoms1.MoveNext()) { atoms2.MoveNext(); var atom1 = atoms1.Current; var atom2 = atoms2.Current; Assert.AreEqual(atom1.GetProperty <long>(InvPair.CanonicalLabelPropertyKey), atom2.GetProperty <long>(InvPair.CanonicalLabelPropertyKey)); } }
/// <summary> /// Method will return an appropriate reader for the provided format. Each reader is stored /// in a map, if no reader is available for the specified format a new reader is created. The /// <see cref="IChemObjectReader.ErrorHandler"/> and /// <see cref="IChemObjectReader.ReaderMode"/> are set. /// </summary> /// <param name="format">The format to obtain a reader for</param> /// <returns>instance of a reader appropriate for the provided format</returns> private ISimpleChemObjectReader GetReader(IChemFormat format, TextReader input) { ISimpleChemObjectReader reader; switch (format) { case MDLV2000Format _: reader = new MDLV2000Reader(input); break; case MDLV3000Format _: reader = new MDLV3000Reader(input); break; case MDLFormat _: reader = new MDLReader(input); break; default: throw new ArgumentException($"Unexpected format: {format}"); } reader.ErrorHandler = this.ErrorHandler; reader.ReaderMode = this.ReaderMode; if (currentFormat is MDLV2000Format) { reader.AddSettings(IOSettings.Settings); } return(reader); }
/// <summary> /// Creates a new instance of MolHandler /// </summary> /// <param name="molFile">atomContainer file name</param> public MolHandler(string molFile, bool removeHydrogen, bool cleanMolecule) { MDLReader molRead = null; this.removeHydrogen = removeHydrogen; try { Stream readMolecule = null; readMolecule = new FileStream(molFile, FileMode.Open, FileAccess.Read); molRead = new MDLReader(new StreamReader(readMolecule)); this.atomContainer = (IAtomContainer)molRead.Read(new AtomContainer()); molRead.Close(); readMolecule.Close(); /* Remove Hydrogen by Asad */ if (removeHydrogen) { atomContainer = ExtAtomContainerManipulator.RemoveHydrogensExceptSingleAndPreserveAtomID(atomContainer); } if (cleanMolecule) { if (!IsPseudoAtoms()) { atomContainer = canonLabeler.GetCanonicalMolecule(atomContainer); } // percieve atoms, set valency etc ExtAtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(atomContainer); //Add implicit Hydrogens var adder = CDK.HydrogenAdder; adder.AddImplicitHydrogens(atomContainer); // figure out which atoms are in aromatic rings: Aromaticity.CDKLegacy.Apply(atomContainer); BondTools.MakeUpDownBonds(atomContainer); } } catch (IOException ex) { Debug.WriteLine(ex); } catch (CDKException e) { Console.Error.WriteLine(e); } finally { if (molRead != null) { try { molRead.Close(); } catch (IOException ioe) { Trace.TraceWarning("Couldn't close molReader: ", ioe.Message); Debug.WriteLine(ioe); } } } }
public void TestGetAllAtomContainers_IChemFile() { var filename = "NCDK.Data.MDL.prev2000.sd"; Trace.TraceInformation("Testing: " + filename); var ins = ResourceLoader.GetAsStream(filename); var reader = new MDLReader(ins, ChemObjectReaderMode.Strict); var chemFile = reader.Read(builder.NewChemFile()); Assert.IsNotNull(chemFile); var containersList = ChemFileManipulator.GetAllAtomContainers(chemFile).ToReadOnlyList(); Assert.AreEqual(2, containersList.Count); }
public void TestPiSystemWithCarbokation() { Trace.TraceInformation("Entering testPiSystemWithCarbokation."); IAtomContainer mol = null; var filename = "NCDK.Data.MDL.piSystemWithCarbokation.mol"; var ins = ResourceLoader.GetAsStream(filename); MDLReader reader = new MDLReader(ins); var chemFile = reader.Read(builder.NewChemFile()); mol = chemFile[0][0].MoleculeSet[0]; AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol); Aromaticity.CDKLegacy.Apply(mol); var acSet = ConjugatedPiSystemsDetector.Detect(mol); Assert.AreEqual(2, acSet.Count); IAtomContainer ac1 = acSet[0]; Assert.AreEqual(4, ac1.Atoms.Count); Assert.AreEqual(3, ac1.Bonds.Count); for (int i = 0; i < ac1.Atoms.Count; i++) { Assert.IsTrue(mol.Contains(ac1.Atoms[i])); } for (int i = 0; i < ac1.Bonds.Count; i++) { Assert.IsTrue(mol.Contains(ac1.Bonds[i])); } IAtomContainer ac2 = acSet[0]; Assert.AreEqual(4, ac2.Atoms.Count); Assert.AreEqual(3, ac2.Bonds.Count); for (int i = 0; i < ac2.Atoms.Count; i++) { Assert.IsTrue(mol.Contains(ac2.Atoms[i])); } for (int i = 0; i < ac2.Bonds.Count; i++) { Assert.IsTrue(mol.Contains(ac2.Bonds[i])); } }
/// <summary> /// Loads a molecule with two adamantanes and one cubane /// substructure and tests whether all are found. /// </summary> public void GetMappedSubstructures_IAtomContainer() { // Set up molecule reader var filename = "NCDK.Data.MDL.diadamantane-cubane.mol"; var ins = ResourceLoader.GetAsStream(filename); var molReader = new MDLReader(ins, ChemObjectReaderMode.Strict); // Read molecule var molecule = molReader.Read(builder.NewAtomContainer()); // Map templates var th = new TemplateHandler(); var mappedStructures = th.GetMappedSubstructures(molecule); // Do the Assert.assertion Assert.AreEqual(3, mappedStructures.Count, "3 mapped templates"); }
/// <summary> /// This one tests adding hydrogens to all atoms of a molecule and doing the /// layout for them. It is intended for visually checking the work of /// HydrogenPlacer, not to be run as a JUnit test. Thus the name without /// "test". /// </summary> public void VisualFullMolecule2DEvaluation() { var hydrogenPlacer = new HydrogenPlacer(); var filename = "NCDK.Data.MDL.reserpine.mol"; var ins = ResourceLoader.GetAsStream(filename); var reader = new MDLReader(ins, ChemObjectReaderMode.Strict); var chemFile = reader.Read(builder.NewChemFile()); var seq = chemFile[0]; var model = seq[0]; var mol = model.MoleculeSet[0]; var bondLength = GeometryUtil.GetBondLengthAverage(mol); Debug.WriteLine("Read Reserpine"); Debug.WriteLine("Starting addition of H's"); AddExplicitHydrogens(mol); Debug.WriteLine("ended addition of H's"); hydrogenPlacer.PlaceHydrogens2D(mol, bondLength); }
/// <summary> Read a Reaction from a file in MDL RXN format /// /// </summary> /// <returns> The Reaction that was read from the MDL file. /// </returns> private IReaction readReaction(IChemObjectBuilder builder) { IReaction reaction = builder.newReaction(); try { input.ReadLine(); // first line should be $RXN input.ReadLine(); // second line input.ReadLine(); // third line input.ReadLine(); // fourth line } catch (System.IO.IOException exception) { //logger.debug(exception); throw new CDKException("Error while reading header of RXN file", exception); } int reactantCount = 0; int productCount = 0; try { System.String countsLine = input.ReadLine(); /* this line contains the number of reactants and products */ SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(countsLine); reactantCount = System.Int32.Parse(tokenizer.NextToken()); //logger.info("Expecting " + reactantCount + " reactants in file"); productCount = System.Int32.Parse(tokenizer.NextToken()); //logger.info("Expecting " + productCount + " products in file"); } catch (System.Exception exception) { //logger.debug(exception); throw new CDKException("Error while counts line of RXN file", exception); } // now read the reactants try { for (int i = 1; i <= reactantCount; i++) { System.Text.StringBuilder molFile = new System.Text.StringBuilder(); input.ReadLine(); // announceMDLFileLine System.String molFileLine = ""; do { molFileLine = input.ReadLine(); molFile.Append(molFileLine); molFile.Append("\n"); } while (!molFileLine.Equals("M END")); // read MDL molfile content MDLReader reader = new MDLReader(new StreamReader(molFile.ToString())); IMolecule reactant = (IMolecule)reader.read(builder.newMolecule()); // add reactant reaction.addReactant(reactant); } } catch (CDKException exception) { // rethrow exception from MDLReader throw exception; } catch (System.Exception exception) { //logger.debug(exception); throw new CDKException("Error while reading reactant", exception); } // now read the products try { for (int i = 1; i <= productCount; i++) { System.Text.StringBuilder molFile = new System.Text.StringBuilder(); input.ReadLine(); // String announceMDLFileLine = System.String molFileLine = ""; do { molFileLine = input.ReadLine(); molFile.Append(molFileLine); molFile.Append("\n"); } while (!molFileLine.Equals("M END")); // read MDL molfile content MDLReader reader = new MDLReader(new StreamReader(molFile.ToString())); IMolecule product = (IMolecule)reader.read(builder.newMolecule()); // add reactant reaction.addProduct(product); } } catch (CDKException exception) { // rethrow exception from MDLReader throw exception; } catch (System.Exception exception) { //logger.debug(exception); throw new CDKException("Error while reading products", exception); } // now try to map things, if wanted //logger.info("Reading atom-atom mapping from file"); // distribute all atoms over two AtomContainer's IAtomContainer reactingSide = builder.newAtomContainer(); IMolecule[] molecules = reaction.Reactants.Molecules; for (int i = 0; i < molecules.Length; i++) { reactingSide.add(molecules[i]); } IAtomContainer producedSide = builder.newAtomContainer(); molecules = reaction.Products.Molecules; for (int i = 0; i < molecules.Length; i++) { producedSide.add(molecules[i]); } // map the atoms int mappingCount = 0; IAtom[] reactantAtoms = reactingSide.Atoms; IAtom[] producedAtoms = producedSide.Atoms; for (int i = 0; i < reactantAtoms.Length; i++) { for (int j = 0; j < producedAtoms.Length; j++) { if (reactantAtoms[i].ID != null && reactantAtoms[i].ID.Equals(producedAtoms[j].ID)) { reaction.addMapping(builder.newMapping(reactantAtoms[i], producedAtoms[j])); mappingCount++; break; } } } //logger.info("Mapped atom pairs: " + mappingCount); return reaction; }