public Curve(Molecule mol, Vector2 pos, Camera VectroCam = null) { _mol = mol; _label = mol.getName(); _points = new LinkedList<Vector2>(); //_pts = new Vector2[_maxPoints]; _pts = new List<Vector2>(); _minY = 0; _maxY = 0; _color = new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f)); //_line = new VectorLine(mol.getName(), _pts, _color, null, 2.0f, LineType.Continuous, Joins.Weld); _line = new VectorLine(mol.getName(), _pts, 2.0f, LineType.Continuous, Joins.Weld); _line.color = _color; _isEnabled = true; _vectroCam = VectroCam; // _pos = pos; // _lines = new VectorLine[_maxPoints]; // _linesTypes = new _linesTypes[_maxPoints - 1]; VectorManager.useDraw3D = true; if (_vectroCam != null) //Vectrosity.VectorLine.SetCamera(_vectroCam); Vectrosity.VectorLine.SetCamera3D(_vectroCam); else Logger.Log("No Camera set for the Graph Window.", Logger.Level.ERROR); }
public void Init(Molecule mo,Material ma,float s) { mol = mo; mat= ma; GradientCharges (); scale =s; }
public void mouseClicked(MouseEvent e) { MViewPane mViewPane = mviewControl.getMViewPane(); int selectedIndex = mViewPane.getSelectedIndex(); currentMol = mViewPane.getM(selectedIndex); updateMolProperties(); }
// Treat reaction as a stack for undoing functionality // Store reactants and then products // Map reactants to products using indicies // Have 2D array and look at x and y to get product // playerReactant = x // gameMolecule = y public void returnProduct(Molecule playerReactant, Molecule gameMolecule, Molecule [,] reactionTable){ // go to the index of the two ints to get the product // return product //Molecule product = new Molecule(); }
public static Molecule GetMolecule(this dcFertilizer dc, string moleculeSymbol) { IEnumerable<Molecule> c = dc.Molecules.Where(co => co.Symbol == moleculeSymbol); Molecule mol; if (c.Count() < 1) { //insert List<ElementMolecule> elements = dc.GetElementMoleculeBySymbol(moleculeSymbol); mol = new Molecule { Symbol = moleculeSymbol }; mol.ElementMolecules.AddRange(elements); //FigureAtomicWeight(mol); mol.AtomicMass = 0; foreach (ElementMolecule ec in mol.ElementMolecules) { mol.AtomicMass += ec.MolecularMass; } dc.Molecules.InsertOnSubmit(mol); dc.SubmitChanges(); } else { mol = c.FirstOrDefault(); } return mol; }
public OrganicMolecule(Molecule m) : base(m.Atoms) { if (!m.Atoms.Any((BondingAtom b) => b.Element == Element.C)) throw new ArgumentException("Molecule is inorganic."); chain = new CarbonChainFinder(atoms).GetChain(); if (!VerifyOrder()) chain = chain.Reverse().ToArray(); name = new OrganicMoleculeNamer(this).GetName(); }
internal AtomeInfo(Molecule.Serialization.Atome atome, string atomePath) { this.atome = atome; this.atomePath = atomePath; this.id = System.IO.Path.GetFileName(this.atomePath); if(atome.ClassName != null) atomeInstance = (IAtome)Activator.CreateInstance(Type.GetType(atome.ClassName)); }
public void Connect(Molecule other, int channel) { //seems to work only if this is downward and other is upward if (upward || !other.upward) { Debug.LogError ("wrong connection!"); return; } // channel code 0 = R, 1 = L, 2 = B if (channel == 0) { //right --> right of other jointRight.connectedBody = other.physics; jointRight.anchor = pinRight; jointRight.connectedAnchor = plugLeft; jointRight.enabled = true; other.jointRight.connectedBody = physics; other.jointRight.anchor = other.pinRight; other.jointRight.connectedAnchor = plugRight; other.jointRight.enabled = true; } if (channel == 1) { //right --> right of other jointLeft.connectedBody = other.physics; jointLeft.anchor = pinLeft; jointLeft.connectedAnchor = plugBottom; jointLeft.enabled = true; other.jointLeft.connectedBody = physics; other.jointLeft.anchor = other.pinLeft; other.jointLeft.connectedAnchor = plugLeft; other.jointLeft.enabled = true; } if (channel == 2) { //right --> right of other jointBottom.connectedBody = other.physics; jointBottom.anchor = pinBottom; jointBottom.connectedAnchor = plugRight; jointBottom.enabled = true; other.jointBottom.connectedBody = physics; other.jointBottom.anchor = other.pinBottom; other.jointBottom.connectedAnchor = plugBottom; other.jointBottom.enabled = true; } }
public void propertyChange(PropertyChangeEvent pcEvent) { String name = pcEvent.getPropertyName(); if (name.Equals("mol")) { currentMol = (Molecule) pcEvent.getNewValue(); textBoxFormula.Text = currentMol.getFormula(); textBoxSmiles.Text = currentMol.toFormat("smiles"); textBoxWeight.Text = Convert.ToString(currentMol.getMass()); } }
private void btnOpenMolecule_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.OpenFileDialog openDialog = new System.Windows.Forms.OpenFileDialog(); try { openDialog.ShowDialog(); MoleGrid.Children.Clear(); if (openDialog.FileName == "" || openDialog.FileName == null) { return; } selectedMolecule = MoleculeFileManager.ReadMolecule(openDialog.FileName); MoleGrid.Children.Add(new MoleculePane(selectedMolecule)); } catch { } }
public Molecule(Molecule mol = null) { if (mol != null) { if(_debug) Logger.Log("Molecule::Molecule("+mol+")", Logger.Level.TRACE); setName(mol._name); _type = mol._type; _description = mol._description; _concentration = mol._concentration; _degradationRate = mol._degradationRate; _fickFactor = mol._fickFactor; _newConcentration = mol._newConcentration; if(_debug) Logger.Log("Molecule::Molecule("+mol+") built "+this, Logger.Level.TRACE); } else { if(_debug) Logger.Log("Molecule::Molecule(null)", Logger.Level.TRACE); } }
/*! \brief Load Molecules from a MoleculeSet \param molSet The set to Load \param allMolecules The list of all the molecules */ public void initMoleculesFromMoleculeSets(MoleculeSet molSet, ArrayList allMolecules) { Logger.Log("Medium::initMoleculesFromMoleculeSets medium#"+_numberId,Logger.Level.TRACE); Molecule newMol; Molecule startingMolStatus; _molecules = new ArrayList(); foreach (Molecule mol in allMolecules) { newMol = new Molecule(mol); startingMolStatus = ReactionEngine.getMoleculeFromName(mol.getName(), molSet.molecules); if (startingMolStatus == null) { newMol.setConcentration(0); } else { newMol.setConcentration(startingMolStatus.getConcentration()); } Logger.Log("Medium::initMoleculesFromMoleculeSets medium#"+_numberId +" add mol "+newMol.getName() +" with cc="+newMol.getConcentration() ,Logger.Level.TRACE ); _molecules.Add(newMol); } }
private IMolecule createMolecule(IAtomContainer atomContainer, String bondEnergy, int treeDepth) { IMolecule molecule = new Molecule(atomContainer); molecule.setProperties(atomContainer.getProperties()); molecule.setProperty("BondEnergy", bondEnergy); molecule.setProperty("TreeDepth", treeDepth.toString()); return molecule; }
private async void Chemical_Searched(object sender, EventArgs e) { try { if (!await CheckNetworkStatus() || completedPaths.Count == 0) { return; } guidePaths.Clear(); var carbon = eb.CreateElement("C"); var atomdict = new Dictionary <SKPoint, AtomNode>(); Molecule mole = new Molecule(); foreach (var x in completedPaths) { var line = x.GetLine(); var first = line[0]; var second = line[1]; if (!atomdict.ContainsKey(first)) { var atom = diffElements.ContainsKey(first) ? new AtomNode(diffElements[first]) : new AtomNode(carbon); atomdict.Add(first, atom); mole = new Molecule(atom); } if (!atomdict.ContainsKey(second)) { var keys = atomdict.Keys; var point = keys.FirstOrDefault(pt => Math.Abs(SKPoint.Distance(pt, second)) <= 2); if (point != default) { second = point; } else { var atom2 = diffElements.ContainsKey(second) ? new AtomNode(diffElements[second]) : new AtomNode(carbon); atomdict.Add(second, atom2); } } mole.AddBond(x.Order, atomdict[first], atomdict[second]); } var smiles = mole.ToSMILES().Replace("=", "%3D"); if (smiles.Contains("XXOVERFLOWXX")) { throw new StackOverflowException(); } smiles = smiles.Replace("#", "%23"); var mass = mole.GetMolecularMass(); var formula = mole.GetMolecularFormula(); await Shell.Current.GoToAsync($"resultPage?mass={mass}&search={smiles}&formula={formula}"); } catch (Exception) { DisplayErrorMessage(sender, e); } }
public virtual SdfState ImportFromStream(StreamReader reader, Molecule molecule, out string message) { message = null; return(SdfState.Null); }
private void btnClearAll_Click(object sender, RoutedEventArgs e) { try { cmbSelected.SelectedIndex = 1; cmbSelected.SelectedIndex = 0; cmbSelected.SelectedIndex = 1; selectedMolecule = null; MoleGrid.Children.Clear(); } catch { } }
public static void WriteNative(System.IO.Stream ostr, Molecule mol) { //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'" WriteNative(new System.IO.StreamWriter(new System.IO.StreamWriter(ostr, System.Text.Encoding.Default).BaseStream, new System.IO.StreamWriter(ostr, System.Text.Encoding.Default).Encoding), mol); }
public static bool CheckForDuplicateStructure(string filename, string qrymolfile, int recindex, out Molecule mol_out) { bool blStatus = false; try { bool blIsChiral = false; MolHandler mHandler = new MolHandler(qrymolfile); Molecule qryMol = mHandler.getMolecule(); qryMol = StandardizeMolecule(qryMol, out blIsChiral); string strqryMolInchi = qryMol.toFormat("inchi:key"); strqryMolInchi = Validations.GetInchiKeyFromInchiString(strqryMolInchi); //Specify input file to MolInputStream object MolInputStream molInStream = new MolInputStream(new FileInputStream(filename)); MolImporter molImp = new MolImporter(molInStream); Molecule objMol = new Molecule(); blIsChiral = false; string strInchiKey = ""; int intRecIndx = 0; Molecule molObj_Stand = null; while (molImp.read(objMol)) { molObj_Stand = StandardizeMolecule(objMol, out blIsChiral); strInchiKey = objMol.toFormat("inchi:key"); strInchiKey = Validations.GetInchiKeyFromInchiString(strInchiKey); intRecIndx++; if ((strInchiKey == strqryMolInchi) && (intRecIndx != recindex)) { blStatus = true; mol_out = objMol; return(blStatus); } } molImp.close(); molInStream.close(); } catch (Exception ex) { ErrorHandling_NTS.WriteErrorLog(ex.ToString()); } mol_out = null; return(blStatus); }
public SimulationTimestepCompleteEventArgs(UnitValue t, Molecule molecule) : this(t) { Atoms = AtomExtractor.FromMolecule(molecule); }
//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 void buildDecelerationSequence() { //get the settings we need double voltage = (double)settings["voltage"]; int initspeed = (int)settings["initspeed"]; double onposition = (double)settings["onposition"] / 1000; double offposition = (double)settings["offposition"] / 1000; int numberOfStages = (int)settings["numberOfStages"]; int resonanceOrder = (int)settings["resonanceOrder"]; int jState = (int)settings["jState"]; int mState = (int)settings["mState"]; // make the FieldMap FieldMap map = new FieldMap((string)Environs.FileSystem.Paths["decelerationUtilitiesPath"] + (string)Environs.Hardware.GetInfo("deceleratorFieldMap"), (int)Environs.Hardware.GetInfo("mapPoints"), (double)Environs.Hardware.GetInfo("mapStartPoint"), (double)Environs.Hardware.GetInfo("mapResolution")); //make the molecule Molecule mol = new Molecule((string)Environs.Hardware.GetInfo("moleculeName"), (double)Environs.Hardware.GetInfo("moleculeMass"), (double)Environs.Hardware.GetInfo("moleculeRotationalConstant"), (double)Environs.Hardware.GetInfo("moleculeDipoleMoment")); //make the decelerator and the experiment Decelerator decel = new Decelerator(); DecelerationExperiment experiment = new DecelerationExperiment(); //assign a map and a lens spacing to the decelerator decel.Map = map; decel.LensSpacing = (double)Environs.Hardware.GetInfo("deceleratorLensSpacing"); //assign decelerator, molecule, quantum state and switch structure to the experiment experiment.Decelerator = decel; experiment.Molecule = mol; experiment.QuantumState = new int[] { jState, mState }; experiment.Structure = (DecelerationExperiment.SwitchStructure)Environs.Hardware.GetInfo("deceleratorStructure"); //get the timing sequence double[] timesdouble = experiment.GetTimingSequence(voltage, onposition, offposition, initspeed, numberOfStages, resonanceOrder); // The list of times is in seconds and is measured from the moment when the synchronous molecule // reaches the decelerator. Add on the amount of time it takes to reach this point. // Then convert to the units of the clockFrequency and round to the nearest unit. double nominalTimeToDecelerator = (double)Environs.Hardware.GetInfo("sourceToSoftwareDecelerator") / initspeed; int[] times = new int[timesdouble.Length]; for (int i = 0; i < timesdouble.Length; i++) { times[i] = (int)Math.Round((int)settings["clockFrequency"] * (nominalTimeToDecelerator + timesdouble[i])); } int[] structure = new int[times.Length]; // the last switch must send all electrodes to ground structure[structure.Length - 1] = 0; // build the rest of the structure int k = 0; switch (experiment.Structure) { case DecelerationExperiment.SwitchStructure.H_Off_V_Off: while (k < structure.Length - 1) { if (k < structure.Length - 1) { structure[k] = 2; k++; } if (k < structure.Length - 1) { structure[k] = 0; k++; } if (k < structure.Length - 1) { structure[k] = 1; k++; } if (k < structure.Length - 1) { structure[k] = 0; k++; } } break; case DecelerationExperiment.SwitchStructure.V_Off_H_Off: while (k < structure.Length - 1) { if (k < structure.Length - 1) { structure[k] = 1; k++; } if (k < structure.Length - 1) { structure[k] = 0; k++; } if (k < structure.Length - 1) { structure[k] = 2; k++; } if (k < structure.Length - 1) { structure[k] = 0; k++; } } break; case DecelerationExperiment.SwitchStructure.H_V: while (k < structure.Length - 1) { if (k < structure.Length - 1) { structure[k] = 2; k++; } if (k < structure.Length - 1) { structure[k] = 1; k++; } } break; case DecelerationExperiment.SwitchStructure.V_H: while (k < structure.Length - 1) { if (k < structure.Length - 1) { structure[k] = 1; k++; } if (k < structure.Length - 1) { structure[k] = 2; k++; } } break; } // keep track of the state of the horizontal and vertical electrodes bool[] states = { false, false }; //{horizontal, vertical} decelSequence = new TimingSequence(); // The timing sequence is built within this for loop. The structure of the decelerator is encoded // as follows: 0 means everything off, 1 means V on, H off, 2 means H on V off and 3 means both on. for (int i = 0; i < times.Length && i < structure.Length; i++) { if (structure[i] == 0) //horizontal = false, vertical = false { if (states[0] != false) { decelSequence.Add("decelhplus", times[i], false); decelSequence.Add("decelhminus", times[i], false); states[0] = false; } if (states[1] != false) { decelSequence.Add("decelvplus", times[i], false); decelSequence.Add("decelvminus", times[i], false); states[1] = false; } } if (structure[i] == 1) //horizontal = false, vertical = true { if (states[0] != false) { decelSequence.Add("decelhplus", times[i], false); decelSequence.Add("decelhminus", times[i], false); states[0] = false; } if (states[1] != true) { decelSequence.Add("decelvplus", times[i], true); decelSequence.Add("decelvminus", times[i], true); states[1] = true; } } if (structure[i] == 2) //horizontal = true, vertical = false { if (states[0] != true) { decelSequence.Add("decelhplus", times[i], true); decelSequence.Add("decelhminus", times[i], true); states[0] = true; } if (states[1] != false) { decelSequence.Add("decelvplus", times[i], false); decelSequence.Add("decelvminus", times[i], false); states[1] = false; } } if (structure[i] == 3) //horizontal = true, vertical = true { if (states[0] != true) { decelSequence.Add("decelhplus", times[i], true); decelSequence.Add("decelhminus", times[i], true); states[0] = true; } if (states[1] != true) { decelSequence.Add("decelvplus", times[i], true); decelSequence.Add("decelvminus", times[i], true); states[1] = true; } } } Console.WriteLine(decelSequence.ToString()); }
/// <summary> /// Creates a molecule from a CML representation /// </summary> /// <param name="cmlElement">CML containing the molecule representation</param> /// <returns>Molecule object</returns> private Molecule CreateMolecule(XElement cmlElement) { var m = new Molecule(); m.Id = cmlElement.Attribute("id")?.Value; var childMolecules = Converters.CML.CML.GetMolecules(cmlElement); var atomElements = Converters.CML.CML.GetAtoms(cmlElement); var bondElements = Converters.CML.CML.GetBonds(cmlElement); var nameElements = Converters.CML.CML.GetNames(cmlElement); var formulaElements = Converters.CML.CML.GetFormulas(cmlElement); Dictionary <string, Atom> newAtoms = new Dictionary <string, Atom>(); foreach (XElement childElement in childMolecules) { var newMol = CreateMolecule(childElement); m.Molecules.Add(newMol); //Debug.WriteLine(m.Molecules.Count); //Debug.WriteLine(m.AllAtoms.Count); //Debug.WriteLine(m.AllBonds.Count); } foreach (XElement atomElement in atomElements) { List <string> messages = new List <string>(); var newAtom = CreateAtom(atomElement, out messages); if (messages.Count > 0) { m.Errors.AddRange(messages); } if (newAtom != null) { newAtoms[newAtom.Id] = newAtom; //store the reference to help us build bonds m.Atoms.Add(newAtom); } } foreach (XElement bondElement in bondElements) { string message = ""; var newBond = CreateBond(bondElement, out message); if (!string.IsNullOrEmpty(message)) { m.Errors.Add(message); } string[] atomRefs = bondElement.Attribute("atomRefs2")?.Value.Split(' '); if (atomRefs?.Length == 2) { Atom startAtom = null; if (newAtoms.ContainsKey(atomRefs[0])) { startAtom = newAtoms[atomRefs[0]]; } else { m.Errors.Add($"Can't find atom '{atomRefs[0]}' of {bondElement}"); } Atom endAtom = null; if (newAtoms.ContainsKey(atomRefs[1])) { endAtom = newAtoms[atomRefs[1]]; } else { m.Errors.Add($"Can't find atom '{atomRefs[1]}' of {bondElement}"); } if (startAtom != null && endAtom != null) { newBond.StartAtom = startAtom; newBond.EndAtom = endAtom; m.Bonds.Add(newBond); } } } foreach (XElement nameElement in nameElements) { var newName = XmlToName(nameElement); m.ChemicalNames.Add(newName); } foreach (XElement formulaElement in formulaElements) { // Only import Concise Once if (string.IsNullOrEmpty(m.ConciseFormula)) { m.ConciseFormula = XmlToConsiseFormula(formulaElement); } var formula = XmlToFormula(formulaElement); if (formula.IsValid) { m.Formulas.Add(formula); } } return(m); }
public Model Import(object data) { Model model = null; if (data != null) { string dataAsString = (string)data; if (!dataAsString.Contains("v3000") && !dataAsString.Contains("V3000")) { model = new Model(); LineNumber = 0; // Convert incoming string to a stream MemoryStream stream = new MemoryStream(); StreamWriter writer = new StreamWriter(stream); writer.Write(dataAsString); writer.Flush(); stream.Position = 0; StreamReader sr = new StreamReader(stream); Molecule molecule = null; SdfState state = SdfState.Null; string message = null; while (!sr.EndOfStream) { switch (state) { case SdfState.Null: case SdfState.EndOfData: molecule = new Molecule(); CtabProcessor pct = new CtabProcessor(); state = pct.ImportFromStream(sr, molecule, out message); if (state == SdfState.Error) { model.GeneralErrors.Add(message); } Molecule copy = molecule.Copy(); copy.SplitIntoChildren(); // If copy now contains (child) molecules, replace original if (copy.Molecules.Count > 1) { molecule = copy; } //Ensure we add the molecule after it's populated model.AddMolecule(molecule); molecule.Parent = model; if (model.Molecules.Count >= 16) { model.GeneralErrors.Add("This file has greater than 16 structures!"); sr.ReadToEnd(); } break; case SdfState.EndOfCtab: DataProcessor dp = new DataProcessor(_propertyTypes); state = dp.ImportFromStream(sr, molecule, out message); break; case SdfState.Error: // Swallow rest of stream sr.ReadToEnd(); break; case SdfState.Unsupported: // Swallow rest of stream sr.ReadToEnd(); break; } } model.Relabel(true); model.Refresh(); } } return(model); }
private eType _type; //!< The type of the molecule #endregion Fields #region Constructors //! Default constructor public Molecule(Molecule mol = null) { if (mol != null) { _name = mol._name; _type = mol._type; _description = mol._description; _concentration = mol._concentration; _degradationRate = mol._degradationRate; _fickFactor = mol._fickFactor; _newConcentration = mol._newConcentration; } }
public void SetParticles(Molecule m,Color32 c) { int index = 0; for(int i=0;i<selectedAtoms.Count;i++){ p[index].size = 1.0f; p[index].position = m.Atoms[selectedAtoms[i].Number].Location[Main.current_frame]; p[index].color = c; index++; } for (int i=0; i<selectedResidues.Count; i++) { for(int j=0;j<selectedResidues[i].Atoms.Count;j++){ p[index].size = 1.0f; p[index].position = m.Atoms[selectedResidues[i].Atoms[j].Number].Location[Main.current_frame]; p[index].color = c; index++; } } for (int i=0; i<selectedChains.Count; i++) { for(int j=0;j<selectedChains[i].Atoms.Count;j++){ p[index].size = 1.0f; p[index].position = m.Atoms[selectedChains[i].Atoms[j].Number].Location[Main.current_frame]; p[index].color = c; index++; } } switch (m.select) { case SelectDisplay.Atom : p[index].size = 1.0f; p[index].position = minDistAtom.Location[Main.current_frame]; p[index].color = c; index++; break; case SelectDisplay.Residue : for (int i=0; i<minDistResidue.Atoms.Count; i++) { p[index].size = 1.0f; p[index].position = minDistResidue.Atoms[i].Location[Main.current_frame]; p[index].color = c; index++; } break; case SelectDisplay.Chain : for (int i=0; i<minDistChain.Atoms.Count; i++) { p[index].size = 1.0f; p[index].position = minDistChain.Atoms[i].Location[Main.current_frame]; p[index].color = c; index++; } break; default:break; } par.SetParticles(p,index); }
private bool storeMolecule(XmlNode node, Molecule.eType type, ArrayList molecules) { Molecule mol = new Molecule(); mol.setType(type); foreach (XmlNode attr in node) { switch (attr.Name) { case "name": mol.setName(attr.InnerText); break; case "description": mol.setDescription(attr.InnerText); break; case "concentration": mol.setConcentration(float.Parse(attr.InnerText.Replace(",", "."))); break; case "degradationRate": mol.setDegradationRate(float.Parse(attr.InnerText.Replace(",", "."))); break; case "size": mol.setSize(float.Parse(attr.InnerText.Replace(",", "."))); break; } } molecules.Add(mol); //FIXME : create a real reaction for degradation with rate and name // _reactions.AddLast(new Degradation(mol.getDegradationRate(), mol.getName())); return true; }
private void TestAdductOperators() { // Test some underlying formula handling for fanciful user-supplied values Assert.IsTrue(Molecule.AreEquivalentFormulas("C10H30Si5O5H-CH4", "C9H27O5Si5")); Assert.AreEqual("C7H27O5Si4", BioMassCalc.MONOISOTOPIC.FindFormulaIntersection(new[] { "C8H30Si5O5H-CH4", "C9H27O5Si4", "C9H27O5Si5Na" })); Assert.AreEqual("C7H27O5Si4", BioMassCalc.MONOISOTOPIC.FindFormulaIntersectionUnlabeled(new[] { "C7C'H30Si5O5H-CH4", "C9H27O5Si4", "C9H25H'2O5Si5Na" })); // There is a difference between a proteomic adduct and non proteomic, primarily in how they display Assert.AreEqual(Adduct.FromStringAssumeChargeOnly("M+H"), Adduct.M_PLUS_H); Assert.AreEqual(Adduct.FromStringAssumeProtonatedNonProteomic("1"), Adduct.M_PLUS_H); Assert.AreEqual(Adduct.FromStringAssumeChargeOnly("1"), Adduct.M_PLUS); Assert.AreEqual(Adduct.FromStringAssumeProtonatedNonProteomic("M+H"), Adduct.M_PLUS_H); Assert.AreEqual(Adduct.FromStringAssumeProtonated("1"), Adduct.SINGLY_PROTONATED); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M+H"), Adduct.SINGLY_PROTONATED); Assert.AreEqual(Adduct.FromStringAssumeChargeOnly("M+H").AsFormula(), Adduct.SINGLY_PROTONATED.AsFormula()); // But the underlying chemistry is the same Assert.AreEqual(Adduct.FromStringAssumeProtonated("[M+S]+"), Adduct.FromStringAssumeProtonated("M+S").ChangeCharge(1)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M(-1.234)+2Na"), Adduct.FromStringAssumeProtonated("M(-1.234)+3Na").ChangeCharge(2)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M1.234+2Na"), Adduct.FromStringAssumeProtonated("M1.234+3Na").ChangeCharge(2)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M2Cl37-2Na"), Adduct.FromStringAssumeProtonated("M2Cl37+3Na").ChangeCharge(-2)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M1.234-2Na"), Adduct.FromStringAssumeProtonated("M1.234+3Na").ChangeCharge(-2)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M(-1.234)-2Na"), Adduct.FromStringAssumeProtonated("M(-1.234)+3Na").ChangeCharge(-2)); Assert.IsFalse(Adduct.M_PLUS_H.IsProteomic); Assert.IsTrue(Adduct.M_PLUS_H.IsProtonated); Assert.IsTrue(Adduct.SINGLY_PROTONATED.IsProteomic); Assert.IsTrue(Adduct.SINGLY_PROTONATED.IsProtonated); Assert.IsFalse(Adduct.SINGLY_PROTONATED.IsEmpty); Assert.IsFalse(Adduct.EMPTY.IsProteomic); Assert.IsTrue(Adduct.EMPTY.IsEmpty); // Exercise the ability to work with masses and isotope labels Assert.IsTrue(ReferenceEquals(Adduct.SINGLY_PROTONATED, Adduct.SINGLY_PROTONATED.Unlabeled)); var nolabel = Adduct.FromStringAssumeProtonated("M-2Na"); var label = Adduct.FromStringAssumeProtonated("M2Cl37-2Na"); Assert.AreEqual(nolabel, label.Unlabeled); Assert.IsTrue(ReferenceEquals(nolabel, nolabel.Unlabeled)); Assert.IsFalse(nolabel.MassFromMz(300.0, MassType.Monoisotopic).IsHeavy()); Assert.IsFalse(label.MassFromMz(300.0, MassType.Monoisotopic).IsHeavy()); Assert.IsTrue(label.MassFromMz(300.0, MassType.MonoisotopicHeavy).IsHeavy()); Assert.IsTrue(label.MassFromMz(300.0, MassType.Monoisotopic).IsMonoIsotopic()); Assert.IsFalse(nolabel.MassFromMz(300.0, MassType.Average).IsHeavy()); Assert.IsFalse(label.MassFromMz(300.0, MassType.Average).IsHeavy()); Assert.IsTrue(label.MassFromMz(300.0, MassType.AverageHeavy).IsHeavy()); Assert.IsTrue(label.MassFromMz(300.0, MassType.Average).IsAverage()); var massHeavy = label.ApplyToMass(new TypedMass(300, MassType.MonoisotopicHeavy)); // Will not have isotope effect added in mz calc, as it's already heavy var massLight = label.ApplyToMass(new TypedMass(300, MassType.Monoisotopic)); // Will have isotope effect added in mz calc Assert.AreNotEqual(massHeavy, massLight); Assert.AreNotEqual(label.MzFromNeutralMass(massHeavy), label.MzFromNeutralMass(massLight)); Assert.IsTrue(Adduct.PossibleAdductDescriptionStart("[")); Assert.IsTrue(Adduct.PossibleAdductDescriptionStart("M")); Assert.IsTrue(Adduct.PossibleAdductDescriptionStart("[2M+CH3COO]")); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M+2CH3COO"), Adduct.FromStringAssumeProtonated("M+CH3COO").ChangeCharge(-2)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M-2CH3COO"), Adduct.FromStringAssumeProtonated("M+CH3COO").ChangeCharge(2)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M-2Na"), Adduct.FromStringAssumeProtonated("M+Na").ChangeCharge(-2)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M+Na"), Adduct.FromStringAssumeProtonated("M+Na").ChangeCharge(1)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M+2Na"), Adduct.FromStringAssumeProtonated("M+Na").ChangeCharge(2)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M+2Na"), Adduct.FromStringAssumeProtonated("M+3Na").ChangeCharge(2)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M2Cl37+2Na"), Adduct.FromStringAssumeProtonated("M2Cl37+3Na").ChangeCharge(2)); AssertEx.ThrowsException <InvalidOperationException>(() => Adduct.FromStringAssumeProtonated("M+2Na-H").ChangeCharge(2)); // Too complex to adjust formula Assert.AreEqual(Adduct.FromStringAssumeProtonated("M++++").AdductCharge, Adduct.FromChargeNoMass(4).AdductCharge); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M+4"), Adduct.FromChargeNoMass(4)); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M--").AdductCharge, Adduct.FromChargeNoMass(-2).AdductCharge); Assert.AreEqual(Adduct.FromStringAssumeProtonated("M-2"), Adduct.FromChargeNoMass(-2)); Assert.IsTrue(ReferenceEquals(Adduct.FromStringAssumeChargeOnly("M-"), Adduct.FromChargeNoMass(-1))); // Both should return Adduct.M_MINUS Assert.IsTrue(ReferenceEquals(Adduct.FromStringAssumeChargeOnly("M+"), Adduct.FromChargeNoMass(1))); // Both should return Adduct.M_PLUS Assert.IsTrue(ReferenceEquals(Adduct.FromStringAssumeChargeOnly("[M+]"), Adduct.FromChargeNoMass(1))); // Both should return Adduct.M_PLUS Assert.IsTrue(ReferenceEquals(Adduct.FromStringAssumeChargeOnly("M-H"), Adduct.M_MINUS_H)); Assert.IsTrue(ReferenceEquals(Adduct.FromStringAssumeChargeOnly("M+H"), Adduct.M_PLUS_H)); var a = Adduct.FromChargeProtonated(-1); var aa = Adduct.FromStringAssumeProtonated("M+CH3COO"); var b = Adduct.FromChargeProtonated(2); var bb = Adduct.FromChargeProtonated(2); var bbb = Adduct.FromChargeProtonated(2); var bbbb = Adduct.FromChargeProtonated(2); var c = Adduct.FromChargeProtonated(3); var cc = Adduct.FromStringAssumeChargeOnly("M+3H"); var ccc = Adduct.FromStringAssumeChargeOnly("[M+3H]"); Assert.AreEqual(a.AdductCharge, aa.AdductCharge); Assert.IsTrue(b == bb); Assert.IsTrue(b == bbb); Assert.IsTrue(ReferenceEquals(bbb, bbbb)); Assert.IsTrue(c.AdductCharge == cc.AdductCharge); Assert.IsFalse(c == cc); Assert.IsTrue(c != cc); Assert.IsTrue(cc == ccc); Assert.IsTrue(a < aa); Assert.IsTrue(a < b); Assert.IsTrue(b > a); Assert.IsTrue(b != a); var sorted = new List <Adduct> { a, aa, b, bb, bbb, bbbb, c, cc, ccc }; var unsorted = new List <Adduct> { bb, aa, ccc, b, c, bbb, a, bbbb, cc }; Assert.IsFalse(sorted.SequenceEqual(unsorted)); unsorted.Sort(); Assert.IsTrue(sorted.SequenceEqual(unsorted)); var ints = new AdductMap <int>(); Assert.AreEqual(0, ints[a]); ints[a] = 7; Assert.AreEqual(7, ints[a]); var adducts = new AdductMap <Adduct>(); Assert.AreEqual(null, adducts[a]); adducts[a] = b; Assert.AreEqual(b, adducts[a]); adducts[a] = c; Assert.AreEqual(c, adducts[a]); var d = Adduct.FromStringAssumeProtonated("[2M+3H]"); var dd = Adduct.FromStringAssumeProtonated("[M+3H]"); var ddd = Adduct.FromStringAssumeProtonated("[M-Na]"); Assert.IsTrue(d.ChangeMassMultiplier(1).SameEffect(dd)); Assert.IsTrue(dd.ChangeMassMultiplier(2).SameEffect(d)); Assert.AreEqual(dd.ChangeIonFormula("-Na"), ddd); Assert.AreEqual(d.ChangeMassMultiplier(1).ChangeIonFormula("-Na"), ddd); CheckLabel(BioMassCalc.Cl37); CheckLabel(BioMassCalc.Br81); CheckLabel(BioMassCalc.S33); CheckLabel(BioMassCalc.S34); CheckLabel(BioMassCalc.P32); CheckLabel(BioMassCalc.O17); CheckLabel(BioMassCalc.O18); var tips = Adduct.Tips; foreach (var nickname in Adduct.DICT_ADDUCT_NICKNAMES) { Assert.IsTrue(tips.Contains(nickname.Key)); } foreach (var nickname in Adduct.DICT_ADDUCT_ISOTOPE_NICKNAMES) { Assert.IsTrue(tips.Contains(nickname.Key)); } }
public ForceDirectedGraph(Molecule m) { molecule = m; }
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; }
public static bool WriteXmlFileUsingXSD(string infilename, string tannumber, string outputfilepath) { bool blStatus = false; try { patentInfo patentInfo_Obj = new patentInfo(); patentInfo_Obj.tan = tannumber; patentInfo_Obj.language = languageType.en; //Specify input file to MolInputStream object MolInputStream molInStream = new MolInputStream(new FileInputStream(infilename)); MolImporter molImp = new MolImporter(molInStream); Molecule mol = new Molecule(); //int intMolCnt = molImp.getRecordCount(); int intMolCnt = ChemistryOperations.GetMoleculeCountFromFile(infilename); patentLocation patLoc = null; name[] name_Arr = null; name name_obj = null; names names_Arr = null; nameType namType = null; structureDataType structDtype = null; string[] strIUpacName = null; propheticSubstance propSubstance_Obj = null; propheticSubstance[] propSubstance_Arr = new propheticSubstance[intMolCnt]; propheticSubstances propSubstances_Obj = null; patent patent_Obj = new patent(); int intCntr = 0; //Read molecules from molImporter while (molImp.read(mol)) { patLoc = new patentLocation(); patLoc.pageLabel = mol.getProperty("Page Label"); patLoc.pageNumber = mol.getProperty("Page Number"); patLoc.exampleLabel = mol.getProperty("Example Number"); name_Arr = new name[1]; name_obj = new name(); name_obj.lang = languageType.en; string[] strArr_EnName = new string[1]; strArr_EnName[0] = mol.getProperty("en name").Trim(); name_obj.Text = strArr_EnName; name_Arr[0] = name_obj; strIUpacName = new string[1]; strIUpacName[0] = mol.getProperty("IUPAC Name").Trim(); namType = new nameType(); namType.Text = strIUpacName; names_Arr = new names(); names_Arr.IUPACName = namType; names_Arr.name = name_Arr; string strMol = mol.toFormat("mol"); int v3000 = strMol.IndexOf("V3000"); double nullMol = mol.getExactMass(); byte[] barr_Mol = null; if (v3000 == -1 && nullMol != 0) { barr_Mol = System.Text.ASCIIEncoding.ASCII.GetBytes(strMol); } structDtype = new structureDataType(); structDtype.Value = barr_Mol; propSubstance_Obj = new propheticSubstance(); propSubstance_Obj.structureData = structDtype; propSubstance_Obj.patentLocation = patLoc; propSubstance_Obj.names = names_Arr; propSubstance_Arr[intCntr] = propSubstance_Obj; intCntr++; } propSubstances_Obj = new propheticSubstances(); propSubstances_Obj.propheticSubstance = propSubstance_Arr; patent_Obj.patentInfo = patentInfo_Obj; patent_Obj.propheticSubstances = propSubstances_Obj; // Serialization XmlSerializer xmlSer = new XmlSerializer(typeof(patent)); TextWriter txtWriter = new StreamWriter(outputfilepath); xmlSer.Serialize(txtWriter, patent_Obj); txtWriter.Close(); txtWriter.Dispose(); molInStream.close(); molImp.close(); blStatus = true; return(blStatus); } catch (Exception ex) { PepsiLiteErrorHandling.WriteErrorLog(ex.ToString()); } return(blStatus); }
private static void AddAllMolecules() { var moleculeTypes = (MoleculeType[])Enum.GetValues(typeof(MoleculeType)); for (int i = 0; i < moleculeTypes.Length; i++) { var molecule = new Molecule(); switch (moleculeTypes[i]) { case MoleculeType.CoOH: molecule.Bind(Get(ElementType.Co), Get(ElementType.O), Get(ElementType.H)); break; case MoleculeType.NH2: molecule.Bind(Get(ElementType.N), Get(ElementType.H), Get(ElementType.H)); // Find a better for the double H add? break; } molecules.Add(moleculeTypes[i], molecule); } }
public static bool WriteXmlFile(string infilename, string tannumber, string outputfilepath) { System.IO.StreamWriter sWriter = null; try { sWriter = new System.IO.StreamWriter(outputfilepath); //xml file header information sWriter.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>"); sWriter.WriteLine("<patent xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"PatentEnhancedPrioritySubstanceIndexing-2.3.xsd\">"); sWriter.WriteLine("<patentInfo>"); sWriter.WriteLine("<tan>" + tannumber + "</tan>"); sWriter.WriteLine("<language>en</language>"); sWriter.WriteLine("</patentInfo>"); sWriter.WriteLine("<propheticSubstances>"); //Specify input file to MolInputStream object MolInputStream molInStream = new MolInputStream(new FileInputStream(infilename)); MolImporter molImp = new MolImporter(molInStream); Molecule mol = new Molecule(); //Declare mol property variables string strPage_No = ""; string strPage_Lbl = ""; string strExample_Lbl = ""; string strEn_name = ""; string strIUPAC_Name = ""; string strStandMol = ""; string strMolBase64 = ""; //Read molecules from molImporter while (molImp.read(mol)) { sWriter.WriteLine("<propheticSubstance>"); sWriter.WriteLine("<patentLocation>"); //Page No strPage_No = ""; strPage_No = mol.getProperty("Page Number").Trim(); sWriter.WriteLine("<pageNumber>" + strPage_No + "</pageNumber>"); //Page Label strPage_Lbl = ""; strPage_Lbl = mol.getProperty("Page Label").Trim(); sWriter.WriteLine("<pageLabel>" + strPage_Lbl + "</pageLabel>"); //Example label strExample_Lbl = ""; strExample_Lbl = mol.getProperty("Example Number").Trim(); sWriter.WriteLine("<exampleLabel>" + strExample_Lbl + "</exampleLabel>"); sWriter.WriteLine("</patentLocation>"); sWriter.WriteLine("<names>"); //en Name strEn_name = ""; strEn_name = mol.getProperty("en name").Trim();//En Name sWriter.WriteLine("<name lang=\"en\">" + strEn_name + "</name>"); //IUPAC Name strIUPAC_Name = ""; strIUPAC_Name = mol.getProperty("IUPAC Name").Trim(); sWriter.WriteLine("<IUPACName>" + strIUPAC_Name + "</IUPACName>"); sWriter.WriteLine("</names>"); //Check here for V2000 format, if not write in error log string mol2d = mol.toFormat("mol"); int v3000 = mol2d.IndexOf("V3000"); if (v3000 != -1) { //System.out.println("V3000 Error has occured! at Molecule Number: " + molCount + " in SDF file " + fileName); //System.exit(0); } double nullMol = mol.getExactMass(); if (nullMol == 0) { //System.out.println("NULL Mol Error has occured! at Molecule Number: " + molCount + " in SDF file " + fileName); //System.exit(0); } strStandMol = ""; strStandMol = mol.toFormat("mol");//MoleculeStandardizer.GetStandardizedMolecule(mol.toFormat("mol")); strMolBase64 = ""; strMolBase64 = ConvertToBase64.GetConvertedMolString(strStandMol); sWriter.WriteLine("<structureData encoding=\"Base64\" type=\"MDL Molfile V2000\">" + strMolBase64 + "</structureData>");//Base64 Molstring sWriter.WriteLine("</propheticSubstance>"); } sWriter.WriteLine("</propheticSubstances>"); sWriter.WriteLine("</patent>"); sWriter.Close(); sWriter.Dispose(); return(true); } catch (Exception ex) { PepsiLiteErrorHandling.WriteErrorLog(ex.ToString()); } finally { sWriter.Close(); sWriter.Dispose(); } return(true); }
// Use this for initialization void Start() { text = this.GetComponent<Text>(); mol = molecule.GetComponent<Molecule>(); }
void OnGUI() { CUE cue = CUE.GetInstance(); // Get selected molecule Molecule m = cue.ReactionManager.SelectedMolecule; // Set following if (following) { CameraControl.Follow = m.gameObject; } else { CameraControl.Follow = null; } // Draw menu or remove script if no moleule is selected if (m == null) { RemoveScript(); } else { GuiBoxReset(); GuiBeginBox("Molecule", 94); string reaction; string reactionStatus; if (m.ReactionPrep != null) { reaction = m.ReactionPrep.ReactionType.ToString(); reactionStatus = "performing"; } else { ReactionType selectedReaction = cue.ReactionManager.SelectedReaction; if (selectedReaction != null) { reaction = selectedReaction.ToString(); reactionStatus = "waiting"; } else { reaction = "none"; reactionStatus = ""; } } GuiCaptionValue("Species:", m.Species.Name); GuiCaptionValue("Reaction:", reaction + "\n\r" + reactionStatus); GUILayout.BeginHorizontal(); if (GUILayout.Button(following ? "Stay" : "Follow")) { following = !following; } if (GUILayout.Button("Deselect")) { Deselect(); } if (GUILayout.Button("Hide")) { Hide(); } GUILayout.EndHorizontal(); GuiEndBox(); // // Reactions // List <ReactionType> reactions = new List <ReactionType>(); foreach (var r in cue.ReactionTypes) { if (Utils.ArrayContains <MoleculeSpecies>(r.Reagents, m.Species)) { reactions.Add(r); } } GuiBeginBox("Reaction", (reactions.Count + 1) * (guiReactionHeight) + guiReactionSpace); if (GUILayout.Button("none")) { cue.ReactionManager.SelectedReaction = null; } GUILayout.Space(guiReactionSpace); foreach (var r in reactions) { if (GUILayout.Button(r.ToString())) { cue.ReactionManager.SelectedReaction = r; } } GuiEndBox(); if (Input.GetKey("escape")) { Deselect(); } if (Input.GetKey("return")) { Hide(); } } }
public virtual void ExportToStream(Molecule molecule, StreamWriter writer, out string message) { message = null; }
// ReSharper disable once ParameterTypeCanBeEnumerable.Local private MassDistribution GetMzDistribution(Molecule molecule, int charge, IsotopeAbundances abundances, double unexplainedMass, bool isMassH) { // Low resolution to get back only peaks at Dalton (i.e. neutron) boundaries var md = new MassDistribution(_massResolution, _minimumAbundance); var result = md; foreach (var element in molecule) { result = result.Add(md.Add(abundances[element.Key]).Multiply(element.Value)); } return result.OffsetAndDivide(unexplainedMass + charge* (isMassH ? BioMassCalc.MassProton : -BioMassCalc.MassElectron), charge); }
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 ActionResult getMolecule(string input) { List <ConvertableMol> Clist = JsonConvert.DeserializeObject <List <ConvertableMol> >(input); var map = new Dictionary <string, String[]>(); List <Node> nodeList = new List <Node>(); List <Node> convertedList = new List <Node>(); foreach (ConvertableMol C in Clist) { Node n = new Node() { NodeTag = C.ID }; nodeList.Add(n); map.Add(n.NodeTag, C.b); } foreach (var pair in map) { List <Node> _neighbors = new List <Node>(); Node n = nodeList.Find(x => x.NodeTag == pair.Key); foreach (string s in pair.Value) { _neighbors.Add(nodeList.Find(x => x.NodeTag == s)); } if (_neighbors.Count >= 1) { ; } n.Neighbors = _neighbors; convertedList.Add(n); } //int length = scanner._longestChain(convertedList); if (convertedList.Count <= 3) { String Name = ""; switch (convertedList.Count) { case 1: Name = "Methane"; break; case 2: Name = "Ethane"; break; case 3: Name = "Propane"; break; } return(PartialView("~/Views/Home/RatingModal.cshtml", new RatingModalModel() { MoleculeName = Name, UserIdEncrypt = User.Identity.GetUserId(), MoleculeJson = input })); } else { try { List <string> _mainChainJson = new List <string>(); Molecule mol = scanner.FindLongestChain(convertedList); foreach (Node n in mol.ParentChain.NodeList) { _mainChainJson.Add(n.NodeTag); } string[][] jsonChain = _mainChainJson.Select(x => new string[] { x }).ToArray(); return(PartialView("~/Views/Home/RatingModal.cshtml", new RatingModalModel() { MoleculeName = mol.getName(_context), UserIdEncrypt = User.Identity.GetUserId(), MoleculeJson = input, MainChainJson = JsonConvert.SerializeObject(jsonChain) })); } catch (Exception ex) { return(PartialView("~/Views/Home/RatingModal.cshtml", new RatingModalModel() { MoleculeName = "Couldn't find a name!", UserIdEncrypt = User.Identity.GetUserId(), MoleculeJson = input })); } } }
/// <summary> /// Generated coordinates for a given ring, which is connected to a spiro ring. /// The rings share exactly one atom. /// </summary> /// <param name="ring">The ring to be placed</param> /// <param name="sharedAtoms">The atoms of this ring, also members of another ring, which are already placed</param> /// <param name="sharedAtomsCenter">The geometric center of these atoms</param> /// <param name="ringCenterVector">A vector pointing the center of the new ring</param> /// <param name="bondLength">The standard bond length</param> public virtual void PlaceSpiroRing(IRing ring, IAtomContainer sharedAtoms, Vector2 sharedAtomsCenter, Vector2 ringCenterVector, double bondLength) { var startAtom = sharedAtoms.Atoms[0]; var mBonds = Molecule.GetConnectedBonds(sharedAtoms.Atoms[0]).ToReadOnlyList(); var degree = mBonds.Count; Debug.WriteLine($"placeSpiroRing: D={degree}"); // recalculate the ringCentreVector if (degree != 4) { int numPlaced = 0; foreach (var bond in mBonds) { var nbr = bond.GetOther(sharedAtoms.Atoms[0]); if (!nbr.IsPlaced) { continue; } numPlaced++; } if (numPlaced == 2) { // nudge the shared atom such that bond lengths will be // equal startAtom.Point2D += ringCenterVector; sharedAtomsCenter += ringCenterVector; } var theta = Math.PI - (2 * Math.PI / (degree / 2)); ringCenterVector = Rotate(ringCenterVector, theta); } var radius = GetNativeRingRadius(ring, bondLength); var ringCenter = sharedAtomsCenter; if (degree == 4) { ringCenterVector = Vector2.Normalize(ringCenterVector); ringCenterVector *= radius; } else { // spread things out a little for multiple spiro centres ringCenterVector = Vector2.Normalize(ringCenterVector); ringCenterVector *= (2 * radius); } ringCenter += ringCenterVector; var addAngle = 2 * Math.PI / ring.RingSize; var currentAtom = startAtom; var startAngle = GeometryUtil.GetAngle( startAtom.Point2D.Value.X - ringCenter.X, startAtom.Point2D.Value.Y - ringCenter.Y); // Get one bond connected to the spiro bridge atom. It doesn't matter in which direction we draw. var rBonds = ring.GetConnectedBonds(startAtom); var currentBond = rBonds.First(); var atomsToDraw = new List <IAtom>(); // Store all atoms to draw in consequtive order relative to the chosen bond. for (int i = 0; i < ring.Bonds.Count; i++) { currentBond = ring.GetNextBond(currentBond, currentAtom); currentAtom = currentBond.GetOther(currentAtom); if (!currentAtom.Equals(startAtom)) { atomsToDraw.Add(currentAtom); } } Debug.WriteLine($"currentAtom {currentAtom}"); Debug.WriteLine($"startAtom {startAtom}"); AtomPlacer.PopulatePolygonCorners(atomsToDraw, ringCenter, startAngle, addAngle, radius); }
public MoleculeVisual(Molecule molecule, Rect?bb = null) { _molecule = molecule; _boundingBox = bb ?? molecule.BoundingBox; }
public static DataTable GetRGroupEnumerationResults(DataTable _enumDataTbl, string _qryRCore) { DataTable dtEnumResData = new DataTable(); try { dtEnumResData.Columns.Add("id", typeof(string)); dtEnumResData.Columns.Add("structure", typeof(object)); dtEnumResData.Columns.Add("mol_weight", typeof(double)); dtEnumResData.Columns.Add("mol_formula", typeof(string)); dtEnumResData.Columns.Add("iupac_name", typeof(string)); dtEnumResData.Columns.Add("inchi_key", typeof(string)); int rgrpNum = 1; Molecule molEnum = null; MolHandler mHandler = null; Molecule rCoreMol = null; RgMolecule rgMol = null; MolHandler mHand_Result = null; DataRow dtRow = null; string strMolFile = ""; string strIUPACName = ""; string strErrMsg = ""; if (_enumDataTbl != null) { if (_enumDataTbl.Rows.Count > 0) { for (int rowindx = 0; rowindx < _enumDataTbl.Rows.Count; rowindx++) { molEnum = new Molecule(); mHandler = new MolHandler(_qryRCore); rCoreMol = mHandler.getMolecule(); try { for (int colindx = 1; colindx < _enumDataTbl.Columns.Count; colindx++) { rgrpNum = GetRgroupNumFromRGroupName(_enumDataTbl.Columns[colindx].ColumnName); rgMol = ReturnRGroupMolecule(_enumDataTbl.Rows[rowindx][colindx].ToString(), rgrpNum); //molEnum = AddRGrpMolToCoreMolecule(rgMol, rCoreMol, rgrpNum); AddRGrpMolToCoreMolecule(ref rCoreMol, rgMol, rgrpNum); } //Set Radical Empty to Result Mol SetRadicalEmptyToResultMol(ref rCoreMol); mHand_Result = new MolHandler(rCoreMol); strMolFile = ""; strMolFile = mHand_Result.toFormat("mol"); } catch { } dtRow = dtEnumResData.NewRow(); dtRow["id"] = _enumDataTbl.Rows[rowindx][0].ToString(); dtRow["structure"] = strMolFile; if (strMolFile != "") { dtRow["mol_weight"] = mHand_Result.calcMolWeight(); dtRow["mol_formula"] = mHand_Result.calcMolFormula(); dtRow["inchi_key"] = ChemistryOperations.GetStructureInchiKey(strMolFile); strIUPACName = ""; strErrMsg = ""; if (ChemistryOperations.GetIUPACNameFromStructure(strMolFile, out strIUPACName, out strErrMsg)) { strIUPACName = Validations.GetConvertedIUPACName(strIUPACName); } else { strIUPACName = "IUPAC name not provided"; } dtRow["iupac_name"] = strIUPACName; } dtEnumResData.Rows.Add(dtRow); } return(dtEnumResData); } } } catch (Exception ex) { PepsiLiteErrorHandling.WriteErrorLog(ex.ToString()); } return(dtEnumResData); }
public Reaction(IEnumerable<Molecule> reactants, Molecule product) { _reactants = reactants.ToList(); Product = product; }
public MainViewModel() { SelectedMolecule = new Molecule(); InitializeCommands(); }
/// <summary> /// Parses MDL file /// </summary> /// <param name="data">Text</param> /// <returns>Molecule</returns> public static Molecule Parse(string data) { string[] lines = data.Split(new char[] {'\n'}); if (lines.Length < 4) new Exception("Invalid file format"); if (lines[3].Contains("V3000")) throw new NotSupportedException("The Extended Connection Table (V3000) is not supported"); if (!lines[3].Contains("V2000")) /* JMol, for example, do not write V2000 text */; // First 3 lines are header block Molecule molecule = new Molecule(); molecule.Name = String.IsNullOrEmpty(lines[0]) ? "Untitled" : lines[0]; // Fourth line contains how much atoms and bons has the molecule int atomCount, bondCount; if (!Int32.TryParse(lines[3].Substring(0, 3), NumberStyles.Integer, CultureInfo.InvariantCulture, out atomCount)) new Exception("Invalid header data"); if (!Int32.TryParse(lines[3].Substring(3, 3), NumberStyles.Integer, CultureInfo.InvariantCulture, out bondCount)) new Exception("Invalid header data"); // Add atoms for (int i = 4; i < 4 + atomCount; i++) { double x = 0, y = 0, z = 0; if ((!Double.TryParse(lines[i].Substring(0, 10), NumberStyles.Any, CultureInfo.InvariantCulture, out x)) || (!Double.TryParse(lines[i].Substring(10, 10), NumberStyles.Any, CultureInfo.InvariantCulture, out y)) || (!Double.TryParse(lines[i].Substring(20, 10), NumberStyles.Any, CultureInfo.InvariantCulture, out z))) new Exception("Invalid atom data"); string atomSymbol = lines[i].Substring(31, Math.Min(3, lines[i].Length - 31)).Trim(); molecule.Atoms.Add(new Atom() { Element=Element.GetBySymbol(atomSymbol), Position = new Point3D(x,y,z) } ); } // Add bonds int beginIndex = 0; int endIndex = 0; for (int i = 4 + atomCount; i < 4 + atomCount + bondCount; i++) { // Index 1-based? if ((!Int32.TryParse(lines[i].Substring(0, 3), out beginIndex)) || (!Int32.TryParse(lines[i].Substring(3, 3), out endIndex))) new Exception("Invalid bonds data"); molecule.Bonds.Add(new Bond() { Begin = molecule.Atoms[beginIndex - 1], End = molecule.Atoms[endIndex - 1] }); } return molecule; }
private static void AddMolecule(dynamic data, Model newModel) { var newMol = new Molecule(); Element ce; // 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)) { bool ok = Globals.PeriodicTable.HasElement(a.l); ce = Globals.PeriodicTable.Elements[a.l]; } 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; } newMol.Atoms.Add(atom); } } if (data.b != null) { foreach (BondJSON b in data.b) { string o; if (b.o != null) { o = Bond.OrderValueToOrder(double.Parse(b.o.ToString())); } else { o = Bond.OrderSingle; } BondStereo s; if (!string.IsNullOrEmpty(b.s)) { if (o == Bond.OrderDouble) { if (b.s.Equals(Ambiguous)) { s = BondStereo.Indeterminate; } else { s = BondStereo.None; } } else { if (b.s.Equals(Recessed)) { s = BondStereo.Hatch; } else if (b.s.Equals(Protruding)) { s = BondStereo.Wedge; } else if (b.s.Equals(Ambiguous)) { s = BondStereo.Indeterminate; } else { s = BondStereo.None; } } } else { s = BondStereo.None; } // Azure DevOps #715 if (b.b.HasValue && b.b.Value < newMol.Atoms.Count && b.e.HasValue && b.e.Value < newMol.Atoms.Count) { Bond newBond = new Bond() { StartAtom = newMol.Atoms[b.b.Value], EndAtom = newMol.Atoms[b.e.Value], Stereo = s, Order = o }; newMol.Bonds.Add(newBond); } } } newModel.Molecules.Add(newMol); }
public bool SetMolecule(string text,bool addMol,int currentMol =0) { string[] sl; bool not; sl = text.Split (new Char[] {' '}, StringSplitOptions.RemoveEmptyEntries); Molecule mol; if (addMol) { mol = new Molecule (molecules [0]); molecules.Add (mol); } else { mol = molecules[currentMol]; } if (sl [0] == "not") { not = true; } else { not = false; } mol.SetActive(not); for (int ii =0; ii<sl.Length; ii++) { if (sl [0] == "all") { mol.SetActive(true); return true; } /* if(ii-1 >-1){ if(sl [ii-1] == "not"){ not=true; } } */ switch (sl [ii]) { case "chain": if (ii + 1 >= sl.Length) { return false; } for (int i=0; i< mol.Chains.Count; i++) { if (mol.Chains [i].ChainID == sl [ii + 1]) { mol.Chains [i].SetActive (!not); } } break; case "residue": if (ii + 1 >= sl.Length) { return false; } for (int i=0; i< mol.Residues.Count; i++) { if (mol.Residues [i].ResName == sl [ii + 1]) { mol.Residues [i].SetActive (!not); } } break; case "atom": if (ii + 1 >= sl.Length) { return false; } for (int i=0; i< mol.Atoms.Count; i++) { if (mol.Atoms [i].AtomName == sl [ii + 1]) { mol.Atoms [i].Active = !not; } } break; case "hetero": for (int i=0; i< mol.Chains.Count; i++) { if (mol.Chains [i].Type == "HETATM" ) { mol.Chains [i].SetActive(!not); } } break; case "water": for (int i=0; i< mol.Chains.Count; i++) { for (int j=0; j< mol.Chains[i].Residues.Count; j++) { if ((mol.Chains [i].Type == "HETATM" && (mol.Chains[i].Residues[j].ResName =="WAT") || (mol.Chains[i].Residues[j].ResName =="SOL") || (mol.Chains[i].Residues[j].ResName == "HOH"))) { //mol.Chains[i].SetActive (true); mol.Chains[i].Residues[j].SetActive (!not); } } } break; default: break; } } return true; }
public static DataTable GetDuplicateRecords(string filename, string qrymolstring, out int totalrecs_out) { DataTable dtDupRecs = null; int totalRecCnt = 0; try { dtDupRecs = CreateTANDetailsTable(); dtDupRecs.Columns.Add("OrigRecIndex", typeof(Int32)); bool blIsChiral = false; string InchiKey_Qry = ""; string InchiKey_Trgt = ""; MolHandler mHandler = new MolHandler(qrymolstring); Molecule qryMol = mHandler.getMolecule(); StandardizeMolecule(qryMol, out blIsChiral); InchiKey_Qry = qryMol.toFormat("inchi:key"); InchiKey_Qry = Validations.GetInchiKeyFromInchiString(InchiKey_Qry); MolInputStream molInStream = new MolInputStream(new FileInputStream(filename)); MolImporter molImp = new MolImporter(molInStream); Molecule objMol = new Molecule(); DataRow dtRow = null; while (molImp.read(objMol)) { objMol = StandardizeMolecule(objMol, out blIsChiral); InchiKey_Trgt = objMol.toFormat("inchi:key"); InchiKey_Trgt = Validations.GetInchiKeyFromInchiString(InchiKey_Trgt); if (InchiKey_Qry == InchiKey_Trgt) { dtRow = dtDupRecs.NewRow(); //Mol Structure dtRow["Structure"] = objMol.toFormat("mol"); //Mol Weight dtRow["MolWeight"] = objMol.getMass().ToString(); //Mol Formula dtRow["MolFormula"] = objMol.getFormula(); //Page No dtRow["PageNumber"] = objMol.getProperty("Page Number").Trim(); //Page Label dtRow["PageLabel"] = objMol.getProperty("Page Label").Trim(); //Example Number dtRow["ExampleNumber"] = objMol.getProperty("Example Number").Trim(); //IUPAC Name dtRow["IupacName"] = objMol.getProperty("IUPAC Name").Trim(); //en name dtRow["EnName"] = objMol.getProperty("en name").Trim(); //Is Chiral if (objMol.isAbsStereo()) { dtRow["IsChiral"] = "True"; } else { dtRow["IsChiral"] = "False"; } dtRow["OrigRecIndex"] = totalRecCnt; dtDupRecs.Rows.Add(dtRow); } totalRecCnt++; } molImp.close(); molInStream.close(); totalrecs_out = totalRecCnt; return(dtDupRecs); } catch (Exception ex) { ErrorHandling_NTS.WriteErrorLog(ex.ToString()); } totalrecs_out = totalRecCnt; return(dtDupRecs); }
public void propertyChange(PropertyChangeEvent pcEvent) { String name = pcEvent.getPropertyName(); if (name.Equals("mol")) { currentMol = (Molecule) pcEvent.getNewValue(); updateMolProperties(); } }
private static MolJSON ExportMol(Molecule m1) { MolJSON mj = new MolJSON(); mj.a = new AtomJSON[m1.Atoms.Count]; Dictionary <Atom, int> indexLookup = new Dictionary <Atom, int>(); int iAtom = 0; foreach (Atom a in m1.Atoms.Values) { string elem = null; if (a.Element.Symbol != "C") { if (a.Element is Element element) { elem = element.Symbol; } if (a.Element is FunctionalGroup functionalGroup) { elem = functionalGroup.Name; } } mj.a[iAtom] = new AtomJSON() { i = a.Id, x = a.Position.X, y = a.Position.Y, l = elem }; if (a.FormalCharge != null) { mj.a[iAtom].c = a.FormalCharge.Value; } indexLookup[a] = iAtom; iAtom++; } int iBond = 0; if (m1.Bonds.Any()) { mj.b = new BondJSON[m1.Bonds.Count]; foreach (Bond bond in m1.Bonds) { mj.b[iBond] = new BondJSON() { i = bond.Id, b = indexLookup[bond.StartAtom], e = indexLookup[bond.EndAtom] }; if (bond.Stereo == Globals.BondStereo.Wedge) { mj.b[iBond].s = Protruding; } else if (bond.Stereo == Globals.BondStereo.Hatch) { mj.b[iBond].s = Recessed; } else if (bond.Stereo == Globals.BondStereo.Indeterminate) { mj.b[iBond].s = Ambiguous; } if (bond.Order != Globals.OrderSingle) { mj.b[iBond].o = bond.OrderValue; } iBond++; } } return(mj); }
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); } } }
void ComposeRendering(Molecule molecule) { if (molecule is Strand) this.ComposeRendering(molecule as Strand); if (molecule is Plex) this.ComposeRendering(molecule as Plex); }
public GroupVisual(Molecule parent, Rect?boundingBox = null) { ParentMolecule = parent; BoundingBox = boundingBox ?? ParentMolecule.BoundingBox; Render(); }
public void initMoleculePhenotype() { _mol = ReactionEngine.getMoleculeFromName (_speedName, _molecules); }
public Level(Molecule[] _molecules, Molecule _targetMolecule) { molecules = _molecules; targetMolecule = _targetMolecule; }
public VibrationalMode(Molecule molecule, VibrationalModeDefinition def) { this.Molecule = molecule; this.Wavenumber = def.Wavenumber; this.Displacements = def.Displacements; }
public void SetClosestElements(Molecule m,GameObject d) { int index; for (index =0; index < m.Atoms.Count; index++) { if (m.Atoms [index].Active) break; } minDistChain = m.Atoms [index].AtomChain; minDistResidue = m.Atoms[index].AtomResidue; minDistAtom = m.Atoms [index]; float minDist = Vector3.Distance(minDistAtom.Location[Main.current_frame],d.transform.position); float dist; //Future implementation ? /* Ray ray = new Ray (o.transform.position, o.transform.forward); RaycastHit rHit; if (Physics.Raycast(ray, out rHit)) { minDistAtom.atom = rHit.collider.gameObject; } */ for (int i =index+1; i < m.Atoms.Count; i++) { if(m.Atoms[i].Active){ dist = Vector3.Distance(m.Atoms[i].Location[Main.current_frame],d.transform.position); if(dist < minDist){ minDist = dist; minDistAtom = m.Atoms[i]; minDistResidue = m.Atoms[i].AtomResidue; minDistChain =m.Atoms[i].AtomChain; } } } }
/// <summary> /// Downloads the mass tags /// </summary> /// <returns></returns> protected virtual List<MassTagLight> LoadMassTags() { var massTags = new List<MassTagLight>(); using (var connection = CreateConnection(CreateConnectionString())) { connection.Open(); using (var command = connection.CreateCommand()) { SetupMassTagCommand(command); try { using (var reader = command.ExecuteReader()) { while (reader.Read()) { var massTag = new MassTagLight(); if (reader["Mass_Tag_ID"] != DBNull.Value) { var id = Convert.ToInt32(reader["Mass_Tag_ID"]); var peptide = ""; float ganet = -1; float xcorr_max = 0; float stdNet = 0; var monoMass = 0.0; float highDiscriminant = 0; var numObservations = 0; var modification = ""; var modCount = 0; short cleaveageState = 2; float driftTime = 0; var charge = 0; var conformerID = 0; float highPeptideProphetProbability = 0; double msgf = 0; if (reader["Peptide"] != DBNull.Value) peptide = reader["Peptide"].ToString(); if (reader["Net_Value_to_Use"] != DBNull.Value) ganet = Convert.ToSingle(reader["Net_Value_to_Use"]); if (reader["High_Normalized_Score"] != DBNull.Value) xcorr_max = Convert.ToSingle(reader["High_Normalized_Score"]); if (reader["StD_GANET"] != DBNull.Value) stdNet = Convert.ToSingle(reader["StD_GANET"]); if (reader["Monoisotopic_Mass"] != DBNull.Value) monoMass = Convert.ToDouble(reader["Monoisotopic_Mass"]); if (reader["Min_MSGF_SpecProb"] != DBNull.Value) msgf = Convert.ToDouble(reader["Min_MSGF_SpecProb"]); if (reader["Peptide_Obs_Count_Passing_Filter"] != DBNull.Value) numObservations = Convert.ToInt32(reader["Peptide_Obs_Count_Passing_Filter"]); if (reader["Mod_Count"] != DBNull.Value) modCount = Convert.ToInt32(reader["Mod_Count"]); if (reader["Mod_Description"] != DBNull.Value) modification = reader["Mod_Description"].ToString(); if (reader["High_Peptide_Prophet_Probability"] != DBNull.Value) highPeptideProphetProbability = Convert.ToSingle(reader["High_Peptide_Prophet_Probability"]); if (reader["Cleavage_State"] != DBNull.Value) cleaveageState = Convert.ToInt16(reader["Cleavage_State"]); if (reader["Drift_Time_Avg"] != DBNull.Value) driftTime = Convert.ToSingle(reader["Drift_Time_Avg"]); if (reader["Conformer_Charge"] != DBNull.Value) charge = Convert.ToInt32(reader["Conformer_Charge"]); if (reader["Conformer_ID"] != DBNull.Value) conformerID = Convert.ToInt32(reader["Conformer_ID"]); /// Make sure the mass tag has been seen enough times if (numObservations >= Options.MinimumObservationCountFilter) { var molecule = new Molecule(); molecule.Name = peptide; massTag.Id = id; massTag.Molecule = molecule; massTag.Net = ganet; massTag.NetAverage = ganet; massTag.XCorr = xcorr_max; massTag.DiscriminantMax = highDiscriminant; massTag.MassMonoisotopic = monoMass; massTag.ConformationId = conformerID; massTag.NetStandardDeviation = stdNet; massTag.ObservationCount = numObservations; massTag.DriftTime = driftTime; massTag.PriorProbability = highPeptideProphetProbability; massTag.CleavageState = cleaveageState; massTag.ModificationCount = modCount; massTag.MsgfSpecProbMax = msgf; massTag.PeptideSequence = peptide; massTag.ChargeState = charge; if (massTag.NetAverage != -1) { var shouldAdd = false; // If we are using drift time, then we should only // use mass tags that have drift time. if (Options.OnlyLoadTagsWithDriftTime) { if (driftTime > 0) { shouldAdd = true; } } else { shouldAdd = true; } if (shouldAdd) { massTags.Add(massTag); } } } } } reader.Close(); } } catch (Exception) { throw; } } connection.Close(); } return massTags; }
/// <summary> Parses a SMILES string and returns a Molecule object. /// /// </summary> /// <param name="smiles"> A SMILES string /// </param> /// <returns> A Molecule representing the constitution /// given in the SMILES string /// </returns> /// <exception cref="InvalidSmilesException"> Exception thrown when the SMILES string /// is invalid /// </exception> public virtual Molecule parseSmiles(System.String smiles) { //logger.debug("parseSmiles()..."); Bond bond = null; nodeCounter = 0; bondStatus = 0; bondIsAromatic = false; bool bondExists = true; thisRing = - 1; currentSymbol = null; molecule = new Molecule(); position = 0; // we don't want more than 1024 rings rings = new Atom[1024]; ringbonds = new double[1024]; for (int f = 0; f < 1024; f++) { rings[f] = null; ringbonds[f] = - 1; } char mychar = 'X'; char[] chars = new char[1]; Atom lastNode = null; System.Collections.ArrayList atomStack = new System.Collections.ArrayList(); System.Collections.ArrayList bondStack = new System.Collections.ArrayList(); Atom atom = null; do { try { mychar = smiles[position]; //logger.debug(""); //logger.debug("Processing: " + mychar); if (lastNode != null) { //logger.debug("Lastnode: ", lastNode.GetHashCode()); } if ((mychar >= 'A' && mychar <= 'Z') || (mychar >= 'a' && mychar <= 'z') || (mychar == '*')) { status = 1; //logger.debug("Found a must-be 'organic subset' element"); // only 'organic subset' elements allowed atom = null; if (mychar == '*') { currentSymbol = "*"; atom = new PseudoAtom("*"); } else { currentSymbol = getSymbolForOrganicSubsetElement(smiles, position); if (currentSymbol != null) { if (currentSymbol.Length == 1) { if (!(currentSymbol.ToUpper()).Equals(currentSymbol)) { currentSymbol = currentSymbol.ToUpper(); atom = new Atom(currentSymbol); atom.Hybridization = CDKConstants.HYBRIDIZATION_SP2; } else { atom = new Atom(currentSymbol); } } else { atom = new Atom(currentSymbol); } //logger.debug("Made atom: ", atom); } else { throw new InvalidSmilesException("Found element which is not a 'organic subset' element. You must " + "use [" + mychar + "]."); } } molecule.addAtom(atom); //logger.debug("Adding atom ", atom.GetHashCode()); if ((lastNode != null) && bondExists) { //logger.debug("Creating bond between ", atom.Symbol, " and ", lastNode.Symbol); bond = new Bond(atom, lastNode, bondStatus); if (bondIsAromatic) { bond.setFlag(CDKConstants.ISAROMATIC, true); } molecule.addBond(bond); } bondStatus = CDKConstants.BONDORDER_SINGLE; lastNode = atom; nodeCounter++; position = position + currentSymbol.Length; bondExists = true; bondIsAromatic = false; } else if (mychar == '=') { position++; if (status == 2 || smiles.Length == position + 1 || !(smiles[position] >= '0' && smiles[position] <= '9')) { bondStatus = CDKConstants.BONDORDER_DOUBLE; } else { bondStatusForRingClosure = CDKConstants.BONDORDER_DOUBLE; } } else if (mychar == '#') { position++; if (status == 2 || smiles.Length == position + 1 || !(smiles[position] >= '0' && smiles[position] <= '9')) { bondStatus = CDKConstants.BONDORDER_TRIPLE; } else { bondStatusForRingClosure = CDKConstants.BONDORDER_TRIPLE; } } else if (mychar == '(') { atomStack.Add(lastNode); //logger.debug("Stack:"); System.Collections.IEnumerator ses = atomStack.GetEnumerator(); //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" while (ses.MoveNext()) { //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" Atom a = (Atom) ses.Current; //logger.debug("", a.GetHashCode()); } //logger.debug("------"); bondStack.Add((double) bondStatus); position++; } else if (mychar == ')') { lastNode = (Atom) SupportClass.StackSupport.Pop(atomStack); //logger.debug("Stack:"); System.Collections.IEnumerator ses = atomStack.GetEnumerator(); //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'" while (ses.MoveNext()) { //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'" Atom a = (Atom) ses.Current; //logger.debug("", a.GetHashCode()); } //logger.debug("------"); bondStatus = ((System.Double) SupportClass.StackSupport.Pop(bondStack)); position++; } else if (mychar >= '0' && mychar <= '9') { status = 2; chars[0] = mychar; currentSymbol = new System.String(chars); thisRing = (System.Int32.Parse(currentSymbol)); handleRing(lastNode); position++; } else if (mychar == '%') { currentSymbol = getRingNumber(smiles, position); thisRing = (System.Int32.Parse(currentSymbol)); handleRing(lastNode); position += currentSymbol.Length + 1; } else if (mychar == '[') { currentSymbol = getAtomString(smiles, position); atom = assembleAtom(currentSymbol); molecule.addAtom(atom); //logger.debug("Added atom: ", atom); if (lastNode != null && bondExists) { bond = new Bond(atom, lastNode, bondStatus); if (bondIsAromatic) { bond.setFlag(CDKConstants.ISAROMATIC, true); } molecule.addBond(bond); //logger.debug("Added bond: ", bond); } bondStatus = CDKConstants.BONDORDER_SINGLE; bondIsAromatic = false; lastNode = atom; nodeCounter++; position = position + currentSymbol.Length + 2; // plus two for [ and ] bondExists = true; } else if (mychar == '.') { bondExists = false; position++; } else if (mychar == '-') { bondExists = true; // a simple single bond position++; } else if (mychar == ':') { bondExists = true; bondIsAromatic = true; position++; } else if (mychar == '/' || mychar == '\\') { //logger.warn("Ignoring stereo information for double bond"); position++; } else if (mychar == '@') { if (position < smiles.Length - 1 && smiles[position + 1] == '@') { position++; } //logger.warn("Ignoring stereo information for atom"); position++; } else { throw new InvalidSmilesException("Unexpected character found: " + mychar); } } catch (InvalidSmilesException exc) { //logger.error("InvalidSmilesException while parsing char (in parseSmiles()): " + mychar); //logger.debug(exc); throw exc; } catch (System.Exception exception) { //logger.error("Error while parsing char: " + mychar); //logger.debug(exception); throw new InvalidSmilesException("Error while parsing char: " + mychar); } //logger.debug("Parsing next char"); } while (position < smiles.Length); // add implicit hydrogens try { //logger.debug("before H-adding: ", molecule); hAdder.addImplicitHydrogensToSatisfyValency(molecule); //logger.debug("after H-adding: ", molecule); } catch (System.Exception exception) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //logger.error("Error while calculation Hcount for SMILES atom: ", exception.Message); } // setup missing bond orders try { valencyChecker.saturate(molecule); //logger.debug("after adding missing bond orders: ", molecule); } catch (System.Exception exception) { //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'" //logger.error("Error while calculation Hcount for SMILES atom: ", exception.Message); } // conceive aromatic perception IMolecule[] moleculeSet = ConnectivityChecker.partitionIntoMolecules(molecule).Molecules; //logger.debug("#mols ", moleculeSet.Length); for (int i = 0; i < moleculeSet.Length; i++) { //logger.debug("mol: ", moleculeSet[i]); try { valencyChecker.saturate(moleculeSet[i]); //logger.debug(" after saturation: ", moleculeSet[i]); if (HueckelAromaticityDetector.detectAromaticity(moleculeSet[i])) { //logger.debug("Structure is aromatic..."); } } catch (System.Exception exception) { //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 perceive aromaticity: ", exception.Message); //logger.debug(exception); } } return molecule; }
/*! \brief Load Molecules from a MoleculesSet \param molSet The set to Load \param allMolecules The list of all the molecules */ public void initMoleculesFromMoleculesSets(MoleculesSet molSet, ArrayList allMolecules) { Molecule newMol; Molecule startingMolStatus; _molecules = new ArrayList(); foreach (Molecule mol in allMolecules) { newMol = new Molecule(mol); startingMolStatus = ReactionEngine.getMoleculeFromName(mol.getName(), molSet.molecules); if (startingMolStatus == null) newMol.setConcentration(0); else newMol.setConcentration(startingMolStatus.getConcentration()); _molecules.Add(newMol); } }
//! Tell if a Molecule is already present in a Molecule list (based on the name attribute) /*! \param mol Molecule to match. \param list Molecule list where to search in. */ public static bool isMoleculeDuplicated(Molecule mol, ArrayList list) { foreach (Molecule mol2 in list) if (mol2.getName() == mol.getName()) return true; return false; }