示例#1
0
            public static void Align(IList <Vector> C1
                                     , IList <Anisou> anisou1
                                     , ref IList <Vector> C2
                                     , ref IList <Anisou> anisou2
                                     , HPack <Trans3> outTrans  = null
                                     , HPack <double> optEnergy = null
                                     )
            {
                Trans3 trans = GetTrans(C1, anisou1, C2, anisou2, optEnergy: optEnergy);

                C2      = new List <Vector>(C2);
                anisou2 = new List <Anisou>(anisou2);

                Vector[] nC2 = trans.GetTransformed(C2).ToArray();
                for (int i = 0; i < C2.Count; i++)
                {
                    Vector p2i  = C2[i];
                    Anisou a2i  = anisou2[i];
                    Vector np2i = trans.DoTransform(p2i);
                    Anisou na2i = a2i.Clone();
                    na2i.eigvecs[0] = (trans.DoTransform(p2i + a2i.eigvecs[0]) - np2i).UnitVector();
                    na2i.eigvecs[1] = (trans.DoTransform(p2i + a2i.eigvecs[1]) - np2i).UnitVector();
                    na2i.eigvecs[2] = (trans.DoTransform(p2i + a2i.eigvecs[2]) - np2i).UnitVector();
                    C2[i]           = np2i;
                    anisou2[i]      = na2i;
                }
                if (outTrans != null)
                {
                    outTrans.value = trans;
                }
            }
示例#2
0
            public static void GetEnergies(AlignData data1, IList <Vector> coords2
                                           , out double pot_rmsd, out double pot_enrg, out double pot_enrg_full, out double pot_enrg_anisou
                                           , Pdb pdb2           = null
                                           , string pdb2outpath = null
                                           )
            {
                Anisou[] anisous1;// = data1.GetAnisous();
                double[] bfactor1;
                {
                    List <Mode> modes = new List <Mode>(data1.GetModes());
                    for (int i = 0; i < 6; i++)
                    {
                        modes.RemoveAt(0);
                    }
                    bfactor1 = HBioinfo.GetBFactor(modes.ToArray(), data1.masses);
                    HDebug.Assert(data1.size == bfactor1.Length);
                    anisous1 = Anisou.FromBFactor(bfactor1, scale: 10000 * 1000);
                }
                //Trans3 trans = MinAnisou.GetTrans(data1.coords, anisous1, coords2);
                Trans3        trans        = GetTrans(data1.coords, bfactor1, coords2);
                List <Vector> coords2trans = new List <Vector>(trans.GetTransformed(coords2));

                if (pdb2 != null && pdb2outpath != null)
                {
                    data1.pdb.ToFile(pdb2outpath, coords2trans, anisous: anisous1.GetUs());
                }

                pot_rmsd        = data1.GetRmsdFrom(coords2trans);
                pot_enrg        = data1.GetEnergyFromDiag(coords2trans);
                pot_enrg_full   = data1.GetEnergyFromFull(coords2trans);
                pot_enrg_anisou = data1.GetEnergyFromAnisou(coords2trans);
            }
示例#3
0
        public static Anisou[] FromCoords(List <Vector[]> ensemble, Vector[] meanconf = null, double eigvalthres = double.NegativeInfinity)
        {
            int size = ensemble[0].Length;

            Anisou[] anisous = new Anisou[size];

            HDebug.AssertNotNull(ensemble);
            System.Threading.Tasks.Parallel.For(0, size, delegate(int ai)
                                                //for(int ai=0; ai<size; ai++)
            {
                Vector mean     = meanconf[ai];
                MatrixByArr cov = new double[3, 3];
                {
                    for (int ei = 0; ei < ensemble.Count; ei++)
                    {
                        Vector vec = ensemble[ei][ai] - mean;
                        cov       += LinAlg.VVt(vec, vec);
                    }
                }
                anisous[ai] = Anisou.FromMatrix(cov, eigvalthres: eigvalthres);
            }
                                                );

            return(anisous);
        }
示例#4
0
        public Anisou Clone()
        {
            Anisou anis = new Anisou();

            anis.U       = this.U;
            anis.eigvecs = this.eigvecs;
            anis.eigvals = this.eigvals;
            return(anis);
        }
示例#5
0
 public static Anisou[] FromMatrix(IList <MatrixByArr> Us)
 {
     Anisou[] anisous = new Anisou[Us.Count];
     for (int i = 0; i < anisous.Length; i++)
     {
         anisous[i] = FromMatrix(Us[i]);
     }
     return(anisous);
 }
示例#6
0
        public static Anisou FromValues(MatrixByArr U, Vector[] eigvecs, double[] eigvals)
        {
            Anisou anisou = new Anisou();

            anisou.U       = U.CloneT();
            anisou.eigvecs = eigvecs.HClone <Vector>(); HDebug.Assert(eigvecs.Length == 3, eigvecs[0].Size == 3, eigvecs[1].Size == 3, eigvecs[2].Size == 3);
            anisou.eigvals = eigvals.HClone <double>(); HDebug.Assert(eigvals.Length == 3);
            return(anisou);
        }
示例#7
0
        public static List <Anisou> ListBioAnisou(this IList <Pdb.Anisou> anisous)
        {
            int size = anisous.Count;

            Anisou[] bioanisou = new Anisou[size];
            for (int i = 0; i < size; i++)
            {
                bioanisou[i] = Anisou.FromMatrix(anisous[i].U);
            }
            return(new List <Anisou>(bioanisou));
        }
示例#8
0
            public Anisou[] GetAnisous()
            {
                if (_anisous != null)
                {
                    return(_anisous);
                }
                MatrixByArr hess = MatrixByArr.FromMatrixArray(this.hess);

                _anisous = Anisou.FromHessian(hess, masses, scale: 10000000, cachepath: cachebase + "Anisous.data");
                //_anisous = Bioinfo.GetAnisou(GetModes(), masses, scale: 10000000);
                return(_anisous);
            }
示例#9
0
 public static Anisou[] FromBFactor(double[] bfactor, double scale = 10000 *1000)
 {
     Anisou[] anisou = new Anisou[bfactor.Length];
     for (int i = 0; i < anisou.Length; i++)
     {
         double      rad2 = bfactor[i];
         MatrixByArr U    = new double[3, 3] {
             { rad2, 0, 0 }, { 0, rad2, 0 }, { 0, 0, rad2 }
         };
         anisou[i] = Anisou.FromMatrix(U * scale);
     }
     return(anisou);
 }
示例#10
0
        public static List <Tuple <Anisou, int> > UpdateAnisous(Element[] elements)
        {
            int[] collection = Collect(elements, Anisou.RecordName);
            List <Tuple <Anisou, int> > anisous = new List <Tuple <Anisou, int> >();

            foreach (int idx in collection)
            {
                string line   = elements[idx].line;
                Anisou anisou = Anisou.FromString(line);
                elements[idx] = anisou;
                anisous.Add(new Tuple <Anisou, int>(anisou, idx));
            }
            return(anisous);
        }
示例#11
0
            public static void DetermineThrmlFluc(List <Vector>[] ensemble, Vector[] meanconf, Anisou[] anisous, double[] bfactors, double eigvalthres)
            {
                #region old code
                //int size = ensemble[0].Count;
                //
                //Debug.AssertNotNull(ensemble);
                //Parallel.For(0, size, delegate(int ai)
                ////for(int i=0; i<size; i++)
                //{
                //    Vector mean = meanconf[ai];
                //    Matrix cov = new double[3, 3];
                //    {
                //        for(int ei=0; ei<ensemble.Length; ei++)
                //        {
                //            Vector vec = ensemble[ei][ai] - mean;
                //            cov += Matrix.VVt(vec, vec);
                //        }
                //    }
                //    anisous[ai] = Anisou.FromMatrix(cov);
                //    if(anisous[ai].eigvals[0] < eigvalthres) anisous[ai].eigvals[0] = 0;
                //    if(anisous[ai].eigvals[1] < eigvalthres) anisous[ai].eigvals[1] = 0;
                //    if(anisous[ai].eigvals[2] < eigvalthres) anisous[ai].eigvals[2] = 0;
                //    Debug.Assert((anisous[ai].eigvals[0] == 0 && anisous[ai].eigvals[1] == 0  && anisous[ai].eigvals[2] == 0) == false);
                //    if(bfactors != null) bfactors[ai] = (cov[0, 0] + cov[1, 1] + cov[2, 2]);
                //}
                //);
                #endregion

                List <Vector[]> lensemble = new List <Vector[]>();
                for (int i = 0; i < ensemble.Length; i++)
                {
                    lensemble.Add(ensemble[i].ToArray());
                }

                int      size     = ensemble[0].Count;
                Anisou[] lanisous = Anisou.FromCoords(lensemble, meanconf: meanconf, eigvalthres: eigvalthres);

                for (int i = 0; i < size; i++)
                {
                    anisous[i] = lanisous[i];
                    if (bfactors != null)
                    {
                        bfactors[i] = anisous[i].bfactor;
                    }
                }
            }
示例#12
0
        public static Anisou FromCoords(IList <Vector> coords, Vector meancoord = null, double eigvalthres = double.NegativeInfinity)
        {
            if (meancoord == null)
            {
                meancoord = coords.Mean();
            }

            MatrixByArr cov = new double[3, 3];
            {
                for (int i = 0; i < coords.Count; i++)
                {
                    Vector vec = coords[i] - meancoord;
                    cov += LinAlg.VVt(vec, vec);
                }
            }
            Anisou anisou = Anisou.FromMatrix(cov, eigvalthres);

            return(anisou);
        }
示例#13
0
        public static Anisou[] FromHessian(Mode[] modesMassWeighted, double[] mass, double scale = 10000 *1000
                                           , string cachepath = null
                                           )
        {
            if (cachepath != null && HFile.Exists(cachepath))
            {
                List <Anisou> lstanisou;
                HDebug.Verify(HSerialize.Deserialize(cachepath, null, out lstanisou));
                return(lstanisou.ToArray());
            }

            int size = modesMassWeighted.Size();

            HDebug.Assert(size == mass.Length);
            Anisou[] anisous = new Anisou[size];

            for (int i = 0; i < size; i++)
            {
                MatrixByArr invHii = new double[3, 3];
                foreach (Mode mode in modesMassWeighted)
                {
                    Vector modei = mode.GetEigvecOfAtom(i);
                    invHii = invHii + LinAlg.VVt(modei, modei) * mode.eigval;
                }

                MatrixByArr Ui = invHii * scale / mass[i];

                anisous[i] = Anisou.FromMatrix(Ui);
            }

            if (cachepath != null)
            {
                HSerialize.Serialize(cachepath, null, new List <Anisou>(anisous));
            }

            return(anisous);
        }
示例#14
0
        public static Anisou FromMatrix(MatrixByArr U, Func <MatrixByArr, Tuple <Vector[], double[]> > Eig, double eigvalthres = double.NegativeInfinity)
        {
            Anisou anisou = new Anisou();

            anisou.U = U.CloneT();

            anisou.eigvecs = new Vector[3];
            anisou.eigvals = new double[3];
            {
                var      eigvecval = Eig(anisou.U);
                Vector[] eigvec    = eigvecval.Item1;
                double[] eigval    = eigvecval.Item2;

                if (eigval[0] < eigvalthres)
                {
                    eigval[0] = 0;
                }
                if (eigval[1] < eigvalthres)
                {
                    eigval[1] = 0;
                }
                if (eigval[2] < eigvalthres)
                {
                    eigval[2] = 0;
                }
                HDebug.Assert((eigval[0] == 0 && eigval[1] == 0 && eigval[2] == 0) == false);

                {   // normalize eigval and eigvec
                    double l;
                    l = eigvec[0].Dist; anisou.eigvecs[0] = eigvec[0] / l; anisou.eigvals[0] = eigval[0] * (l * l);
                    l = eigvec[1].Dist; anisou.eigvecs[1] = eigvec[1] / l; anisou.eigvals[1] = eigval[1] * (l * l);
                    l = eigvec[2].Dist; anisou.eigvecs[2] = eigvec[2] / l; anisou.eigvals[2] = eigval[2] * (l * l);
                }
            }
            return(anisou);
        }
示例#15
0
            public static Element UpdateElement(string line)
            {
                line = (line + "                                                                                ").Substring(0, 80);
                if (Header.IsHeader(line))
                {
                    return(Header.FromString(line));                        // Title Section
                }
                if (Title.IsTitle(line))
                {
                    return(Title.FromString(line));                         // Title Section
                }
                if (Compnd.IsCompnd(line))
                {
                    return(Compnd.FromString(line));                        // Title Section
                }
                if (Source.IsSource(line))
                {
                    return(Source.FromString(line));                        // Title Section
                }
                if (Keywds.IsKeywds(line))
                {
                    return(Keywds.FromString(line));                        // Title Section
                }
                if (Expdta.IsExpdta(line))
                {
                    return(Expdta.FromString(line));                        // Title Section
                }
                if (Nummdl.IsNummdl(line))
                {
                    return(Nummdl.FromString(line));                        // Title Section
                }
                if (Author.IsAuthor(line))
                {
                    return(Author.FromString(line));                        // Title Section
                }
                if (Revdat.IsRevdat(line))
                {
                    return(Revdat.FromString(line));                        // Title Section
                }
                if (Jrnl.IsJrnl(line))
                {
                    return(Jrnl.FromString(line));                          // Title Section
                }
                if (Remark.IsRemark(line))
                {
                    return(Remark.FromString(line));                        // Title Section
                }
                if (Seqres.IsSeqres(line))
                {
                    return(Seqres.FromString(line));                        // Primary Structure Section
                }
                if (Seqadv.IsSeqadv(line))
                {
                    return(Seqadv.FromString(line));                        // Primary Structure Section
                }
                if (Helix.IsHelix(line))
                {
                    return(Helix.FromString(line));                         // Secondary Structure Section
                }
                if (Sheet.IsSheet(line))
                {
                    return(Sheet.FromString(line));                         // Secondary Structure Section
                }
                if (Site.IsSite(line))
                {
                    return(Site.FromString(line));                          // Miscellaneous Features Section
                }
                if (Cryst1.IsCryst1(line))
                {
                    return(Cryst1.FromString(line));                        // Crystallographic and Coordinate Transformation Section
                }
                if (Anisou.IsAnisou(line))
                {
                    return(Anisou.FromString(line));                        // Coordinate Section
                }
                if (Atom.IsAtom(line))
                {
                    return(Atom.FromString(line));                          // Coordinate Section
                }
                if (Endmdl.IsEndmdl(line))
                {
                    return(Endmdl.FromString(line));                        // Coordinate Section
                }
                if (Hetatm.IsHetatm(line))
                {
                    return(Hetatm.FromString(line));                        // Coordinate Section
                }
                if (Model.IsModel(line))
                {
                    return(Model.FromString(line));                         // Coordinate Section
                }
                if (Siguij.IsSiguij(line))
                {
                    return(Siguij.FromString(line));                        // Coordinate Section
                }
                if (Ter.IsTer(line))
                {
                    return(Ter.FromString(line));                           // Coordinate Section
                }
                if (Conect.IsConect(line))
                {
                    return(Conect.FromString(line));                        // Connectivity Section
                }
                if (Master.IsMaster(line))
                {
                    return(Master.FromString(line));                        // Bookkeeping Section
                }
                if (End.IsEnd(line))
                {
                    return(End.FromString(line));                           // Bookkeeping Section
                }
                if (line.Substring(0, 6) == "DBREF ")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SEQRES")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "MODRES")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "HET   ")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "HETNAM")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "FORMUL")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SSBOND")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "LINK  ")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "ORIGX1")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "ORIGX2")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "ORIGX3")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SCALE1")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SCALE2")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SCALE3")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "CISPEP")
                {
                    return(new Element(line));                                  // Connectivity Annotation Section
                }
                if (line.Substring(0, 6) == "HETSYN")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SEQADV")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SPRSDE")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "MTRIX1")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "MTRIX2")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "MTRIX3")
                {
                    return(new Element(line));
                }

                if (line.Substring(0, 6) == "MDLTYP")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SPLIT ")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "CAVEAT")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "OBSLTE")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "HYDBND")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SLTBRG")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "TVECT ")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "DBREF1")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "DBREF2")
                {
                    return(new Element(line));
                }
                if (line.Substring(0, 6) == "SIGATM")
                {
                    return(new Element(line));
                }

                HDebug.Assert(false);
                return(new Element(line));
            }
示例#16
0
        public static Anisou[] FromHessian(MatrixByArr hessMassWeighted, double[] mass, double scale = 10000 *1000
                                           , string cachepath = null
                                           )
        {
            /// Estimation of "anisotropic temperature factors" (ANISOU)
            ///
            /// delta = hess^-1 * force
            ///       = (0 + V7*V7'/L7 + V8*V8'/L8 + V9*V9'/L9 + ...) * force    (* assume that 1-6 eigvecs/eigvals are ignored, because rot,trans *)
            ///
            /// Assume that force[i] follows gaussian distributions N(0,1). Here, if there are 1000 samples, let denote i-th force as fi, and its j-th element as fi[j]
            /// Then, $V7' * fi = si7, V8' * fi = si8, ...$ follows gaussian distribution N(0,1), too.
            /// Its moved position by k-th eigen component is determined then, as
            ///     dik = (Vk * Vk' / Lk) * Fi
            ///         = Vk / Lk * (Vk' * Fi)
            ///         = Vk / Lk * Sik.
            /// Additionally, the moved position j-th atom is:
            ///     dik[j] = Vk[j] / Lk[j] * Sik.
            /// and its correlation matrix is written as (because its mean position is 0 !!!):
            ///     Cik[j] = dik[j] * dik[j]'
            ///            = [dik[j]_x * dik[j]_x    dik[j]_x * dik[j]_y    dik[j]_x * dik[j]_z]
            ///              [dik[j]_y * dik[j]_x    dik[j]_y * dik[j]_y    dik[j]_y * dik[j]_z]
            ///              [dik[j]_z * dik[j]_x    dik[j]_z * dik[j]_y    dik[j]_z * dik[j]_z]
            ///            = (Vk[j] * Vk[j]') / (Lk[j]*Lk[j]) * (Sik*Sik).
            ///
            /// Note that Sik*Sik follows the chi-square distribution, because Sik follows the gaussian distribution N(0,1).
            /// Additionally, note that the thermal fluctuation is (not one projection toward k-th eigen component with only i-th force, but) the results of 1..i.. forced movements and 1..k.. eigen components.
            /// Therefore, for j-th atom, the accumulation of the correlation over all forces (1..i..) with all eigen components (1..k..) is:
            ///     C[j] = sum_{i,k} {(Vk[j] * Vk[j]') / (Lk[j]*Lk[j]) * (Sik*Sik)}.
            ///
            /// Here, Sik is normal distribution independent to i and k. Therefore, the mean of C[j] is
            ///     E(C[j]) = E( sum_{i,k} {(Vk[j] * Vk[j]') / (Lk[j]*Lk[j]) * (Sik*Sik)} )
            ///             = sum_{i,k} E( (Vk[j] * Vk[j]') / (Lk[j]*Lk[j]) * (Sik*Sik) )
            ///             = sum_{i,k} { (Vk[j] * Vk[j]') / (Lk[j]*Lk[j]) * E(Sik*Sik) }
            ///             = sum_{i,k} { (Vk[j] * Vk[j]') / (Lk[j]*Lk[j]) * 1          }          (* because mean of E(x*x)=1 where x~N(0,1) *)
            ///             = sum_{k} { (Vk[j] * Vk[j]') / (Lk[j]*Lk[j]) }
            ///
            /// Note that E(C[j]) is same to the j-th diagonal component of inverse hessian matrix (except, the eigenvalues are squared).
            ///
            /// Fixation: Gromacx generate the ensemble X by
            ///               X[j] = sum_{k} {Vk / sqrt(Lk[j]) / sqrt(mass[j]) * x_k},
            ///           where x~N(0,1). However, the above is assumed as
            ///               X[j] = sum_{k} {Vk / Lk[j] * x_k}.
            ///           In order to apply the assumption by the Gromacs ensemble, The equation should be fixed as
            ///               E(C[j]) = sum_{k} { (Vk[j] * Vk[j]') / (sqrt(Lk[j])*sqrt(Lk[j])) }
            ///                       = sum_{k} { (Vk[j] * Vk[j]') / Lk[j] / mass[j] }
            ///

            int size = mass.Length;

            HDebug.Assert(hessMassWeighted.RowSize == size * 3, hessMassWeighted.ColSize == size * 3);
            Anisou[] anisous = new Anisou[size];

            if (cachepath != null && HFile.Exists(cachepath))
            {
                List <Anisou> lstanisou;
                HDebug.Verify(HSerialize.Deserialize <List <Anisou> >(cachepath, null, out lstanisou));
                anisous = lstanisou.ToArray();
                return(anisous);
            }

            // anisotropic temperature factors
            using (new Matlab.NamedLock("ANISOU"))
            {
                Matlab.Clear("ANISOU");
                Matlab.PutMatrix("ANISOU.H", hessMassWeighted);
                Matlab.Execute("[ANISOU.V,ANISOU.D] = eig(ANISOU.H);");
                Matlab.Execute("ANISOU.D = diag(ANISOU.D);");                                 // get diagonal
                {
                    Matlab.Execute("[ANISOU.sortD, ANISOU.sortIdxD] = sort(abs(ANISOU.D));"); // sorted index of abs(D)
                    Matlab.Execute("ANISOU.D(ANISOU.sortIdxD(1:6)) = 0;");                    // set the 6 smallest eigenvalues as zero
                    //Matlab.Execute("ANISOU.D(ANISOU.D < 0) = 0;");                              // set negative eigenvalues as zero
                }
                //{
                //    Matlab.Execute("ANISOU.D(1:6) = 0;");
                //}
                Matlab.Execute("ANISOU.invD = 1 ./ ANISOU.D;");                             // set invD
                Matlab.Execute("ANISOU.invD(ANISOU.D == 0) = 0;");                          // set Inf (by divided by zero) as zero
                //Matlab.Execute("ANISOU.D = ANISOU.D .^ 2;"); // assume the gromacs ensemble condition
                Matlab.Execute("ANISOU.invH = ANISOU.V * diag(ANISOU.invD) * ANISOU.V';");
                for (int i = 0; i < size; i++)
                {
                    string      idx = string.Format("{0}:{1}", i * 3 + 1, i * 3 + 3);
                    MatrixByArr U   = Matlab.GetMatrix("ANISOU.invH(" + idx + "," + idx + ")");
                    U *= (scale / mass[i]);

                    anisous[i] = Anisou.FromMatrix(U);
                }
                Matlab.Clear("ANISOU");
            }

            if (cachepath != null)
            {
                HSerialize.Serialize(cachepath, null, new List <Anisou>(anisous));
            }

            return(anisous);
        }
示例#17
0
        public static void ToFile(string filepath
                                  , IList <Atom> atoms
                                  , IList <Vector> coords       = null
                                  , IList <MatrixByArr> anisous = null
                                  , double?anisouScale          = null
                                  , IList <double> bfactors     = null
                                  , bool append            = false
                                  , IList <string> headers = null
                                  , int?modelidx           = null
                                  )
        {
            List <string> lines = new List <string>();
            int           size  = atoms.Count;

            if (coords != null)
            {
                HDebug.Assert(size == coords.Count);
            }
            if (anisous != null)
            {
                HDebug.Assert(size == anisous.Count);
            }
            //if(anisouScale != null) Debug.Assert(size == anisouScale.Count);
            if (headers != null)
            {
                lines.AddRange(headers);
            }
            {
                //           1         2         3         4         5         6         7         8
                //  12345678901234567890123456789012345678901234567890123456789012345678901234567890
                // "MODEL        1                                                                  "
                string line = "MODEL        1                                                                  ";
                if (modelidx != null)
                {
                    line.Replace("1", modelidx.Value.ToString());
                }
                line = line.Substring(0, 80);
                lines.Add(line);
            }

            for (int i = 0; i < size; i++)
            {
                Atom atom = atoms[i];
                if (atom == null)
                {
                    continue;
                }
                {
                    if (coords != null)
                    {
                        double x = coords[i][0];
                        double y = coords[i][1];
                        double z = coords[i][2];
                        atom = Atom.FromString(atom.GetUpdatedLine(x, y, z));
                    }
                    if (bfactors != null)
                    {
                        atom = Atom.FromString(atom.GetUpdatedLineTempFactor(bfactors[i]));
                    }
                    lines.Add(atom.line);
                }
                {
                    if (anisous != null)
                    {
                        MatrixByArr U = anisous[i];
                        if (anisouScale != null)
                        {
                            U = U * anisouScale.Value;
                        }
                        Anisou anisou = Anisou.FromAtom(atom, U.ToArray().HToInt());
                        string line   = anisou.line; //anisou.GetUpdatedU(anisous[i])
                        lines.Add(line);
                    }
                }
            }
            lines.Add("ENDMDL                                                                          ");
            //int idx = 0;
            //foreach(Element element in elements)
            //{
            //    string line = element.line;
            //    if(typeof(Atom).IsInstanceOfType(element))
            //    {
            //        double x = coords[idx][0];
            //        double y = coords[idx][1];
            //        double z = coords[idx][2];
            //        Atom atom = (Atom)element;
            //        line = atom.GetUpdatedLine(x, y, z);
            //        idx++;
            //    }
            //    lines.Add(line);
            //}
            if (append == false)
            {
                HFile.WriteAllLines(filepath, lines);
            }
            else
            {
                StringBuilder text = new StringBuilder();
                foreach (string line in lines)
                {
                    text.AppendLine(line);
                }
                HFile.AppendAllText(filepath, text.ToString());
            }
        }
示例#18
0
        public Pdb CloneReplaceChainID(string IDfrom, string IDto)
        {
            if (IDfrom == null)
            {
                throw new ArgumentException("IDfrom is null");
            }
            if (IDto == null)
            {
                throw new ArgumentException("IDto is null");
            }
            if (IDfrom.Length != IDto.Length)
            {
                throw new ArgumentException("IDFrom.leng != IDto.leng");
            }

            Dictionary <char, char> from2to = GetPairChainID(IDfrom, IDto);

            if (from2to.ContainsKey('_'))
            {
                throw new ArgumentException("wildkey('_') is not allowed in IDfrom");
            }

            Element[] newelements = new Element[elements.Length];
            for (int i = 0; i < elements.Length; i++)
            {
                Element elem = elements[i];
                char?   ch   = null;
                if (elem is Atom)
                {
                    HDebug.Assert(ch == null); ch = (elem as Atom).chainID;
                }
                if (elem is Hetatm)
                {
                    HDebug.Assert(ch == null); ch = (elem as Hetatm).chainID;
                }
                if (elem is Anisou)
                {
                    HDebug.Assert(ch == null); ch = (elem as Anisou).chainID;
                }

                if (ch != null)
                {
                    if (from2to.ContainsKey(ch.Value))
                    {
                        if (from2to[ch.Value] == '_')
                        {
                            // if wildcard ('_') is in IDto, delete that atom
                            continue;
                        }
                        Element nelem = null;
                        if (elem is Atom)
                        {
                            if (nelem != null)
                            {
                                throw new HException("(nelem != null)");
                            }
                            Atom atom = elem as Atom;
                            nelem = Atom.FromData(
                                serial: atom.serial,
                                name: atom.name,
                                resName: atom.resName,
                                chainID: from2to[atom.chainID],
                                resSeq: atom.resSeq,
                                x: atom.x,
                                y: atom.y,
                                z: atom.z,
                                altLoc: atom.altLoc,
                                iCode: atom.iCode,
                                occupancy: atom.occupancy,
                                tempFactor: atom.tempFactor,
                                element: atom.element,
                                charge: atom.charge
                                );
                        }
                        if (elem is Hetatm)
                        {
                            if (nelem != null)
                            {
                                throw new HException("(nelem != null)");
                            }
                            Hetatm hetatm = elem as Hetatm;
                            nelem = Hetatm.FromData(
                                serial: hetatm.serial,
                                name: hetatm.name,
                                resName: hetatm.resName,
                                chainID: from2to[hetatm.chainID],
                                resSeq: hetatm.resSeq,
                                x: hetatm.x,
                                y: hetatm.y,
                                z: hetatm.z,
                                altLoc: hetatm.altLoc,
                                iCode: hetatm.iCode,
                                occupancy: hetatm.occupancy,
                                tempFactor: hetatm.tempFactor,
                                element: hetatm.element,
                                charge: hetatm.charge
                                );
                        }
                        if (elem is Anisou)
                        {
                            if (nelem != null)
                            {
                                throw new HException("(nelem != null)");
                            }
                            Anisou anisou = elem as Anisou;
                            nelem = Anisou.FromData(anisou.line
                                                    , chainID: from2to[anisou.chainID]
                                                    );
                        }
                        if (nelem == null)
                        {
                            throw new NotImplementedException();
                        }
                        elem = nelem;
                    }
                }
                newelements[i] = elem.UpdateElement();
            }
            newelements = newelements.HRemoveAll(null);

            return(new Pdb(newelements));
        }
示例#19
0
 public static Anisou[] BFactor2Anisou(IList <double> bfactor, double scale = 10000 *1000)
 {
     return(Anisou.FromBFactor(bfactor.ToArray(), scale: scale));
 }
示例#20
0
            public static void Align(ref List <Vector>[] ensemble
                                     , int maxiteration = int.MaxValue
                                     , HPack <List <Trans3[]> > outTrajTrans = null
                                     )
            {
                List <Vector>[] lensemble = ensemble.HClone <List <Vector> >();

                int size = lensemble[0].Count;

                for (int i = 1; i < lensemble.Length; i++)
                {
                    HDebug.Assert(size == lensemble[i].Count);
                }

                // initial alignment using RMSD
                Trans3[] transs = new Trans3[lensemble.Length];
                transs[0] = Trans3.UnitTrans;

                Vector[] coords             = new Vector[size];
                Anisou[] anisous            = new Anisou[size];
                double   anisou_eigvalthres = 0.00001 * 0.00001;

                double[] bfactors = new double[size];
                {
                    // set ensemble[0] as the initial mean structure
                    for (int i = 0; i < size; i++)
                    {
                        coords[i] = lensemble[0][0].Clone();
                    }
                    // set anisou as sphere (with radii as one)
                    Anisou U0 = Anisou.FromMatrix(new double[3, 3] {
                        { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }
                    });
                    for (int i = 0; i < anisous.Length; i++)
                    {
                        anisous[i] = U0;
                    }
                    // set bfactor as one
                    for (int i = 0; i < bfactors.Length; i++)
                    {
                        bfactors[i] = 1;
                    }
                }

                //List<double>[] bfactorss = new List<double>[ensemble.Length];
                //for(int i=0; i<bfactorss.Length; i++)
                //    bfactorss[i] = new List<double>(bfactors);
                //Pdb.ToFile("ensemble.000.pdb", null, lensemble, bfactorss);

                System.Console.WriteLine("begin iterative alignment");

                double move2 = double.PositiveInfinity;
                //double thres = 0.00001;// *size * lensemble.Length;
                double thres = 0.00001;// *size * lensemble.Length;

                //List<Pdb.Atom> atoms = null;
                //while(thres < move2)
                for (int iter = 0; iter < maxiteration; iter++)
                {
                    transs = new Trans3[ensemble.Length];
                    move2  = Align(lensemble, coords, anisous, transs);

                    if (outTrajTrans != null)
                    {
                        outTrajTrans.value.Add(transs);
                    }

                    System.Console.WriteLine(iter + "th alignment done: (move " + move2 + " Å)");
                    if (move2 < thres)
                    {
                        break;
                    }

                    DetermineMeanConf(lensemble, coords);
                    DetermineThrmlFluc(lensemble, coords, anisous, null, anisou_eigvalthres);
                }

                ensemble = lensemble;
            }
示例#21
0
            public static void WriteResult(string pdbid, List <Pdb.Atom>[] ensemble, List <Trans3[]> trajtrans, string pathroot)
            {
                List <Pdb.Atom> atoms = ensemble[0];

                int    size               = ensemble[0].Count;
                double bfactor0_min       = double.PositiveInfinity;
                double bfactor0_max       = double.NegativeInfinity;
                double anisou_eigvalthres = 0.00001 * 0.00001;
                {
                    Trans3[]        trans     = trajtrans.First();
                    List <Vector>[] lensemble = new List <Vector> [ensemble.Length];
                    for (int i = 0; i < ensemble.Length; i++)
                    {
                        lensemble[i] = new List <Vector>(trans[i].GetTransformed(ensemble[i].ListCoord()));
                    }
                    Vector[] coords   = new Vector[size];
                    Anisou[] anisous  = new Anisou[size];
                    double[] bfactors = new double[size];
                    DetermineMeanConf(lensemble, coords);
                    DetermineThrmlFluc(lensemble, coords, anisous, bfactors, anisou_eigvalthres);
                    List <double>[] bfactorss = new List <double> [ensemble.Length];
                    for (int i = 0; i < bfactorss.Length; i++)
                    {
                        bfactorss[i] = new List <double>(bfactors);
                    }

                    List <int> idxCa = atoms.IndexOfAtoms(atoms.SelectByName("CA"));
                    bfactor0_min = bfactors.HSelectByIndex(idxCa).HMinNth(idxCa.Count / 10);
                    bfactor0_max = bfactors.HSelectByIndex(idxCa).HMaxNth(idxCa.Count / 10);

                    Pdb.ToFile(pathroot + "ensemble.000.pdb", atoms, lensemble, bfactorss);
                    Pdb.ToFile(pathroot + "ensemble.000.anisou.1.pdb", atoms, coords, anisous: anisous.GetUs(1), bfactors: bfactors, append: false);
                    Pdb.ToFile(pathroot + "ensemble.000.anisou.10.pdb", atoms, coords, anisous: anisous.GetUs(10), bfactors: bfactors, append: false);
                    Pdb.ToFile(pathroot + "ensemble.000.anisou.100.pdb", atoms, coords, anisous: anisous.GetUs(100), bfactors: bfactors, append: false);
                    Pdb.ToFile(pathroot + "ensemble.000.anisou.1000.pdb", atoms, coords, anisous: anisous.GetUs(1000), bfactors: bfactors, append: false);
                    Pdb.ToFile(pathroot + "ensemble.000.anisou.10000.pdb", atoms, coords, anisous: anisous.GetUs(10000), bfactors: bfactors, append: false);
                }
                int    iter         = trajtrans.Count - 1;
                double bfactorn_min = double.PositiveInfinity;
                double bfactorn_max = double.NegativeInfinity;
                {
                    Trans3[] trans = new Trans3[ensemble.Length];
                    for (int j = 0; j < trans.Length; j++)
                    {
                        trans[j] = Trans3.UnitTrans;
                    }
                    for (int i = 0; i < trajtrans.Count; i++)
                    {
                        for (int j = 0; j < trans.Length; j++)
                        {
                            trans[j] = Trans3.AppendTrans(trans[j], trajtrans[i][j]);
                        }
                    }

                    List <Vector>[] lensemble = new List <Vector> [ensemble.Length];
                    for (int i = 0; i < ensemble.Length; i++)
                    {
                        lensemble[i] = new List <Vector>(trans[i].GetTransformed(ensemble[i].ListCoord()));
                    }
                    Vector[] coords   = new Vector[size];
                    Anisou[] anisous  = new Anisou[size];
                    double[] bfactors = new double[size];
                    DetermineMeanConf(lensemble, coords);
                    DetermineThrmlFluc(lensemble, coords, anisous, bfactors, anisou_eigvalthres);
                    List <double>[] bfactorss = new List <double> [ensemble.Length];
                    for (int i = 0; i < bfactorss.Length; i++)
                    {
                        bfactorss[i] = new List <double>(bfactors);
                    }

                    List <int> idxCa = atoms.IndexOfAtoms(atoms.SelectByName("CA"));
                    bfactorn_min = bfactors.HSelectByIndex(idxCa).HMinNth(idxCa.Count / 10);
                    bfactorn_max = bfactors.HSelectByIndex(idxCa).HMaxNth(idxCa.Count / 10);

                    Pdb.ToFile((pathroot + "ensemble.{finl}.pdb").Replace("{finl}", iter.ToString("000")), atoms, lensemble, bfactorss);
                    Pdb.ToFile((pathroot + "ensemble.{finl}.anisou.1.pdb").Replace("{finl}", iter.ToString("000")), atoms, coords, anisous: anisous.GetUs(1), bfactors: bfactors, append: false);
                    Pdb.ToFile((pathroot + "ensemble.{finl}.anisou.10.pdb").Replace("{finl}", iter.ToString("000")), atoms, coords, anisous: anisous.GetUs(10), bfactors: bfactors, append: false);
                    Pdb.ToFile((pathroot + "ensemble.{finl}.anisou.100.pdb").Replace("{finl}", iter.ToString("000")), atoms, coords, anisous: anisous.GetUs(100), bfactors: bfactors, append: false);
                    Pdb.ToFile((pathroot + "ensemble.{finl}.anisou.1000.pdb").Replace("{finl}", iter.ToString("000")), atoms, coords, anisous: anisous.GetUs(1000), bfactors: bfactors, append: false);
                    Pdb.ToFile((pathroot + "ensemble.{finl}.anisou.10000.pdb").Replace("{finl}", iter.ToString("000")), atoms, coords, anisous: anisous.GetUs(10000), bfactors: bfactors, append: false);
                }
                {
                    string[] lines = new string[] { @"load ensemble.{init}.pdb,              {init}.align"
                                                    , @"load ensemble.{init}.anisou.10.pdb,    {init}.anisou.10"
                                                    , @"load ensemble.{init}.anisou.100.pdb,   {init}.anisou.100"
                                                    , @"load ensemble.{init}.anisou.1000.pdb,  {init}.anisou.1000"
                                                    , @"load ensemble.{init}.anisou.10000.pdb, {init}.anisou.10000"
                                                    , @"load ensemble.{finl}.pdb,              {finl}.align"
                                                    , @"load ensemble.{finl}.anisou.10.pdb,    {finl}.anisou.10"
                                                    , @"load ensemble.{finl}.anisou.100.pdb,   {finl}.anisou.100"
                                                    , @"load ensemble.{finl}.anisou.1000.pdb,  {finl}.anisou.1000"
                                                    , @"load ensemble.{finl}.anisou.10000.pdb, {finl}.anisou.10000"
                                                    , @"load ..\theseus\{pdbid}_theseus_sup.pdb, theseus"
                                                    , @"align theseus, {finl}.align"
                                                    , @"orient {finl}.align"
                                                    , @"zoom {finl}.align"
                                                    , @""
                                                    , @"select sele, name ca and ({init}.anisou.* or {finl}.anisou.*)"
                                                    , @"hide everything"
                                                    , @"show ellipsoids, sele"
                                                    , @"delete sele"
                                                    , @""
                                                    , @"cartoon loop"
                                                    , @"set cartoon_loop_radius, 0.1"
                                                    , @"set all_states"
                                                    , @"show cartoon, {init}.align or {finl}.align"
                                                    , @"show cartoon, theseus"
                                                    , @"disable all"
                                                    , @""
                                                    , @"spectrum b, rainbow, minimum={bfactor-min}, maximum={bfactor-max}"
                                                    , @"spectrum b, rainbow, minimum=0, maximum=50"
                                                    , @"show line"
                                                    , @"enable {init}.align; png ..\{pdbid}-{init}-line.png;  disable {init}.align;"
                                                    , @"enable {finl}.align; png ..\{pdbid}-{finl}-line.png;  disable {finl}.align;"
                                                    , @"hide line"
                                                    , @"enable {init}.align; png ..\{pdbid}-{init}.png;  disable {init}.align;"
                                                    , @"enable {finl}.align; png ..\{pdbid}-{finl}.png;  disable {finl}.align;"
                                                    , @"enable theseus;      png ..\{pdbid}-theseus.png; disable theseus;"
                                                    , @"enable {init}.align"
                                                    , @"enable {finl}.align"
                                                    , @"enable theseus" };
                    lines = lines.HReplace("{init}", "000");
                    lines = lines.HReplace("{finl}", iter.ToString("000"));
                    lines = lines.HReplace("{pdbid}", pdbid);
                    lines = lines.HReplace("{bfactor-min}", bfactorn_min.ToString());
                    lines = lines.HReplace("{bfactor-max}", bfactorn_max.ToString());

                    string pmlpath = pathroot + "align.pml";
                    HFile.WriteAllLines(pmlpath, lines);

                    {
                        HFile.AppendAllLines(pmlpath, "quit");
                        string curdirectory = System.Environment.CurrentDirectory;
                        string pmldirectory = pmlpath.Substring(0, pmlpath.LastIndexOf('\\') + 1);
                        System.Environment.CurrentDirectory = pmldirectory;
                        System.Diagnostics.ProcessStartInfo pymolStartInfo = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\PyMOL\PyMOL\PymolWin.exe ", "\"" + pmlpath + "\"");
                        pymolStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
                        System.Diagnostics.Process pymol = System.Diagnostics.Process.Start(pymolStartInfo);
                        //pymol.win
                        pymol.WaitForExit();
                        System.Environment.CurrentDirectory = curdirectory;
                        HFile.WriteAllLines(pmlpath, lines);
                    }
                    {
                        List <string> lines_notheseus = new List <string>();
                        for (int i = 0; i < lines.Length; i++)
                        {
                            if (lines[i].Contains("theseus") == false)
                            {
                                lines_notheseus.Add(lines[i]);
                            }
                        }
                        HFile.WriteAllLines(pathroot + "align.notheseus.pml", lines);
                    }
                }
            }
示例#22
0
        public void ToFile(string filepath, IList <Vector> coords = null, IList <double> bfactors = null, IList <MatrixByArr> anisous = null, double anisous_scale = 1, bool append = false)
        {
            List <string> lines = new List <string>();

            if (coords == null)
            {
                coords = this.atoms.ListCoord();
            }
            //Debug.Assert(atoms.Length == coords.Count);
            int idx = 0;

            foreach (Element element in elements)
            {
                //string line = element.line;
                if (typeof(Atom).IsInstanceOfType(element))
                {
                    double x = coords[idx][0];
                    double y = coords[idx][1];
                    double z = coords[idx][2];

                    Atom atom = (Atom)element;
                    atom = Atom.FromString(atom.GetUpdatedLine(x, y, z));

                    if (bfactors != null)
                    {
                        atom = Atom.FromString(atom.GetUpdatedLineTempFactor(bfactors[idx]));
                    }

                    lines.Add(atom.line);

                    if (anisous != null)
                    {
                        MatrixByArr anisoui = anisous[idx] * anisous_scale;
                        int[,] U = new int[3, 3] {
                            { (int)anisoui[0, 0], (int)anisoui[0, 1], (int)anisoui[0, 2], },
                            { (int)anisoui[1, 0], (int)anisoui[1, 1], (int)anisoui[1, 2], },
                            { (int)anisoui[2, 0], (int)anisoui[2, 1], (int)anisoui[2, 2], },
                        };
                        Anisou anisou = Anisou.FromAtom(atom, U);
                        lines.Add(anisou.line);
                    }

                    idx++;
                }
                else if (typeof(Anisou).IsInstanceOfType(element) && anisous != null)
                {
                    // skip because it is handled in the "Atom" part
                }
                else
                {
                    lines.Add(element.line);
                }
            }

            if (append == false)
            {
                HFile.WriteAllLines(filepath, lines);
            }
            else
            {
                StringBuilder text = new StringBuilder();
                foreach (string line in lines)
                {
                    text.AppendLine(line);
                }
                HFile.AppendAllText(filepath, text.ToString());
            }
        }