public void PermuteCNOMolecule() { Molecule molecule = new Molecule(); molecule.AddAtom("C"); molecule.AddAtom("N"); molecule.AddAtom("O"); molecule.AddSingleBond(0, 1); molecule.AddSingleBond(1, 2); PermuteCompletely(molecule); }
public static Molecule Methane() { Molecule molecule = new Molecule(); molecule.AddAtom("C"); molecule.AddAtom("H"); molecule.AddAtom("H"); molecule.AddAtom("H"); molecule.AddAtom("H"); molecule.AddSingleBond(0, 1); molecule.AddSingleBond(0, 2); molecule.AddSingleBond(0, 3); molecule.AddSingleBond(0, 4); return(molecule); }
private void BuildSolution(AtomType[] atomsToAdd, int[] quantityToAdd) { print("SOLUTION CONSTRUCTOR: has started building"); if (atomsToAdd.Length == 0) { print("atomsToAdd.Length == 0"); return; } Molecule newMolecule = ScriptableObject.CreateInstance <Molecule>(); for (int i = 0; i < atomsToAdd.Length; i++) { for (int x = 0; x < quantityToAdd[i];) { print("SOLUTION CONSTRUCTOR: Created one " + atomDictionary.TypeToClass(atomsToAdd[i])); Atom atom = atomDictionary.TypeToClass(atomsToAdd[i]); newMolecule.AddAtom(atom); print("SOLUTION CONSTRUCTOR: Added it to newMolecule"); } } solution.AddMolecule(newMolecule); print("SOLUTION CONSTRUCTOR: called solution.AddMolecule(newMolecule)"); }
public static Molecule ReadNative(System.IO.StreamReader in_Renamed) { Molecule mol = new Molecule(); //UPGRADE_NOTE: Final was removed from the declaration of 'GENERIC_ERROR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" System.String GENERIC_ERROR = "Invalid SketchEl file."; try { System.String line = in_Renamed.ReadLine(); if (!line.StartsWith("SketchEl!")) { throw new System.IO.IOException("Not a SketchEl file."); } int p1 = line.IndexOf('('), p2 = line.IndexOf(','), p3 = line.IndexOf(')'); if (p1 == 0 || p2 == 0 || p3 == 0) { throw new System.IO.IOException(GENERIC_ERROR); } int numAtoms = System.Int32.Parse(line.Substring(p1 + 1, (p2) - (p1 + 1)).Trim()); int numBonds = System.Int32.Parse(line.Substring(p2 + 1, (p3) - (p2 + 1)).Trim()); for (int n = 0; n < numAtoms; n++) { line = in_Renamed.ReadLine(); // TODO: verify java's split method syntax: "[\\=\\,\\;]" System.String[] bits = line.Split('=', ',', ';'); if (bits.Length < 5) { throw new System.IO.IOException(GENERIC_ERROR); } int num = mol.AddAtom(bits[0], System.Double.Parse(bits[1].Trim()), System.Double.Parse(bits[2].Trim()), System.Int32.Parse(bits[3].Trim()), System.Int32.Parse(bits[4].Trim())); if (bits.Length >= 6 && bits[5].Length > 0 && bits[5][0] == 'e') { mol.SetAtomHExplicit(num, System.Int32.Parse(bits[5].Substring(1))); } } for (int n = 0; n < numBonds; n++) { line = in_Renamed.ReadLine(); System.String[] bits = line.Split('-', '=', ','); // "[\\-\\=\\,]"); if (bits.Length < 4) { throw new System.IO.IOException(GENERIC_ERROR); } mol.AddBond(System.Int32.Parse(bits[0].Trim()), System.Int32.Parse(bits[1].Trim()), System.Int32.Parse(bits[2].Trim()), System.Int32.Parse(bits[3].Trim())); } line = in_Renamed.ReadLine(); if (String.CompareOrdinal(line, "!End") != 0) { throw new System.IO.IOException(GENERIC_ERROR); } } catch (System.Exception) { throw new System.IO.IOException(GENERIC_ERROR); } return(mol); }
public void CheckValencyCalculations(string element, int charge, int bonds, int expectedImplicitHCount, bool expectedOverbonding) { // Arrange var model = new Model(); var molecule = new Molecule(); model.AddMolecule(molecule); molecule.Parent = model; var atom = new Atom(); molecule.AddAtom(atom); atom.Parent = molecule; atom.Element = Globals.PeriodicTable.Elements[element]; atom.FormalCharge = charge; AddHBonds(molecule, atom, bonds); var bondOrders = (int)Math.Truncate(atom.BondOrders); // Act var implicitHydrogen = atom.ImplicitHydrogenCount; var over = atom.Overbonded; // Assert Assert.Equal(bondOrders, bonds); Assert.Equal(expectedImplicitHCount, implicitHydrogen); Assert.Equal(expectedOverbonding, over); Debug.Write("."); }
private void AddHBonds(Molecule molecule, Atom atom, int bonds) { for (int i = 0; i < bonds; i++) { Atom h = new Atom(); h.Element = Globals.PeriodicTable.H; molecule.AddAtom(h); h.Parent = molecule; Bond bond = new Bond(atom, h); bond.Order = "S"; molecule.AddBond(bond); bond.Parent = molecule; } }
public void PermuteOCCCSC() { Molecule molecule = new Molecule(); molecule.AddAtom("O"); molecule.AddAtom("C"); molecule.AddAtom("C"); molecule.AddAtom("C"); molecule.AddAtom("S"); molecule.AddAtom("C"); molecule.AddBond(0, 1, Molecule.BondOrder.Double); molecule.AddSingleBond(1, 2); molecule.AddSingleBond(2, 3); molecule.AddSingleBond(3, 4); molecule.AddSingleBond(4, 5); PermuteCompletely(molecule); }
private void BuildSolution(AtomType[] atomsToAdd, int[] quantityToAdd) { if (atomsToAdd.Length == 0) { print("atomsToAdd.Length == 0"); return; } Molecule newMolecule = ScriptableObject.CreateInstance <Molecule>(); for (int i = 0; i < atomsToAdd.Length; i++) { for (int x = 0; x < quantityToAdd[i]; x++) { Atom atom = atomDictionary.TypeToClass(atomsToAdd[i]); newMolecule.AddAtom(atom); } } newMolecule.SetValues(); solution.AddMolecule(newMolecule); }
public void DoubleBondChainTest() { Molecule molecule = new Molecule(); int chainLength = 6; molecule.AddAtom("O"); molecule.AddAtom("C"); molecule.AddAtom("C"); molecule.AddAtom("O"); molecule.AddAtom("C"); molecule.AddAtom("O"); for (int i = 0; i < chainLength - 2; i++) { molecule.AddSingleBond(i, i + 1); } molecule.AddBond(chainLength - 2, chainLength - 1, Molecule.BondOrder.Double); string sigA = ToSignatureString(molecule); // PermuteCompletely(molecule); // TestSpecificPermutation(molecule, new int[] {0,1,3,4,2,5}); Molecule moleculeB = new Molecule(); moleculeB.AddAtom("O"); moleculeB.AddAtom("C"); moleculeB.AddAtom("C"); moleculeB.AddAtom("C"); moleculeB.AddAtom("O"); moleculeB.AddAtom("O"); moleculeB.AddSingleBond(0, 1); moleculeB.AddSingleBond(1, 3); moleculeB.AddSingleBond(2, 4); moleculeB.AddBond(2, 5, Molecule.BondOrder.Double); moleculeB.AddSingleBond(3, 4); string sigB = ToSignatureString(moleculeB); // MoleculeSignature molSig = new MoleculeSignature(moleculeB); // molSig.SignatureStringForVertex(1); Assert.AreEqual(sigA, sigB); }
public static void DoPropertyEdit(MouseButtonEventArgs e, EditorCanvas currentEditor) { EditViewModel evm = (EditViewModel)currentEditor.Chemistry; var position = e.GetPosition(currentEditor); var screenPosition = currentEditor.PointToScreen(position); // Did RightClick occur on a Molecule Selection Adorner? var moleculeAdorner = currentEditor.GetMoleculeAdorner(position); if (moleculeAdorner != null) { if (moleculeAdorner.AdornedMolecules.Count == 1) { screenPosition = GetDpiAwareScaledPosition(screenPosition, moleculeAdorner); var mode = Application.Current.ShutdownMode; Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown; var model = new MoleculePropertiesModel(); model.Centre = screenPosition; model.Path = moleculeAdorner.AdornedMolecules[0].Path; model.Used1DProperties = evm.Used1DProperties; model.Data = new Model(); Molecule mol = moleculeAdorner.AdornedMolecules[0].Copy(); model.Data.AddMolecule(mol); mol.Parent = model.Data; model.Charge = mol.FormalCharge; model.Count = mol.Count; model.SpinMultiplicity = mol.SpinMultiplicity; model.ShowMoleculeBrackets = mol.ShowMoleculeBrackets; var pe = new MoleculePropertyEditor(model); ShowDialog(pe, currentEditor); if (model.Save) { var thisMolecule = model.Data.Molecules.First().Value; evm.UpdateMolecule(moleculeAdorner.AdornedMolecules[0], thisMolecule); } Application.Current.ShutdownMode = mode; } } else { // Did RightClick occur on a ChemicalVisual? var activeVisual = currentEditor.GetTargetedVisual(position); if (activeVisual != null) { screenPosition = GetDpiAwareScaledPosition(screenPosition, activeVisual); // Did RightClick occur on an AtomVisual? if (activeVisual is AtomVisual av) { var mode = Application.Current.ShutdownMode; Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown; var atom = av.ParentAtom; var model = new AtomPropertiesModel { Centre = screenPosition, Path = atom.Path, Element = atom.Element }; if (atom.Element is Element) { model.IsFunctionalGroup = false; model.IsElement = true; model.Charge = atom.FormalCharge ?? 0; model.Isotope = atom.IsotopeNumber.ToString(); model.ShowSymbol = atom.ShowSymbol; } if (atom.Element is FunctionalGroup) { model.IsElement = false; model.IsFunctionalGroup = true; } model.MicroModel = new Model(); Molecule m = new Molecule(); model.MicroModel.AddMolecule(m); m.Parent = model.MicroModel; Atom a = new Atom(); a.Element = atom.Element; a.Position = atom.Position; a.FormalCharge = atom.FormalCharge; a.IsotopeNumber = atom.IsotopeNumber; m.AddAtom(a); a.Parent = m; foreach (var bond in atom.Bonds) { Atom ac = new Atom(); ac.Element = Globals.PeriodicTable.C; ac.ShowSymbol = false; ac.Position = bond.OtherAtom(atom).Position; m.AddAtom(ac); ac.Parent = m; Bond b = new Bond(a, ac); b.Order = bond.Order; if (bond.Stereo != Globals.BondStereo.None) { b.Stereo = bond.Stereo; if (bond.Stereo == Globals.BondStereo.Wedge || bond.Stereo == Globals.BondStereo.Hatch) { if (atom.Path.Equals(bond.StartAtom.Path)) { b.StartAtomInternalId = a.InternalId; b.EndAtomInternalId = ac.InternalId; } else { b.StartAtomInternalId = ac.InternalId; b.EndAtomInternalId = a.InternalId; } } } m.AddBond(b); b.Parent = m; } model.MicroModel.ScaleToAverageBondLength(20); var pe = new AtomPropertyEditor(model); ShowDialog(pe, currentEditor); Application.Current.ShutdownMode = mode; if (model.Save) { evm.UpdateAtom(atom, model); evm.ClearSelection(); evm.AddToSelection(atom); if (model.AddedElement != null) { AddOptionIfNeeded(model); } evm.SelectedElement = model.Element; } } // Did RightClick occur on a BondVisual? if (activeVisual is BondVisual bv) { var mode = Application.Current.ShutdownMode; Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown; var bond = bv.ParentBond; var model = new BondPropertiesModel { Centre = screenPosition, Path = bond.Path, Angle = bond.Angle, BondOrderValue = bond.OrderValue.Value, IsSingle = bond.Order.Equals(Globals.OrderSingle), IsDouble = bond.Order.Equals(Globals.OrderDouble), Is1Point5 = bond.Order.Equals(Globals.OrderPartial12), Is2Point5 = bond.Order.Equals(Globals.OrderPartial23) }; model.DoubleBondChoice = DoubleBondType.Auto; if (model.IsDouble | model.Is1Point5 | model.Is2Point5) { if (bond.ExplicitPlacement != null) { model.DoubleBondChoice = (DoubleBondType)bond.ExplicitPlacement.Value; } else { if (model.IsDouble) { if (bond.Stereo == Globals.BondStereo.Indeterminate) { model.DoubleBondChoice = DoubleBondType.Indeterminate; } } } } if (model.IsSingle) { model.SingleBondChoice = SingleBondType.None; switch (bond.Stereo) { case Globals.BondStereo.Wedge: model.SingleBondChoice = SingleBondType.Wedge; break; case Globals.BondStereo.Hatch: model.SingleBondChoice = SingleBondType.Hatch; break; case Globals.BondStereo.Indeterminate: model.SingleBondChoice = SingleBondType.Indeterminate; break; default: model.SingleBondChoice = SingleBondType.None; break; } } var pe = new BondPropertyEditor(model); ShowDialog(pe, currentEditor); Application.Current.ShutdownMode = mode; if (model.Save) { evm.UpdateBond(bond, model); evm.ClearSelection(); bond.Order = Globals.OrderValueToOrder(model.BondOrderValue); evm.AddToSelection(bond); } } } } void AddOptionIfNeeded(AtomPropertiesModel model) { if (!evm.AtomOptions.Any(ao => ao.Element.Symbol == model.AddedElement.Symbol)) { AtomOption newOption = null; switch (model.AddedElement) { case Element elem: newOption = new AtomOption(elem); break; case FunctionalGroup group: newOption = new AtomOption(group); break; } evm.AtomOptions.Add(newOption); } } }
internal static Molecule ReadXML(FileStream istr) { Molecule mol = new Molecule(); const string NAMESPACE = "http://www.xml-cml.org/schema/cml2/core"; const string ATTRIBUTENS = ""; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(istr); XPathNavigator navigator = xmlDoc.CreateNavigator(); if (navigator.MoveToFirstChild()) { navigator.MoveToChild("molecule", NAMESPACE); //navigator.MoveToFirstChild(); if (navigator.MoveToChild("atomArray", NAMESPACE)) { if (navigator.MoveToChild("atom", NAMESPACE)) { do { string elementType = navigator.GetAttribute("elementType", ATTRIBUTENS); string x2String = navigator.GetAttribute("x2", ATTRIBUTENS); if (!string.IsNullOrEmpty(x2String)) { double x2 = Utility.SafeDouble(x2String); double y2 = Utility.SafeDouble(navigator.GetAttribute("y2", ATTRIBUTENS)); int hydrogenCount = Utility.SafeInt(navigator.GetAttribute("hydrogenCount", ATTRIBUTENS)); // TODO: How do we handle hydrogen count? mol.AddAtom(elementType, x2, y2); } else { double x3 = Utility.SafeDouble(navigator.GetAttribute("x3", ATTRIBUTENS)); double y3 = Utility.SafeDouble(navigator.GetAttribute("y3", ATTRIBUTENS)); int hydrogenCount = Utility.SafeInt(navigator.GetAttribute("hydrogenCount", ATTRIBUTENS)); // TODO: How do we handle hydrogen count? mol.AddAtom(elementType, x3, y3); } } while (navigator.MoveToNext("atom", NAMESPACE)); navigator.MoveToParent(); } navigator.MoveToParent(); } if (navigator.MoveToChild("bondArray", NAMESPACE)) { if (navigator.MoveToChild("bond", NAMESPACE)) { do { string atomRefs = navigator.GetAttribute("atomRefs2", ATTRIBUTENS); string[] parts = atomRefs.Split(' '); if (parts.Length == 2) { int from = Utility.SafeInt(parts[0].Substring(1)); int to = Utility.SafeInt(parts[1].Substring(1)); int order = Utility.SafeInt(navigator.GetAttribute("order", ATTRIBUTENS)); int type = 0; // Where or is type stored? // TODO: How do we handle hydrogen count? mol.AddBond(from, to, order, type); } } while (navigator.MoveToNext("bond", NAMESPACE)); navigator.MoveToParent(); } navigator.MoveToParent(); } } return(mol); }
public static Molecule ReadMDLMOL(StreamReader in_Renamed) { Molecule mol = new Molecule(); //UPGRADE_NOTE: Final was removed from the declaration of 'GENERIC_ERROR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" System.String GENERIC_ERROR = "Invalid MDL MOL file."; try { System.String line = null; for (int n = 0; n < 4; n++) { line = in_Renamed.ReadLine(); } if (line == null || !line.Substring(34, (39) - (34)).Equals("V2000")) { throw new System.IO.IOException(GENERIC_ERROR); } int numAtoms = System.Int32.Parse(line.Substring(0, (3) - (0)).Trim()); int numBonds = System.Int32.Parse(line.Substring(3, (6) - (3)).Trim()); for (int n = 0; n < numAtoms; n++) { line = in_Renamed.ReadLine(); double x = System.Double.Parse(line.Substring(0, (10) - (0)).Trim()); double y = System.Double.Parse(line.Substring(10, (20) - (10)).Trim()); System.String el = line.Substring(31, (33) - (31)).Trim(); int chg = System.Int32.Parse(line.Substring(36, (39) - (36)).Trim()), rad = 0; if (chg <= 3) { } else if (chg == 4) { chg = 0; rad = 2; } else { chg = 4 - chg; } mol.AddAtom(el, x, y, chg, rad); } for (int n = 0; n < numBonds; n++) { line = in_Renamed.ReadLine(); int from = System.Int32.Parse(line.Substring(0, (3) - (0)).Trim()), to = System.Int32.Parse(line.Substring(3, (6) - (3)).Trim()); int type = System.Int32.Parse(line.Substring(6, (9) - (6)).Trim()), stereo = System.Int32.Parse(line.Substring(9, (12) - (9)).Trim()); if (from == to || from < 1 || from > numAtoms || to < 1 || to > numAtoms) { throw new System.IO.IOException(GENERIC_ERROR); } int order = type >= 1 && type <= 3?type:1; int style = Molecule.BONDTYPE_NORMAL; if (stereo == 1) { style = Molecule.BONDTYPE_INCLINED; } else if (stereo == 6) { style = Molecule.BONDTYPE_DECLINED; } else if (stereo == 3 || stereo == 4) { style = Molecule.BONDTYPE_UNKNOWN; } mol.AddBond(from, to, order, style); } while (true) { line = in_Renamed.ReadLine(); if (line.StartsWith("M END")) { break; } int type = 0; if (line.StartsWith("M CHG")) { type = 1; } else if (line.StartsWith("M RAD")) { type = 2; } if (type > 0) { int len = System.Int32.Parse(line.Substring(6, (9) - (6)).Trim()); for (int n = 0; n < len; n++) { int apos = System.Int32.Parse(line.Substring(9 + 8 * n, (13 + 8 * n) - (9 + 8 * n)).Trim()); int aval = System.Int32.Parse(line.Substring(13 + 8 * n, (17 + 8 * n) - (13 + 8 * n)).Trim()); if (type == 1) { mol.SetAtomCharge(apos, aval); } else { mol.SetAtomUnpaired(apos, aval); } } } } } catch (System.Exception) { throw new System.IO.IOException(GENERIC_ERROR); } return(mol); }
public void CheckClone() { Model model = new Model(); Molecule molecule = new Molecule(); molecule.Id = "m1"; model.AddMolecule(molecule); molecule.Parent = model; Atom startAtom = new Atom(); startAtom.Id = "a1"; startAtom.Element = Globals.PeriodicTable.C; startAtom.Position = new Point(5, 5); molecule.AddAtom(startAtom); startAtom.Parent = molecule; Atom endAtom = new Atom(); endAtom.Id = "a2"; endAtom.Element = Globals.PeriodicTable.C; endAtom.Position = new Point(10, 10); molecule.AddAtom(endAtom); endAtom.Parent = molecule; Bond bond = new Bond(startAtom, endAtom); bond.Id = "b1"; bond.Order = Globals.OrderSingle; molecule.AddBond(bond); bond.Parent = molecule; Assert.True(model.Molecules.Count == 1, $"Expected 1 Molecule; Got {model.Molecules.Count}"); var a1 = model.Molecules.Values.First().Atoms.Values.First(); Assert.True(Math.Abs(a1.Position.X - 5.0) < 0.001, $"Expected a1.X = 5; Got {a1.Position.X}"); Assert.True(Math.Abs(a1.Position.Y - 5.0) < 0.001, $"Expected a1.Y = 5; Got {a1.Position.Y}"); Model clone = model.Copy(); Assert.True(model.Molecules.Count == 1, $"Expected 1 Molecule; Got {model.Molecules.Count}"); Assert.True(clone.Molecules.Count == 1, $"Expected 1 Molecule; Got {clone.Molecules.Count}"); var a2 = clone.Molecules.Values.First().Atoms.Values.First(); Assert.True(Math.Abs(a2.Position.X - 5.0) < 0.001, $"Expected a2.X = 5; Got {a2.Position.X}"); Assert.True(Math.Abs(a2.Position.Y - 5.0) < 0.001, $"Expected a2.Y = 5; Got {a2.Position.Y}"); clone.ScaleToAverageBondLength(5); var a3 = model.Molecules.Values.First().Atoms.Values.First(); Assert.True(Math.Abs(a3.Position.X - 5.0) < 0.001, $"Expected a3.X = 5; Got {a3.Position.X}"); Assert.True(Math.Abs(a3.Position.Y - 5.0) < 0.001, $"Expected a3.Y = 5; Got {a3.Position.Y}"); var a4 = clone.Molecules.Values.First().Atoms.Values.First(); Assert.True(Math.Abs(a4.Position.X - 3.535) < 0.001, $"Expected a4.X = 3.535; Got {a4.Position.X}"); Assert.True(Math.Abs(a4.Position.Y - 3.535) < 0.001, $"Expected a4.Y = 3.535; Got {a4.Position.Y}"); }
public override object VisitBranched_atom([NotNull] smilesParser.Branched_atomContext context) { foreach (IParseTree tree in context.children) { if (typeof(smilesParser.AtomContext).IsAssignableFrom(tree.GetType())) { Atom current = (Atom)VisitAtom((smilesParser.AtomContext)tree); if (current.Element != ELEMENTS.H) { retVal.AddAtom(current); if (addExplicitHToNext) { current.ExplicitHydrogens++; addExplicitHToNext = false; } if (last != null) { if (last.AtomType == AtomType.AROMATIC && current.AtomType == AtomType.AROMATIC) { nextBond = BondType.Aromatic; } } Bond b = retVal.AddBond(last, current, nextBond, BondStereo.NotStereoOrUseXYZ, BondTopology.Either, BondReactingCenterStatus.Unmarked); if (!string.IsNullOrEmpty(cisTrans) && nextBond == BondType.Double) { doubleBonds.Add(b); } nextBond = BondType.Single; last = current; } else { if (last != null) { last.ExplicitHydrogens++; } else { addExplicitHToNext = true; } } } else if (typeof(smilesParser.RingbondContext).IsAssignableFrom(tree.GetType())) { int ring = (int)VisitRingbond((smilesParser.RingbondContext)tree); if (ringAtoms.ContainsKey(ring)) { BondType nextType = (BondType)ringbonds[ring]; if (nextType != BondType.Single && (nextBond == BondType.Single || nextBond == nextType)) { nextBond = nextType; } Bond b = retVal.AddBond(last, (Atom)ringAtoms[ring], nextBond, BondStereo.NotStereoOrUseXYZ, BondTopology.Either, BondReactingCenterStatus.Unmarked); if (!string.IsNullOrEmpty(cisTrans) && nextBond == BondType.Double) { doubleBonds.Add(b); } nextBond = BondType.Single; ringAtoms.Remove(ring); ringbonds.Remove(ring); } else { ringAtoms.Add(ring, last); ringbonds.Add(ring, nextBond); nextBond = BondType.Single; } } else if (typeof(smilesParser.BranchContext).IsAssignableFrom(tree.GetType())) { Atom temp = last; VisitBranch((smilesParser.BranchContext)tree); last = temp; } else if (typeof(smilesParser.BondContext).IsAssignableFrom(tree.GetType())) { nextBond = (BondType)VisitBond((smilesParser.BondContext)context.GetChild(1)); } else { throw new System.InvalidOperationException("uhoh"); } } return(null); }
//static Molecule ReadMoleFile(string filename) //{ // using (var reader = new System.IO.StreamReader(filename)) // { // string s = reader.ReadToEnd(); // if (s.Contains("V2000")) return MoleFileReader.ParseMoleFile2(s); // if (s.Contains("V3000")) throw new Exception("Version 3000 Mol file is currently not supported."); // throw new Exception("Mol file type not recognized. It is does not contain a version number."); // } //} static Molecule ParseMoleFile2(string moleFile) { Molecule molecule = new Molecule(); //atoms.Clear(); //cycles.Clear(); //fusedRings.Clear(); int numAtoms = 0; int numBonds = 0; // This information is contained in the header (first 3 lines) of the mol file. It is currently not being used, but code has been created for // future use. string name = string.Empty; string program = string.Empty; string user = string.Empty; //// used to test Line 2 reading below. //string MM = string.Empty; //string DD = string.Empty; //string YY = string.Empty; //string HH = string.Empty; //string mm = string.Empty; int MM = 1; int DD = 1; int YY = 0; int HH = 0; int mm = 0; string dimensionalCodes = string.Empty; //// used to test Line 2 reading below. //string scalingFactor1 = string.Empty; int scalingFactor1 = 0; //// used to test Line 2 reading below. //string scalingFactor2 = string.Empty; double scalingFactor2 = 0; // used to test Line 2 reading below. string energy = string.Empty; string registryNumber = string.Empty; string comments = string.Empty; string[] lines = moleFile.Split('\n'); // Line 1 contains the compound name. It can not be longer than 80 characters, and is allowed to be empty. // The length of the line is not relevant in how this is read, so it is not checked. name = lines[0]; //// used to test Line 2 reading below. //lines[1] = "IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR"; // Line 2 is optional. Skip this if it is not there. if (lines[1] != string.Empty) { // Line format: IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR // A2<--A8--><---A10-->A2I2<--F10.5-><---F12.5--><-I6-> //User's first and last initials (l), program name (P), date/time (M/D/Y,H:m), //dimensional codes (d), scaling factors (S, s), energy (E) if modeling program input, //internal registry number (R) if input through MDL form. if (lines[1].Length > 2) { user = lines[1].Substring(0, 2); // II } if (lines[1].Length > 10) { program = lines[1].Substring(2, 8); // PPPPPPPP } if (lines[1].Length > 20) { //// used to test Line 2 reading below. //MM = lines[1].Substring(10, 2); // MMDDYYHHmm //DD = lines[1].Substring(12, 2); // MMDDYYHHmm //YY = lines[1].Substring(14, 2); // MMDDYYHHmm //HH = lines[1].Substring(16, 2); // MMDDYYHHmm //mm = lines[1].Substring(18, 2); // MMDDYYHHmm MM = Convert.ToInt32(lines[1].Substring(10, 2)); // MMDDYYHHmm DD = Convert.ToInt32(lines[1].Substring(12, 2)); // MMDDYYHHmm YY = Convert.ToInt32(lines[1].Substring(14, 2)); // MMDDYYHHmm HH = Convert.ToInt32(lines[1].Substring(16, 2)); // MMDDYYHHmm mm = Convert.ToInt32(lines[1].Substring(18, 2)); // MMDDYYHHmm } if (lines[1].Length > 22) { dimensionalCodes = lines[1].Substring(20, 2); // dd } //// used to test Line 2 reading below. // if (lines[1].Length > 24) scalingFactor1 = lines[1].Substring(22, 2); //SS if (lines[1].Length > 24) { scalingFactor1 = Convert.ToInt32(lines[1].Substring(22, 2)); //SS } //// used to test Line 2 reading below. // if (lines[1].Length > 34) scalingFactor2 = lines[1].Substring(24, 10); //ss if (lines[1].Length > 34) { scalingFactor2 = Convert.ToDouble(lines[1].Substring(24, 10)); //ss } if (lines[1].Length > 46) { energy = lines[1].Substring(34, 12); //EEEEEEEEEEEE } if (lines[1].Length == 52) { registryNumber = lines[1].Substring(46, 6); //RRRRRR } } comments = lines[2]; // Counts Line // aaabbblllfffcccsssxxxrrrpppiiimmmvvvvvv numAtoms = Convert.ToInt32(lines[3].Substring(0, 3)); numBonds = Convert.ToInt32(lines[3].Substring(3, 3)); int atomLists = Convert.ToInt32(lines[3].Substring(6, 3)); //int fObsolete = Convert.ToInt32(lines[3].Substring(9, 3)); bool chiral = false; if (Convert.ToInt32(lines[3].Substring(12, 3)) == 1) { chiral = true; } int sText = Convert.ToInt32(lines[3].Substring(15, 3)); //int xObsolete = Convert.ToInt32(lines[3].Substring(18, 3)); //int rObsolete = Convert.ToInt32(lines[3].Substring(21, 3)); //int pObsolete = Convert.ToInt32(lines[3].Substring(24, 3)); //int iObsolete = Convert.ToInt32(lines[3].Substring(27, 3)); int properties = Convert.ToInt32(lines[3].Substring(30, 3)); string version = lines[3].Substring(33, 6); for (int i = 0; i < numAtoms; i++) { Atom a = new ChemInfo.Atom(lines[4 + i].Substring(31, 3).Trim()); molecule.AddAtom(a); // xxxxx.xxxxyyyyy.yyyyzzzzz.zzzz aaaddcccssshhhbbbvvvHHHrrriiimmmnnneee //a.x = Convert.ToDouble(lines[4 + i].Substring(0, 10)); //a.y = Convert.ToDouble(lines[4 + i].Substring(10, 10)); //a.z = Convert.ToDouble(lines[4 + i].Substring(20, 10)); string text = lines[4 + i].Substring(34, 2); a.MassDiff = Convert.ToInt32(lines[4 + i].Substring(34, 2)); a.Charge = Convert.ToInt32(lines[4 + i].Substring(36, 3)); a.StereoParity = Convert.ToInt32(lines[4 + i].Substring(39, 3)); a.HydrogenCount = Convert.ToInt32(lines[4 + i].Substring(42, 3)); a.StereoCareBox = Convert.ToInt32(lines[4 + i].Substring(45, 3)); //a.Valence = Convert.ToInt32(lines[4 + i].Substring(48, 3)); // string H0 = lines[4 + i].Substring(51, 3); // a.HO = Convert.ToInt32(lines[4 + i].Substring(51, 3)); a.RNotUsed = lines[4 + i].Substring(54, 3); a.INotUsed = lines[4 + i].Substring(57, 3); a.AtomMapping = Convert.ToInt32(lines[4 + i].Substring(60, 3)); a.InversionRetension = Convert.ToInt32(lines[4 + i].Substring(63, 3)); a.ExactChange = Convert.ToInt32(lines[4 + i].Substring(66, 3)); } for (int i = 0; i < numBonds; i++) { //Bond b = new Bond(); // 111222tttsssxxxrrrccc string line = lines[4 + numAtoms + i]; int firstAtom = Convert.ToInt32(lines[4 + numAtoms + i].Substring(0, 3)); int secondAtom = Convert.ToInt32(lines[4 + numAtoms + i].Substring(3, 3)); BondType bondType = (BondType)Convert.ToInt32(lines[4 + numAtoms + i].Substring(6, 3)); BondStereo bondStereo = (BondStereo)Convert.ToInt32(lines[4 + numAtoms + i].Substring(9, 3)); string xNotUsed = lines[4 + numAtoms + i].Substring(12, 3); BondTopology bondTopology = (BondTopology)Convert.ToInt32(lines[4 + numAtoms + i].Substring(15, 3)); int rc = Convert.ToInt32(lines[4 + numAtoms + i].Substring(18, 3)); BondReactingCenterStatus reactingCenter = BondReactingCenterStatus.Unmarked; if (rc == 13) { reactingCenter = BondReactingCenterStatus.bondMadeOrBroken | BondReactingCenterStatus.bondOrderChanges | BondReactingCenterStatus.aCenter; } else if (rc == 12) { reactingCenter = BondReactingCenterStatus.bondMadeOrBroken | BondReactingCenterStatus.bondOrderChanges; } else if (rc == 9) { reactingCenter = BondReactingCenterStatus.bondOrderChanges | BondReactingCenterStatus.aCenter; } else if (rc == 5) { reactingCenter = BondReactingCenterStatus.bondMadeOrBroken | BondReactingCenterStatus.aCenter; } else { reactingCenter = (BondReactingCenterStatus)rc; } molecule.AddBond(molecule.Atoms[firstAtom - 1], molecule.Atoms[secondAtom - 1], bondType, bondStereo, bondTopology, reactingCenter); } molecule.FindRings(); return(molecule); }
private static void AddMolecule(dynamic data, Model newModel) { Dictionary <int, string> atoms = new Dictionary <int, string>(); var newMol = new Molecule(); ElementBase ce = Globals.PeriodicTable.C; int atomCount = 0; // GitHub: Issue #13 https://github.com/Chem4Word/Version3/issues/13 if (data.a != null) { foreach (AtomJSON a in data.a) { if (!string.IsNullOrEmpty(a.l)) { ElementBase eb; var ok = AtomHelpers.TryParse(a.l, out eb); if (ok) { if (eb is Element element) { ce = element; } if (eb is FunctionalGroup functionalGroup) { ce = functionalGroup; } } } else { ce = Globals.PeriodicTable.C; } Atom atom = new Atom() { Element = ce, Position = new Point(a.x, a.y) }; if (a.c != null) { atom.FormalCharge = a.c.Value; } atoms.Add(atomCount++, atom.InternalId); newMol.AddAtom(atom); atom.Parent = newMol; } } if (data.b != null) { foreach (BondJSON b in data.b) { string o; if (b.o != null) { o = Globals.OrderValueToOrder(double.Parse(b.o.ToString())); } else { o = Globals.OrderSingle; } Globals.BondStereo s; if (!string.IsNullOrEmpty(b.s)) { if (o == Globals.OrderDouble) { if (b.s.Equals(Ambiguous)) { s = Globals.BondStereo.Indeterminate; } else { s = Globals.BondStereo.None; } } else { if (b.s.Equals(Recessed)) { s = Globals.BondStereo.Hatch; } else if (b.s.Equals(Protruding)) { s = Globals.BondStereo.Wedge; } else if (b.s.Equals(Ambiguous)) { s = Globals.BondStereo.Indeterminate; } else { s = Globals.BondStereo.None; } } } else { s = Globals.BondStereo.None; } // Azure DevOps #715 if (b.b.HasValue && b.b.Value < atoms.Count && b.e.HasValue && b.e.Value < atoms.Count) { var sa = atoms[b.b.Value]; var ea = atoms[b.e.Value]; Bond newBond = new Bond() { StartAtomInternalId = sa, EndAtomInternalId = ea, Stereo = s, Order = o }; newMol.AddBond(newBond); newBond.Parent = newMol; } } } newModel.AddMolecule(newMol); newMol.Parent = newModel; }
private void ReadAtoms(StreamReader reader, int atoms) { int idx = 0; while (!reader.EndOfStream && idx < atoms) { string line = SdFileConverter.GetNextLine(reader); if (!string.IsNullOrEmpty(line)) { // create atom Atom thisAtom = new Atom(); double x = Double.Parse(GetSubString(line, 0, 9), CultureInfo.InvariantCulture); double y = Double.Parse(GetSubString(line, 10, 9), CultureInfo.InvariantCulture); double z = Double.Parse(GetSubString(line, 20, 9), CultureInfo.InvariantCulture); // Inverting Y co-ordinate to make it the right way up. thisAtom.Position = new Point(x, 0 - y); // element type string elType = GetSubString(line, 31, 3); ElementBase eb; var ok = AtomHelpers.TryParse(elType, out eb); if (ok) { if (eb is Element element) { thisAtom.Element = element; } if (eb is FunctionalGroup functionalGroup) { thisAtom.Element = functionalGroup; // Fix Invalid data; Force internal FG to prime Element if (functionalGroup.Internal) { AtomHelpers.TryParse(functionalGroup.Components[0].Component, out eb); if (eb is Element chemicalElement) { thisAtom.Element = chemicalElement; } } } } else { _molecule.Errors.Add($"{elType} at Line {SdFileConverter.LineNumber} is not a valid Element"); _molecule.Errors.Add($"{line}"); } // isotope int delta = ParseInteger(line, 34, 2); if (delta != 0) { thisAtom.IsotopeNumber = delta; } // charge int ch = ParseInteger(line, 36, 3); thisAtom.FormalCharge = FormalChargeFromMolfile(ch); thisAtom.DoubletRadical = DoubletRadicalFromMolfile(ch); // field 3 is atom parity (a *write-only* field, so not used) // int parity = ParseInteger(line, 39, 3) // field 4 hydrogen count // int hCount = ParseInteger(line, 42, 3) // field 5 stereoCareBox // int field5 = ParseInteger(line, 45, 3) // field 6 valency/oxidation state // int oxState = ParseInteger(line, 48, 3) // field 7 H0 designator // int hZero = ParseInteger(line, 51, 3) // atom-atom mapping int atomMap = ParseInteger(line, 60, 3); if (atomMap != 0) { // ToDo: What to do here ??? } // inversion/retention flag // int hZero = ParseInteger(line, 63, 3) // exact change flag // int hZero = ParseInteger(line, 66, 3) idx++; // Add atom to molecule thisAtom.Id = $"a{idx}"; _molecule.AddAtom(thisAtom); thisAtom.Parent = _molecule; atomByNumber.Add(idx, thisAtom); } } }
public static Molecule GetMolecule(XElement cmlElement) { Molecule molecule = new Molecule(); string showBracketsValue = cmlElement.Attribute(CMLNamespaces.c4w + CMLConstants.AttributeShowMoleculeBrackets)?.Value; if (!string.IsNullOrEmpty(showBracketsValue)) { molecule.ShowMoleculeBrackets = bool.Parse(showBracketsValue); } string idValue = cmlElement.Attribute(CMLConstants.AttributeId)?.Value; if (!string.IsNullOrEmpty(idValue)) { molecule.Id = idValue; } string countValue = cmlElement.Attribute(CMLConstants.AttributeCount)?.Value; if (!string.IsNullOrEmpty(countValue)) { molecule.Count = int.Parse(countValue); } string chargeValue = cmlElement.Attribute(CMLConstants.AttributeFormalCharge)?.Value; if (!string.IsNullOrEmpty(chargeValue)) { molecule.FormalCharge = int.Parse(chargeValue); } string spinValue = cmlElement.Attribute(CMLConstants.AttributeSpinMultiplicity)?.Value; if (!string.IsNullOrEmpty(spinValue)) { molecule.SpinMultiplicity = int.Parse(spinValue); } molecule.Errors = new List <string>(); molecule.Warnings = new List <string>(); List <XElement> childMolecules = CMLHelper.GetMolecules(cmlElement); List <XElement> atomElements = CMLHelper.GetAtoms(cmlElement); List <XElement> bondElements = CMLHelper.GetBonds(cmlElement); List <XElement> nameElements = CMLHelper.GetNames(cmlElement); List <XElement> formulaElements = CMLHelper.GetFormulas(cmlElement); List <XElement> labelElements = CMLHelper.GetLabels(cmlElement); foreach (XElement childElement in childMolecules) { Molecule newMol = GetMolecule(childElement); molecule.AddMolecule(newMol); newMol.Parent = molecule; } Dictionary <string, string> reverseAtomLookup = new Dictionary <string, string>(); foreach (XElement atomElement in atomElements) { Atom newAtom = GetAtom(atomElement); if (newAtom.Messages.Count > 0) { molecule.Errors.AddRange(newAtom.Messages); } molecule.AddAtom(newAtom); reverseAtomLookup[newAtom.Id] = newAtom.InternalId; newAtom.Parent = molecule; } foreach (XElement bondElement in bondElements) { Bond newBond = GetBond(bondElement, reverseAtomLookup); if (newBond.Messages.Count > 0) { molecule.Errors.AddRange(newBond.Messages); } molecule.AddBond(newBond); newBond.Parent = molecule; } foreach (XElement formulaElement in formulaElements) { var formula = GetFormula(formulaElement); if (formula.IsValid) { molecule.Formulas.Add(formula); } } foreach (XElement nameElement in nameElements) { var name = GetName(nameElement); if (name.IsValid) { molecule.Names.Add(name); } } Molecule copy = molecule.Copy(); copy.SplitIntoChildren(); // If copy now contains (child) molecules, replace original if (copy.Molecules.Count > 1) { molecule = copy; } foreach (var labelElement in labelElements) { var label = GetLabel(labelElement); if (label.IsValid) { molecule.Labels.Add(label); } } // Fix Invalid data; If only one atom if (molecule.Atoms.Count == 1) { // Remove ExplicitC flag molecule.Atoms.First().Value.ExplicitC = null; // Remove invalid molecule properties molecule.ShowMoleculeBrackets = false; molecule.SpinMultiplicity = null; molecule.FormalCharge = null; molecule.Count = null; } molecule.RebuildRings(); return(molecule); }