コード例 #1
0
        public static IAtomContainer GetLargestMoleculeFragment(
            IAtomContainer mol,
            out int acc)
        {
            AtomContainerSet acs;
            IAtomContainer   mol2, molMain = null;

            acs = null;

            if (ConnectivityChecker.isConnected(mol))
            {
                acc = 1;
                return(mol);
            }

            acs = (AtomContainerSet)ConnectivityChecker.partitionIntoMolecules(mol);
            int largestAc = -1;

            acc = acs.getAtomContainerCount();
            for (int aci = 0; aci < acc; aci++)
            {
                mol2 = acs.getAtomContainer(aci);
                int ac2 = mol2.getAtomCount();
                if (ac2 > largestAc)
                {
                    largestAc = mol2.getAtomCount();
                    molMain   = mol2;
                }
            }

            return(molMain);
        }
コード例 #2
0
        /// <summary>
        /// </summary>
        /// <param name="mol"></param>
        /// <param name="mcss"></param>
        /// <param name="shouldMatchBonds"></param>
        /// <returns>IMolecule Set</returns>
        /// <exception cref="CDKException"></exception>
        private static IChemObjectSet <IAtomContainer> GetUncommon(IAtomContainer mol, IAtomContainer mcss, bool shouldMatchBonds)
        {
            List <int> atomSerialsToDelete = new List <int>();

            var matches = CDKMCS.GetSubgraphAtomsMaps(mol, mcss, shouldMatchBonds);
            var mapList = matches[0];

            foreach (var o in mapList)
            {
                CDKRMap rmap = (CDKRMap)o;
                atomSerialsToDelete.Add(rmap.Id1);
            }

            // at this point we have the serial numbers of the bonds to delete
            // we should get the actual bonds rather than delete by serial numbers
            List <IAtom> atomsToDelete = new List <IAtom>();

            foreach (var serial in atomSerialsToDelete)
            {
                atomsToDelete.Add(mol.Atoms[serial]);
            }

            // now lets get rid of the bonds themselves
            foreach (var atom in atomsToDelete)
            {
                mol.RemoveAtomAndConnectedElectronContainers(atom);
            }

            // now we probably have a set of disconnected components
            // so lets get a set of individual atom containers for
            // corresponding to each component
            return(ConnectivityChecker.PartitionIntoMolecules(mol));
        }
コード例 #3
0
        private void CullDegenerateOceans()
        {
            ConnectivityChecker <District> connectivityChecker = new ConnectivityChecker <District>(new AdHocGraph <District>(new List <District>(from d in base.Context.Districts.Values
                                                                                                                                                  where d.Content == District.Contents.Ocean
                                                                                                                                                  select d)));

            connectivityChecker.Execute();
            foreach (HashSet <District> hashSet in connectivityChecker.ConnexNodeSets)
            {
                if (hashSet.Sum((District d) => d.Count) < 30)
                {
                    HashSet <byte> source = new HashSet <byte>(from d in hashSet
                                                               from n in d.Neighbours
                                                               where n.ContinentId > 0
                                                               select n.ContinentId);
                    foreach (District district in hashSet)
                    {
                        district.Content     = District.Contents.Land;
                        district.ContinentId = source.First <byte>();
                        foreach (HexPos hexPos in district)
                        {
                        }
                    }
                }
            }
        }
コード例 #4
0
        protected void ConfirmContinents()
        {
            foreach (CreateContinents.Continent continent in this.Continents)
            {
                foreach (CreateContinents.Blob blob in continent.Blobs)
                {
                    foreach (District district in blob.Districts)
                    {
                        district.Content     = District.Contents.Land;
                        district.ContinentId = (byte)continent.Id;
                    }
                }
                string   format = "Continent {0} : {1} hexes - {2} blobs - {3} districts";
                object[] array  = new object[4];
                array[0] = continent.Id;
                array[1] = continent.HexCount;
                array[2] = continent.Blobs.Count;
                array[3] = continent.Blobs.Sum((CreateContinents.Blob b) => b.Districts.Count);
                base.Trace(string.Format(format, array));
            }
            this.CullDegenerateOceans();
            ConnectivityChecker <District> connectivityChecker = new ConnectivityChecker <District>(new AdHocGraph <District>(from d in base.Context.Districts.Values
                                                                                                                              where d.Content == District.Contents.Land
                                                                                                                              select d));

            connectivityChecker.Execute();
            base.Context.Settings.LandMasses = connectivityChecker.ConnexNodeSets.Count;
        }
コード例 #5
0
        public static IAtomContainer GetLargestMoleculeFragment(
            IAtomContainer mol,
            out int acc)
        {
            IAtomContainer mol2, molMain = null;

            acc = 0;
            if (mol == null)
            {
                return(null);
            }

            if (ConnectivityChecker.IsConnected(mol))
            {
                acc = 1;
                return(mol);
            }

            IReadOnlyList <IAtomContainer> acs = ConnectivityChecker.PartitionIntoMolecules(mol);
            int largestAc = -1;

            acc = acs.Count;
            for (int aci = 0; aci < acc; aci++)
            {
                mol2 = acs[aci];
                int ac2 = mol2.Atoms.Count;
                if (ac2 > largestAc)
                {
                    largestAc = mol2.Atoms.Count;
                    molMain   = mol2;
                }
            }

            return(molMain);
        }
コード例 #6
0
        public async void Ping_Okay(string url)
        {
            using ConnectivityChecker checker = new ConnectivityChecker();

            var ok = await checker.PingAsync(HttpClient, url);

            Assert.True(ok);
        }
コード例 #7
0
        protected void UnifyBlobGraph()
        {
            ConnectivityChecker <CreateContinents.Blob> blobConnexer = new ConnectivityChecker <CreateContinents.Blob>(this.BlobGraph);

            blobConnexer.Execute();
            if (blobConnexer.ConnexNodeSets.Count > 1)
            {
                this.CoreBlobs.RemoveAll((CreateContinents.Blob b) => !blobConnexer.ConnexNodeSets.First <HashSet <CreateContinents.Blob> >().Contains(b));
                this.BlobGraph = new AdHocGraph <CreateContinents.Blob>(this.CoreBlobs);
            }
        }
コード例 #8
0
        public void TestTwentyRandomStructures()
        {
            var            molecule = TestMoleculeFactory.MakeAlphaPinene();
            var            rg       = new RandomGenerator(molecule);
            IAtomContainer result   = null;

            for (int f = 0; f < 50; f++)
            {
                result = rg.ProposeStructure();
                Assert.AreEqual(molecule.Atoms.Count, result.Atoms.Count);
                Assert.AreEqual(1, ConnectivityChecker.PartitionIntoMolecules(result).Count());
            }
        }
コード例 #9
0
    void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(gameObject)

            DontDestroyOnLoad(gameObject);
        }
    }
コード例 #10
0
        public void TestPartialFilledStructureMerger2()
        {
            var sp  = CDK.SmilesParser;
            var acs = ChemObjectBuilder.Instance.NewAtomContainerSet();

            acs.Add(sp.ParseSmiles("[C]=[C]CC[CH2]"));
            acs.Add(sp.ParseSmiles("[C]([CH2])=C1CC1"));
            var pfsm   = new PartialFilledStructureMerger();
            var result = pfsm.Generate(acs);

            Assert.IsTrue(ConnectivityChecker.IsConnected(result));
            Assert.IsTrue(CDK.SaturationChecker.IsSaturated(result));
        }
コード例 #11
0
ファイル: RandomGenerator.cs プロジェクト: ch-hristov/NCDK
        /// <summary>
        /// Proposes a structure which can be accepted or rejected by an external
        /// entity. If rejected, the structure is not used as a starting point
        /// for the next random move in structure space.
        /// </summary>
        /// <returns>A proposed molecule</returns>
        public IAtomContainer ProposeStructure()
        {
            Debug.WriteLine("RandomGenerator->ProposeStructure() Start");
            do
            {
                trial = (IAtomContainer)Molecule.Clone();
                Mutate(trial);
                Debug.WriteLine("BondCounts:    " + string.Join(" ", trial.Atoms.Select(n => trial.GetConnectedBonds(n).Count())));
                Debug.WriteLine("BondOrderSums: " + string.Join(" ", trial.Atoms.Select(n => trial.GetBondOrderSum(n))));
            } while (trial == null || !ConnectivityChecker.IsConnected(trial));
            proposedStructure = trial;

            return(proposedStructure);
        }
コード例 #12
0
ファイル: SmilesParser.cs プロジェクト: carlhuth/GenXSource
        /// <summary>  Description of the Method
        ///
        /// </summary>
        /// <param name="smiles">                     Description of the Parameter
        /// </param>
        /// <returns>                             Description of the Return Value
        /// </returns>
        /// <exception cref="InvalidSmilesException"> Description of the Exception
        /// </exception>
        public virtual Reaction parseReactionSmiles(System.String smiles)
        {
            SupportClass.Tokenizer tokenizer      = new SupportClass.Tokenizer(smiles, ">");
            System.String          reactantSmiles = tokenizer.NextToken();
            System.String          agentSmiles    = "";
            System.String          productSmiles  = tokenizer.NextToken();
            if (tokenizer.HasMoreTokens())
            {
                agentSmiles   = productSmiles;
                productSmiles = tokenizer.NextToken();
            }

            Reaction reaction = new Reaction();

            // add reactants
            IMolecule       reactantContainer = parseSmiles(reactantSmiles);
            ISetOfMolecules reactantSet       = ConnectivityChecker.partitionIntoMolecules(reactantContainer);

            IMolecule[] reactants = reactantSet.Molecules;
            for (int i = 0; i < reactants.Length; i++)
            {
                reaction.addReactant(reactants[i]);
            }

            // add reactants
            if (agentSmiles.Length > 0)
            {
                IMolecule       agentContainer = parseSmiles(agentSmiles);
                ISetOfMolecules agentSet       = ConnectivityChecker.partitionIntoMolecules(agentContainer);
                IMolecule[]     agents         = agentSet.Molecules;
                for (int i = 0; i < agents.Length; i++)
                {
                    reaction.addAgent(agents[i]);
                }
            }

            // add products
            IMolecule       productContainer = parseSmiles(productSmiles);
            ISetOfMolecules productSet       = ConnectivityChecker.partitionIntoMolecules(productContainer);

            IMolecule[] products = productSet.Molecules;
            for (int i = 0; i < products.Length; i++)
            {
                reaction.addProduct(products[i]);
            }

            return(reaction);
        }
コード例 #13
0
        /// <summary>
        /// Fragment a molecule
        /// </summary>
        /// <param name="mol"></param>
        /// <returns></returns>

        public static List <KeyValuePair <string, IAtomContainer> > FragmentMoleculeAndCanonicalizeSmiles(
            IAtomContainer mol,
            bool filterOutCommonCounterIons)
        {
            int aci, fi, i1;

            KeyValuePair <string, IAtomContainer>         kvp;
            List <KeyValuePair <string, IAtomContainer> > frags = new List <KeyValuePair <string, IAtomContainer> >();

            if (mol == null)
            {
                return(frags);
            }

            IReadOnlyList <IAtomContainer> acs = ConnectivityChecker.PartitionIntoMolecules(mol);

            int acc = acs.Count;

            for (aci = 0; aci < acc; aci++)
            {
                IAtomContainer fragMol    = acs[aci];
                string         fragSmiles = AtomContainerToSmiles(fragMol);
                if (filterOutCommonCounterIons)
                {
                    if (CommonSmallFragments.Contains(fragSmiles) ||
                        GetHeavyAtomCount(fragMol) <= 6)
                    {
                        continue;
                    }
                }

                kvp = new KeyValuePair <string, IAtomContainer>(fragSmiles, fragMol);

                int ac = fragMol.Atoms.Count;

                for (fi = frags.Count - 1; fi >= 0; fi--)                 // insert into list so that fragments are ordered largest to smallest
                {
                    if (frags[fi].Value.Atoms.Count >= ac)
                    {
                        break;
                    }
                }
                frags.Insert(fi + 1, kvp);
            }

            return(frags);
        }
コード例 #14
0
        /// <summary>
        /// Modules for cleaning a molecule
        /// </summary>
        /// <param name="molecule"></param>
        /// <returns>cleaned AtomContainer</returns>
        public static IAtomContainer CheckAndCleanMolecule(IAtomContainer molecule)
        {
            bool isMarkush = false;

            foreach (var atom in molecule.Atoms)
            {
                if (atom.Symbol.Equals("R", StringComparison.Ordinal))
                {
                    isMarkush = true;
                    break;
                }
            }

            if (isMarkush)
            {
                Console.Error.WriteLine("Skipping Markush structure for sanity check");
            }

            // Check for salts and such
            if (!ConnectivityChecker.IsConnected(molecule))
            {
                // lets see if we have just two parts if so, we assume its a salt and just work
                // on the larger part. Ideally we should have a check to ensure that the smaller
                //  part is a metal/halogen etc.
                var fragments = ConnectivityChecker.PartitionIntoMolecules(molecule).ToReadOnlyList();
                if (fragments.Count > 2)
                {
                    Console.Error.WriteLine("More than 2 components. Skipped");
                }
                else
                {
                    var frag1 = fragments[0];
                    var frag2 = fragments[1];
                    if (frag1.Atoms.Count > frag2.Atoms.Count)
                    {
                        molecule = frag1;
                    }
                    else
                    {
                        molecule = frag2;
                    }
                }
            }
            Configure(molecule);
            return(molecule);
        }
コード例 #15
0
ファイル: HydrogenAdder.cs プロジェクト: carlhuth/GenXSource
        /// <summary> Method that saturates a molecule by adding implicit hydrogens.
        ///
        /// </summary>
        /// <param name="container"> Molecule to saturate
        /// </param>
        /// <cdk.keyword>           hydrogen, adding </cdk.keyword>
        /// <cdk.keyword>           implicit hydrogen </cdk.keyword>
        //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
        public virtual System.Collections.Hashtable addImplicitHydrogensToSatisfyValency(IAtomContainer container)
        {
            ISetOfMolecules moleculeSet = ConnectivityChecker.partitionIntoMolecules(container);

            IMolecule[] molecules = moleculeSet.Molecules;
            //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
            System.Collections.Hashtable hydrogenAtomMap = new System.Collections.Hashtable();
            for (int k = 0; k < molecules.Length; k++)
            {
                IMolecule molPart = molecules[k];
                IAtom[]   atoms   = molPart.Atoms;
                for (int f = 0; f < atoms.Length; f++)
                {
                    int[] hydrogens = addImplicitHydrogensToSatisfyValency(molPart, atoms[f]);
                    hydrogenAtomMap[atoms[f]] = hydrogens;
                }
            }
            return(hydrogenAtomMap);
        }
コード例 #16
0
        public void TestVicinitySampler_sample()
        {
            IAtomContainer mol = TestMoleculeFactory.MakeEthylPropylPhenantren();

            BODRIsotopeFactory.Instance.ConfigureAtoms(mol);
            AddImplicitHydrogens(mol);

            var structures = VicinitySampler.Sample(mol);
            var count      = 0;

            foreach (var temp in structures)
            {
                Assert.IsNotNull(temp);
                Assert.IsTrue(ConnectivityChecker.IsConnected(temp));
                Assert.AreEqual(mol.Atoms.Count, temp.Atoms.Count);
                count++;
            }
            Assert.AreEqual(37, count);
        }
コード例 #17
0
        // @cdk.bug 1632610
        public void TestCycloButene()
        {
            var mol = parser.ParseSmiles("C=CC=C");

            BODRIsotopeFactory.Instance.ConfigureAtoms(mol);
            AddImplicitHydrogens(mol);

            var structures = VicinitySampler.Sample(mol);
            var count      = 0;

            foreach (var temp in structures)
            {
                Assert.IsNotNull(temp);
                Assert.IsTrue(ConnectivityChecker.IsConnected(temp));
                Assert.AreEqual(mol.Atoms.Count, temp.Atoms.Count);
                count++;
            }
            Assert.AreEqual(1, count);
        }
コード例 #18
0
 public static void RemoveElectronContainer(IChemObjectSet <IAtomContainer> set, IElectronContainer electrons)
 {
     foreach (var atomContainer in set)
     {
         if (atomContainer.Contains(electrons))
         {
             atomContainer.Remove(electrons);
             var molecules = ConnectivityChecker.PartitionIntoMolecules(atomContainer);
             if (molecules.Count > 1)
             {
                 set.Remove(atomContainer);
                 for (int k = 0; k < molecules.Count; k++)
                 {
                     set.Add(molecules[k]);
                 }
             }
             return;
         }
     }
 }
コード例 #19
0
ファイル: BasicBondGenerator.cs プロジェクト: qize/NCDK
        /// <summary>
        /// Determine the ring set for this atom container.
        /// </summary>
        /// <param name="atomContainer">the atom container to find rings in.</param>
        /// <returns>the rings of the molecule</returns>
        protected virtual IRingSet GetRingSet(IAtomContainer atomContainer)
        {
            IRingSet ringSet = atomContainer.Builder.NewRingSet();

            try
            {
                var molecules = ConnectivityChecker.PartitionIntoMolecules(atomContainer);
                foreach (var mol in molecules)
                {
                    ringSet.Add(Cycles.FindSSSR(mol).ToRingSet());
                }

                return(ringSet);
            }
            catch (Exception exception)
            {
                Trace.TraceWarning("Could not partition molecule: " + exception.Message);
                Debug.WriteLine(exception);
                return(ringSet);
            }
        }
コード例 #20
0
        private static int GetFragmentCount(IAtomContainer molecule)
        {
            bool fragmentFlag   = true;
            var  fragmentMolSet = ChemObjectBuilder.Instance.NewAtomContainerSet();
            int  countFrag      = 0;

            if (molecule.Atoms.Count > 0)
            {
                fragmentFlag = ConnectivityChecker.IsConnected(molecule);
                if (!fragmentFlag)
                {
                    fragmentMolSet.AddRange(ConnectivityChecker.PartitionIntoMolecules(molecule));
                }
                else
                {
                    fragmentMolSet.Add(molecule);
                }
                countFrag = fragmentMolSet.Count;
            }
            return(countFrag);
        }
コード例 #21
0
        /// <summary>
        /// Generates a random structure based on the atoms in the given <see cref="IAtomContainer"/>.
        /// </summary>
        public IAtomContainer Generate()
        {
            int  iteration      = 0;
            bool structureFound = false;

            do
            {
                iteration++;
                atomContainer.RemoveAllElectronContainers();
                bool bondFormed;
                do
                {
                    bondFormed = false;
                    foreach (var atom in atomContainer.Atoms)
                    {
                        if (!satCheck.IsSaturated(atom, atomContainer))
                        {
                            var partner = GetAnotherUnsaturatedNode(atom);
                            if (partner != null)
                            {
                                var cmax1 = satCheck.GetCurrentMaxBondOrder(atom, atomContainer);
                                var cmax2 = satCheck.GetCurrentMaxBondOrder(partner, atomContainer);
                                var max   = Math.Min(cmax1, cmax2);
                                var order = Math.Min(Math.Max(1.0, random.NextInt((int)Math.Round(max))), 3.0);
                                Debug.WriteLine($"Forming bond of order {order}");
                                atomContainer.Bonds.Add(atomContainer.Builder.NewBond(atom, partner, BondManipulator.CreateBondOrder(order)));
                                bondFormed = true;
                            }
                        }
                    }
                } while (bondFormed);
                if (ConnectivityChecker.IsConnected(atomContainer) && satCheck.IsSaturated(atomContainer))
                {
                    structureFound = true;
                }
            } while (!structureFound && iteration < 20);
            Debug.WriteLine($"Structure found after #iterations: {iteration}");
            return(atomContainer.Builder.NewAtomContainer(atomContainer));
        }
コード例 #22
0
        /// <summary>
        /// Generates a shortest path based BitArray fingerprint for the given AtomContainer.
        /// </summary>
        /// <param name="ac">The AtomContainer for which a fingerprint is generated</param>
        /// <exception cref="CDKException">if there error in aromaticity perception or other CDK functions</exception>
        /// <returns>A <see cref="BitArray"/> representing the fingerprint</returns>
        public override IBitFingerprint GetBitFingerprint(IAtomContainer ac)
        {
            IAtomContainer atomContainer = null;

            atomContainer = (IAtomContainer)ac.Clone();
            Aromaticity.CDKLegacy.Apply(atomContainer);
            var bitSet = new BitArray(fingerprintLength);

            if (!ConnectivityChecker.IsConnected(atomContainer))
            {
                var partitionedMolecules = ConnectivityChecker.PartitionIntoMolecules(atomContainer);
                foreach (var container in partitionedMolecules)
                {
                    AddUniquePath(container, bitSet);
                }
            }
            else
            {
                AddUniquePath(atomContainer, bitSet);
            }
            return(new BitSetFingerprint(bitSet));
        }
コード例 #23
0
 public static void removeElectronContainer(ISetOfAtomContainers set_Renamed, IElectronContainer electrons)
 {
     IAtomContainer[] acs = set_Renamed.AtomContainers;
     for (int i = 0; i < acs.Length; i++)
     {
         IAtomContainer container = acs[i];
         if (container.contains(electrons))
         {
             container.removeElectronContainer(electrons);
             IMolecule[] molecules = ConnectivityChecker.partitionIntoMolecules(container).Molecules;
             if (molecules.Length > 1)
             {
                 set_Renamed.removeAtomContainer(container);
                 for (int k = 0; k < molecules.Length; k++)
                 {
                     set_Renamed.addAtomContainer(molecules[k]);
                 }
             }
             return;
         }
     }
 }
コード例 #24
0
ファイル: HydrogenAdder.cs プロジェクト: carlhuth/GenXSource
        /// <summary> Method that saturates a molecule by adding explicit hydrogens.
        /// In order to get coordinates for these Hydrogens, you need to
        /// remember the average bondlength of you molecule (coordinates for
        /// all atoms should be available) by using
        /// double bondLength = GeometryTools.getBondLengthAverage(atomContainer);
        /// and then use this method here and then use
        /// org.openscience.cdk.HydrogenPlacer(atomContainer, bondLength);
        ///
        /// </summary>
        /// <param name="molecule"> Molecule to saturate
        /// </param>
        /// <cdk.keyword>           hydrogen, adding </cdk.keyword>
        /// <cdk.keyword>           explicit hydrogen </cdk.keyword>
        public virtual IAtomContainer addExplicitHydrogensToSatisfyValency(IMolecule molecule)
        {
            //logger.debug("Start of addExplicitHydrogensToSatisfyValency");
            ISetOfMolecules moleculeSet = ConnectivityChecker.partitionIntoMolecules(molecule);

            IMolecule[]    molecules             = moleculeSet.Molecules;
            IAtomContainer changedAtomsAndBonds  = molecule.Builder.newAtomContainer();
            IAtomContainer intermediateContainer = null;

            for (int k = 0; k < molecules.Length; k++)
            {
                IMolecule molPart = molecules[k];
                IAtom[]   atoms   = molPart.Atoms;
                for (int i = 0; i < atoms.Length; i++)
                {
                    intermediateContainer = addHydrogensToSatisfyValency(molPart, atoms[i], molecule);
                    changedAtomsAndBonds.add(intermediateContainer);
                }
            }
            //logger.debug("End of addExplicitHydrogensToSatisfyValency");
            return(changedAtomsAndBonds);
        }
コード例 #25
0
ファイル: ModelBuilder3D.cs プロジェクト: roddickchen/NCDK
        /// <summary>
        /// Generate 3D coordinates with force field information.
        /// </summary>
        public IAtomContainer Generate3DCoordinates(IAtomContainer molecule, bool clone)
        {
            var originalAtomTypeNames = molecule.Atoms.Select(n => n.AtomTypeName).ToArray();

            Debug.WriteLine("******** GENERATE COORDINATES ********");
            foreach (var atom in molecule.Atoms)
            {
                atom.IsPlaced  = false;
                atom.IsVisited = false;
            }
            //CHECK FOR CONNECTIVITY!
            Debug.WriteLine($"#atoms>{molecule.Atoms.Count}");
            if (!ConnectivityChecker.IsConnected(molecule))
            {
                throw new CDKException("Molecule is NOT connected, could not layout.");
            }

            // setup helper classes
            AtomPlacer   atomPlacer = new AtomPlacer();
            AtomPlacer3D ap3d       = new AtomPlacer3D(parameterSet);
            AtomTetrahedralLigandPlacer3D atlp3d = new AtomTetrahedralLigandPlacer3D(parameterSet);

            if (clone)
            {
                molecule = (IAtomContainer)molecule.Clone();
            }
            atomPlacer.Molecule = molecule;

            if (ap3d.NumberOfUnplacedHeavyAtoms(molecule) == 1)
            {
                Debug.WriteLine("Only one Heavy Atom");
                ap3d.GetUnplacedHeavyAtom(molecule).Point3D = new Vector3(0.0, 0.0, 0.0);
                try
                {
                    atlp3d.Add3DCoordinatesForSinglyBondedLigands(molecule);
                }
                catch (CDKException ex3)
                {
                    Trace.TraceError($"PlaceSubstitutensERROR: Cannot place substitutents due to:{ex3.Message}");
                    Debug.WriteLine(ex3);
                    throw new CDKException("PlaceSubstitutensERROR: Cannot place substitutents due to:" + ex3.Message,
                                           ex3);
                }
                return(molecule);
            }
            //Assing Atoms to Rings,Aliphatic and Atomtype
            IRingSet ringSetMolecule   = ffc.AssignAtomTyps(molecule);
            IRingSet largestRingSet    = null;
            int      numberOfRingAtoms = 0;

            IReadOnlyList <IRingSet> ringSystems = null;

            if (ringSetMolecule.Count > 0)
            {
                if (templateHandler == null)
                {
                    throw new CDKException("You are trying to generate coordinates for a molecule with rings, but you have no template handler set. Please do SetTemplateHandler() before generation!");
                }
                ringSystems    = RingPartitioner.PartitionRings(ringSetMolecule);
                largestRingSet = RingSetManipulator.GetLargestRingSet(ringSystems);
                IAtomContainer largestRingSetContainer = RingSetManipulator.GetAllInOneContainer(largestRingSet);
                numberOfRingAtoms = largestRingSetContainer.Atoms.Count;
                templateHandler.MapTemplates(largestRingSetContainer, numberOfRingAtoms);
                if (!CheckAllRingAtomsHasCoordinates(largestRingSetContainer))
                {
                    throw new CDKException("RingAtomLayoutError: Not every ring atom is placed! Molecule cannot be layout.");
                }

                SetAtomsToPlace(largestRingSetContainer);
                SearchAndPlaceBranches(molecule, largestRingSetContainer, ap3d, atlp3d, atomPlacer);
                largestRingSet = null;
            }
            else
            {
                //Debug.WriteLine("****** Start of handling aliphatic molecule ******");
                IAtomContainer ac = AtomPlacer.GetInitialLongestChain(molecule);
                SetAtomsToUnVisited(molecule);
                SetAtomsToUnplaced(molecule);
                ap3d.PlaceAliphaticHeavyChain(molecule, ac);
                //ZMatrixApproach
                ap3d.ZMatrixChainToCartesian(molecule, false);
                SearchAndPlaceBranches(molecule, ac, ap3d, atlp3d, atomPlacer);
            }
            LayoutMolecule(ringSystems, molecule, ap3d, atlp3d, atomPlacer);
            //Debug.WriteLine("******* PLACE SUBSTITUENTS ******");
            try
            {
                atlp3d.Add3DCoordinatesForSinglyBondedLigands(molecule);
            }
            catch (CDKException ex3)
            {
                Trace.TraceError($"PlaceSubstitutensERROR: Cannot place substitutents due to:{ex3.Message}");
                Debug.WriteLine(ex3);
                throw new CDKException("PlaceSubstitutensERROR: Cannot place substitutents due to:" + ex3.Message, ex3);
            }
            // restore the original atom type names
            for (int i = 0; i < originalAtomTypeNames.Length; i++)
            {
                molecule.Atoms[i].AtomTypeName = originalAtomTypeNames[i];
            }

            return(molecule);
        }
コード例 #26
0
        /// <summary>
        /// Initiates the process for the given mechanism. The atoms to apply are mapped between
        /// reactants and products.
        /// </summary>
        /// <param name="atomContainerSet"></param>
        /// <param name="atomList">
        /// The list of atoms taking part in the mechanism. Only allowed two atoms.
        ///                    The first atom is the atom which contains the ISingleElectron and the second
        ///                    third is the atom which will be removed
        ///                    the first atom</param>
        /// <param name="bondList">The list of bonds taking part in the mechanism. Only allowed one bond.
        ///                       It is the bond which is moved</param>
        /// <returns>The Reaction mechanism</returns>
        public IReaction Initiate(IChemObjectSet <IAtomContainer> atomContainerSet, IList <IAtom> atomList, IList <IBond> bondList)
        {
            var atMatcher = CDK.AtomTypeMatcher;

            if (atomContainerSet.Count != 1)
            {
                throw new CDKException("RadicalSiteIonizationMechanism only expects one IAtomContainer");
            }
            if (atomList.Count != 3)
            {
                throw new CDKException("RadicalSiteIonizationMechanism expects three atoms in the List");
            }
            if (bondList.Count != 2)
            {
                throw new CDKException("RadicalSiteIonizationMechanism only expect one bond in the List");
            }
            IAtomContainer molecule = atomContainerSet[0];
            IAtomContainer reactantCloned;

            reactantCloned = (IAtomContainer)molecule.Clone();
            IAtom atom1    = atomList[0]; // Atom containing the ISingleElectron
            IAtom atom1C   = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom1)];
            IAtom atom2    = atomList[1]; // Atom
            IAtom atom2C   = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom2)];
            IAtom atom3    = atomList[2]; // Atom to be saved
            IAtom atom3C   = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom3)];
            IBond bond1    = bondList[0]; // Bond to increase the order
            int   posBond1 = molecule.Bonds.IndexOf(bond1);
            IBond bond2    = bondList[1]; // Bond to remove
            int   posBond2 = molecule.Bonds.IndexOf(bond2);

            BondManipulator.IncreaseBondOrder(reactantCloned.Bonds[posBond1]);
            reactantCloned.Bonds.Remove(reactantCloned.Bonds[posBond2]);

            var selectron = reactantCloned.GetConnectedSingleElectrons(atom1C);

            reactantCloned.SingleElectrons.Remove(selectron.Last());
            atom1C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            IAtomType type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C);

            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            atom2C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C);
            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            reactantCloned.SingleElectrons.Add(atom2C.Builder.NewSingleElectron(atom3C));
            atom3C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            type = atMatcher.FindMatchingAtomType(reactantCloned, atom3C);
            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            IReaction reaction = atom2C.Builder.NewReaction();

            reaction.Reactants.Add(molecule);

            /* mapping */
            foreach (var atom in molecule.Atoms)
            {
                IMapping mapping = atom2C.Builder.NewMapping(atom,
                                                             reactantCloned.Atoms[molecule.Atoms.IndexOf(atom)]);
                reaction.Mappings.Add(mapping);
            }

            var moleculeSetP = ConnectivityChecker.PartitionIntoMolecules(reactantCloned);

            foreach (var moleculeP in moleculeSetP)
            {
                reaction.Products.Add(moleculeP);
            }

            return(reaction);
        }
コード例 #27
0
 public void SetConnectionManager(IConnectionManager connectionManager)
 {
     this.connectivityChecker = new ConnectivityChecker(connectionManager, this.testClientIdentity);
     this.connectedTimer.Start();
     Events.SetConnectionManager();
 }
コード例 #28
0
ファイル: SmilesParser.cs プロジェクト: carlhuth/GenXSource
        /// <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);
        }
コード例 #29
0
 public void SetTestCloudProxy(ICloudProxy testClient)
 {
     this.connectivityChecker = new ConnectivityChecker(testClient);
     this.connectedTimer.Start();
     Events.SetTestCloudProxy();
 }
コード例 #30
0
ファイル: RemovingSEofBMechanism.cs プロジェクト: qize/NCDK
        /// <summary>
        /// Initiates the process for the given mechanism. The atoms to apply are mapped between
        /// reactants and products.
        /// </summary>
        /// <param name="atomContainerSet"></param>
        /// <param name="atomList">The list of atoms taking part in the mechanism. Only allowed two atoms. The first atom receives the charge and the second the single electron</param>
        /// <param name="bondList">The list of bonds taking part in the mechanism. Only allowed one bond</param>
        /// <returns>The Reaction mechanism</returns>
        public IReaction Initiate(IChemObjectSet <IAtomContainer> atomContainerSet, IList <IAtom> atomList, IList <IBond> bondList)
        {
            var atMatcher = CDKAtomTypeMatcher.GetInstance(CDKAtomTypeMatcher.Mode.RequireExplicitHydrogens);

            if (atomContainerSet.Count != 1)
            {
                throw new CDKException("RemovingSEofBMechanism only expects one IAtomContainer");
            }
            if (atomList.Count != 2)
            {
                throw new CDKException("RemovingSEofBMechanism expects two atoms in the List");
            }
            if (bondList.Count != 1)
            {
                throw new CDKException("RemovingSEofBMechanism only expects one bond in the List");
            }
            var molecule       = atomContainerSet[0];
            var reactantCloned = (IAtomContainer)molecule.Clone();
            var atom1          = atomList[0];
            var atom1C         = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom1)];
            var atom2          = atomList[1];
            var atom2C         = reactantCloned.Atoms[molecule.Atoms.IndexOf(atom2)];
            var bond1          = bondList[0];
            var posBond1       = molecule.Bonds.IndexOf(bond1);

            if (bond1.Order == BondOrder.Single)
            {
                reactantCloned.Bonds.Remove(reactantCloned.Bonds[posBond1]);
            }
            else
            {
                BondManipulator.DecreaseBondOrder(reactantCloned.Bonds[posBond1]);
            }

            var charge = atom1C.FormalCharge.Value;

            atom1C.FormalCharge = charge + 1;
            reactantCloned.SingleElectrons.Add(atom1C.Builder.NewSingleElectron(atom2C));

            // check if resulting atom type is reasonable
            atom1C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            var type = atMatcher.FindMatchingAtomType(reactantCloned, atom1C);

            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }
            atom2C.Hybridization = Hybridization.Unset;
            AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(reactantCloned);
            type = atMatcher.FindMatchingAtomType(reactantCloned, atom2C);
            if (type == null || type.AtomTypeName.Equals("X", StringComparison.Ordinal))
            {
                return(null);
            }

            var reaction = atom1C.Builder.NewReaction();

            reaction.Reactants.Add(molecule);

            /* mapping */
            foreach (var atom in molecule.Atoms)
            {
                IMapping mapping = atom1C.Builder.NewMapping(atom,
                                                             reactantCloned.Atoms[molecule.Atoms.IndexOf(atom)]);
                reaction.Mappings.Add(mapping);
            }
            if (bond1.Order != BondOrder.Single)
            {
                reaction.Products.Add(reactantCloned);
            }
            else
            {
                var moleculeSetP = ConnectivityChecker.PartitionIntoMolecules(reactantCloned);
                foreach (var moleculeP in moleculeSetP)
                {
                    reaction.Products.Add(moleculeP);
                }
            }

            return(reaction);
        }