Beispiel #1
0
            public static Vector[] ToOrthonormal(Vector[] coords, double[] masses, int[] block, Vector[] PBlk)
            {
                if (HDebug.IsDebuggerAttached)
                #region check if elements in non-block are zeros.
                {
                    int leng = coords.Length;
                    foreach (int i in HEnum.HEnumCount(leng).HEnumExcept(block.HToHashSet()))
                    {
                        for (int r = 0; r < PBlk.Length; r++)
                        {
                            int c0 = i * 3;
                            HDebug.Assert(PBlk[r][c0 + 0] == 0);
                            HDebug.Assert(PBlk[r][c0 + 1] == 0);
                            HDebug.Assert(PBlk[r][c0 + 2] == 0);
                        }
                    }
                }
                #endregion

                Matrix Pmat = new double[block.Length * 3, PBlk.Length];
                for (int r = 0; r < PBlk.Length; r++)
                {
                    for (int i = 0; i < block.Length; i++)
                    {
                        int i0 = i * 3;
                        int c0 = block[i] * 3;
                        Pmat[i0 + 0, r] = PBlk[r][c0 + 0];
                        Pmat[i0 + 1, r] = PBlk[r][c0 + 1];
                        Pmat[i0 + 2, r] = PBlk[r][c0 + 2];
                    }
                }

                using (new Matlab.NamedLock(""))
                {
                    Matlab.PutValue("n", PBlk.Length);
                    Matlab.PutMatrix("P", Pmat);
                    Matlab.Execute("[U,S,V] = svd(P);");
                    Matlab.Execute("U = U(:,1:n);");
                    if (HDebug.IsDebuggerAttached)
                    {
                        Matlab.Execute("SV = S(1:n,1:n)*V';");
                        double err = Matlab.GetValue("max(max(abs(P - U*SV)))");
                        HDebug.Assert(Math.Abs(err) < 0.00000001);
                    }
                    Pmat = Matlab.GetMatrix("U");
                }

                Vector[] PBlkOrth = new Vector[PBlk.Length];
                for (int r = 0; r < PBlk.Length; r++)
                {
                    Vector PBlkOrth_r = new double[PBlk[r].Size];
                    for (int i = 0; i < block.Length; i++)
                    {
                        int i0 = i * 3;
                        int c0 = block[i] * 3;
                        PBlkOrth_r[c0 + 0] = Pmat[i0 + 0, r];
                        PBlkOrth_r[c0 + 1] = Pmat[i0 + 1, r];
                        PBlkOrth_r[c0 + 2] = Pmat[i0 + 2, r];
                    }
                    PBlkOrth[r] = PBlkOrth_r;
                }

                if (HDebug.IsDebuggerAttached)
                #region checi the orthonormal condition, and rot/trans condition (using ANM)
                {
                    {   // check if all trans/rot modes are orthonormal
                        for (int i = 0; i < PBlkOrth.Length; i++)
                        {
                            HDebug.Exception(Math.Abs(PBlkOrth[i].Dist - 1) < 0.00000001);
                            for (int j = i + 1; j < PBlkOrth.Length; j++)
                            {
                                double dot = LinAlg.VtV(PBlkOrth[i], PBlkOrth[j]);
                                HDebug.Exception(Math.Abs(dot) < 0.00000001);
                            }
                        }
                    }
                    {   // check if this is true rot/trans modes using ANM
                        Vector[] anmcoords = coords.HClone();
                        int      leng      = coords.Length;
                        foreach (int i in HEnum.HEnumCount(leng).HEnumExcept(block.HToHashSet()))
                        {
                            anmcoords[i] = null;
                        }
                        HessMatrix H = GetHessAnm(anmcoords, 100);
                        Matrix     PHP;
                        using (new Matlab.NamedLock(""))
                        {
                            Matlab.PutSparseMatrix("H", H.GetMatrixSparse(), 3, 3);
                            Matlab.PutMatrix("P", PBlkOrth.ToMatrix(true));
                            PHP = Matlab.GetMatrix("P'*H*P");
                        }
                        double maxerr = PHP.HAbsMax();
                        HDebug.Exception(Math.Abs(maxerr) < 0.00000001);
                    }
                }
                #endregion

                return(PBlkOrth);
            }
Beispiel #2
0
            public static double[] GetRotAngles(Universe univ
                                                , Vector[] coords
                                                , Vector[] forces
                                                , double t // 0.1
                                                , MatrixByArr J = null
                                                , Graph <Universe.Atom[], Universe.Bond> univ_flexgraph = null
                                                , List <Universe.RotableInfo> univ_rotinfos             = null
                                                , HPack <Vector[]> forcesProjectedByTorsional           = null
                                                , HPack <Vector[]> dcoordsProjectedByTorsional          = null
                                                )
            {
                Vector mass = univ.GetMasses();
                //Vector[] dcoords = new Vector[univ.size];
                double t2 = t * t;

                //for(int i=0; i<univ.size; i++)
                //    dcoords[i] = forces[i] * (0.5*t2/mass[i]);

                if (J == null)
                {
                    if (univ_rotinfos == null)
                    {
                        if (univ_flexgraph == null)
                        {
                            univ_flexgraph = univ.BuildFlexibilityGraph();
                        }
                        univ_rotinfos = univ.GetRotableInfo(univ_flexgraph);
                    }
                    J = TNM.GetJ(univ, coords, univ_rotinfos);
                }

                double[] dangles;
                using (new Matlab.NamedLock("TEST"))
                {
                    Matlab.Clear("TEST");
                    Matlab.PutVector("TEST.F", Vector.FromBlockvector(forces));
                    Matlab.PutValue("TEST.t2", t2);
                    //Matlab.PutVector("TEST.R", Vector.FromBlockvector(dcoords));
                    Matlab.PutMatrix("TEST.J", J);
                    Matlab.PutVector("TEST.M", univ.GetMasses(3));
                    Matlab.Execute("TEST.M = diag(TEST.M);");
                    /// f = m a
                    /// d = 1/2 a t^2
                    ///   = 0.5 f/m t^2
                    /// f = m a
                    ///   = 2 m d t^-2
                    ///
                    /// coord change
                    /// dcoord = 0.5 a t^2
                    ///        = (0.5 t^2) f/m
                    ///        = (0.5 t^2) M^-1 F  : M is mass matrix, F is the net force of each atom
                    ///
                    /// torsional angle change
                    /// dtor =           (J' M J)^-1 J' M * dcoord                  : (6) of TNM paper
                    ///      =           (J' M J)^-1 J' M * (0.5 t^2) M^-1 F
                    ///      = (0.5 t^2) (J' M J)^-1 J'                    F
                    ///      = (0.5 t^2) (J' M J)^-1 J' F
                    ///      = (0.5 t2)  invJMJ      JF
                    ///
                    /// force filtered by torsional ...
                    /// F_tor = m a
                    ///       = 2 m d t^-2
                    ///       = 2 M (J * dtor) t^-2
                    ///       = 2 M (J * (0.5 t^2) (J' M J)^-1 J' F) t^-2
                    ///       = M J (J' M J)^-1 J' F
                    ///       = MJ  invJMJ      JF
                    ///
                    /// coord change filtered by torsional
                    /// R_tor = (0.5 t^2) M^-1 * F_tor
                    ///       = (0.5 t^2) J (J' M J)^-1 J' F
                    ///       = (0.5 t2)  J invJMJ      JF
                    Matlab.Execute("TEST.JMJ    = TEST.J' * TEST.M * TEST.J;");
                    Matlab.Execute("TEST.invJMJ = inv(TEST.JMJ);");
                    Matlab.Execute("TEST.MJ     = TEST.M * TEST.J;");
                    Matlab.Execute("TEST.JF     = TEST.J' * TEST.F;");
                    Matlab.Execute("TEST.dtor   = (0.5 * TEST.t2) * TEST.invJMJ * TEST.JF;"); // (6) of TNM paper
                    Matlab.Execute("TEST.F_tor  = TEST.MJ * TEST.invJMJ * TEST.JF;");
                    Matlab.Execute("TEST.R_tor  = (0.5 * TEST.t2) * TEST.J * TEST.invJMJ * TEST.JF;");

                    dangles = Matlab.GetVector("TEST.dtor");
                    if (forcesProjectedByTorsional != null)
                    {
                        Vector F_tor = Matlab.GetVector("TEST.F_tor");
                        HDebug.Assert(F_tor.Size == forces.Length * 3);
                        forcesProjectedByTorsional.value = new Vector[forces.Length];
                        for (int i = 0; i < forces.Length; i++)
                        {
                            int i3 = i * 3;
                            forcesProjectedByTorsional.value[i] = new double[] { F_tor[i3 + 0], F_tor[i3 + 1], F_tor[i3 + 2] };
                        }
                    }
                    if (dcoordsProjectedByTorsional != null)
                    {
                        Vector R_tor = Matlab.GetVector("TEST.R_tor");
                        HDebug.Assert(R_tor.Size == coords.Length * 3);
                        dcoordsProjectedByTorsional.value = new Vector[coords.Length];
                        for (int i = 0; i < coords.Length; i++)
                        {
                            int i3 = i * 3;
                            dcoordsProjectedByTorsional.value[i] = new double[] { R_tor[i3 + 0], R_tor[i3 + 1], R_tor[i3 + 2] };
                        }
                    }
                    Matlab.Clear("TEST");
                }

                return(dangles);
            }
Beispiel #3
0
            public static CGetHessCoarseResiIterImpl GetHessCoarseResiIterImpl_Matlab(HessMatrix H, List <int>[] lstNewIdxRemv, double thres_zeroblk)
            {
                HessMatrix CGH = null;
                List <HessCoarseResiIterInfo> iterinfos = new List <HessCoarseResiIterInfo>();

                using (new Matlab.NamedLock("CGHessIter"))
                {
                    Matlab.PutSparseMatrix("CG.H", H.GetMatrixSparse(), 3, 3);
                    Matlab.PutValue("CG.th", thres_zeroblk);
                    Matlab.PutValue("CG.iter", lstNewIdxRemv.Length);
                    for (int iter = lstNewIdxRemv.Length - 1; iter >= 0; iter--)
                    {
                        int[] iremv   = lstNewIdxRemv[iter].ToArray();
                        int[] idxkeep = HEnum.HEnumFromTo(0, iremv.Min() - 1).ToArray();
                        int[] idxremv = HEnum.HEnumFromTo(iremv.Min(), iremv.Max()).ToArray();
                        Matlab.PutVector("CG.idxkeep", idxkeep);
                        Matlab.PutVector("CG.idxremv", idxremv);
                        Matlab.Execute("CG.idxkeep = sort([CG.idxkeep*3+1; CG.idxkeep*3+2; CG.idxkeep*3+3]);");
                        Matlab.Execute("CG.idxremv = sort([CG.idxremv*3+1; CG.idxremv*3+2; CG.idxremv*3+3]);");

                        HessCoarseResiIterInfo iterinfo = new HessCoarseResiIterInfo();
                        iterinfo.sizeHessBlkMat  = idxremv.Max() + 1; // H.ColBlockSize;
                        iterinfo.numAtomsRemoved = idxremv.Length;
                        iterinfo.idxkeep         = idxkeep.HClone();
                        iterinfo.idxremv         = idxremv.HClone();
                        iterinfo.time0           = DateTime.UtcNow;

                        if (HDebug.IsDebuggerAttached)
                        {
                            int maxkeep = Matlab.GetValueInt("max(CG.idxkeep)");
                            int minremv = Matlab.GetValueInt("min(CG.idxremv)");
                            HDebug.Assert(maxkeep + 1 == minremv);
                            int maxremv = Matlab.GetValueInt("max(CG.idxremv)");
                            int Hsize   = Matlab.GetValueInt("max(size(CG.H))");
                            HDebug.Assert(Hsize == maxremv);
                            int idxsize = Matlab.GetValueInt("length(union(CG.idxkeep,CG.idxremv))");
                            HDebug.Assert(Hsize == idxsize);
                        }
                        Matlab.Execute("CG.A = CG.H(CG.idxkeep, CG.idxkeep);");
                        Matlab.Execute("CG.B = CG.H(CG.idxkeep, CG.idxremv);");
                        //Matlab.Execute("CG.C = CG.H(CG.idxremv, CG.idxkeep);");
                        Matlab.Execute("CG.D = CG.H(CG.idxremv, CG.idxremv);");
                        HDebug.Assert(false);
                        Matlab.Execute("CG.B(abs(CG.B) < CG.th) = 0;");     /// matlab cannot handle this call. Matlab try to use 20G memory.
                        Matlab.Execute("CG.BDC = CG.B * inv(full(CG.D)) * CG.B';");
                        Matlab.Execute("CG.BDC = sparse(CG.BDC);");
                        Matlab.Execute("CG.BDC(abs(CG.BDC) < (CG.th / CG.iter)) = 0;");
                        Matlab.Execute("CG.H = CG.A - sparse(CG.BDC);");

                        iterinfo.numSetZeroBlock = -1;
                        iterinfo.numNonZeroBlock = -1;
                        iterinfo.numAddIgnrBlock = -1;
                        iterinfo.usedMemoryByte  = -1;
                        iterinfo.time1           = DateTime.UtcNow;
                        iterinfos.Add(iterinfo);

                        System.Console.WriteLine(" - {0:000} : makezero {1,5}, nonzero {2,5}, numIgnMul {3,7}, numRemvAtoms {4,3}, {5,5:0.00} sec, {6} mb, {7}x{7}"
                                                 , iter
                                                 , iterinfo.numSetZeroBlock
                                                 , iterinfo.numNonZeroBlock
                                                 , iterinfo.numAddIgnrBlock
                                                 , iterinfo.numAtomsRemoved
                                                 , iterinfo.compSec
                                                 , iterinfo.usedMemoryByte / (1024 * 1024)
                                                 , (idxkeep.Length * 3)
                                                 );
                    }
                    Matrix CG_H = Matlab.GetMatrix("CG.H");
                    CGH = new HessMatrixDense {
                        hess = CG_H
                    };
                }

                return(new CGetHessCoarseResiIterImpl
                {
                    iterinfos = iterinfos,
                    H = CGH,
                });
            }
Beispiel #4
0
        public static bool GetHessAnmSelfTest()
        {
            if (HDebug.Selftest() == false)
            {
                return(true);
            }

            string pdbpath = @"C:\Users\htna\svn\htnasvn_htna\VisualStudioSolutions\Library2\HTLib2.Bioinfo\Bioinfo.Data\pdb\1MJC.pdb";

            if (HFile.Exists(pdbpath) == false)
            {
                return(false);
            }

            Pdb pdb = Pdb.FromFile(pdbpath);

            for (int i = 0; i < pdb.atoms.Length; i++)
            {
                HDebug.Assert(pdb.atoms[0].altLoc == pdb.atoms[i].altLoc);
                HDebug.Assert(pdb.atoms[0].chainID == pdb.atoms[i].chainID);
            }
            List <Vector> coords = pdb.atoms.ListCoord();
            double        cutoff = 13;

            Matlab.Execute("clear");
            Matlab.PutMatrix("x", Matrix.FromRowVectorList(coords).ToArray());
            Matlab.PutValue("cutoffR", cutoff);
            Matlab.Execute(@"%  function cx = contactsNew(x, cutoffR)
                                % Contact matrix within cutoff distance.
                                % Author: Guang Song
                                % New: 10/25/2006
                                %

                                %n = size(x,1); 
                                % Method 1: slow
                                %for i=1:n
                                %  center = x(i,:);
                                %  distSqr(:,i) = sum((x-center(ones(n,1),:)).^2,2);
                                %end
                                %cx = sparse(distSqr<=cutoffR^2);

                                % Method 2: fast! about 28 times faster when array size is 659x3
                                %tot = zeros(n,n);
                                %for i=1:3
                                %  xi = x(:,ones(n,1)*i);
                                %  %tmp = (xi - xi.').^2;
                                %  %tot = tot + tmp;
                                %  tot = tot +  (xi - xi.').^2;
                                %end
                                %cx = sparse(tot<=cutoffR^2);

                                % Method 3: this implementation is the shortest! but sligtly slower than 
                                % method 2
                                %xn = x(:,:,ones(n,1)); % create n copy x
                                %xnp = permute(xn,[3,2,1]);
                                %tot = sum((xn-xnp).^2,2); % sum along x, y, z
                                %cx = sparse(permute(tot,[1,3,2])<=cutoffR^2);
                                % put it into one line like below actually slows it down. Don't do that.
                                %cx =  sparse(permute(sum((xn-permute(xn,[3,2,1])).^2,2),[1,3,2])<=cutoffR^2);

                                %Method 4: using function pdist, which I just know
                                % this one line implementation is even faster. 2 times than method 2.
                                cx = sparse(squareform(pdist(x)<=cutoffR));
                            ");
            Matlab.Execute(@"%  function [anm,xij,normxij] = baseHess(x,cx)
                                % Basic Hessian Matrix
                                % Author: Guang Song
                                % Created: Feb 23, 2005
                                % Rev: 11/09/06
                                %
                                % cx is the contact map. Also with gama info (new! 02/23/05)
                                dim = size(x,1);
                                nx = x(:,:,ones(1,dim));
                                xij = permute(nx,[3,1,2]) - permute(nx,[1,3,2]); % xj - xi for any i j
                                normxij = squareform(pdist(x)) + diag(ones(1,dim)); % + diag part added to avoid divided by zero.
                                anm = zeros(3*dim,3*dim);
                                for i=1:3
                                  for j=1:3
                                     tmp = xij(:,:,i).*xij(:,:,j).*cx./normxij.^2;
                                     tmp = diag(sum(tmp)) - tmp;
                                     anm(i:3:3*dim,j:3:3*dim) = tmp;
                                  end
                                end

                                % if dR is scalar, then dR = 1, back to GNM.
                                %if abs(i-j) == 1 % virtual bonds. should stay around 3.81 A
                                %   K33 = K33*100;
                                %end 
                                anm = (anm+anm')/2; % make sure return matrix is symmetric (fix numeric error)
                            ");
            Matrix anm_gsong = Matlab.GetMatrix("anm");

            Matlab.Execute("clear;");

            Matrix anm = GetHessAnm(coords.ToArray(), cutoff);

            if (anm_gsong.RowSize != anm.RowSize)
            {
                HDebug.Assert(false); return(false);
            }
            if (anm_gsong.ColSize != anm.ColSize)
            {
                HDebug.Assert(false); return(false);
            }

            for (int c = 0; c < anm.ColSize; c++)
            {
                for (int r = 0; r < anm.RowSize; r++)
                {
                    if (Math.Abs(anm_gsong[c, r] - anm[c, r]) >= 0.00000001)
                    {
                        HDebug.Assert(false); return(false);
                    }
                }
            }

            return(true);
        }
Beispiel #5
0
            public Mode[] GetModesMassReduced(bool delhess, int?numModeReturn, Dictionary <string, object> secs)
            {
                HessMatrix       mwhess_ = GetHessMassWeighted(delhess);
                IMatrix <double> mwhess  = mwhess_;
                bool             bsparse = (mwhess_ is HessMatrixSparse);

                Mode[] modes;
                using (new Matlab.NamedLock(""))
                {
                    string msg = "";
                    {
                        if (bsparse)
                        {
                            Matlab.PutSparseMatrix("V", mwhess_.GetMatrixSparse(), 3, 3);
                        }
                        else
                        {
                            Matlab.PutMatrix("V", ref mwhess, true, true);
                        }
                    }
                    msg += Matlab.Execute("tic;");
                    msg += Matlab.Execute("V = (V+V')/2;                   "); // make symmetric
                    {                                                          // eigen-decomposition
                        if (bsparse)
                        {
                            if (numModeReturn != null)
                            {
                                int    numeig = numModeReturn.Value;
                                string cmd    = "eigs(V," + numeig + ",'sm')";
                                msg += Matlab.Execute("[V,D] = " + cmd + ";        ");
                            }
                            else
                            {
                                msg += Matlab.Execute("[V,D] = eig(full(V));         ");
                            }
                        }
                        else
                        {
                            msg += Matlab.Execute("[V,D] = eig(V);         ");
                        }
                    }
                    msg += Matlab.Execute("tm=toc;                         ");
                    if (secs != null)
                    {
                        int    numcore = Matlab.Environment.NumCores;
                        double tm      = Matlab.GetValue("tm");
                        secs.Clear();
                        secs.Add("num cores", numcore);
                        secs.Add("secs multi-threaded", tm);
                        secs.Add("secs estimated single-threaded", tm * Math.Sqrt(numcore));
                        /// x=[]; for i=1:20; tic; H=rand(100*i); [V,D]=eig(H+H'); xx=toc; x=[x;i,xx]; fprintf('%d, %f\n',i,xx); end; x
                        ///
                        /// http://www.mathworks.com/help/matlab/ref/matlabwindows.html
                        ///     run matlab in single-thread: matlab -nodesktop -singleCompThread
                        ///                    multi-thread: matlab -nodesktop
                        ///
                        /// my computer, single thread: cst1={0.0038,0.0106,0.0277,0.0606,0.1062,0.1600,0.2448,0.3483,0.4963,0.6740,0.9399,1.1530,1.4568,1.7902,2.1794,2.6387,3.0510,3.6241,4.2203,4.8914};
                        ///                    2 cores: cst2={0.0045,0.0098,0.0252,0.0435,0.0784,0.1203,0.1734,0.2382,0.3316,0.4381,0.5544,0.6969,1.0170,1.1677,1.4386,1.7165,2.0246,2.4121,2.8124,3.2775};
                        ///                      scale: (cst1.cst2)/(cst1.cst1)              = 0.663824
                        ///                     approx: (cst1.cst2)/(cst1.cst1)*Sqrt[2.2222] = 0.989566
                        /// my computer, single thread: cst1={0.0073,0.0158,0.0287,0.0573,0.0998,0.1580,0.2377,0.3439,0.4811,0.6612,0.8738,1.0974,1.4033,1.7649,2.1764,2.6505,3.1142,3.5791,4.1910,4.8849};
                        ///                    2 cores: cst2={0.0085,0.0114,0.0250,0.0475,0.0719,0.1191,0.1702,0.2395,0.3179,0.4319,0.5638,0.7582,0.9454,1.1526,1.4428,1.7518,2.0291,2.4517,2.8200,3.3090};
                        ///                      scale: (cst1.cst2)/(cst1.cst1)              = 0.671237
                        ///                     approx: (cst1.cst2)/(cst1.cst1)*Sqrt[2.2222] = 1.00062
                        /// ts4-stat   , singhe thread: cst1={0.0048,0.0213,0.0641,0.1111,0.1560,0.2013,0.3307,0.3860,0.4213,0.8433,1.0184,1.3060,1.9358,2.2699,2.1718,3.0149,3.1081,4.3594,5.0356,5.5260};
                        ///                   12 cores: cst2={0.2368,0.0614,0.0235,0.1321,0.0574,0.0829,0.1078,0.1558,0.1949,0.3229,0.4507,0.3883,0.4685,0.6249,0.6835,0.8998,0.9674,1.1851,1.3415,1.6266};
                        ///                      scale: (cst1.cst2)/(cst1.cst1)                 = 0.286778
                        ///                             (cst1.cst2)/(cst1.cst1)*Sqrt[12*1.1111] = 1.04716
                        /// ts4-stat   , singhe thread: cst1={0.0138,0.0215,0.0522,0.0930,0.1783,0.2240,0.2583,0.4054,0.4603,0.9036,0.9239,1.5220,1.9443,2.1042,2.3583,3.0208,3.5507,3.8810,3.6943,6.2085};
                        ///                   12 cores: cst2={0.1648,0.1429,0.1647,0.0358,0.0561,0.0837,0.1101,0.1525,0.2084,0.2680,0.3359,0.4525,0.4775,0.7065,0.6691,0.9564,1.0898,1.2259,1.2926,1.5879};
                        ///                      scale: (cst1.cst2)/(cst1.cst1)          = 0.294706
                        ///                             (cst1.cst2)/(cst1.cst1)*Sqrt[12] = 1.02089
                        /// ts4-stat   , singhe thread: cst1={0.0126,0.0183,0.0476,0.0890,0.1353,0.1821,0.2265,0.3079,0.4551,0.5703,1.0009,1.2175,1.5922,1.8805,2.1991,2.3096,3.7680,3.7538,3.9216,5.2899,5.6737,7.0783,8.8045,9.0091,9.9658,11.6888,12.8311,14.4933,17.2462,17.5660};
                        ///                   12 cores: cst2={0.0690,0.0117,0.0275,0.0523,0.0819,0.1071,0.1684,0.1984,0.1974,0.2659,0.3305,0.4080,0.4951,0.7089,0.9068,0.7936,1.2632,1.0708,1.3187,1.6106,1.7216,2.1114,2.8249,2.7840,2.8259,3.3394,4.3092,4.2708,5.3358,5.7479};
                        ///                      scale: (cst1.cst2)/(cst1.cst1)          = 0.311008
                        ///                             (cst1.cst2)/(cst1.cst1)*Sqrt[12]  = 1.07736
                        /// Therefore, the speedup using multi-core could be sqrt(#core)
                    }
                    msg += Matlab.Execute("D = diag(D);                    ");

                    if (msg.Trim() != "")
                    {
                        System.Console.WriteLine();
                        bool domanual = HConsole.ReadValue <bool>("possibly failed. Will you do ((('V = (V+V')/2;[V,D] = eig(V);D = diag(D);))) manually ?", false, null, false, true);
                        if (domanual)
                        {
                            Matlab.Clear();
                            Matlab.PutMatrix("V", ref mwhess, true, true);
                            System.Console.WriteLine("cleaning working-space and copying V in matlab are done.");
                            System.Console.WriteLine("do V = (V+V')/2; [V,D]=eig(V); D=diag(D);");
                            while (HConsole.ReadValue <bool>("V and D are ready to use in matlab?", false, null, false, true) == false)
                            {
                                ;
                            }
                            //string path_V = HConsole.ReadValue<string>("path V.mat", @"C:\temp\V.mat", null, false, true);
                            //Matlab.Execute("clear;");
                            //Matlab.PutMatrix("V", ref mwhess, true, true);
                            //Matlab.Execute(string.Format("save('{0}', '-V7.3');", path_V));
                            //while(HConsole.ReadValue<bool>("ready for VD.mat containing V and D?", false, null, false, true) == false) ;
                            //string path_VD = HConsole.ReadValue<string>("path VD.mat", @"C:\temp\VD.mat", null, false, true);
                            //Matlab.Execute(string.Format("load '{0}';", path_V));
                        }
                    }

                    if (numModeReturn != null)
                    {
                        Matlab.PutValue("nmode", numModeReturn.Value);
                        Matlab.Execute("V = V(:,1:nmode);");
                        Matlab.Execute("D = D(1:nmode);");
                    }
                    MatrixByRowCol V = Matlab.GetMatrix("V", MatrixByRowCol.Zeros, true, true);
                    Vector         D = Matlab.GetVector("D");
                    HDebug.Assert(V.RowSize == D.Size);
                    modes = new Mode[D.Size];
                    for (int i = 0; i < D.Size; i++)
                    {
                        Vector eigvec = V.GetColVector(i);
                        double eigval = D[i];
                        modes[i] = new Mode
                        {
                            th     = i,
                            eigval = eigval,
                            eigvec = eigvec,
                        };
                    }
                    V = null;
                }
                System.GC.Collect();

                modes.UpdateMassReduced(mass.ToArray());

                return(modes);
            }
        public static HessMatrixDense GetHessCoarseBlkmat(HessMatrix hess, IList <int> idx_heavy, string invopt = "inv")
        {
            /// Hess = [ HH HL ] = [ A B ]
            ///        [ LH LL ]   [ C D ]
            ///
            /// Hess_HH = HH - HL * LL^-1 * LH
            ///         = A  - B  *  D^-1 * C

            Matrix hess_HH;

            using (new Matlab.NamedLock(""))
            {
                Matlab.Clear();
                if (hess is HessMatrixSparse)
                {
                    Matlab.PutSparseMatrix("H", hess.GetMatrixSparse(), 3, 3);
                }
                else
                {
                    Matlab.PutMatrix("H", hess, true);
                }

                Matlab.Execute("H = (H + H')/2;");

                int[] idx0 = new int[idx_heavy.Count * 3];
                for (int i = 0; i < idx_heavy.Count; i++)
                {
                    idx0[i * 3 + 0] = idx_heavy[i] * 3 + 0;
                    idx0[i * 3 + 1] = idx_heavy[i] * 3 + 1;
                    idx0[i * 3 + 2] = idx_heavy[i] * 3 + 2;
                }
                Matlab.PutVector("idx0", idx0);
                Matlab.Execute("idx0 = idx0+1;");
                Matlab.PutValue("idx1", hess.ColSize);
                Matlab.Execute("idx1 = setdiff(1:idx1, idx0)';");
                HDebug.Assert(Matlab.GetValueInt("length(union(idx0,idx1))") == hess.ColSize);

                Matlab.Execute("A = full(H(idx0,idx0));");
                Matlab.Execute("B =      H(idx0,idx1) ;");
                Matlab.Execute("C =      H(idx1,idx0) ;");
                Matlab.Execute("D = full(H(idx1,idx1));");
                Matlab.Execute("clear H;");

                object linvopt = null;
                switch (invopt)
                {
                case  "B/D":
                    Matlab.Execute("bhess = A -(B / D)* C;");
                    break;

                case  "inv":
                    Matlab.Execute("D =  inv(D);");
                    Matlab.Execute("bhess = A - B * D * C;");
                    break;

                case "pinv":
                    Matlab.Execute("D = pinv(D);");
                    Matlab.Execute("bhess = A - B * D * C;");
                    break;

                case "_eig":
                    bool bCheckInv = false;
                    if (bCheckInv)
                    {
                        Matlab.Execute("Dbak = D;");
                    }
                    Matlab.Execute("[D,DD] = eig(D);");
                    if (HDebug.False)
                    {
                        Matlab.Execute("DD(abs(DD)<" + linvopt + ") = 0;");
                        Matlab.Execute("DD = pinv(DD);");
                    }
                    else
                    {
                        Matlab.Execute("DD = diag(DD);");
                        Matlab.Execute("DDidx = abs(DD)<" + linvopt + ";");
                        Matlab.Execute("DD = 1./DD;");
                        Matlab.Execute("DD(DDidx) = 0;");
                        Matlab.Execute("DD = diag(DD);");
                        Matlab.Execute("clear DDidx;");
                    }
                    Matlab.Execute("D = D * DD * D';");
                    if (bCheckInv)
                    {
                        double err0 = Matlab.GetValue("max(max(abs(eye(size(D)) - Dbak * D)))");
                    }
                    if (bCheckInv)
                    {
                        double err1 = Matlab.GetValue("max(max(abs(eye(size(D)) - D * Dbak)))");
                    }
                    if (bCheckInv)
                    {
                        Matlab.Execute("clear Dbak;");
                    }
                    Matlab.Execute("clear DD;");
                    Matlab.Execute("bhess = A - B * D * C;");
                    break;

                default:
                {
                    if (invopt.StartsWith("eig(threshold:") && invopt.EndsWith(")"))
                    {
                        // ex: "eig(threshold:0.000000001)"
                        linvopt = invopt.Replace("eig(threshold:", "").Replace(")", "");
                        linvopt = double.Parse(linvopt as string);
                        goto case "_eig";
                    }
                }
                    throw new HException();
                }

                Matlab.Execute("clear A; clear B; clear C; clear D;");
                Matlab.Execute("bhess = (bhess + bhess')/2;");
                hess_HH = Matlab.GetMatrix("bhess", Matrix.Zeros, true);

                Matlab.Clear();
            }
            return(new HessMatrixDense {
                hess = hess_HH
            });
        }
Beispiel #7
0
        public static bool GetHessGnmSelfTest()
        {
            if (HDebug.Selftest() == false)
            {
                return(true);
            }

            Pdb pdb = Pdb.FromPdbid("1MJC");

            for (int i = 0; i < pdb.atoms.Length; i++)
            {
                HDebug.Assert(pdb.atoms[0].altLoc == pdb.atoms[i].altLoc);
                HDebug.Assert(pdb.atoms[0].chainID == pdb.atoms[i].chainID);
            }
            List <Vector> coords = pdb.atoms.ListCoord();
            double        cutoff = 13;

            Matlab.Execute("clear");
            Matlab.PutMatrix("x", MatrixByArr.FromRowVectorList(coords).ToArray());
            Matlab.PutValue("cutoffR", cutoff);
            Matlab.Execute(@"%  function cx = contactsNew(x, cutoffR)
                                % Contact matrix within cutoff distance.
                                % Author: Guang Song
                                % New: 10/25/2006
                                %

                                %n = size(x,1); 
                                % Method 1: slow
                                %for i=1:n
                                %  center = x(i,:);
                                %  distSqr(:,i) = sum((x-center(ones(n,1),:)).^2,2);
                                %end
                                %cx = sparse(distSqr<=cutoffR^2);

                                % Method 2: fast! about 28 times faster when array size is 659x3
                                %tot = zeros(n,n);
                                %for i=1:3
                                %  xi = x(:,ones(n,1)*i);
                                %  %tmp = (xi - xi.').^2;
                                %  %tot = tot + tmp;
                                %  tot = tot +  (xi - xi.').^2;
                                %end
                                %cx = sparse(tot<=cutoffR^2);

                                % Method 3: this implementation is the shortest! but sligtly slower than 
                                % method 2
                                %xn = x(:,:,ones(n,1)); % create n copy x
                                %xnp = permute(xn,[3,2,1]);
                                %tot = sum((xn-xnp).^2,2); % sum along x, y, z
                                %cx = sparse(permute(tot,[1,3,2])<=cutoffR^2);
                                % put it into one line like below actually slows it down. Don't do that.
                                %cx =  sparse(permute(sum((xn-permute(xn,[3,2,1])).^2,2),[1,3,2])<=cutoffR^2);

                                %Method 4: using function pdist, which I just know
                                % this one line implementation is even faster. 2 times than method 2.
                                cx = sparse(squareform(pdist(x)<=cutoffR));
                            ");
            Matlab.Execute(@"%  function gnm = kirchhoff(cx)
                                % the returned gnm provide the kirchhoff matrix
                                % cx is the contact map.
                                % Guang Song
                                % 11/09/06
                                gnm = diag(sum(cx)) - cx;
                            ");
            Matlab.Execute("gnm = full(gnm);");
            Matrix gnm_gsong = Matlab.GetMatrix("gnm");

            Matlab.Execute("clear;");

            Matrix gnm = GetHessGnm(coords.ToArray(), cutoff);

            if (gnm_gsong.RowSize != gnm.RowSize)
            {
                HDebug.Assert(false); return(false);
            }
            if (gnm_gsong.ColSize != gnm.ColSize)
            {
                HDebug.Assert(false); return(false);
            }

            for (int c = 0; c < gnm.ColSize; c++)
            {
                for (int r = 0; r < gnm.RowSize; r++)
                {
                    if (Math.Abs(gnm_gsong[c, r] - gnm[c, r]) >= 0.00000001)
                    {
                        HDebug.Assert(false); return(false);
                    }
                }
            }

            return(true);
        }