Ejemplo n.º 1
0
        public void TestElement()
        {
            Assert.IsNull(ChemicalElement.Get(0));
            Assert.IsNull(ChemicalElement.Get(-1));
            Assert.IsNull(ChemicalElement.Get("Nothing"));
            Assert.IsFalse(new ChemicalElement(-1, null, "Nothing", true).IsValid());
            Assert.IsFalse(ChemicalElement.IsValid("Nothing"));

            var h = ChemicalElement.Get(1);

            Assert.IsTrue(h.IsValid());
            Assert.AreEqual(1, h.AtomicNumber);
            Assert.AreEqual("H", h.Symbol);
            Assert.AreEqual("Hydrogen", h.EnglishName);
            Assert.AreEqual(1, h.Period);
            Assert.AreEqual(1, h.Group);
            Assert.AreEqual(0, h.IndexInPeriod);
            Assert.AreEqual("s", h.Block);
            Assert.AreEqual(h, ChemicalElement.Get("H"));
            Assert.AreEqual(h, ChemicalElement.H);
            Assert.AreEqual(h, new ChemicalElement(1, "H", "No.1", true));
            Assert.IsTrue(h.HasAtomicWeight);
            Assert.IsTrue(h.AtomicWeight >= 1);
            Assert.IsTrue(h.ToString().Contains(h.Symbol));
            Assert.IsTrue(h.IsNonMetallic);
            Assert.IsFalse(h.IsAlkaliMetal);
            Assert.IsFalse(h.IsAlkalineEarthMetal);
            Assert.IsFalse(h.IsChalcogen);
            Assert.IsFalse(h.IsHalogen);
            Assert.IsFalse(h.IsInBoronGroup);
            Assert.IsFalse(h.IsInCarbonGroup);
            Assert.IsFalse(h.IsInNitrogenGroup);
            Assert.IsFalse(h.IsInVIII);
            Assert.IsFalse(h.IsMetal);
            Assert.IsFalse(h.IsNoble);
            Assert.IsFalse(h.IsTransition);
            Assert.IsFalse(h.IsRadioelement());
            Assert.AreEqual("H", ((JsonObjectNode)h).TryGetStringValue("symbol"));
            var d = h.Isotope(2);

            Assert.AreEqual("D", d.ToString());
            Assert.AreEqual(h, d.Element);
            Assert.AreEqual(1, d.AtomicNumber);
            Assert.AreEqual(2, d.AtomicMassNumber);
            Assert.AreEqual(1, d.Neutrons);
            Assert.IsTrue(d.HasAtomicWeight);
            Assert.AreEqual(d, new Isotope(h, 2));
            Assert.IsFalse(h.Isotope(10).HasAtomicWeight);

            var c = ChemicalElement.Get(6);

            Assert.IsTrue(c.IsValid());
            Assert.IsFalse(c == h);
            Assert.IsTrue(c != h);
            Assert.IsTrue(c > h);
            Assert.IsTrue(c >= h);
            Assert.IsFalse(c < h);
            Assert.IsFalse(c <= h);
            Assert.AreNotEqual(h, c);
            Assert.AreEqual(6, c.AtomicNumber);
            Assert.AreEqual("C", c.Symbol);
            Assert.AreEqual("Carbon", c.EnglishName);
            Assert.AreEqual(2, c.Period);
            Assert.AreEqual(14, c.Group);
            Assert.AreEqual(3, c.IndexInPeriod);
            Assert.AreEqual("p", c.Block);
            Assert.AreEqual(c, ChemicalElement.Get("C"));
            Assert.AreEqual(c, ChemicalElement.C);
            Assert.AreEqual(c, new ChemicalElement(6, "C", "No.6", true));
            Assert.IsTrue(c.HasAtomicWeight);
            Assert.IsTrue(c.AtomicWeight >= 12);
            Assert.IsTrue(c.ToString().Contains(c.Symbol));
            Assert.AreEqual(6, ((JsonObjectNode)c).TryGetInt32Value("number"));
            var c12 = c.Isotope(12);

            Assert.AreNotEqual(h, c12);
            Assert.AreEqual(3, c12.ToString().Length);
            Assert.IsTrue(c12.ToString().EndsWith("C"));
            Assert.AreEqual(c, c12.Element);
            Assert.AreEqual(6, c12.AtomicNumber);
            Assert.AreEqual(12, c12.AtomicMassNumber);
            Assert.AreEqual(6, c12.Neutrons);
            Assert.IsTrue(c12.HasAtomicWeight);
            Assert.AreEqual(12, c12.AtomicWeight);
            Assert.AreEqual(c12, new Isotope(6, 12));

            var count = 0;

            foreach (var prop in typeof(ChemicalElement).GetProperties(BindingFlags.Static | BindingFlags.Public))
            {
                if (!prop.CanRead || prop.PropertyType != typeof(ChemicalElement))
                {
                    continue;
                }
                var ele = (ChemicalElement)prop.GetValue(null);
                Assert.IsNotNull(ele);
                Assert.AreEqual(prop.Name, ele.Symbol);
                Assert.AreEqual(ele, ChemicalElement.Get(ele.AtomicNumber));
                Assert.AreEqual(ele, ChemicalElement.Get(ele.Symbol));
                Assert.IsFalse(string.IsNullOrWhiteSpace(ele.Name));
                count++;
            }

            Assert.IsTrue(count >= 118);
            var usn = ChemicalElement.Get(170);

            Assert.AreNotEqual(h, usn);
            Assert.AreNotEqual(c, usn);
            Assert.AreEqual("Usn", usn.Symbol);
            Assert.AreEqual("Unseptnilium", usn.EnglishName);
            Assert.AreEqual(9, usn.Period);
            Assert.AreEqual(2, usn.Group);
            Assert.AreEqual(1, usn.IndexInPeriod);
            Assert.AreEqual("s", usn.Block);
            Assert.AreEqual(usn, ChemicalElement.Get("Usn"));
            Assert.IsFalse(usn.HasAtomicWeight);
            Assert.IsTrue(double.IsNaN(usn.AtomicWeight));
            Assert.IsTrue(usn.ToString().Contains(usn.Symbol));

            var bbb = ChemicalElement.Get(222);

            Assert.AreEqual("Bbb", bbb.Symbol);
            Assert.AreEqual("i", bbb.Block);

            var one = new ChemicalElement(17, "Seventeen", "A new sample element", true);

            Assert.IsTrue(one.IsValid());
            Assert.AreNotEqual(ChemicalElement.Get(17), one);
        }
Ejemplo n.º 2
0
    /// <inheritdoc />
    protected override async Task OnProcessAsync(CancellationToken cancellationToken = default)
    {
        await RunAsync(null, cancellationToken);

        var s       = Arguments.Verb?.TryGet(0);
        var console = GetConsole();

        if (s == "period" || s == "p" || s == "周期" || (s == "Period" && Arguments.Verb.Count > 1))
        {
            s = Arguments.Verb.TryGet(1);
            if (string.IsNullOrEmpty(s))
            {
                ChemistryCommandLine.WriteTable(GetConsole(), ChemicalElementStyle);
            }
            else if (int.TryParse(s, out var period) && period > 0)
            {
                if (period > 7)
                {
                    var start = ChemicalElement.FirstAtomicNumberInPeriod(period);
                    var end   = ChemicalElement.LastAtomicNumberInPeriod(period);
                    if (start <= 0 || end <= 0 || start >= end)
                    {
                        WriteError(" The period was too large.");
                    }
                    else
                    {
                        console.WriteLine(ChemistryResource.ChemicalElement);
                        console.WriteLine($"{start} - {end} (Total {end - start + 1})");
                    }

                    return;
                }

                var elements = ChemicalElement.GetExisted();
                var has      = false;
                foreach (var element in elements)
                {
                    if (element is null)
                    {
                        continue;
                    }
                    if (element.Period != period)
                    {
                        if (has)
                        {
                            break;
                        }
                        continue;
                    }

                    WriteSimpleInfo(element, Arguments.Has("en"));
                }
            }
            else if (s.Equals("help", StringComparison.OrdinalIgnoreCase) || s.Equals("?", StringComparison.Ordinal))
            {
                WriteHelp(Arguments.Verb?.Key, "period");
            }
            else
            {
                WriteError(" The period should be a natural number.");
            }

            return;
        }

        var q = Arguments.GetMergedValue("q")?.Trim();

        if (q.Length < 1)
        {
            q = null;
        }

        if (s == "*" || s == "all" || s == "a")
        {
            foreach (var i in ChemicalElement.Where(GetFilter(q)))
            {
                WriteSimpleInfo(i, Arguments.Has("en"));
            }

            return;
        }

        if (s == "ls" || s == "l" || s == "list" || s == "dir" || s == "全部")
        {
            var filter = Arguments.Verb.TryGet(1)?.Trim()?.Split('-');
            List <ChemicalElement> col = null;
            if (filter is null || filter.Length < 1 || string.IsNullOrWhiteSpace(filter[0]))
            {
            }
            else if (filter[0].Equals("help", StringComparison.OrdinalIgnoreCase) || filter[0].Equals("?", StringComparison.Ordinal))
            {
                WriteHelp(Arguments.Verb?.Key, "ls");
                return;
            }
            else if (!int.TryParse(filter[0], out var begin))
            {
            }
            else if (filter.Length == 1)
            {
                col = ChemicalElement.Range(0, begin).ToList();
            }
            else if (filter.Length == 2 && int.TryParse(filter[1], out var end))
            {
                col = ChemicalElement.Range(begin, end - begin).ToList();
            }

            if (col is null)
            {
                col = ChemicalElement.Where(null).ToList();
            }
            var filter2 = GetFilter(q);
            foreach (var i in filter2 is null ? col : col.Where(filter2))
            {
                WriteSimpleInfo(i, Arguments.Has("en"));
            }

            return;
        }
Ejemplo n.º 3
0
        public void Update(List <PlatformObject> objects)
        {
            if (!triggered)
            {
                return;
            }

            foreach (PlatformObject obj in objects)
            {
                if (obj.bounds.Intersects(bounds))
                {
                    return;
                }
            }

            ChemicalSignature signature = Game1.instance.platformLevel.SpawnInputChemical(inputIndex);

            if (signature == null)
            {
                return;
            }

            triggered = false;

            int height = signature.height;
            int width  = signature.width;

            float startX = bounds.CenterX - width * 32 / 2;
            float startY = bounds.CenterY - height * 32 / 2;
            float curX   = startX;
            float curY   = startY;

            ChemBlock[,] blocksSpawned = new ChemBlock[width, height];

            for (int col = 0; col < width; ++col)
            {
                for (int row = 0; row < height; ++row)
                {
                    ChemicalElement c = signature[col, row];
                    if (c != ChemicalElement.NONE)
                    {
                        ChemBlock newBlock = new ChemBlock(c, c.ToTexture(false), new Vector2(curX, curY), new Vector2(32, 32), c.ToColor());
                        objects.Add(newBlock);

                        blocksSpawned[col, row] = newBlock;

                        if (col > 0 && blocksSpawned[col - 1, row] != null)
                        {
                            blocksSpawned[col - 1, row].NailOnto(newBlock);
                        }

                        if (row > 0 && blocksSpawned[col, row - 1] != null)
                        {
                            blocksSpawned[col, row - 1].NailOnto(newBlock);
                        }
                    }

                    curY += 32.5f;
                }

                curX += 32.5f;
                curY  = startY;

                Game1.instance.platformLevel.UpdateAnyBlocksLeft();
            }
        }
Ejemplo n.º 4
0
 public IPseudoAtom NewPseudoAtom(ChemicalElement element) => (IPseudoAtom) new PseudoAtom(element);
Ejemplo n.º 5
0
        public Color GetAtomColor(IAtom atom, Color defaultColor)
        {
            var elem = ChemicalElement.OfSymbol(atom.Symbol).AtomicNumber;

            if (elem == AtomicNumbers.Unknown)
            {
                elem = atom.AtomicNumber;
            }
            switch (elem)
            {
            case AtomicNumbers.Helium:
                return(hexD9FFFF);

            case AtomicNumbers.Lithium:
                return(hexCC80FF);

            case AtomicNumbers.Beryllium:
                return(hexC2FF00);

            case AtomicNumbers.Boron:
                return(hexFFB5B5);

            case AtomicNumbers.Hydrogen:
            case AtomicNumbers.Carbon:
            case AtomicNumbers.Unknown:
                return(WPF.Media.Colors.Black);

            case AtomicNumbers.Nitrogen:
                return(hex3050F8);

            case AtomicNumbers.Oxygen:
                return(hexFF0D0D);

            case AtomicNumbers.Fluorine:
                return(hex90E050);

            case AtomicNumbers.Neon:
                return(hexB3E3F5);

            case AtomicNumbers.Sodium:
                return(hexAB5CF2);

            case AtomicNumbers.Magnesium:
                return(hex8AFF00);

            case AtomicNumbers.Aluminium:
                return(hexBFA6A6);

            case AtomicNumbers.Silicon:
                return(hexF0C8A0);

            case AtomicNumbers.Phosphorus:
                return(hexFF8000);

            case AtomicNumbers.Sulfur:
                return(hexFFFF30);

            case AtomicNumbers.Chlorine:
                return(hex1FF01F);

            case AtomicNumbers.Argon:
                return(hex80D1E3);

            case AtomicNumbers.Potassium:
                return(hex8F40D4);

            case AtomicNumbers.Calcium:
                return(hex3DFF00);

            case AtomicNumbers.Scandium:
                return(hexE6E6E6);

            case AtomicNumbers.Titanium:
                return(hexBFC2C7);

            case AtomicNumbers.Vanadium:
                return(hexA6A6AB);

            case AtomicNumbers.Chromium:
                return(hex8A99C7);

            case AtomicNumbers.Manganese:
                return(hex9C7AC7);

            case AtomicNumbers.Iron:
                return(hexE06633);

            case AtomicNumbers.Cobalt:
                return(hexF090A0);

            case AtomicNumbers.Nickel:
                return(hex50D050);

            case AtomicNumbers.Copper:
                return(hexC88033);

            case AtomicNumbers.Zinc:
                return(hex7D80B0);

            case AtomicNumbers.Gallium:
                return(hexC28F8F);

            case AtomicNumbers.Germanium:
                return(hex668F8F);

            case AtomicNumbers.Arsenic:
                return(hexBD80E3);

            case AtomicNumbers.Selenium:
                return(hexFFA100);

            case AtomicNumbers.Bromine:
                return(hexA62929);

            case AtomicNumbers.Krypton:
                return(hex5CB8D1);

            case AtomicNumbers.Rubidium:
                return(hex702EB0);

            case AtomicNumbers.Strontium:
                return(hex00FF00);

            case AtomicNumbers.Yttrium:
                return(hex94FFFF);

            case AtomicNumbers.Zirconium:
                return(hex94E0E0);

            case AtomicNumbers.Niobium:
                return(hex73C2C9);

            case AtomicNumbers.Molybdenum:
                return(hex54B5B5);

            case AtomicNumbers.Technetium:
                return(hex3B9E9E);

            case AtomicNumbers.Ruthenium:
                return(hex248F8F);

            case AtomicNumbers.Rhodium:
                return(hex0A7D8C);

            case AtomicNumbers.Palladium:
                return(hex006985);

            case AtomicNumbers.Silver:
                return(hexC0C0C0);

            case AtomicNumbers.Cadmium:
                return(hexFFD98F);

            case AtomicNumbers.Indium:
                return(hexA67573);

            case AtomicNumbers.Tin:
                return(hex668080);

            case AtomicNumbers.Antimony:
                return(hex9E63B5);

            case AtomicNumbers.Tellurium:
                return(hexD47A00);

            case AtomicNumbers.Iodine:
                return(hex940094);

            case AtomicNumbers.Xenon:
                return(hex429EB0);

            case AtomicNumbers.Caesium:
                return(hex57178F);

            case AtomicNumbers.Barium:
                return(hex00C900);

            case AtomicNumbers.Lanthanum:
                return(hex70D4FF);

            case AtomicNumbers.Cerium:
                return(hexFFFFC7);

            case AtomicNumbers.Praseodymium:
                return(hexD9FFC7);

            case AtomicNumbers.Neodymium:
                return(hexC7FFC7);

            case AtomicNumbers.Promethium:
                return(hexA3FFC7);

            case AtomicNumbers.Samarium:
                return(hex8FFFC7);

            case AtomicNumbers.Europium:
                return(hex61FFC7);

            case AtomicNumbers.Gadolinium:
                return(hex45FFC7);

            case AtomicNumbers.Terbium:
                return(hex30FFC7);

            case AtomicNumbers.Dysprosium:
                return(hex1FFFC7);

            case AtomicNumbers.Holmium:
                return(hex00FF9C);

            case AtomicNumbers.Erbium:
                return(hex00E675);

            case AtomicNumbers.Thulium:
                return(hex00D452);

            case AtomicNumbers.Ytterbium:
                return(hex00BF38);

            case AtomicNumbers.Lutetium:
                return(hex00AB24);

            case AtomicNumbers.Hafnium:
                return(hex4DC2FF);

            case AtomicNumbers.Tantalum:
                return(hex4DA6FF);

            case AtomicNumbers.Tungsten:
                return(hex2194D6);

            case AtomicNumbers.Rhenium:
                return(hex267DAB);

            case AtomicNumbers.Osmium:
                return(hex266696);

            case AtomicNumbers.Iridium:
                return(hex175487);

            case AtomicNumbers.Platinum:
                return(hexD0D0E0);

            case AtomicNumbers.Gold:
                return(hexFFD123);

            case AtomicNumbers.Mercury:
                return(hexB8B8D0);

            case AtomicNumbers.Thallium:
                return(hexA6544D);

            case AtomicNumbers.Lead:
                return(hex575961);

            case AtomicNumbers.Bismuth:
                return(hex9E4FB5);

            case AtomicNumbers.Polonium:
                return(hexAB5C00);

            case AtomicNumbers.Astatine:
                return(hex754F45);

            case AtomicNumbers.Radon:
                return(hex428296);

            case AtomicNumbers.Francium:
                return(hex420066);

            case AtomicNumbers.Radium:
                return(hex007D00);

            case AtomicNumbers.Actinium:
                return(hex70ABFA);

            case AtomicNumbers.Thorium:
                return(hex00BAFF);

            case AtomicNumbers.Protactinium:
                return(hex00A1FF);

            case AtomicNumbers.Uranium:
                return(hex008FFF);

            case AtomicNumbers.Neptunium:
                return(hex0080FF);

            case AtomicNumbers.Plutonium:
                return(hex006BFF);

            case AtomicNumbers.Americium:
                return(hex545CF2);

            case AtomicNumbers.Curium:
                return(hex785CE3);

            case AtomicNumbers.Berkelium:
                return(hex8A4FE3);

            case AtomicNumbers.Californium:
                return(hexA136D4);

            case AtomicNumbers.Einsteinium:
                return(hexB31FD4);

            case AtomicNumbers.Fermium:
                return(hexB31FBA);

            case AtomicNumbers.Mendelevium:
                return(hexB30DA6);

            case AtomicNumbers.Nobelium:
                return(hexBD0D87);

            case AtomicNumbers.Lawrencium:
                return(hexC70066);

            case AtomicNumbers.Rutherfordium:
                return(hexCC0059);

            case AtomicNumbers.Dubnium:
                return(hexD1004F);

            case AtomicNumbers.Seaborgium:
                return(hexD90045);

            case AtomicNumbers.Bohrium:
                return(hexE00038);

            case AtomicNumbers.Hassium:
                return(hexE6002E);

            case AtomicNumbers.Meitnerium:
                return(hexEB0026);

            default:
                return(defaultColor);
            }
        }
Ejemplo n.º 6
0
 public IAtomType NewAtomType(ChemicalElement element) => (IAtomType) new AtomType(element);
Ejemplo n.º 7
0
 public IIsotope NewIsotope(ChemicalElement element, int massNumber) => (IIsotope) new Isotope(element, massNumber);
Ejemplo n.º 8
0
 /// <summary>
 /// Get the period of the element.
 /// </summary>
 /// <param name="symbol">the symbol of the element</param>
 /// <returns>the period</returns>
 public static int GetPeriod(string symbol)
 {
     return(NaturalElement.Periods[ChemicalElement.OfSymbol(symbol).AtomicNumber]);
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Get the Pauling electronegativity of an element.
 /// </summary>
 /// <param name="symbol">the symbol of the element</param>
 /// <returns>the Pauling electronegativity</returns>
 public static double?GetPaulingElectronegativity(string symbol)
 {
     return(NaturalElement.Electronegativities[ChemicalElement.OfSymbol(symbol).AtomicNumber]);
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Get the name of the element.
 /// </summary>
 /// <param name="symbol">the symbol of the element</param>
 /// <returns>the name of the element</returns>
 public static string GetName(string symbol)
 {
     return(GetName(ChemicalElement.OfSymbol(symbol).AtomicNumber));
 }
Ejemplo n.º 11
0
 /// <summary>
 /// Get the name of the element.
 /// </summary>
 /// <param name="atomicNumber">Atomic number</param>
 /// <returns>The name of the element</returns>
 public static string GetName(int atomicNumber)
 {
     return(ChemicalElement.Of(atomicNumber).Name);
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Find all enabled abbreviations in the provided molecule. They are not
        /// added to the existing Sgroups and may need filtering.
        /// </summary>
        /// <param name="mol">molecule</param>
        /// <returns>list of new abbreviation Sgroups</returns>
        public IList <Sgroup> Generate(IAtomContainer mol)
        {
            // mark which atoms have already been abbreviated or are
            // part of an existing Sgroup
            var usedAtoms = new HashSet <IAtom>();
            var sgroups   = mol.GetCtabSgroups();

            if (sgroups != null)
            {
                foreach (var sgroup in sgroups)
                {
                    foreach (var atom in sgroup.Atoms)
                    {
                        usedAtoms.Add(atom);
                    }
                }
            }

            // disconnected abbreviations, salts, common reagents, large compounds
            if (!usedAtoms.Any())
            {
                try
                {
                    var    copy   = AtomContainerManipulator.CopyAndSuppressedHydrogens(mol);
                    string cansmi = usmigen.Create(copy);
                    if (disconnectedAbbreviations.TryGetValue(cansmi, out string label) && !disabled.Contains(label))
                    {
                        var sgroup = new Sgroup
                        {
                            Type      = SgroupType.CtabAbbreviation,
                            Subscript = label
                        };
                        foreach (var atom in mol.Atoms)
                        {
                            sgroup.Atoms.Add(atom);
                        }
                        return(new[] { sgroup });
                    }
                    else if (cansmi.Contains("."))
                    {
                        var parts = ConnectivityChecker.PartitionIntoMolecules(mol);
                        // partiton in two two parts
                        Sgroup best = null;
                        for (int i = 0; i < parts.Count; i++)
                        {
                            var a = parts[i];
                            var b = a.Builder.NewAtomContainer();
                            for (int j = 0; j < parts.Count; j++)
                            {
                                if (j != i)
                                {
                                    b.Add(parts[j]);
                                }
                            }
                            var sgroup1 = GetAbbr(a);
                            var sgroup2 = GetAbbr(b);
                            if (sgroup1 != null && sgroup2 != null)
                            {
                                var combined = new Sgroup();
                                label = null;
                                foreach (var atom in sgroup1.Atoms)
                                {
                                    combined.Atoms.Add(atom);
                                }
                                foreach (var atom in sgroup2.Atoms)
                                {
                                    combined.Atoms.Add(atom);
                                }
                                if (sgroup1.Subscript.Length > sgroup2.Subscript.Length)
                                {
                                    combined.Subscript = sgroup1.Subscript + String_Interpunct + sgroup2.Subscript;
                                }
                                else
                                {
                                    combined.Subscript = sgroup2.Subscript + String_Interpunct + sgroup1.Subscript;
                                }
                                combined.Type = SgroupType.CtabAbbreviation;
                                return(new[] { combined });
                            }
                            if (sgroup1 != null && (best == null || sgroup1.Atoms.Count > best.Atoms.Count))
                            {
                                best = sgroup1;
                            }
                            if (sgroup2 != null && (best == null || sgroup2.Atoms.Count > best.Atoms.Count))
                            {
                                best = sgroup2;
                            }
                        }
                        if (best != null)
                        {
                            return new[] { best }
                        }
                        ;
                    }
                }
                catch (CDKException)
                {
                }
            }

            var newSgroups = new List <Sgroup>();
            var fragments  = GenerateFragments(mol);
            var sgroupAdjs = new MultiDictionary <IAtom, Sgroup>();

            foreach (var frag in fragments)
            {
                try
                {
                    var smi = usmigen.Create(AtomContainerManipulator.CopyAndSuppressedHydrogens(frag));
                    if (!connectedAbbreviations.TryGetValue(smi, out string label) || disabled.Contains(label))
                    {
                        continue;
                    }

                    bool overlap = false;

                    // note: first atom is '*'
                    var numAtoms = frag.Atoms.Count;
                    var numBonds = frag.Bonds.Count;
                    for (int i = 1; i < numAtoms; i++)
                    {
                        if (usedAtoms.Contains(frag.Atoms[i]))
                        {
                            overlap = true;

                            break;
                        }
                    }

                    // overlaps with previous assignment
                    if (overlap)
                    {
                        continue;
                    }

                    // create new abbreviation Sgroup
                    var sgroup = new Sgroup
                    {
                        Type      = SgroupType.CtabAbbreviation,
                        Subscript = label
                    };

                    var   attachBond = frag.Bonds[0].GetProperty <IBond>(PropertyName_CutBond);
                    IAtom attachAtom = null;
                    sgroup.Bonds.Add(attachBond);
                    for (int i = 1; i < numAtoms; i++)
                    {
                        var atom = frag.Atoms[i];
                        usedAtoms.Add(atom);
                        sgroup.Atoms.Add(atom);
                        if (attachBond.Begin.Equals(atom))
                        {
                            attachAtom = attachBond.End;
                        }
                        else if (attachBond.End.Equals(atom))
                        {
                            attachAtom = attachBond.Begin;
                        }
                    }

                    if (attachAtom != null)
                    {
                        sgroupAdjs.Add(attachAtom, sgroup);
                    }
                    newSgroups.Add(sgroup);
                }
                catch (CDKException)
                {
                    // ignore
                }
            }

            if (!ContractOnHetero)
            {
                return(newSgroups);
            }

            // now collapse
            foreach (var attach in mol.Atoms)
            {
                if (usedAtoms.Contains(attach))
                {
                    continue;
                }

                // skip charged or isotopic labelled, C or R/*, H, He
                if ((attach.FormalCharge != null && attach.FormalCharge != 0) ||
                    attach.MassNumber != null ||
                    attach.AtomicNumber == 6 ||
                    attach.AtomicNumber < 2)
                {
                    continue;
                }

                var hcount   = attach.ImplicitHydrogenCount.Value;
                var xatoms   = new HashSet <IAtom>();
                var xbonds   = new HashSet <IBond>();
                var newbonds = new HashSet <IBond>();
                xatoms.Add(attach);

                var nbrSymbols = new List <string>();
                var todelete   = new HashSet <Sgroup>();
                foreach (var sgroup in sgroupAdjs[attach])
                {
                    if (ContainsChargeChar(sgroup.Subscript))
                    {
                        continue;
                    }
                    if (sgroup.Bonds.Count != 1)
                    {
                        continue;
                    }
                    var xbond = sgroup.Bonds.First();
                    xbonds.Add(xbond);
                    foreach (var a in sgroup.Atoms)
                    {
                        xatoms.Add(a);
                    }
                    if (attach.Symbol.Length == 1 &&
                        char.IsLower(sgroup.Subscript[0]))
                    {
                        if (ChemicalElement.OfSymbol(attach.Symbol + sgroup.Subscript[0]) != ChemicalElement.R)
                        {
                            goto continue_collapse;
                        }
                    }
                    nbrSymbols.Add(sgroup.Subscript);
                    todelete.Add(sgroup);
                }
                int numSGrpNbrs = nbrSymbols.Count;
                foreach (var bond in mol.GetConnectedBonds(attach))
                {
                    if (!xbonds.Contains(bond))
                    {
                        var nbr = bond.GetOther(attach);
                        // contract terminal bonds
                        if (mol.GetConnectedBonds(nbr).Count() == 1)
                        {
                            if (nbr.MassNumber != null ||
                                (nbr.FormalCharge != null && nbr.FormalCharge != 0))
                            {
                                newbonds.Add(bond);
                            }
                            else if (nbr.AtomicNumber == 1)
                            {
                                hcount++;
                                xatoms.Add(nbr);
                            }
                            else if (nbr.AtomicNumber > 0)
                            {
                                nbrSymbols.Add(NewSymbol(nbr.AtomicNumber, nbr.ImplicitHydrogenCount.Value, false));
                                xatoms.Add(nbr);
                            }
                        }
                        else
                        {
                            newbonds.Add(bond);
                        }
                    }
                }

                // reject if no symbols
                // reject if no bonds (<1), except if all symbols are identical... (HashSet.size==1)
                // reject if more that 2 bonds
                if (!nbrSymbols.Any() ||
                    newbonds.Count < 1 && (new HashSet <string>(nbrSymbols).Count != 1) ||
                    newbonds.Count > 2)
                {
                    continue;
                }

                // create the symbol
                var sb = new StringBuilder();
                sb.Append(NewSymbol(attach.AtomicNumber, hcount, newbonds.Count == 0));
                string prev  = null;
                int    count = 0;
                nbrSymbols.Sort((o1, o2) =>
                {
                    int cmp = o1.Length.CompareTo(o2.Length);
                    if (cmp != 0)
                    {
                        return(cmp);
                    }
                    return(o1.CompareTo(o2));
                });
                foreach (string nbrSymbol in nbrSymbols)
                {
                    if (nbrSymbol.Equals(prev))
                    {
                        count++;
                    }
                    else
                    {
                        bool useParen = count == 0 || CountUpper(prev) > 1 || (prev != null && nbrSymbol.StartsWith(prev));
                        AppendGroup(sb, prev, count, useParen);
                        prev  = nbrSymbol;
                        count = 1;
                    }
                }
                AppendGroup(sb, prev, count, false);

                // remove existing
                foreach (var e in todelete)
                {
                    newSgroups.Remove(e);
                }

                // create new
                var newSgroup = new Sgroup
                {
                    Type      = SgroupType.CtabAbbreviation,
                    Subscript = sb.ToString()
                };
                foreach (var bond in newbonds)
                {
                    newSgroup.Bonds.Add(bond);
                }
                foreach (var atom in xatoms)
                {
                    newSgroup.Atoms.Add(atom);
                }

                newSgroups.Add(newSgroup);
                foreach (var a in xatoms)
                {
                    usedAtoms.Add(a);
                }
continue_collapse:
                ;
            }

            return(newSgroups);
        }
Ejemplo n.º 13
0
 public IntToChemicalData(int c, ChemicalElement t, bool e = false)
 {
     this.couple = c;
     this.type   = t;
     this.empty  = e;
 }
Ejemplo n.º 14
0
 public ChemicalToArrayData(ChemicalElement e, ChemicalElement[] a)
 {
     this.element = e;
     this.array   = a;
 }
Ejemplo n.º 15
0
 public IAtom NewAtom(ChemicalElement element) => (IAtom) new Atom(element);
Ejemplo n.º 16
0
 /// <summary>
 /// Get the symbol for the specified atomic number.
 /// </summary>
 /// <param name="atomicNumber">the atomic number of the element</param>
 /// <returns>the corresponding symbol</returns>
 public static string GetSymbol(int atomicNumber)
 {
     return(ChemicalElement.Of(atomicNumber).Symbol);
 }
Ejemplo n.º 17
0
 public IAtom NewAtom(ChemicalElement element, Vector3 point3d) => (IAtom) new Atom(element, point3d);
Ejemplo n.º 18
0
 /// <summary>
 /// Get the Van der Waals radius for the element in question.
 /// </summary>
 /// <param name="symbol">The symbol of the element</param>
 /// <returns>the Van der waals radius</returns>
 public static double?GetVdwRadius(string symbol)
 {
     return(GetVdwRadius(ChemicalElement.OfSymbol(symbol).AtomicNumber));
 }
Ejemplo n.º 19
0
 public IIsotope NewIsotope(ChemicalElement element) => (IIsotope) new Isotope(element);
Ejemplo n.º 20
0
 /// <summary>
 /// Get the covalent radius for an element.
 /// </summary>
 /// <param name="symbol">the symbol of the element</param>
 /// <returns>the covalent radius</returns>
 public static double?GetCovalentRadius(string symbol)
 {
     return(NaturalElement.CovalentRadiuses[ChemicalElement.OfSymbol(symbol).AtomicNumber]);
 }
Ejemplo n.º 21
0
 public IIsotope NewIsotope(ChemicalElement element, double exactMass, double abundance) => (IIsotope) new Isotope(element, exactMass, abundance);
Ejemplo n.º 22
0
 /// <summary>
 /// Get the CAS ID for an element.
 /// </summary>
 /// <param name="symbol">the symbol of the element</param>
 /// <returns>the CAS ID</returns>
 public static string GetCASId(string symbol)
 {
     return(MapToCasId[ChemicalElement.OfSymbol(symbol).AtomicNumber]);
 }
Ejemplo n.º 23
0
 public IPDBAtom NewPDBAtom(ChemicalElement element) => (IPDBAtom) new PDBAtom(element);
Ejemplo n.º 24
0
 /// <summary>
 /// Get the group of the element.
 /// </summary>
 /// <param name="symbol">the symbol of the element</param>
 /// <returns>the group</returns>
 public static int GetGroup(string symbol)
 {
     return(GetGroup(ChemicalElement.OfSymbol(symbol).AtomicNumber));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ChemicalFormulaComponent"/> class.
 /// </summary>
 /// <param name="element">The chemical element that is part of the molecule.</param>
 /// <param name="atomCount">The number of atoms contributed to the molecule.</param>
 public ChemicalFormulaComponent(ChemicalElement element, int atomCount = 1)
 {
     this.Element = element;
     this.AtomCount = atomCount;
 }
Ejemplo n.º 26
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);
        }