Esempio n. 1
0
//        public static bool isInCone(OBVector3 x, OBVector3 apex, OBVector3 axis, double aperture )
//        {
//            //got it from here:http://stackoverflow.com/questions/10768142/verify-if-point-is-inside-a-cone-in-3d-space
//            //test if point x is inside an infinite cone defined by apex point with normal vector axis and aperture angle(in radians)
//            double halfAperture=aperture/2;
//            OBVector3 apexToXVect = OBVector3(apex,x);
//            OBVector3.
//            bool insideCone = StarMath.dotProduct(apex,axis)/StarMath.norm2(apexToXVect)/StarMath.norm2(axis) > Math.Cos(aperture);
//            return insideCone;
//        }
        public static bool atomsInCarboxylateCone(OBAtom a, OBAtom carba, OBMol mol)
        {
            //angle should probably not be hardcoded
            double aperture = 120 * Math.PI / 180;

            double[] axis = obvec2dubs(OBVector3.Sub(carba.GetVector(), a.GetVector()));
            //axis = StarMath.divide (axis, StarMath.norm2 (axis));
            double[]    apex    = obvec2dubs(carba.GetVector());
            List <uint> exclude = new List <uint>();

            exclude.Add(carba.GetIdx());
            foreach (OBBond b in carba.Bonds())
            {
                OBAtom other = b.GetNbrAtom(carba);
                if (other != a)
                {
                    exclude.Add(other.GetIdx());
                }
            }
            foreach (OBAtom n in mol.Atoms())
            {
                if (!exclude.Contains(n.GetIdx()))
                {
                    double[] x = obvec2dubs(n.GetVector());
                    //if any point is found to be in the carboxylate's cone, return true
                    if (isInCone(x, apex, axis, aperture))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Esempio n. 2
0
        public static bool carboxylatesBlocked(OBMol mol, OBAtom aA, OBAtom carbA, OBAtom aB, OBAtom carbB)
        {
            bool inCone = OBFunctions.atomsInCarboxylateCone(aA, carbA, mol);

            inCone = inCone || OBFunctions.atomsInCarboxylateCone(aB, carbB, mol);
            return(inCone);
        }
        /// <summary>
        /// Determines the principle quantum number of an atom
        /// </summary>
        /// <param name="atom"></param>
        /// <returns></returns>
        public static int PrincipleQuantumNumber(this OBAtom atom)
        {
            var atomicNumber = atom.GetAtomicNum();

            if (atomicNumber <= 2)
            {
                return(1);
            }
            if (atomicNumber <= 10)
            {
                return(2);
            }
            if (atomicNumber <= 18)
            {
                return(3);
            }
            if (atomicNumber <= 36)
            {
                return(4);
            }
            if (atomicNumber <= 54)
            {
                return(5);
            }
            if (atomicNumber <= 86)
            {
                return(6);
            }
            return(7);
        }
        /// <summary>
        /// Performs hybridization mapping from OpenBabel to rdkit values
        /// </summary>
        /// <param name="atom"></param>
        /// <returns></returns>
        public static int Hybridization(this OBAtom atom)
        {
            switch (atom.GetHyb())
            {
            case 1:
                return(2);

            case 2:
                return(3);

            case 3:
                return(4);

            case 4:
                return(6);

            case 5:
                return(5);

            case 6:
                return(6);

            default:
                return(4);
            }
        }
Esempio n. 5
0
        public static bool pairwiseangle(OBMol mol, ref double pangle)
        {
            VectorVecInt mapping = new VectorVecInt();

            if (findcarboxylates(mol, ref mapping))
            {
                double        sum    = 0;
                List <double> angles = new List <double>();
                if (mapping.Count > 1)
                {
                    OBAtom c1 = mol.GetAtom(mapping[0][1]);
                    OBAtom a1 = mol.GetAtom(mapping[0][3]);
                    OBAtom c2 = mol.GetAtom(mapping[1][1]);
                    OBAtom a2 = mol.GetAtom(mapping[1][3]);

                    pangle = pairwiseangle(c1, a1, c2, a2);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
Esempio n. 6
0
        public static double radial_weight(OBMol mol, OBAtom carbon1, OBAtom a1)
        {
            OBVector3 compos = mol_com(mol);
            OBVector3 v2     = carbon1.GetVector();
            OBVector3 v3     = a1.GetVector();

            return(openbabel_csharp.Point2Line(compos, v2, v3));
        }
        public static void writeatominfotoscreen(OBAtom a)
        {
            Console.WriteLine("atomtype: " + a.GetAtomType() + " id " + a.GetIdx() + " index " + a.GetIndex() +
                              " CIdx" + a.GetCIdx() + " title" + a.GetTitle() + " hash" + a.GetHashCode());
            var    ddd    = OpenBabel.OBBuilder.GetNewBondVector(a);
            string foobar = ddd.GetX() + " " + ddd.GetY() + " " + ddd.GetZ();

            Console.WriteLine(foobar);
        }
Esempio n. 8
0
        /// <summary>
        /// A variant which returns an OBMol based on host.
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        public static OBMol designgraphtomol(designGraph host)
        {
            var mol = new OBMol();
            Dictionary <string, int> nodeatomlookup = new Dictionary <string, int>(); //dictionary for looking up which nodes go to which atoms by their names
            int i = 0;

            foreach (node n in host.nodes)
            {
                OBAtom atom = new OBAtom();
                double x    = scale * n.X;
                double y    = scale * n.Y;
                double z    = scale * n.Z; //set coordinates of atom
                atom.SetVector(x, y, z);
                n.localLabels.Sort();
                foreach (string label in n.localLabels)
                {
                    if (label.Length < 4)
                    {
                        if (label != "sp2" && label != "sp3")       ///so openbabel gets less crap
                        {
                            atom.SetAtomicNum(elementTabel[label]); //set atomic number
                            break;
                        }
                    }
                }
                i++;

                nodeatomlookup.Add(n.name, i); //add the atom to dictionary and mol
                mol.AddAtom(atom);
            }
            foreach (arc a in host.arcs)
            {
                int  bondorder = 0;
                bool hassingle = a.localLabels.Contains("s");
                bool hasdouble = a.localLabels.Contains("d");
                bool hastriple = a.localLabels.Contains("t"); //bonds will probably not be anything other than single, double, or triple
                //although we could have dative bonds
                if (hassingle ^ hasdouble ^ hastriple)        //we do not want more than one bond type
                {
                    if (hassingle)
                    {
                        bondorder = 1;
                    }
                    if (hasdouble)
                    {
                        bondorder = 2;
                    }
                    if (hastriple)
                    {
                        bondorder = 3;
                    }
                }
                mol.AddBond(nodeatomlookup[a.To.name], nodeatomlookup[a.From.name], bondorder);
            }
            return(mol);
        }
Esempio n. 9
0
        public static double atom2linedistance(OBAtom x0, OBAtom a1, OBAtom a2)
        {
            //a1 and a2 are atoms that define the axis in question, x0 is the atom that we want to know the distance from the axis

            OBVector3 v0 = x0.GetVector();
            OBVector3 v1 = a1.GetVector();
            OBVector3 v2 = a2.GetVector();

            return(openbabel_csharp.Point2Line(v0, v1, v2));
        }
Esempio n. 10
0
        public static double atomdist(OBAtom a0, OBAtom a1)
        {
            OBVector3 disp = OBVector3.Sub(a0.GetVector(), a1.GetVector());
            double    x    = disp.GetX();
            double    y    = disp.GetY();
            double    z    = disp.GetZ();
            double    dist = Math.Sqrt(x * x + y * y + z * z);

            return(dist);
        }
        /// <summary>
        /// Retrieves the RCov value for atom
        /// </summary>
        /// <param name="atom"></param>
        /// <returns></returns>
        public static double GetRBO(this OBAtom atom)
        {
            var index = atom.GetAtomicNum();

            if (index >= AtomicConstants.GetLength())
            {
                throw new IndexOutOfRangeException(string.Format("GetRBO: {0} is out of range", index));
            }
            return(AtomicConstants.GetRBO(index));
        }
Esempio n. 12
0
        public static double pairwiseangle(OBAtom carbon1, OBAtom a1, OBAtom carbon2, OBAtom a2)
        {
            //carbon1 and carbon2 are carbon atoms connected to oxygen
            //a1 and a2 connect to carbon1 and carbon2 respectively

            OBVector3 vec1  = OBVector3.Sub(carbon1.GetVector(), a1.GetVector());
            OBVector3 vec2  = OBVector3.Sub(carbon2.GetVector(), a2.GetVector());
            double    angle = angle_between_vectors(vec1, vec2);

            return(angle);
        }
        public static OBMol molecule_merge(OBMol mol1, OBAtom a, OBMol mol2, OBAtom b)
        {
            //takes two molecules and two atoms in each molecule and
            //assuming atoms are in the same place, delete one atom and copy bond to the other
            //a
            //foreach(OBBond bond in b.Bonds())
            //{

            //}

            int keepid     = Convert.ToInt32(a.GetIdx());
            int todeleteid = Convert.ToInt32(b.GetIdx());
            //var bonds = b.Bonds();
            List <OBBond> bondlist = new List <OBBond>();

            foreach (OBBond bon in b.Bonds())
            {
                bondlist.Add(bon);
            }
            OBBond bond      = bondlist[0];
            int    connectid = (int)bond.GetNbrAtomIdx(b);
            int    prevatms  = (int)mol1.NumAtoms(); //number of atoms before we combine things

            //OBMol mol3 = new OBMol ();

            mol1 = addmol(mol2, mol1);
            mol1.BeginModify();
            OBAtom keep      = mol1.GetAtom(keepid);
            OBAtom todelete  = mol1.GetAtom(todeleteid + prevatms);
            OBAtom toconnect = mol1.GetAtom(connectid + prevatms);
            OBBond newbond   = new OBBond();

            newbond.SetBegin(keep);
            newbond.SetEnd(toconnect);
            newbond.SetBO(1);
            mol1.AddBond(newbond);
            mol1.DeleteAtom(todelete);
            //OBAtom= atom1
            //var a = map2[0];
            //int c1 = (int)(map1[1]);
            //int c2 = (int)(map2[1] + prevatms);
            //int h1 = (int)(map1[0]);
            ///int h2 = (int)(map2[0] + prevatms);
            //OBAtom carbon1 = mol1.GetAtom(c1);
            //OBAtom carbon2 = mol1.GetAtom(c2);
            //OBAtom hydrogen1 = mol1.GetAtom(h1);
            ///OBAtom hydrogen2 = mol1.GetAtom(h2);
            //OBBuilder.Connect(mol1, c1, c2);//connect fragments
            //mol1.DeleteAtom(hydrogen1);
            //mol1.DeleteAtom(hydrogen2);
            mol1.EndModify();
            return(mol1);
        }
 public static bool updatexyz(OBMol mol, double[,] xyz)
 {
     //OBMol newmol = new OBMol(mol);
     for (int i = 0; i < mol.NumAtoms(); i++)
     {
         OBAtom a = mol.GetAtom(i + 1);
         a.SetVector(xyz[i, 0], xyz[i, 1], xyz[i, 2]);
         //OBVector3 vec = OpenBabelFunctions.OBFunctions.dubs2obvec(xyz[i]);
         //a.SetVector(vec);
     }
     return(true);
 }
        public static designGraph updatepositions(designGraph graph, OBMol mol)
        {
            int count = graph.nodes.Count;

            for (int i = 0; i <= count - 1; i++)
            {
                OBAtom a = mol.GetAtom(i + 1);
                //a.GetVector
                node n = graph.nodes[i];
                n.X = a.GetX() / scale;
                n.Y = a.GetY() / scale;
                n.Z = a.GetZ() / scale;
            }
            return(graph);
        }
Esempio n. 16
0
        public static double greatest_radial_distance(OBMol mol, OBAtom carbon1, OBAtom a1)
        {
            OBVector3 v2   = carbon1.GetVector();
            OBVector3 v3   = a1.GetVector();
            double    maxd = 0;

            foreach (OBAtom a in mol.Atoms())
            {
                OBVector3 v1 = a.GetVector();
                double    d  = openbabel_csharp.Point2Line(v1, v2, v3);
                if (d > maxd)
                {
                    maxd = d;
                }
            }
            return(maxd);
        }
Esempio n. 17
0
        public static bool averagepairwiseangle(OBMol mol, ref double avgangle)
        {
            VectorVecInt mapping = new VectorVecInt();

            if (findcarboxylates(mol, ref mapping))
            {
                double        sum    = 0;
                List <double> angles = new List <double>();
                if (mapping.Count > 1)
                {
                    OBAtom c1 = mol.GetAtom(mapping[0][1]);
                    OBAtom a1 = mol.GetAtom(mapping[0][3]);
                    OBAtom c2 = mol.GetAtom(mapping[1][1]);
                    OBAtom a2 = mol.GetAtom(mapping[1][3]);

                    double pangle = pairwiseangle(c1, a1, c2, a2);
                    angles.Add(pangle);
                    sum += pangle;
                    OBForceField MMFF94 = OBForceField.FindForceField("MMFF94");
                    MMFF94.Setup(mol);

                    for (int i = 0; i < 300; i++)
                    {
                        MMFF94.MolecularDynamicsTakeNSteps(1, 300, 1.2, 1);
                        MMFF94.GetCoordinates(mol);
                        pangle = pairwiseangle(c1, a1, c2,
                                               a2); //this function is sufficiently fast that it does not need to be optimized, molecular dynamics takes about 15 milliseconds per step, this take practically nothing
                        angles.Add(pangle);
                        sum += pangle;
                    }
                    avgangle = sum / angles.Count;
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
 public static OBMol connect_within_radius(OBMol mol, OBAtom n, double radius)
 {
     foreach (OBAtom a in mol.Atoms())
     {
         if (a.GetIdx() == n.GetIdx())
         {
             continue;
         }
         else
         {
             double len = Math.Round(StarMath.norm2(obvec2dubs(OBVector3.Sub(a.GetVector(), n.GetVector()))),
                                     7); //gets length
             if (len <= radius)
             {
                 mol.AddBond((int)a.GetIdx(), (int)n.GetIdx(), 1);
             }
         }
     }
     return(mol);
 }
Esempio n. 19
0
 public static void DepthLimitedSearch(OBAtom atom, int depth, List <OBAtom> path, ref List <IEnumerable <OBAtom> > foundPaths)
 {
     path.Add(atom);
     if (depth >= 0)
     {
         if (depth == 0)
         {
             foundPaths.Add(path);
         }
         else
         {
             var neighbors = atom.Neighbors().Where(n => !path.Select(v => v.GetIdx()).Contains(n.GetIdx()));
             foreach (var neighbor in neighbors)
             {
                 var pathArray = new OBAtom[path.Count()];
                 path.CopyTo(pathArray);
                 Search.DepthLimitedSearch(neighbor, depth - 1, pathArray.ToList(), ref foundPaths);
             }
         }
     }
 }
        /// <summary>
        /// Retrieves first relevant atom type based on SMARTS pattern that matches atom
        /// </summary>
        /// <param name="atom"></param>
        /// <returns>Crippen Atom Type key if atom matches a pattern, otherwise empty string.</returns>
        public static string GetCrippenKey(this OBAtom atom)
        {
            var element = atom.GetCrippenAtomType();

            if (string.IsNullOrEmpty(element))
            {
                throw new Exception(string.Format("Crippen atom type could not be determined for {0}", atom.GetAtomicNum()));
            }
            var keys = CrippenConstants.CrippenContributions.Where(g => g.Key.Contains(element)).Select(g => g.Key);

            foreach (var key in keys)
            {
                foreach (var pattern in CrippenConstants.GetSmarts(key))
                {
                    if (atom.MatchesSMARTS(pattern))
                    {
                        return(key);
                    }
                }
            }
            return(string.Empty);
        }
Esempio n. 21
0
        public static double greatest_axial_distance(OBMol mol, OBAtom carbon1, OBAtom a1)
        {
            //finds the distance of the most distant atom along the axis defined by the carboxyl defined by carbon 1 and a1
            double[] vec = obvec2dubs(OBVector3.Sub(carbon1.GetVector(), a1.GetVector()));
            vec = StarMath.normalize(vec);
            double maxd = 0;

            foreach (OBAtom a in mol.Atoms())
            {
                if (a == carbon1)
                {
                    continue;
                }
                double d = StarMath.dotProduct(vec,
                                               obvec2dubs(OBVector3.Sub(carbon1.GetVector(),
                                                                        a.GetVector()))); // get pairwise axial distance by taking the scalar projection of the carbon's position to atom A
                if (d > maxd)
                {
                    maxd = d;
                }
            }
            return(maxd);
        }
        public static OBMol molecule_merge(OBMol mol1, OBAtom tokeep, OBAtom todelete)
        {
            //takes a molecule and two atoms in the molecule and
            //assuming atoms are in the same place, delete one atom and copy bond to the other

            mol1.BeginModify();
            uint todeleteid = todelete.GetIdx();
            //var bonds = b.Bonds();


            List <OBBond> bondlist = new List <OBBond>();

            foreach (OBBond bon in todelete.Bonds())
            {
                bondlist.Add(bon);
            }

            foreach (OBBond bon in bondlist)
            {
                mol1.AddBond((int)tokeep.GetIdx(), (int)bon.GetNbrAtomIdx(todelete), (int)bon.GetBondOrder());
            }
            //writeatominfotoscreen(mol1);
            //int connectid = (int)bond.GetNbrAtomIdx(b);


            //todelete = mol1.GetAtomById(todeleteid);
            ///OBAtom toconnect = mol1.GetAtom(connectid);
            //OBBond newbond = new OBBond();
            //newbond.SetBegin(keep);
            //newbond.SetEnd(toconnect);
            //newbond.SetBO(1);
            //mol1.AddBond(newbond);
            mol1.DeleteAtom(todelete);

            mol1.EndModify();
            return(mol1);
        }
Esempio n. 23
0
        public static void trajectoryFrameToCIF(string frame, string outFile, List <int> esequence,
                                                OBConversion obconv)
        {
            //converts a frame from the above function into a CIF file
            //lammps trajectory files have unit cell dimension data for every frame
            //requires an element sequence for identifying element type from lammps atom types
            OBUnitCell  uc  = new OBUnitCell();
            OBMol       mol = new OBMol();
            OBMatrix3x3 mat = new OBMatrix3x3();

            using (StringReader reader = new StringReader(frame)) {
                string line        = "";
                bool   foundMatrix = false;

                do
                {
                    line = reader.ReadLine();
                    if (line.Contains("BOX BOUNDS"))
                    {
                        //data from lammps is in this format
                        //ITEM: BOX BOUNDS xy xz yz
                        //xlo_bound xhi_bound xy
                        //ylo_bound yhi_bound xz
                        //zlo_bound zhi_bound yz
                        string row0 = reader.ReadLine();

                        double[] row0d = OBFunctions.spacedStringToDoubleArray(row0);
                        double   xlo   = row0d[0];

                        double xhi = row0d[1];
                        double xy  = row0d[2];

                        string   row1  = reader.ReadLine();
                        double[] row1d = OBFunctions.spacedStringToDoubleArray(row1);
                        double   ylo   = row1d[0];
                        double   yhi   = row1d[1];
                        double   xz    = row1d[2];


                        string   row2  = reader.ReadLine();
                        double[] row2d = OBFunctions.spacedStringToDoubleArray(row2);
                        double   zlo   = row2d[0];
                        double   zhi   = row2d[1];
                        double   yz    = row2d[2];


                        //adjust box bounds, taken from VMD's source for reading lammps files

                        double xdelta = Math.Min(0, xy);
                        xdelta = Math.Min(xdelta, xz);
                        xdelta = Math.Min(xdelta, xy + xz);
                        xlo    = xlo - xdelta;
                        xdelta = Math.Max(0, xy);
                        xdelta = Math.Max(xdelta, xz);
                        xdelta = Math.Max(xdelta, xy + xz);
                        xhi    = xhi - xdelta;
                        ylo    = ylo - Math.Min(0, yz);
                        yhi    = yhi - Math.Max(0, yz);
                        OBVector3 A = new OBVector3(xhi - xlo, 0, 0);
                        OBVector3 B = new OBVector3(xy, yhi - ylo, 0);
                        OBVector3 C = new OBVector3(xz, yz, zhi - zlo);
                        //OBVector3 A = new OBVector3 (xhi-xlo, xy, xz);
                        //OBVector3 B = new OBVector3 (0, yhi-ylo, yz);
                        //OBVector3 C= new OBVector3 (0, 0, zhi-zlo);
                        mat = new OBMatrix3x3(A, B, C);
                        uc.SetData(A, B, C);

                        foundMatrix = true;
                    }
                } while (!foundMatrix);
                //uc.SetData (mat);
                bool foundAtoms = false;
                do
                {
                    line = reader.ReadLine();
                    if (line.Contains("ITEM: ATOMS"))
                    {
                        foundAtoms = true;
                    }
                } while (!foundAtoms);

                while ((line = reader.ReadLine()) != null)
                {
                    string[] splitline  = line.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
                    int      lammpstype = Convert.ToInt32(splitline[1]) - 1;
                    int      atype      = esequence[lammpstype];
                    OBAtom   a          = new OBAtom();
                    a.SetAtomicNum(atype);
                    //position in fraction coordinates
                    OBVector3 fvec = new OBVector3(Convert.ToDouble(splitline[3]), Convert.ToDouble(splitline[4]),
                                                   Convert.ToDouble(splitline[5]));
                    //OBVector3 fvec = new OBVector3 (Convert.ToDouble (splitline [2]), Convert.ToDouble (splitline [3]), Convert.ToDouble (splitline [4]));
                    //convert to cartesian.
                    OBVector3 cvec = uc.FractionalToCartesian(fvec);
                    a.SetVector(cvec);
                    mol.AddAtom(a);
                }

                mol.CloneData(uc);
                obconv.SetOutFormat("cif");
                obconv.AddOption("b");
                obconv.WriteFile(mol, outFile);
            }
        }
 /// <summary>
 /// Calculates the valence number as defined by the number of outer shell electrons minus the total number of hydrogens
 /// (implicit and explicit)
 /// </summary>
 /// <param name="atom"></param>
 /// <returns></returns>
 public static int ValenceNumber(this OBAtom atom)
 {
     return(atom.NOuterShellElectrons() - (int)atom.TotalNumHydrogens());
 }
 public static bool IsHeavyAtom(this OBAtom atom)
 {
     return(!atom.IsHydrogen());
 }
        /// <summary>
        /// Determines the possible Crippen atom type for the OBAtom object
        /// </summary>
        /// <param name="atom"></param>
        /// <returns>Crippen atom type as string if found, otherwise empty string</returns>
        private static string GetCrippenAtomType(this OBAtom atom)
        {
            var partialCharge = Convert.ToInt32(atom.GetPartialCharge());
            var atomicNumber  = atom.GetAtomicNum();

            if (partialCharge != 0)
            {
                if (atomicNumber == 9 ||
                    atomicNumber == 17 ||
                    atomicNumber == 35 ||
                    atomicNumber == 53 ||
                    atomicNumber == 3 ||
                    atomicNumber == 11 ||
                    atomicNumber == 19 ||
                    atomicNumber == 37 ||
                    atomicNumber == 55)
                {
                    return("Ha");
                }
            }
            else
            {
                if (atomicNumber == 6)
                {
                    return("C");
                }
                if (atomicNumber == 1)
                {
                    return("H");
                }
                if (atomicNumber == 7)
                {
                    return("N");
                }
                if (atomicNumber == 8)
                {
                    return("O");
                }
                if (atomicNumber == 15)
                {
                    return("P");
                }
                if (atomicNumber == 16)
                {
                    return("S");
                }
                if (atomicNumber == 9)
                {
                    return("F");
                }
                if (atomicNumber == 17)
                {
                    return("Cl");
                }
                if (atomicNumber == 35)
                {
                    return("Br");
                }
                if (atomicNumber == 53)
                {
                    return("I");
                }
                if ((atomicNumber >= 21 && atomicNumber <= 30) ||
                    (atomicNumber >= 39 && atomicNumber <= 48) ||
                    (atomicNumber >= 72 && atomicNumber <= 80) ||
                    atomicNumber == 3 ||
                    atomicNumber == 4 ||
                    atomicNumber == 5 ||
                    atomicNumber == 11 ||
                    atomicNumber == 12 ||
                    atomicNumber == 13 ||
                    atomicNumber == 14 ||
                    atomicNumber == 19 ||
                    atomicNumber == 20 ||
                    atomicNumber == 31 ||
                    atomicNumber == 32 ||
                    atomicNumber == 33 ||
                    atomicNumber == 34 ||
                    atomicNumber == 37 ||
                    atomicNumber == 38 ||
                    atomicNumber == 49 ||
                    atomicNumber == 50 ||
                    atomicNumber == 51 ||
                    atomicNumber == 52 ||
                    atomicNumber == 55 ||
                    atomicNumber == 56 ||
                    atomicNumber == 81 ||
                    atomicNumber == 82 ||
                    atomicNumber == 83 ||
                    atomicNumber == 84)
                {
                    return("Me");
                }
            }
            return(string.Empty);
        }
        public static OBMol addmol(OBMol source, OBMol dest)
        {
            //combines two OBMols into one molecule
            // this is designed to do the same thing as the += operator in mol.cpp, in other words this implements functionality present in openbabel, but not in the C# api
            dest.BeginModify();
            uint prevatms = dest.NumAtoms();
            uint nextatms = source.NumAtoms();

            // First, handle atoms and bonds
            foreach (OBAtom atom in source.Atoms())
            {
                atom.SetId(0); ////Need to remove ID which relates to source mol rather than this mol// But in the C++ it had a NoId thing I couldn't figure out
                dest.AddAtom(atom);
                //var foooo = dest.Atoms ();
            }
            //writeatominfotoscreen (dest);
            foreach (OBBond bond in source.Bonds())
            {
                bond.SetId(0);

                dest.AddBond((int)(bond.GetBeginAtomIdx() + prevatms), (int)(bond.GetEndAtomIdx() + prevatms),
                             (int)bond.GetBO(), (int)bond.GetFlags());
            }

            //don't really understand what they mean by residues
            //I think it's an amino acid or nucleotide so you can build up proteins and stuff?
            //don't think I'm going to use them either, but it might be useful

            foreach (OBResidue residue in source.Residues())
            {
                OBResidue newres = new OBResidue();
                dest.AddResidue(newres);

                OBResidueAtomIter ai = new OBResidueAtomIter(residue);
                //dammit why didn't they implement a residue.atoms sort of thing? I don't want to play with enumerators
                ////#define FOR_ATOMS_OF_RESIDUE(a,r) for( OBResidueAtomIter a(r); a; ++a )
                while (ai.MoveNext())
                {
                    OBAtom resatom = new OBAtom();
                    resatom = ai.Current;
                    // This is the equivalent atom in our combined molecule
                    OBAtom atom = dest.GetAtom((int)(resatom.GetIdx() + prevatms));
                    // So we add this to the last-added residue
                    // (i.e., what we just copied)
                    //[dest.NumResidues () - 1]

                    var res = dest.Residues().GetEnumerator();
                    while (!res.MoveNext())
                    {
                    }                           //move to the last residue
                    res.Current.AddAtom(atom);

                    //var item = dest.Cast<RMSRequestProcessor.RMSMedia> ().ElementAt (1);
                }


                //for(OBAtom resatom in )
            }
            dest.EndModify();

            return(dest);
        }
        public static bool designgraphtomol(designGraph host, ref OBMol mol)
        {
            OBElementTable periodictable = new OBElementTable();

            //OBMol mol = new OBMol();
            Dictionary <string, int>
            nodeatomlookup =
                new Dictionary <string, int>();    //dictionary for looking up which nodes go to which atoms by their names
            int i = 0;

            foreach (node n in host.nodes)
            {
                OBAtom atom = new OBAtom();

                double x = scale * n.X;
                double y = scale * n.Y;
                double z = scale * n.Z; //set coordinates of atom
                atom.SetVector(x, y, z);
                int anum = 0;
                n.localLabels.Sort();
                foreach (string label in n.localLabels)
                {
                    if (label.Length < 4)
                    {
                        if (label != "sp2" && label != "sp3") ///so openbabel gets less crap
                        {
                            anum = periodictable.GetAtomicNum(label);
                            if (anum > 0)
                            {
                                break;
                            }
                        }
                    }
                }
                i++;
                atom.SetAtomicNum(anum);       //set atomic number
                nodeatomlookup.Add(n.name, i); //add the atom to dictionary and mol
                mol.AddAtom(atom);
            }
            foreach (arc a in host.arcs)
            {
                OBBond bond      = new OBBond();
                int    bondorder = 0;
                bool   hassingle = a.localLabels.Contains("s");
                bool   hasdouble = a.localLabels.Contains("d");
                bool   hastriple =
                    a.localLabels
                    .Contains("t");                    //bonds will probably not be anything other than single, double, or triple
                //although we could have dative bonds
                if (hassingle ^ hasdouble ^ hastriple) //we do not want more than one bond type
                {
                    if (hassingle)
                    {
                        bondorder = 1;
                    }
                    if (hasdouble)
                    {
                        bondorder = 2;
                    }
                    if (hastriple)
                    {
                        bondorder = 3;
                    }
                }
                mol.AddBond(nodeatomlookup[a.To.name], nodeatomlookup[a.From.name], bondorder);
//                OBAtom begin = nodeatomlookup[a.From.name];
//                OBAtom end = nodeatomlookup[a.To.name];
//                bond.SetBegin(begin);
//                bond.SetEnd(end);
//                bond.SetBondOrder(bondorder);
//                mol.AddBond(bond);
//                mol.Bonds();
            }

            //mol.FindRingAtomsAndBonds();

            return(true);
        }
Esempio n. 29
0
    public void parsePDB()
    {
        // for determining hydrogen bonds
        List <Vector3> hBondAcceptors = new List <Vector3> ();
        List <Vector3> hBondDonors    = new List <Vector3> ();


parseMol:                                                       // iteration start if multiple input files are used

        BezierSpline[] ribbonSplineList = new BezierSpline[30]; //for drawing protein lines (30 is max number of chains)


        int numAtoms = (int)mol.NumAtoms() + 1;


        atoms = new GameObject[numAtoms];


        int maxHelix = 500;

        radius = new float[maxHelix, numAtoms];

        int ribbonChainIndex = 0;


        OBElementTable table = new OBElementTable();

        int currentChain = -1;


        OBAtom[] alphaCarbons     = new OBAtom[numAtoms / 4];
        int      alphaCarbonCount = 0;

        List <Vector3> atomPositions = new List <Vector3> ();
        List <string>  atomElements  = new List <string> ();


        for (int i = 1; i < numAtoms; i++)
        {
            OBAtom    atom = mol.GetAtom(i);
            string    tag;
            OBResidue res      = atom.GetResidue();
            Vector3   position = new Vector3((float)atom.GetX(), (float)atom.GetY(), (float)atom.GetZ());
            string    elem     = table.GetSymbol((int)atom.GetAtomicNum()).ToUpper();


            //checks for pharmacophore labels
            if (res.GetName() == "ACC" || res.GetName() == "FOB" || res.GetName() == "POS" || res.GetName() == "NEG" || res.GetName() == "RNG" || res.GetName() == "DON")
            {
                if (atom.IsHydrogen())                //added hydrogens gets the same resName and has to be ignored
                {
                    continue;
                }
                renderPharmacophore = true;
            }
            else
            {
                renderPharmacophore = false;
            }

            // pharmacophores
            if (res.GetName() == "EXC")
            {
                if (atom.IsHydrogen())                //added hydrogens gets the same resName and has to be ignored
                {
                    continue;
                }
                renderEXC           = true;
                renderPharmacophore = true;
            }
            else
            {
                renderEXC = false;
            }

            //creates the atom object
            atoms[i] = createAtomType(elem, position);

            int n;
            if (int.TryParse(res.GetName(), out n))
            {
                if (CollectionOfLigands == null)
                {
                    CollectionOfLigands = new List <List <GameObject> >();
                    CollectionOfLigands.Add(new List <GameObject>());
                }
                while (n + 1 > CollectionOfLigands.Count)
                {
                    CollectionOfLigands.Add(new List <GameObject>());
                }
                CollectionOfLigands[n].Add(atoms[i]);
            }

            if (res.GetResidueProperty(9))             //water
            {
                tag = "water";
            }
            else if (res.GetAtomProperty(atom, 4) || (atom.IsHydrogen() && !res.GetResidueProperty(5))) //ligand
            {
                if (res.GetResidueProperty(5))                                                          //ion (should be 3 but a bug in openbabel labels ions as protein, thats why the check has to be done inside the ligand check)
                {
                    tag = "ion";
                }
                else
                {
                    TextMesh lText = atoms [i].transform.Find("Text").GetComponent <TextMesh> ();
                    lText.color = textColor;
                    if (renderPharmacophore)
                    {
                        tag            = "hetatms";              //make sure pharmacophores always show
                        lText.text     = res.GetName() + ":" + res.GetIdx();
                        lText.fontSize = labelFontSize;
                    }
                    else
                    {
                        tag = "hetatmbs";
                        if (ligandText)
                        {
                            lText.text     = elem + ":" + i.ToString();
                            lText.fontSize = labelFontSize;
                        }
                    }


                    if (sphere)
                    {
                        atoms [i].transform.localScale *= 4;
                    }

                    if (atom.IsHbondAcceptor())
                    {
                        foreach (Vector3 candidatePos in hBondDonors)
                        {
                            checkHBond(candidatePos, position);
                        }
                    }

                    if (atom.IsHbondDonor())
                    {
                        foreach (Vector3 candidatePos in hBondAcceptors)
                        {
                            checkHBond(candidatePos, position);
                        }
                    }
                }
            }
            else               //protein
            {
                tag = "balls";

                atomPositions.Add(position);

                atomElements.Add(elem);

                if (atom.IsHbondAcceptor())
                {
                    hBondAcceptors.Add(position);
                }
                else
                {
                    hBondDonors.Add(position);
                }

                if (res.GetAtomProperty(atom, 0))                //alpha carbon
                {
                    alphaCarbons[alphaCarbonCount] = atom;
                    if (alphaCarbonCount > 6)                   //check if the ribbon is alpha helix using torsion angles
                    {
                        double torsion     = mol.GetTorsion(atom, alphaCarbons[alphaCarbonCount - 1], alphaCarbons[alphaCarbonCount - 2], alphaCarbons[alphaCarbonCount - 3]);
                        double prevTorsion = mol.GetTorsion(alphaCarbons[alphaCarbonCount - 4], alphaCarbons[alphaCarbonCount - 5], alphaCarbons[alphaCarbonCount - 6], alphaCarbons[alphaCarbonCount - 7]);
                        double torsionSum  = torsion + prevTorsion;
                        if (torsionSum > 99 && torsionSum < 111)
                        {
                            for (int j = ribbonChainIndex - 7; j <= ribbonChainIndex; j++)
                            {
                                radius [currentChain, j] = 1.5f;                                        //alpha helix
                            }
                        }
                        else
                        {
                            radius [currentChain, ribbonChainIndex] = 0.5f;
                        }
                    }
                    alphaCarbonCount++;


                    if (proteinText)                       //only displays text on alpha carbons
                    {
                        TextMesh pText = atoms [i].transform.Find("Text").GetComponent <TextMesh> ();
                        pText.color    = textColor;
                        pText.text     = res.GetName() + " -" + res.GetNumString();
                        pText.fontSize = labelFontSize;
                    }

                    int tempChain = (int)res.GetChainNum();
                    if (tempChain != currentChain)
                    {
                        currentChain     = tempChain;
                        ribbonChainIndex = 0;
                    }


                    //add points for ribbon rendering
                    addBezierPoint(ribbonSplineList, currentChain, ribbonChainIndex, position);



                    ribbonChainIndex++;
                }
            }

            atoms[i].transform.tag = tag;
            centerPos += position;
            centerCount++;
        }

        //createSurface (atomPositions,atomElements);
        Debug.Log(hBondAcceptors.Count + " " + hBondDonors.Count);
        //evaluate bonds
        for (int i = 0; i < mol.NumBonds(); i++)
        {
            OBBond    bond   = mol.GetBond(i);
            OBAtom    atom   = mol.GetAtom((int)bond.GetBeginAtomIdx());
            OBResidue res    = atom.GetResidue();
            bool      ligand = res.GetAtomProperty(atom, 4) || (atom.IsHydrogen() && !res.GetResidueProperty(5));
            if (ligand && sphere)            //no ligand bonds if display mode is CPK sphere
            {
                continue;
            }
            try {
                connect(atoms[bond.GetBeginAtomIdx()], atoms[bond.GetEndAtomIdx()], bond);
            } catch (System.Exception e) {
                Debug.Log(e);
            }
        }

        //handle pharmacophore vectors
        if (mol.HasData("VECTOR"))
        {
            string[] vectors = mol.GetData("VECTOR").GetValue().Split(new string[] { "\n" }, StringSplitOptions.None);
            foreach (string vector in vectors)
            {
                string[] idx = vector.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
                try {
                    Vector3 pos = new Vector3(float.Parse(idx[1]), float.Parse(idx[2]), float.Parse(idx[3]));
                    int     id  = int.Parse(idx[0]);
                    drawVector(atoms[id], pos, mol.GetAtom(id).GetResidue().GetName());
                } catch (System.Exception e) {
                    Debug.Log(e);
                }
            }
        }


        //render protein ribbons
        drawRibbons(ribbonSplineList, "ribbons");          //must be before alpha due to indexing
        drawRibbons(ribbonSplineList, "alpha");

        // check for separate ligand file
        if (file.Contains("protein"))
        {
            file = file.Replace("protein", "ligand");
            string file1 = file.Replace("." + extension, ".sdf");          // .+extension incase the format would also appear in the file name
            string file2 = file.Replace("." + extension, ".mol2");
            if (File.Exists(file1))
            {
                readMol(file);
                goto parseMol;
            }
            else if (File.Exists(file2))
            {
                readMol(file);
                goto parseMol;
            }
        }

        center = createObject(new GameObject(), centerPos / centerCount);           //the center of the pdb
        show();
    }
Esempio n. 30
0
 public static uint GetHeteroValence(this OBAtom atom)
 {
     return(atom.GetHeteroDegree());
 }