Ejemplo n.º 1
0
        public static void MakeCanonicalSmileFromRingSystems(string dataFileIn, string dataFileOut)
        {
            Console.Out.WriteLine("Start make SMILES...");
            var data   = new List <string>();
            var smiles = new SmilesGenerator();

            try
            {
                Console.Out.WriteLine("Start...");
                using (var imdl = new EnumerableSDFReader(new StreamReader(dataFileIn), builder))
                {
                    Console.Out.WriteLine("Read File in..");

                    foreach (var m in imdl)
                    {
                        try
                        {
                            data.Add((string)smiles.Create(builder.NewAtomContainer(m)));
                        }
                        catch (Exception exc1)
                        {
                            if (!(exc1 is CDKException || exc1 is IOException))
                            {
                                throw;
                            }
                            Console.Out.WriteLine("Could not create smile due to: " + exc1.Message);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Console.Out.WriteLine("Could not read Molecules from file " + dataFileIn + " due to: " + exc.Message);
            }

            Console.Out.Write("...ready\nWrite data...");
            try
            {
                using (var fout = new StreamWriter(dataFileOut))
                {
                    for (int i = 0; i < data.Count; i++)
                    {
                        try
                        {
                            fout.Write(((string)data[i]));
                            fout.WriteLine();
                        }
                        catch (Exception)
                        {
                        }
                    }
                    Console.Out.WriteLine($"number of smiles: {data.Count}");
                }
            }
            catch (Exception exc3)
            {
                Console.Out.WriteLine($"Could not write smile in file {dataFileOut} due to: {exc3.Message}");
            }
            Console.Out.WriteLine("...ready");
        }
Ejemplo n.º 2
0
        //    private IAtomContainer CreateBenzaldehyde() {
        //        Molecule result = new DefaultMolecule();
        //        Atom c1 = result.Atoms.Add("C");
        //        Atom c2 = result.Atoms.Add("C");
        //        Atom c3 = result.Atoms.Add("C");
        //        Atom c4 = result.Atoms.Add("C");
        //        Atom c5 = result.Atoms.Add("C");
        //        Atom c6 = result.Atoms.Add("C");
        //        Atom c7 = result.Atoms.Add("C");
        //        Atom o8 = result.Atoms.Add("O");
        //
        //        result.Connect(c1, c2, 1);
        //        result.Connect(c2, c3, 2);
        //        result.Connect(c3, c4, 1);
        //        result.Connect(c4, c5, 2);
        //        result.Connect(c5, c6, 1);
        //        result.Connect(c6, c1, 2);
        //        result.Connect(c7, c1, 1);
        //        result.Connect(c7, o8, 2);
        //
        //        return result;
        //    }
        //
        //    private IAtomContainer CreateBenzoicAcid() {
        //        Molecule result = CreateBenzaldehyde();
        //
        //        result.Connect(result.Atoms[6], result.Atoms.Add("O"), 1);
        //
        //        return result;
        //    }
        //
        //    private IAtomContainer CreateBlockedBenzaldehyde() {
        //        Molecule result = CreateBenzaldehyde();
        //
        //        result.Connect(result.Atoms[6], result.Atoms.Add("H"), 1);
        //
        //        return result;
        //    }
        //    private Molecule Create4Toluene() {
        //        Molecule result = new DefaultMolecule();
        //        Atom c1 = result.Atoms.Add("C");
        //        Atom c2 = result.Atoms.Add("C");
        //        Atom c3 = result.Atoms.Add("C");
        //        Atom c4 = result.Atoms.Add("C");
        //        Atom c5 = result.Atoms.Add("C");
        //        Atom c6 = result.Atoms.Add("C");
        //        Atom c7 = result.Atoms.Add("C");
        //
        //        result.Connect(c1, c2, 1);
        //        result.Connect(c2, c3, 2);
        //        result.Connect(c3, c4, 1);
        //        result.Connect(c4, c5, 2);
        //        result.Connect(c5, c6, 1);
        //        result.Connect(c6, c1, 2);
        //        result.Connect(c7, c4, 1);
        //
        //        return result;
        //    }
        public static IAtomContainer CreateSimpleImine()
        {
            IAtomContainer result = builder.NewAtomContainer();

            IAtom c1 = builder.NewAtom("C");
            IAtom c2 = builder.NewAtom("N");

            result.Atoms.Add(c1);
            result.Atoms.Add(c2);

            IBond bond = builder.NewBond(c1, c2, BondOrder.Double);

            result.Bonds.Add(bond);

            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(result);
            var adder = CDK.HydrogenAdder;

            adder.AddImplicitHydrogens(result);
            Aromaticity.CDKLegacy.Apply(result);

            SmilesGenerator sg        = new SmilesGenerator();
            string          oldSmiles = sg.Create(result);

            Console.Out.WriteLine("SimpleImine " + oldSmiles);

            return(result);
        }
Ejemplo n.º 3
0
        public void TestSplit()
        {
            var          mol       = smilesParser.ParseSmiles("C1CC1C2CCC2");
            SpanningTree st        = new SpanningTree(mol);
            IRingSet     rings     = st.GetAllRings();
            IBond        splitBond = null;

            for (int i = 0; i < mol.Bonds.Count; i++)
            {
                if (rings.GetRings(mol.Bonds[i]).Count() == 0)
                {
                    splitBond = mol.Bonds[i];
                    break;
                }
            }
            var             frags       = FragmentUtils.SplitMolecule(mol, splitBond);
            SmilesGenerator sg          = new SmilesGenerator();
            var             uniqueFrags = new HashSet <string>();

            foreach (var frag in frags)
            {
                uniqueFrags.Add(sg.Create(frag));
            }
            Assert.AreEqual(2, uniqueFrags.Count);
            // You can put the fragments back together with a ring closure and dot
            // [CH]12CC1.[CH]12CCC1
            Assert.IsTrue(uniqueFrags.IsSupersetOf(new[] { "[CH]1CC1", "[CH]1CCC1" }));
        }
Ejemplo n.º 4
0
        public void TestTermination()
        {
            int ringSize = 7;
            var ring     = builder.NewAtomContainer();

            for (int i = 0; i < ringSize; i++)
            {
                ring.Atoms.Add(builder.NewAtom("C"));
            }
            for (int j = 0; j < ringSize - 1; j++)
            {
                ring.AddBond(ring.Atoms[j], ring.Atoms[j + 1], BondOrder.Single);
            }
            ring.AddBond(ring.Atoms[ringSize - 1], ring.Atoms[0], BondOrder.Single);

            ring.Atoms.Add(builder.NewAtom("Cl"));
            ring.Atoms.Add(builder.NewAtom("F"));
            ring.AddBond(ring.Atoms[0], ring.Atoms[ringSize], BondOrder.Single);
            ring.AddBond(ring.Atoms[0], ring.Atoms[ringSize + 1], BondOrder.Single);
            ring.Atoms.Add(builder.NewAtom("O"));
            ring.AddBond(ring.Atoms[1], ring.Atoms[ringSize + 2], BondOrder.Single);
            var atoms        = new IAtom[] { ring.Atoms[ringSize], ring.Atoms[ringSize + 1], ring.Atoms[ringSize - 1], ring.Atoms[1] };
            var stereoCenter = new TetrahedralChirality(ring.Atoms[0], atoms, TetrahedralStereo.AntiClockwise);

            ring.StereoElements.Add(stereoCenter);
            SmilesGenerator generator = new SmilesGenerator();

            CIPTool.GetCIPChirality(ring, stereoCenter);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Writes the content from molecule to output.
        /// </summary>
        /// <param name="molecule">Molecule of which the data is given as output.</param>
        public void WriteAtomContainer(IAtomContainer molecule)
        {
            SmilesGenerator sg = new SmilesGenerator();

            if (useAromaticityFlag.IsSet)
            {
                sg = sg.Aromatic();
            }
            string smiles = "";

            try
            {
                smiles = sg.Create(molecule);
                Debug.WriteLine($"Generated SMILES: {smiles}");
                writer.Write(smiles);
                writer.Write('\n');
                writer.Flush();
                Debug.WriteLine("file flushed...");
            }
            catch (Exception exc)
            {
                if (exc is CDKException | exc is IOException)
                {
                    Trace.TraceError($"Error while writing Molecule: {exc.Message}");
                    Debug.WriteLine(exc);
                }
                else
                {
                    throw;
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Method assigns certain properties to an atom. Necessary for the atom type matching
        /// Properties:
        /// <list type="bullet">
        ///   <item>aromaticity</item>
        ///   <item>ChemicalGroup (CDKChemicalRingGroupConstant)</item>
        ///   <item>
        ///     <item>SSSR</item>
        ///     <item>Ring/Group, ringSize, aromaticity</item>
        ///     <item>SphericalMatcher (HoSe Code)</item>
        ///   </item>
        /// </list>
        /// </summary>
        /// <param name="molecule"></param>
        /// <param name="aromaticity"><see langword="true"/> if aromaticity should be calculated</param>
        /// <returns>sssrf ring set of the molecule</returns>
        public static IRingSet AssignAtomTypePropertiesToAtom(IAtomContainer molecule, bool aromaticity)
        {
            var sg = new SmilesGenerator();

            Debug.WriteLine("assignAtomTypePropertiesToAtom Start ...");
            string hoseCode        = "";
            var    ringSetMolecule = Cycles.FindSSSR(molecule).ToRingSet();

            Debug.WriteLine(ringSetMolecule);

            if (aromaticity)
            {
                try
                {
                    Aromaticity.CDKLegacy.Apply(molecule);
                }
                catch (Exception cdk1)
                {
                    Trace.TraceError($"AROMATICITYError: Cannot determine aromaticity due to: {cdk1.ToString()}");
                }
            }

            for (int i = 0; i < molecule.Atoms.Count; i++)
            {
                // FIXME: remove casting
                var atom2 = molecule.Atoms[i];
                //Atom aromatic is set by HueckelAromaticityDetector
                //Atom in ring?
                if (ringSetMolecule.Contains(atom2))
                {
                    var ringSetA = ringSetMolecule.Builder.NewRingSet();
                    ringSetA.AddRange(ringSetMolecule.GetRings(atom2));
                    RingSetManipulator.Sort(ringSetA);
                    var sring = ringSetA.Last();
                    atom2.SetProperty(CDKPropertyName.PartOfRingOfSize, sring.RingSize);
                    atom2.SetProperty(
                        CDKPropertyName.ChemicalGroupConstant,
                        RingSystemClassifier(sring, GetSubgraphSmiles(sring, molecule)));
                    atom2.IsInRing    = true;
                    atom2.IsAliphatic = false;
                }
                else
                {
                    atom2.SetProperty(CDKPropertyName.ChemicalGroupConstant, NotInRing);
                    atom2.IsInRing    = false;
                    atom2.IsAliphatic = true;
                }
                try
                {
                    hoseCode = hcg.GetHOSECode(molecule, atom2, 3);
                    hoseCode = RemoveAromaticityFlagsFromHoseCode(hoseCode);
                    atom2.SetProperty(CDKPropertyName.SphericalMatcher, hoseCode);
                }
                catch (CDKException ex1)
                {
                    throw new CDKException($"Could not build HOSECode from atom {i} due to {ex1.ToString()}", ex1);
                }
            }
            return(ringSetMolecule);
        }
Ejemplo n.º 7
0
        public void InliningReactionsWithRadicals()
        {
            IChemObjectBuilder bldr     = ChemObjectBuilder.Instance;
            SmilesParser       smipar   = new SmilesParser(bldr);
            IReaction          reaction = smipar.ParseReactionSmiles("[CH2]CO.CC(=O)O>[H+]>CCOC(=O)C.O |^1:0| ethyl esterification");
            SmilesGenerator    smigen   = new SmilesGenerator(SmiFlavors.CxSmiles);
            // convert to molecule
            IAtomContainer mol = ReactionManipulator.ToMolecule(reaction);

            Assert.AreEqual("[CH2]CO.CC(=O)O.[H+].CCOC(=O)C.O |^1:0|", smigen.Create(mol));
            Assert.AreEqual("[CH2]CO.CC(=O)O>[H+]>CCOC(=O)C.O |^1:0|", smigen.CreateReactionSMILES(ReactionManipulator.ToReaction(mol)));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Generate Smiles
        /// </summary>
        /// <param name="mol"></param>
        /// <param name="flags"></param>
        /// <returns></returns>
        public static String AtomContainerToSmiles(
            IAtomContainer mol,
            SmilesGeneratorType flags)
        {
            ApplyAromaticity(mol);

            SmilesGenerator sg = null;

            if ((flags & SmilesGeneratorType.Generic) != 0)
            {
                sg = SmilesGenerator.generic();
            }

            else if ((flags & SmilesGeneratorType.Isomeric) != 0)
            {
                sg = SmilesGenerator.isomeric();
            }

            else if ((flags & SmilesGeneratorType.Unique) != 0)
            {
                sg = SmilesGenerator.unique();
            }

            else if ((flags & SmilesGeneratorType.Absolute) != 0)
            {
                sg = SmilesGenerator.unique();
            }

            else
            {
                throw new Exception("Canonical/Stereo/Isotop types not defined");
            }

            if ((flags & SmilesGeneratorType.NotAromatic) != 0)
            {
            }                                                                   // not aromatic
            else
            {
                sg = sg.aromatic();              // aromatic by default even if not specified
            }
            if ((flags & SmilesGeneratorType.WithAtomClasses) != 0)
            {
                sg = sg.withAtomClasses();
            }

            string smiles = sg.create(mol);

            return(smiles);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Instantiate Murcko fragmenter.
        /// </summary>
        /// <param name="singleFrameworkOnly">if <see langword="true"/>, only the true Murcko framework is generated.</param>
        /// <param name="minimumFragmentSize">the smallest size of fragment to consider</param>
        /// <param name="generator">An instance of a <see cref="IMoleculeHashGenerator"/> to be used to check for duplicate fragments</param>
        public MurckoFragmenter(bool singleFrameworkOnly, int minimumFragmentSize, IMoleculeHashGenerator generator)
        {
            this.singleFrameworkOnly = singleFrameworkOnly;
            this.minimumFragmentSize = minimumFragmentSize;

            if (generator == null)
            {
                this.generator = new HashGeneratorMaker().Depth(8).Elemental().Isotopic().Charged().Orbital().Molecular();
            }
            else
            {
                this.generator = generator;
            }

            smigen = SmilesGenerator.Unique.Aromatic();
        }
Ejemplo n.º 10
0
        public void TestIndoleAgainstItself()
        {
            IAtomContainer indole = TestMoleculeFactory.MakeIndole();

            AddImplicitHydrogens(indole);
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(indole);
            Aromaticity.CDKLegacy.Apply(indole);
            SmilesGenerator generator    = new SmilesGenerator().Aromatic();
            string          indoleSmiles = generator.Create(indole);
            var             smilesParser = CDK.SmilesParser;

            indole = smilesParser.ParseSmiles(indoleSmiles);

            SMARTSQueryTool querytool = new SMARTSQueryTool(indoleSmiles, ChemObjectBuilder.Instance);

            Assert.IsTrue(querytool.Matches(indole));
        }
Ejemplo n.º 11
0
        /// <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);
            }
        }
Ejemplo n.º 12
0
        public static void ExtractUniqueRingSystemsFromFile(string dataFile)
        {
            Console.Out.WriteLine("****** EXTRACT UNIQUE RING SYSTEMS ******");
            Console.Out.WriteLine($"From file: {dataFile}");

            Dictionary <string, string> hashRingSystems = new Dictionary <string, string>();
            SmilesGenerator             smilesGenerator = new SmilesGenerator();

            int            counterRings       = 0;
            int            counterMolecules   = 0;
            int            counterUniqueRings = 0;
            IRingSet       ringSet            = null;
            string         key = "";
            IAtomContainer ac  = null;

            string molfile = dataFile + "_UniqueRings";

            try
            {
                using (var fout = new FileStream(molfile, FileMode.Create))
                    using (var mdlw = new MDLV2000Writer(fout))
                    {
                        try
                        {
                            Console.Out.WriteLine("Start...");
                            using (var fin = new StreamReader(dataFile))
                                using (var imdl = new EnumerableSDFReader(fin, builder))
                                {
                                    Console.Out.WriteLine("Read File in..");

                                    foreach (var m in imdl)
                                    {
                                        counterMolecules = counterMolecules + 1;

                                        IRingSet ringSetM = Cycles.FindSSSR(m).ToRingSet();

                                        if (counterMolecules % 1000 == 0)
                                        {
                                            Console.Out.WriteLine("Molecules:" + counterMolecules);
                                        }

                                        if (ringSetM.Count > 0)
                                        {
                                            var ringSystems = RingPartitioner.PartitionRings(ringSetM);

                                            for (int i = 0; i < ringSystems.Count; i++)
                                            {
                                                ringSet = (IRingSet)ringSystems[i];
                                                ac      = builder.NewAtomContainer();
                                                var containers = RingSetManipulator.GetAllAtomContainers(ringSet);
                                                foreach (var container in containers)
                                                {
                                                    ac.Add(container);
                                                }
                                                counterRings = counterRings + 1;
                                                // Only connection is important
                                                for (int j = 0; j < ac.Atoms.Count; j++)
                                                {
                                                    (ac.Atoms[j]).Symbol = "C";
                                                }

                                                try
                                                {
                                                    key = smilesGenerator.Create(builder.NewAtomContainer(ac));
                                                }
                                                catch (CDKException e)
                                                {
                                                    Trace.TraceError(e.Message);
                                                    return;
                                                }

                                                if (hashRingSystems.ContainsKey(key))
                                                {
                                                }
                                                else
                                                {
                                                    counterUniqueRings = counterUniqueRings + 1; hashRingSystems[key] = "1";
                                                    try
                                                    {
                                                        mdlw.Write(builder.NewAtomContainer(ac));
                                                    }
                                                    catch (Exception emdl)
                                                    {
                                                        if (!(emdl is ArgumentException || emdl is CDKException))
                                                        {
                                                            throw;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                        }
                        catch (Exception exc)
                        {
                            Console.Out.WriteLine($"Could not read Molecules from file {dataFile} due to: {exc.Message}");
                        }
                    }
            }
            catch (Exception ex2)
            {
                Console.Out.WriteLine($"IOError:cannot write file due to: {ex2.ToString()}");
            }
            Console.Out.WriteLine($"READY Molecules:{counterMolecules} RingSystems:{counterRings} UniqueRingsSystem:{counterUniqueRings}");
            Console.Out.WriteLine($"HashtableKeys:{hashRingSystems.Count}");
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Instantiate fragmenter with user specified minimum fragment size.
 /// </summary>
 /// <param name="minFragSize">the minimum fragment size desired</param>
 public ExhaustiveFragmenter(int minFragSize)
 {
     this.MinimumFragmentSize = minFragSize;
     fragMap         = new Dictionary <string, IAtomContainer>();
     smilesGenerator = SmilesGenerator.Unique.Aromatic();
 }
Ejemplo n.º 14
0
        public static string MolToSmiles(IAtomContainer mol)
        {
            var gen = new SmilesGenerator();

            return(gen.Create(mol));
        }