public void Ctor()
 {
     {
         #region 1
         IAtomContainer methane = new AtomContainer();
         IAtom          carbon  = new Atom("C");
         methane.Atoms.Add(carbon);
         CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance();
         foreach (var atom in methane.Atoms)
         {
             IAtomType type = matcher.FindMatchingAtomType(methane, atom);
             AtomTypeManipulator.Configure(atom, type);
         }
         var adder = CDK.HydrogenAdder;
         adder.AddImplicitHydrogens(methane);
         #endregion
     }
     {
         #region 2
         IAtomContainer ethane  = new AtomContainer();
         IAtom          carbon1 = new Atom("C");
         IAtom          carbon2 = new Atom("C");
         ethane.Atoms.Add(carbon1);
         ethane.Atoms.Add(carbon2);
         CDKAtomTypeMatcher matcher = CDKAtomTypeMatcher.GetInstance();
         IAtomType          type    = matcher.FindMatchingAtomType(ethane, carbon1);
         AtomTypeManipulator.Configure(carbon1, type);
         var adder = CDK.HydrogenAdder;
         adder.AddImplicitHydrogens(ethane, carbon1);
         #endregion
     }
 }
        /// <summary>
        /// Calculates the topological polar surface area and expresses it as a ratio to molecule size.
        /// </summary>
        /// <returns>Descriptor(s) retaining to polar surface area</returns>
        public Result Calculate(IAtomContainer container)
        {
            container = (IAtomContainer)container.Clone();

            // type & assign implicit hydrogens
            var matcher = CDK.AtomTypeMatcher;

            foreach (var atom in container.Atoms)
            {
                var type = matcher.FindMatchingAtomType(container, atom);
                AtomTypeManipulator.Configure(atom, type);
            }
            var adder = CDK.HydrogenAdder;

            adder.AddImplicitHydrogens(container);

            double polar  = 0;
            double weight = 0;

            // polar surface area: chain it off the TPSADescriptor
            var tpsa  = new TPSADescriptor();
            var value = tpsa.Calculate(container);

            polar = value.Value;

            //  molecular weight
            foreach (var atom in container.Atoms)
            {
                weight += CDK.IsotopeFactory.GetMajorIsotope(atom.Symbol).ExactMass.Value;
                weight += (atom.ImplicitHydrogenCount ?? 0) * 1.00782504;
            }

            return(new Result(weight == 0 ? 0 : polar / weight));
        }
示例#3
0
        public Result Calculate(IAtomContainer container)
        {
            // we don't make a clone, since removeHydrogens returns a deep copy
            container = AtomContainerManipulator.RemoveHydrogens(container);

            var matcher = CDK.AtomTypeMatcher;

            foreach (var atom in container.Atoms)
            {
                var type = matcher.FindMatchingAtomType(container, atom);
                AtomTypeManipulator.Configure(atom, type);
            }
            var hAdder = CDK.HydrogenAdder;

            hAdder.AddImplicitHydrogens(container);

            var subgraph3 = Order3(container);
            var subgraph4 = Order4(container);
            var subgraph5 = Order5(container);
            var subgraph6 = Order6(container);
            var subgraph7 = Order7(container);

            try
            {
                var order3s = ChiIndexUtils.EvalSimpleIndex(container, subgraph3);
                var order4s = ChiIndexUtils.EvalSimpleIndex(container, subgraph4);
                var order5s = ChiIndexUtils.EvalSimpleIndex(container, subgraph5);
                var order6s = ChiIndexUtils.EvalSimpleIndex(container, subgraph6);
                var order7s = ChiIndexUtils.EvalSimpleIndex(container, subgraph7);

                var order3v = ChiIndexUtils.EvalValenceIndex(container, subgraph3);
                var order4v = ChiIndexUtils.EvalValenceIndex(container, subgraph4);
                var order5v = ChiIndexUtils.EvalValenceIndex(container, subgraph5);
                var order6v = ChiIndexUtils.EvalValenceIndex(container, subgraph6);
                var order7v = ChiIndexUtils.EvalValenceIndex(container, subgraph7);

                return(new Result(new double[]
                {
                    order3s,
                    order4s,
                    order5s,
                    order6s,
                    order7s,
                    order3v,
                    order4v,
                    order5v,
                    order6v,
                    order7v,
                }));
            }
            catch (CDKException e)
            {
                return(new Result(e));
            }
        }
示例#4
0
        private void FindAndConfigureAtomTypesForAllAtoms(IAtomContainer container)
        {
            var atoms = container.Atoms.GetEnumerator();

            while (atoms.MoveNext())
            {
                var atom = atoms.Current;
                var type = matcher.FindMatchingAtomType(container, atom);
                Assert.IsNotNull(type);
                AtomTypeManipulator.Configure(atom, type);
            }
        }
示例#5
0
        /// <summary>
        /// Convenience method that perceives atom types (CDK scheme) and
        /// adds implicit hydrogens accordingly. It does not create 2D or 3D
        /// coordinates for the new hydrogens.
        /// </summary>
        /// <param name="container">to which implicit hydrogens are added.</param>
        protected override void AddImplicitHydrogens(IAtomContainer container)
        {
            var matcher = CDK.AtomTypeMatcher;

            foreach (var atom in container.Atoms)
            {
                var type = matcher.FindMatchingAtomType(container, atom);
                AtomTypeManipulator.Configure(atom, type);
            }
            var hAdder = CDK.HydrogenAdder;

            hAdder.AddImplicitHydrogens(container);
        }
示例#6
0
        private void FindAndConfigureAtomTypesForAllAtoms(IAtomContainer container)
        {
            var matcher = CDK.AtomTypeMatcher;

            foreach (var atom in container.Atoms)
            {
                var type = matcher.FindMatchingAtomType(container, atom);
                if (type != null)
                {
                    AtomTypeManipulator.Configure(atom, type);
                }
            }
        }
示例#7
0
        public void TestMethane()
        {
            var molecule = builder.NewAtomContainer();
            var newAtom  = builder.NewAtom(ChemicalElement.C);

            molecule.Atoms.Add(newAtom);
            var type = matcher.FindMatchingAtomType(molecule, newAtom);

            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(newAtom, type);

            adder.AddImplicitHydrogens(molecule);
            Assert.IsNotNull(newAtom.ImplicitHydrogenCount);
            Assert.AreEqual(4, newAtom.ImplicitHydrogenCount.Value);
        }
示例#8
0
        public void TestWater()
        {
            var mol    = builder.NewAtomContainer();
            var oxygen = builder.NewAtom("O");

            mol.Atoms.Add(oxygen);
            var type = matcher.FindMatchingAtomType(mol, oxygen);

            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(oxygen, type);

            adder.AddImplicitHydrogens(mol);
            Assert.IsNotNull(oxygen.ImplicitHydrogenCount);
            Assert.AreEqual(2, oxygen.ImplicitHydrogenCount.Value);
        }
        private static void PercieveAtomTypesAndConfigureAtoms(IAtomContainer container)
        {
            var matcher = SybylAtomTypeMatcher.GetInstance();
            var atoms   = container.Atoms.GetEnumerator();

            while (atoms.MoveNext())
            {
                var atom = atoms.Current;
                atom.AtomTypeName = null;
                var matched = matcher.FindMatchingAtomType(container, atom);
                if (matched != null)
                {
                    AtomTypeManipulator.Configure(atom, matched);
                }
            }
        }
示例#10
0
        private void HalogenTest(string halogen)
        {
            var mol  = builder.NewAtomContainer();
            var atom = builder.NewAtom(halogen);

            mol.Atoms.Add(atom);
            var type = matcher.FindMatchingAtomType(mol, atom);

            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(atom, type);

            adder.AddImplicitHydrogens(mol);
            Assert.AreEqual(1, mol.Atoms.Count);
            Assert.IsNotNull(atom.ImplicitHydrogenCount);
            Assert.AreEqual(1, atom.ImplicitHydrogenCount.Value);
        }
示例#11
0
        public void TestAmmonium()
        {
            var mol      = builder.NewAtomContainer();
            var nitrogen = builder.NewAtom("N");

            nitrogen.FormalCharge = +1;
            mol.Atoms.Add(nitrogen);
            var type = matcher.FindMatchingAtomType(mol, nitrogen);

            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(nitrogen, type);

            adder.AddImplicitHydrogens(mol);
            Assert.IsNotNull(nitrogen.ImplicitHydrogenCount);
            Assert.AreEqual(4, nitrogen.ImplicitHydrogenCount.Value);
        }
示例#12
0
        /// <summary>
        /// Convenience method to perceive atom types for all <see cref="IAtom"/>s in the
        /// <see cref="IAtomContainer"/>, using the <see cref="CDKAtomTypeMatcher"/>. If the
        /// matcher finds atom matching atom type, the <see cref="IAtom"/> will be configured
        /// to have the same properties as the <see cref="IAtomType"/>. If no matching atom
        /// type is found, no configuration is performed.
        /// </summary>
        /// <param name="container"></param>
        /// <exception cref="CDKException"></exception>
        public static void PercieveAtomTypesAndConfigureAtoms(IAtomContainer container)
        {
            var matcher = CDK.AtomTypeMatcher;

            foreach (var atom in container.Atoms)
            {
                if (!(atom is IPseudoAtom))
                {
                    var matched = matcher.FindMatchingAtomType(container, atom);
                    if (matched != null)
                    {
                        AtomTypeManipulator.Configure(atom, matched);
                    }
                }
            }
        }
示例#13
0
        public void TestSulfite()
        {
            var mol = builder.NewAtomContainer();
            var s   = builder.NewAtom("S");
            var o1  = builder.NewAtom("O");
            var o2  = builder.NewAtom("O");
            var o3  = builder.NewAtom("O");

            mol.Atoms.Add(s);
            mol.Atoms.Add(o1);
            mol.Atoms.Add(o2);
            mol.Atoms.Add(o3);
            var b1 = builder.NewBond(s, o1, BondOrder.Single);
            var b2 = builder.NewBond(s, o2, BondOrder.Single);
            var b3 = builder.NewBond(s, o3, BondOrder.Double);

            mol.Bonds.Add(b1);
            mol.Bonds.Add(b2);
            mol.Bonds.Add(b3);
            var type = matcher.FindMatchingAtomType(mol, s);

            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(s, type);
            type = matcher.FindMatchingAtomType(mol, o1);
            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(o1, type);
            type = matcher.FindMatchingAtomType(mol, o2);
            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(o2, type);
            type = matcher.FindMatchingAtomType(mol, o3);
            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(o3, type);

            adder.AddImplicitHydrogens(mol);

            Assert.AreEqual(4, mol.Atoms.Count);
            Assert.AreEqual(3, mol.Bonds.Count);
            Assert.IsNotNull(s.ImplicitHydrogenCount);
            Assert.AreEqual(0, s.ImplicitHydrogenCount.Value);
            Assert.IsNotNull(o1.ImplicitHydrogenCount);
            Assert.AreEqual(1, o1.ImplicitHydrogenCount.Value);
            Assert.IsNotNull(o2.ImplicitHydrogenCount);
            Assert.AreEqual(1, o2.ImplicitHydrogenCount.Value);
            Assert.IsNotNull(o3.ImplicitHydrogenCount);
            Assert.AreEqual(0, o3.ImplicitHydrogenCount.Value);
        }
示例#14
0
        public void TestSulphur()
        {
            var mol  = builder.NewAtomContainer();
            var atom = builder.NewAtom("S");

            mol.Atoms.Add(atom);
            var type = matcher.FindMatchingAtomType(mol, atom);

            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(atom, type);

            Assert.AreNotEqual(2, atom.ImplicitHydrogenCount);
            adder.AddImplicitHydrogens(mol);
            Assert.AreEqual(1, mol.Atoms.Count);
            Assert.IsNotNull(atom.ImplicitHydrogenCount);
            Assert.AreEqual(2, atom.ImplicitHydrogenCount.Value);
        }
示例#15
0
 private static void AddExplicitHydrogens(IAtomContainer container)
 {
     try
     {
         var matcher = CDK.AtomTypeMatcher;
         foreach (var atom in container.Atoms)
         {
             var type = matcher.FindMatchingAtomType(container, atom);
             AtomTypeManipulator.Configure(atom, type);
         }
         var hAdder = CDK.HydrogenAdder;
         hAdder.AddImplicitHydrogens(container);
         AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(container);
     }
     catch (Exception)
     {
         Debug.WriteLine("Error in hydrogen addition");
     }
 }
示例#16
0
        private bool createBondsWithRebondTool(IBioPolymer pol)
        {
            RebondTool tool = new RebondTool(2.0, 0.5, 0.5);

            try
            {
                //			 configure atoms
                AtomTypeFactory factory = AtomTypeFactory.getInstance("jmol_atomtypes.txt", pol.Builder);
                IAtom[]         atoms   = pol.Atoms;
                for (int i = 0; i < atoms.Length; i++)
                {
                    try
                    {
                        IAtomType[] types = factory.getAtomTypes(atoms[i].Symbol);
                        if (types.Length > 0)
                        {
                            // just pick the first one
                            AtomTypeManipulator.configure(atoms[i], types[0]);
                        }
                        else
                        {
                            System.Console.Out.WriteLine("Could not configure atom with symbol: " + atoms[i].Symbol);
                        }
                    }
                    catch (System.Exception 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'"
                        System.Console.Out.WriteLine("Could not configure atom (but don't care): " + e.Message);
                        //logger.debug(e);
                    }
                }
                tool.rebond(pol);
            }
            catch (System.Exception 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("Could not rebond the polymer: " + e.Message);
                //logger.debug(e);
            }
            return(true);
        }
示例#17
0
        /// <summary>
        /// Helper method to test if atom types are correctly perceived. Meanwhile, it maintains a list
        /// of atom types that have been tested so far, which allows testing afterwards that all atom
        /// types are at least tested once.
        /// </summary>
        /// <param name="testedAtomTypes">List of atom types tested so far.</param>
        /// <param name="expectedTypes">Expected atom types for the atoms given in <paramref name="mol"/>.</param>
        /// <param name="mol">The <see cref="IAtomContainer"/> with <see cref="IAtom"/>s for which atom types should be perceived.</param>
        /// <exception cref="System.Exception">Thrown if something went wrong during the atom type perception.</exception>
        public virtual void AssertAtomTypes(IDictionary <string, int> testedAtomTypes, string[] expectedTypes, IAtomContainer mol)
        {
            Assert.AreEqual(expectedTypes.Length, mol.Atoms.Count, "The number of expected atom types is unequal to the number of atoms");
            var atm = GetAtomTypeMatcher(mol.Builder);

            for (int i = 0; i < expectedTypes.Length; i++)
            {
                var testedAtom = mol.Atoms[i];
                var foundType  = atm.FindMatchingAtomType(mol, testedAtom);
                AssertAtomType(testedAtomTypes, "Incorrect perception for atom " + i, expectedTypes[i], foundType);
                AssertConsistentProperties(mol, testedAtom, foundType);
                // test for bug #1890702: configure, and then make sure the same atom type is perceived
                AtomTypeManipulator.Configure(testedAtom, foundType);
                var secondType = atm.FindMatchingAtomType(mol, testedAtom);
                AssertAtomType(
                    testedAtomTypes,
                    $"Incorrect perception *after* assigning atom type properties for atom {i}",
                    expectedTypes[i],
                    secondType);
            }
        }
示例#18
0
        public void TestHydrogen()
        {
            var mol    = builder.NewAtomContainer();
            var proton = builder.NewAtom("H");

            mol.Atoms.Add(proton);
            var type = matcher.FindMatchingAtomType(mol, proton);

            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(proton, type);

            adder.AddImplicitHydrogens(mol);

            Assert.AreEqual(1, mol.Atoms.Count);
            IMolecularFormula formula = MolecularFormulaManipulator.GetMolecularFormula(mol);

            Assert.AreEqual(2, MolecularFormulaManipulator.GetElementCount(formula, ChemicalElement.H));
            Assert.AreEqual(0, mol.GetConnectedBonds(proton).Count());
            Assert.IsNotNull(proton.ImplicitHydrogenCount);
            Assert.AreEqual(1, proton.ImplicitHydrogenCount.Value);
        }
示例#19
0
        public void TestFormaldehyde()
        {
            var molecule = builder.NewAtomContainer();
            var newAtom  = builder.NewAtom(ChemicalElement.C);
            var newAtom2 = builder.NewAtom(ChemicalElement.O);

            molecule.Atoms.Add(newAtom);
            molecule.Atoms.Add(newAtom2);
            molecule.AddBond(molecule.Atoms[0], molecule.Atoms[1], BondOrder.Double);
            var type = matcher.FindMatchingAtomType(molecule, newAtom);

            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(newAtom, type);
            type = matcher.FindMatchingAtomType(molecule, newAtom2);
            Assert.IsNotNull(type);
            AtomTypeManipulator.Configure(newAtom2, type);

            adder.AddImplicitHydrogens(molecule);
            Assert.IsNotNull(newAtom.ImplicitHydrogenCount);
            Assert.IsNotNull(newAtom2.ImplicitHydrogenCount);
            Assert.AreEqual(2, newAtom.ImplicitHydrogenCount.Value);
            Assert.AreEqual(0, newAtom2.ImplicitHydrogenCount.Value);
        }
示例#20
0
        private static void TypeAndRetype(string smiles)
        {
            var mol   = smilesParser.ParseSmiles(smiles);
            var types = atomTypeMatcher.FindMatchingAtomTypes(mol).ToReadOnlyList();

            for (int i = 0; i < types.Count; i++)
            {
                AtomTypeManipulator.Configure(mol.Atoms[i], types[i]);
            }
            var retyped = atomTypeMatcher.FindMatchingAtomTypes(mol).ToReadOnlyList();

            for (int i = 0; i < types.Count; i++)
            {
                Assert.AreEqual(types[i], retyped[i],
                                $"First perception resulted in {types[i]} but the second perception gave {retyped[i]}");
            }
            retyped = atomTypeMatcher.FindMatchingAtomTypes(mol).ToReadOnlyList();
            for (int i = 0; i < types.Count; i++)
            {
                Assert.AreEqual(types[i], retyped[i],
                                $"First perception resulted in {types[i]} but the third perception gave {retyped[i]}");
            }
        }
示例#21
0
        private static bool CreateBondsWithRebondTool(IAtomContainer molecule)
        {
            var tool = new RebondTool(2.0, 0.5, 0.5);

            try
            {
                foreach (var atom in molecule.Atoms)
                {
                    try
                    {
                        var types = factory.GetAtomTypes(atom.Symbol);
                        var type  = types.FirstOrDefault();
                        if (type != null)
                        {
                            // just pick the first one
                            AtomTypeManipulator.Configure(atom, type);
                        }
                        else
                        {
                            Trace.TraceWarning("Could not configure atom with symbol: " + atom.Symbol);
                        }
                    }
                    catch (Exception e)
                    {
                        Trace.TraceWarning("Could not configure atom (but don't care): " + e.Message);
                        Debug.WriteLine(e);
                    }
                }
                tool.Rebond(molecule);
            }
            catch (Exception e)
            {
                Trace.TraceError($"Could not rebond the polymer: {e.Message}");
                Debug.WriteLine(e);
            }
            return(true);
        }
        public void TestUITTimeoutFix()
        {
            // Load molecules
            var filename  = "NCDK.Data.MDL.UITTimeout.sdf";
            var ins       = ResourceLoader.GetAsStream(filename);
            var reader    = new MDLV2000Reader(ins);
            var content   = reader.Read(builder.NewChemFile());
            var cList     = ChemFileManipulator.GetAllAtomContainers(content).ToReadOnlyList();
            var molecules = new IAtomContainer[2];

            for (int j = 0; j < 2; j++)
            {
                var aAtomContainer = cList[j];
                var tmpMatcher     = CDK.AtomTypeMatcher;
                var tmpAdder       = CDK.HydrogenAdder;
                for (int i = 0; i < aAtomContainer.Atoms.Count; i++)
                {
                    var tmpAtom = aAtomContainer.Atoms[i];
                    var tmpType = tmpMatcher.FindMatchingAtomType(aAtomContainer, tmpAtom);
                    AtomTypeManipulator.Configure(tmpAtom, tmpType);
                    tmpAdder.AddImplicitHydrogens(aAtomContainer, tmpAtom);
                }
                AtomContainerManipulator.ConvertImplicitToExplicitHydrogens(aAtomContainer);
                molecules[j] = aAtomContainer;
            }
            var query = QueryAtomContainerCreator.CreateAnyAtomForPseudoAtomQueryContainer(molecules[1]);
            // test
            var starttime = System.DateTime.Now.Ticks;

            uiTester.Timeout = 200;
            uiTester.GetSubgraphAtomsMaps(molecules[0], query);
            var duration = System.DateTime.Now.Ticks - starttime;

            // The search must last much longer then two seconds if the timeout not works
            Assert.IsTrue(duration < 2000 * 10000);  // 1 msec = 10000 ticks
        }
        public void TestButadiene()
        {
            var mol    = new AtomContainer();
            var carbon = new AtomType(ChemicalElement.C);

            var a0 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 2
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a0, carbon);
            var a1 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 1
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a1, carbon);
            var a2 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 1
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a2, carbon);
            var a3 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 2
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a3, carbon);

            mol.Atoms.Add(a0);
            mol.Atoms.Add(a1);
            mol.Atoms.Add(a2);
            mol.Atoms.Add(a3);

            var b0 = new Bond(a0, a1)
            {
                IsSingleOrDouble = true
            };

            mol.Bonds.Add(b0);
            var b1 = new Bond(a1, a2)
            {
                IsSingleOrDouble = true
            };

            mol.Bonds.Add(b1);
            IBond b2 = new Bond(a2, a3)
            {
                IsSingleOrDouble = true
            };

            mol.Bonds.Add(b2);

            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol);

            atasc.DecideBondOrder(mol, true);

            Assert.AreEqual(BondOrder.Double, mol.Bonds[0].Order);
            Assert.AreEqual(BondOrder.Single, mol.Bonds[1].Order);
            Assert.AreEqual(BondOrder.Double, mol.Bonds[2].Order);
        }
        public void TestASimpleCarbonRing()
        {
            // First we create a simple carbon ring to play with...
            var mol    = new AtomContainer();
            var carbon = new AtomType(ChemicalElement.C);

            var a0 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 1
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a0, carbon);
            var a1 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 1
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a1, carbon);
            var a2 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 1
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a2, carbon);
            var a3 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 1
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a3, carbon);
            var a4 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 1
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a4, carbon);
            var a5 = new Atom("C")
            {
                Hybridization         = Hybridization.SP2,
                ImplicitHydrogenCount = 1
            };

            AtomTypeManipulator.ConfigureUnsetProperties(a5, carbon);

            mol.Atoms.Add(a0);
            mol.Atoms.Add(a1);
            mol.Atoms.Add(a2);
            mol.Atoms.Add(a3);
            mol.Atoms.Add(a4);
            mol.Atoms.Add(a5);

            var b0 = new Bond(a0, a1)
            {
                IsSingleOrDouble = true
            };

            mol.Bonds.Add(b0);
            var b1 = new Bond(a1, a2)
            {
                IsSingleOrDouble = true
            };

            mol.Bonds.Add(b1);
            var b2 = new Bond(a2, a3)
            {
                IsSingleOrDouble = true
            };

            mol.Bonds.Add(b2);
            var b3 = new Bond(a3, a4)
            {
                IsSingleOrDouble = true
            };

            mol.Bonds.Add(b3);
            var b4 = new Bond(a4, a5)
            {
                IsSingleOrDouble = true
            };

            mol.Bonds.Add(b4);
            var b5 = new Bond(a5, a0)
            {
                IsSingleOrDouble = true
            };

            mol.Bonds.Add(b5);

            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(mol);

            // ...then we send it to the method we want to test...
            atasc.DecideBondOrder(mol, false);

            Assert.AreEqual(BondOrder.Double, b0.Order);
            Assert.AreEqual(BondOrder.Single, b1.Order);
            Assert.AreEqual(BondOrder.Double, b2.Order);
            Assert.AreEqual(BondOrder.Single, b3.Order);
            Assert.AreEqual(BondOrder.Double, b4.Order);
            Assert.AreEqual(BondOrder.Single, b5.Order);

            Assert.IsTrue(satcheck.IsSaturated(a0, mol));
        }
示例#25
0
        /// <summary>
        /// Read a Reaction from a file in MDL RXN format
        /// </summary>
        /// <returns>The Reaction that was read from the MDL file.</returns>
        private IAtomContainer ReadMolecule(IAtomContainer molecule)
        {
            try
            {
                int atomCount = 0;
                int bondCount = 0;

                string line;
                while (true)
                {
                    line = input.ReadLine();
                    if (line == null)
                    {
                        return(null);
                    }
                    if (line.StartsWith("@<TRIPOS>MOLECULE", StringComparison.Ordinal))
                    {
                        break;
                    }
                    if (!line.StartsWithChar('#') && line.Trim().Length > 0)
                    {
                        break;
                    }
                }

                // ok, if we're coming from the chemfile function, we've already read the molecule RTI
                if (firstLineisMolecule)
                {
                    molecule.Title = line;
                }
                else
                {
                    line           = input.ReadLine();
                    molecule.Title = line;
                }

                // get atom and bond counts
                var counts    = input.ReadLine();
                var tokenizer = Strings.Tokenize(counts);
                try
                {
                    atomCount = int.Parse(tokenizer[0], NumberFormatInfo.InvariantInfo);
                }
                catch (FormatException nfExc)
                {
                    string error = "Error while reading atom count from MOLECULE block";
                    Trace.TraceError(error);
                    Debug.WriteLine(nfExc);
                    throw new CDKException(error, nfExc);
                }
                if (tokenizer.Count > 1)
                {
                    try
                    {
                        bondCount = int.Parse(tokenizer[1], NumberFormatInfo.InvariantInfo);
                    }
                    catch (FormatException nfExc)
                    {
                        string error = "Error while reading atom and bond counts";
                        Trace.TraceError(error);
                        Debug.WriteLine(nfExc);
                        throw new CDKException(error, nfExc);
                    }
                }
                else
                {
                    bondCount = 0;
                }
                Trace.TraceInformation("Reading #atoms: ", atomCount);
                Trace.TraceInformation("Reading #bonds: ", bondCount);

                // we skip mol type, charge type and status bit lines
                Trace.TraceWarning("Not reading molecule qualifiers");

                line = input.ReadLine();
                bool molend = false;
                while (line != null)
                {
                    if (line.StartsWith("@<TRIPOS>MOLECULE", StringComparison.Ordinal))
                    {
                        molend = true;
                        break;
                    }
                    else if (line.StartsWith("@<TRIPOS>ATOM", StringComparison.Ordinal))
                    {
                        Trace.TraceInformation("Reading atom block");
                        for (int i = 0; i < atomCount; i++)
                        {
                            line = input.ReadLine().Trim();
                            if (line.StartsWith("@<TRIPOS>MOLECULE", StringComparison.Ordinal))
                            {
                                molend = true;
                                break;
                            }
                            tokenizer = Strings.Tokenize(line);
                            // disregard the id token
                            var nameStr     = tokenizer[1];
                            var xStr        = tokenizer[2];
                            var yStr        = tokenizer[3];
                            var zStr        = tokenizer[4];
                            var atomTypeStr = tokenizer[5];

                            // replace unrecognised atom type
                            if (ATOM_TYPE_ALIASES.ContainsKey(atomTypeStr))
                            {
                                atomTypeStr = ATOM_TYPE_ALIASES[atomTypeStr];
                            }

                            var       atom = molecule.Builder.NewAtom();
                            IAtomType atomType;
                            try
                            {
                                atomType = atFactory.GetAtomType(atomTypeStr);
                            }
                            catch (Exception)
                            {
                                // ok, *not* an mol2 atom type
                                atomType = null;
                            }
                            // Maybe it is just an element
                            if (atomType == null && IsElementSymbol(atomTypeStr))
                            {
                                atom.Symbol = atomTypeStr;
                            }
                            else
                            {
                                if (atomType == null)
                                {
                                    atomType = atFactory.GetAtomType("X");
                                    Trace.TraceError($"Could not find specified atom type: {atomTypeStr}");
                                }
                                AtomTypeManipulator.Configure(atom, atomType);
                            }

                            atom.AtomicNumber = ChemicalElement.OfSymbol(atom.Symbol).AtomicNumber;
                            atom.Id           = nameStr;
                            atom.AtomTypeName = atomTypeStr;
                            try
                            {
                                var x = double.Parse(xStr, NumberFormatInfo.InvariantInfo);
                                var y = double.Parse(yStr, NumberFormatInfo.InvariantInfo);
                                var z = double.Parse(zStr, NumberFormatInfo.InvariantInfo);
                                atom.Point3D = new Vector3(x, y, z);
                            }
                            catch (FormatException nfExc)
                            {
                                string error = "Error while reading atom coordinates";
                                Trace.TraceError(error);
                                Debug.WriteLine(nfExc);
                                throw new CDKException(error, nfExc);
                            }
                            molecule.Atoms.Add(atom);
                        }
                    }
                    else if (line.StartsWith("@<TRIPOS>BOND", StringComparison.Ordinal))
                    {
                        Trace.TraceInformation("Reading bond block");
                        for (int i = 0; i < bondCount; i++)
                        {
                            line = input.ReadLine();
                            if (line.StartsWith("@<TRIPOS>MOLECULE", StringComparison.Ordinal))
                            {
                                molend = true;
                                break;
                            }
                            tokenizer = Strings.Tokenize(line);
                            // disregard the id token
                            var atom1Str = tokenizer[1];
                            var atom2Str = tokenizer[2];
                            var orderStr = tokenizer[3];
                            try
                            {
                                var atom1 = int.Parse(atom1Str, NumberFormatInfo.InvariantInfo);
                                var atom2 = int.Parse(atom2Str, NumberFormatInfo.InvariantInfo);
                                if (string.Equals("nc", orderStr, StringComparison.Ordinal))
                                {
                                    // do not connect the atoms
                                }
                                else
                                {
                                    var bond = molecule.Builder.NewBond(molecule.Atoms[atom1 - 1], molecule.Atoms[atom2 - 1]);
                                    switch (orderStr)
                                    {
                                    case "1":
                                        bond.Order = BondOrder.Single;
                                        break;

                                    case "2":
                                        bond.Order = BondOrder.Double;
                                        break;

                                    case "3":
                                        bond.Order = BondOrder.Triple;
                                        break;

                                    case "am":
                                    case "ar":
                                        bond.Order            = BondOrder.Single;
                                        bond.IsAromatic       = true;
                                        bond.Begin.IsAromatic = true;
                                        bond.End.IsAromatic   = true;
                                        break;

                                    case "du":
                                        bond.Order = BondOrder.Single;
                                        break;

                                    case "un":
                                        bond.Order = BondOrder.Single;
                                        break;

                                    default:
                                        break;
                                    }
                                    molecule.Bonds.Add(bond);
                                }
                            }
                            catch (FormatException nfExc)
                            {
                                var error = "Error while reading bond information";
                                Trace.TraceError(error);
                                Debug.WriteLine(nfExc);
                                throw new CDKException(error, nfExc);
                            }
                        }
                    }
                    if (molend)
                    {
                        return(molecule);
                    }
                    line = input.ReadLine();
                }
            }
            catch (IOException exception)
            {
                var error = "Error while reading general structure";
                Trace.TraceError(error);
                Debug.WriteLine(exception);
                throw new CDKException(error, exception);
            }
            return(molecule);
        }