Example #1
0
            public static double Corr(Vector bfactor1, Vector bfactor2, bool ignore_nan = false)
            {
                double hcorr = HMath.HCorr(bfactor1, bfactor2, ignore_nan);

                if (HDebug.IsDebuggerAttached)
                {
                    double corr = double.NaN;
                    using (new Matlab.NamedLock("CORR"))
                    {
                        Matlab.Clear("CORR");
                        Matlab.PutVector("CORR.bfactor1", bfactor1);
                        Matlab.PutVector("CORR.bfactor2", bfactor2);
                        if (ignore_nan)
                        {
                            Matlab.Execute("CORR.idxnan = isnan(CORR.bfactor1) | isnan(CORR.bfactor2);");
                            Matlab.Execute("CORR.bfactor1 = CORR.bfactor1(~CORR.idxnan);");
                            Matlab.Execute("CORR.bfactor2 = CORR.bfactor2(~CORR.idxnan);");
                        }
                        if (Matlab.GetValueInt("min(size(CORR.bfactor1))") != 0)
                        {
                            corr = Matlab.GetValue("corr(CORR.bfactor1, CORR.bfactor2)");
                        }
                        Matlab.Clear("CORR");
                    }
                    if ((double.IsNaN(hcorr) && double.IsNaN(corr)) == false)
                    {
                        HDebug.AssertTolerance(0.00000001, hcorr - corr);
                    }
                    //HDebug.ToDo("use HMath.HCorr(...) instead");
                }
                return(hcorr);
            }
Example #2
0
        /// Score = nwalign(Seq1,Seq2)
        /// [Score, Alignment] = nwalign(Seq1,Seq2)
        /// [Score, Alignment, Start] = nwalign(Seq1,Seq2)
        ///
        /// Example:
        ///     [Score, Alignment, Start] = nwalign('VSPAGMASGYD','IPGKASYD')
        ///
        ///     Score = 7.3333
        ///     Alignment = 3x11 char
        ///        ['VSPAGMASGYD']
        ///        [': | | || ||']
        ///        ['I-P-GKAS-YD']
        ///     Start = 2x1 double
        ///        [1]
        ///        [1]

        public static NwalignInfo Nwalign(string Seq1, string Seq2)
        {
            Seq1 = Seq1.Trim();
            Seq2 = Seq2.Trim();
            double Score = Matlab.GetValue(string.Format("nwalign('{0}', '{1}')", Seq1, Seq2));

            return(new NwalignInfo
            {
                Seq1 = Seq1,
                Seq2 = Seq2,
                Score = Score
            });
        }
Example #3
0
        public static double SimFluc(IList <Mode> modes1, IList <Mode> modes2)
        {
            /// need to confirm again...
            ///

            Matrix M1 = modes1.ToModeMatrix();
            Vector V1 = modes1.ToArray().ListEigval();
            Matrix M2 = modes2.ToModeMatrix();
            Vector V2 = modes2.ToArray().ListEigval();

            using (new Matlab.NamedLock("SimFluc"))
            {
                Matlab.Execute("");
                Matlab.Execute("clear");
                Matlab.PutMatrix("MM1", M1); Matlab.PutVector("VV1", V1);
                Matlab.PutMatrix("MM2", M2); Matlab.PutVector("VV2", V2);

                Matlab.Execute("[U2,S2,V2] = svd(MM2);");
                Matlab.Execute("U2 = U2(:, 1:length(VV2));");
                Matlab.Execute("S2 = S2(1:length(VV2), :);");
                Matlab.Execute("invSV2 = diag(1./diag(S2))*V2';");
                // covariance of mode2
                Matlab.Execute("C2 = invSV2*diag(1./VV2)*invSV2';");
                Matlab.Execute("C2 = (C2 + C2')/2;");
                // covariance of mode 1 projected onto U2
                Matlab.Execute("C1 = U2'*(MM1*diag(VV1)*MM1')*U2;");
                Matlab.Execute("C1 = pinv((C1 + C1')/2);");
                Matlab.Execute("C1 = (C1 + C1')/2;");
                // compute the fluctuation similarity
                Matlab.Execute("detInvC1 = det(inv(C1));");
                Matlab.Execute("detInvC2 = det(inv(C2));");
                Matlab.Execute("detInvC1InvC2 = det((inv(C1)+inv(C2))/2);");
                Matlab.Execute("simfluc0 = ((detInvC1*detInvC2)^0.25);");
                Matlab.Execute("simfluc1 = (detInvC1InvC2)^0.5;");
                Matlab.Execute("simfluc = simfluc0 / simfluc1;");

                double simfluc = Matlab.GetValue("simfluc");
                Matlab.Execute("clear");
                return(simfluc);
            }
        }
            private static HessMatrix GetHessCoarseResiIterImpl_Matlab_IterLowerTri_Get_BInvDC
                (HessMatrix A
                , HessMatrix C
                , HessMatrix D
                , bool process_disp_console
                , string[] options
                , double?thld_BinvDC = null
                , bool parallel      = false
                )
            {
                if (options == null)
                {
                    options = new string[0];
                }

                HessMatrix            B_invD_C;
                Dictionary <int, int> Cbr_CCbr = new Dictionary <int, int>();
                List <int>            CCbr_Cbr = new List <int>();

                foreach (ValueTuple <int, int, MatrixByArr> bc_br_bval in C.EnumBlocks())
                {
                    int Cbr = bc_br_bval.Item2;
                    if (Cbr_CCbr.ContainsKey(Cbr) == false)
                    {
                        HDebug.Assert(Cbr_CCbr.Count == CCbr_Cbr.Count);
                        int CCbr = Cbr_CCbr.Count;
                        Cbr_CCbr.Add(Cbr, CCbr);
                        CCbr_Cbr.Add(Cbr);
                        HDebug.Assert(CCbr_Cbr[CCbr] == Cbr);
                    }
                }

                HessMatrix CC = C.Zeros(C.ColSize, Cbr_CCbr.Count * 3);

                {
                    Action <ValueTuple <int, int, MatrixByArr> > func = delegate(ValueTuple <int, int, MatrixByArr> bc_br_bval)
                    {
                        int Cbc = bc_br_bval.Item1; int CCbc = Cbc;
                        int Cbr = bc_br_bval.Item2; int CCbr = Cbr_CCbr[Cbr];
                        var bval = bc_br_bval.Item3;
                        lock (CC)
                            CC.SetBlock(CCbc, CCbr, bval);
                    };

                    if (parallel)
                    {
                        Parallel.ForEach(C.EnumBlocks(), func);
                    }
                    else
                    {
                        foreach (var bc_br_bval in C.EnumBlocks())
                        {
                            func(bc_br_bval);
                        }
                    }
                }
                if (process_disp_console)
                {
                    System.Console.Write("squeezeC({0,6}->{1,6} blk), ", C.RowBlockSize, CC.RowBlockSize);
                }
                {
                    /// If a diagonal element of D is null, that row and column should be empty.
                    /// This assume that the atom is removed. In this case, the removed diagonal block
                    /// is replace as the 3x3 identity matrix.
                    ///
                    ///  [B1  0] [ A 0 ]^-1 [C1 C2 C3] = [B1  0] [ A^-1  0    ] [C1 C2 C3]
                    ///  [B2  0] [ 0 I ]    [ 0  0  0]   [B2  0] [ 0     I^-1 ] [ 0  0  0]
                    ///  [B3  0]                         [B3  0]
                    ///                                = [B1.invA  0] [C1 C2 C3]
                    ///                                  [B2.invA  0] [ 0  0  0]
                    ///                                  [B3.invA  0]
                    ///                                = [B1.invA.C1  B1.invA.C2  B1.invA.C3]
                    ///                                  [B2.invA.C1  B2.invA.C2  B2.invA.C3]
                    ///                                  [B3.invA.C1  B3.invA.C2  B3.invA.C3]
                    ///
                    {
                        //HDebug.Exception(D.ColBlockSize == D.RowBlockSize);
                        for (int bi = 0; bi < D.ColBlockSize; bi++)
                        {
                            if (D.HasBlock(bi, bi) == true)
                            {
                                continue;
                            }
                            //for(int bc=0; bc< D.ColBlockSize; bc++) HDebug.Exception( D.HasBlock(bc, bi) == false);
                            //for(int br=0; br< D.RowBlockSize; br++) HDebug.Exception( D.HasBlock(bi, br) == false);
                            //for(int br=0; br<CC.RowBlockSize; br++) HDebug.Exception(CC.HasBlock(bi, br) == false);
                            D.SetBlock(bi, bi, new double[3, 3] {
                                { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }
                            });
                        }
                    }

                    HessMatrix BB_invDD_CC;
                    using (new Matlab.NamedLock(""))
                    {
                        Matlab.Execute("clear;");   if (process_disp_console)
                        {
                            System.Console.Write("matlab(");
                        }
                        Matlab.PutMatrix("C", CC);  if (process_disp_console)
                        {
                            System.Console.Write("C");                                                  //Matlab.PutSparseMatrix("C", CC.GetMatrixSparse(), 3, 3);
                        }
                        Matlab.PutMatrix("D", D);   if (process_disp_console)
                        {
                            System.Console.Write("D");
                        }

                        // Matlab.Execute("BinvDC = (C' / D) * C;");
                        {
                            if (options.Contains("pinv(D)"))
                            {
                                Matlab.Execute("BinvDC = C' * pinv(D) * C;");
                            }
                            if (options.Contains("/D -> pinv(D)"))
                            {
                                string msg = Matlab.Execute("BinvDC = (C' / D) * C;", true);
                                if (msg != "")
                                {
                                    Matlab.Execute("BinvDC = C' * pinv(D) * C;");
                                }
                            }
                            else if (options.Contains("/D"))
                            {
                                Matlab.Execute("BinvDC = (C' / D) * C;");
                            }
                            else
                            {
                                Matlab.Execute("BinvDC = (C' / D) * C;");
                            }
                        }
                        if (process_disp_console)
                        {
                            System.Console.Write("X");
                        }

                        //Matrix BBinvDDCC = Matlab.GetMatrix("BinvDC", true);
                        if (thld_BinvDC != null)
                        {
                            Matlab.Execute("BinvDC(find(BinvDC < " + thld_BinvDC.ToString() + ")) = 0;");
                        }
                        if (Matlab.GetValue("nnz(BinvDC)/numel(BinvDC)") > 0.5 || HDebug.True)
                        {
                            Func <int, int, HessMatrix> Zeros = delegate(int colsize, int rowsize)
                            {
                                return(HessMatrixDense.ZerosDense(colsize, rowsize));
                            };
                            BB_invDD_CC = Matlab.GetMatrix("BinvDC", Zeros, true);
                            if (process_disp_console)
                            {
                                System.Console.Write("Y), ");
                            }
                        }
                        else
                        {
                            Matlab.Execute("[i,j,s] = find(sparse(BinvDC));");
                            TVector <int>    listi = Matlab.GetVectorLargeInt("i", true);
                            TVector <int>    listj = Matlab.GetVectorLargeInt("j", true);
                            TVector <double> lists = Matlab.GetVectorLarge("s", true);
                            int colsize            = Matlab.GetValueInt("size(BinvDC,1)");
                            int rowsize            = Matlab.GetValueInt("size(BinvDC,2)");

                            Dictionary <ValueTuple <int, int>, MatrixByArr> lst_bc_br_bval = new Dictionary <ValueTuple <int, int>, MatrixByArr>();
                            for (long i = 0; i < listi.SizeLong; i++)
                            {
                                int    c = listi[i] - 1; int bc = c / 3; int ic = c % 3;
                                int    r = listj[i] - 1; int br = r / 3; int ir = r % 3;
                                double v = lists[i];
                                ValueTuple <int, int> bc_br = new ValueTuple <int, int>(bc, br);
                                if (lst_bc_br_bval.ContainsKey(bc_br) == false)
                                {
                                    lst_bc_br_bval.Add(bc_br, new double[3, 3]);
                                }
                                lst_bc_br_bval[bc_br][ic, ir] = v;
                            }

                            //  Matrix BBinvDDCC = Matrix.Zeros(colsize, rowsize);
                            //  for(int i=0; i<listi.Length; i++)
                            //      BBinvDDCC[listi[i]-1, listj[i]-1] = lists[i];
                            //  //GC.Collect(0);
                            BB_invDD_CC = D.Zeros(colsize, rowsize);
                            foreach (var bc_br_bval in lst_bc_br_bval)
                            {
                                int bc   = bc_br_bval.Key.Item1;
                                int br   = bc_br_bval.Key.Item2;
                                var bval = bc_br_bval.Value;
                                BB_invDD_CC.SetBlock(bc, br, bval);
                            }
                            if (process_disp_console)
                            {
                                System.Console.Write("Z), ");
                            }

                            if (HDebug.IsDebuggerAttached)
                            {
                                for (int i = 0; i < listi.Size; i++)
                                {
                                    int    c = listi[i] - 1;
                                    int    r = listj[i] - 1;
                                    double v = lists[i];
                                    HDebug.Assert(BB_invDD_CC[c, r] == v);
                                }
                            }
                        }
                        Matlab.Execute("clear;");
                    }
                    //GC.Collect(0);

                    B_invD_C = A.Zeros(C.RowSize, C.RowSize);
                    {
                        //  for(int bcc=0; bcc<CCbr_Cbr.Count; bcc++)
                        //  {
                        //      int bc = CCbr_Cbr[bcc];
                        //      for(int brr=0; brr<CCbr_Cbr.Count; brr++)
                        //      {
                        //          int br   = CCbr_Cbr[brr];
                        //          HDebug.Assert(B_invD_C.HasBlock(bc, br) == false);
                        //          if(BB_invDD_CC.HasBlock(bcc, brr) == false)
                        //              continue;
                        //          var bval = BB_invDD_CC.GetBlock(bcc, brr);
                        //          B_invD_C.SetBlock(bc, br, bval);
                        //          HDebug.Exception(A.HasBlock(bc, bc));
                        //          HDebug.Exception(A.HasBlock(br, br));
                        //      }
                        //  }
                        Action <ValueTuple <int, int, MatrixByArr> > func = delegate(ValueTuple <int, int, MatrixByArr> bcc_brr_bval)
                        {
                            int bcc  = bcc_brr_bval.Item1;
                            int brr  = bcc_brr_bval.Item2;
                            var bval = bcc_brr_bval.Item3;

                            int bc = CCbr_Cbr[bcc];
                            int br = CCbr_Cbr[brr];
                            //lock(B_invD_C)
                            B_invD_C.SetBlockLock(bc, br, bval);
                        };

                        if (parallel)
                        {
                            Parallel.ForEach(BB_invDD_CC.EnumBlocks(), func);
                        }
                        else
                        {
                            foreach (var bcc_brr_bval in BB_invDD_CC.EnumBlocks())
                            {
                                func(bcc_brr_bval);
                            }
                        }
                    }
                }
                GC.Collect(0);
                return(B_invD_C);
            }
Example #5
0
        public void __MinimizeTNM(List <ForceField.IForceField> frcflds)
        {
            HDebug.Assert(false);
            // do not use this, because not finished yet

            Graph <Universe.Atom[], Universe.Bond> univ_flexgraph = this.BuildFlexibilityGraph();
            List <Universe.RotableInfo>            univ_rotinfos  = this.GetRotableInfo(univ_flexgraph);

            Vector[] coords      = this.GetCoords();
            double   tor_normInf = double.PositiveInfinity;

            //double maxRotAngle = 0.1;
            Vector[]    forces          = null;
            MatrixByArr hessian         = null;
            double      forces_normsInf = 1;
            int         iter            = 0;
            double      scale           = 1;

            this._SaveCoordsToPdb(iter.ToString("0000") + ".pdb", coords);

            while (true)
            {
                iter++;
                forces  = this.GetVectorsZero();
                hessian = new double[size * 3, size *3];
                Dictionary <string, object> cache = new Dictionary <string, object>();
                double energy = this.GetPotential(frcflds, coords, ref forces, ref hessian, cache);
                forces_normsInf = (new Vectors(forces)).NormsInf().ToArray().Max();
                //System.Console.WriteLine("iter {0:###}: frcnrminf {1}, energy {2}, scale {3}", iter, forces_normsInf, energy, scale);

                //if(forces_normsInf < 0.001)
                //{
                //    break;
                //}
                Vector torz    = null;
                double maxcarz = 1;
                Vector car     = null;
                //double
                using (new Matlab.NamedLock("TEST"))
                {
                    MatrixByArr H = hessian;
                    MatrixByArr J = Paper.TNM.GetJ(this, this.GetCoords(), univ_rotinfos);
                    Vector      m = this.GetMasses(3);
                    Matlab.PutVector("TEST.F", Vector.FromBlockvector(forces));
                    Matlab.PutMatrix("TEST.J", J);
                    Matlab.PutMatrix("TEST.H", H);
                    Matlab.PutVector("TEST.M", m);
                    Matlab.Execute("TEST.M = diag(TEST.M);");
                    Matlab.Execute("TEST.JMJ = TEST.J' * TEST.M * TEST.J;");
                    Matlab.Execute("TEST.JHJ = TEST.J' * TEST.H * TEST.J;");
                    // (J' H J) tor = J' F
                    // (V' D V) tor = J' F  <= (V,D) are (eigvec,eigval) of generalized eigenvalue problem with (A = JHJ, B = JMJ)
                    // tor = inv(V' D V) J' F
                    Matlab.Execute("[TEST.V, TEST.D] = eig(TEST.JHJ, TEST.JMJ);");
                    //Matlab.Execute("TEST.zidx = 3:end;");

                    Matlab.Execute("TEST.invJHJ  = TEST.V * pinv(TEST.D ) * TEST.V';");
                    Matlab.Execute("TEST.tor  = TEST.invJHJ * TEST.J' * TEST.F;");
                    Matlab.Execute("TEST.car  = TEST.J * TEST.tor;");
                    car = Matlab.GetVector("TEST.car");

                    Matlab.Execute("[TEST.DS, TEST.DSI] = sort(abs(diag(TEST.D)));");
                    Matlab.Execute("TEST.zidx = TEST.DSI(6:end);");
                    Matlab.Execute("TEST.Dz = TEST.D;");
                    //Matlab.Execute("TEST.Dz(TEST.zidx,TEST.zidx) = 0;");
                    Matlab.Execute("TEST.invJHJz = TEST.V * pinv(TEST.Dz) * TEST.V';");
                    Matlab.Execute("TEST.torz = TEST.invJHJz * TEST.J' * TEST.F;");
                    Matlab.Execute("TEST.carz = TEST.J * TEST.torz;");
                    torz    = Matlab.GetVector("TEST.torz");
                    maxcarz = Matlab.GetValue("max(max(abs(TEST.carz)))");
                    scale   = 1;
                    if (maxcarz > 0.01)
                    {
                        scale = scale * 0.01 / maxcarz;
                    }
                    Matlab.Clear("TEST");
                };
                tor_normInf = torz.NormInf();
                double frcnrinf = car.ToArray().HAbs().Max();
                if (maxcarz < 0.001)
                {
                    break;
                }
                System.Console.WriteLine("iter {0:###}: frcnrminf {1}, tor(frcnrinf) {2}, energy {3}, scale {4}", iter, forces_normsInf, frcnrinf, energy, scale);

                HDebug.Assert(univ_rotinfos.Count == torz.Size);
                for (int i = 0; i < univ_rotinfos.Count; i++)
                {
                    Universe.RotableInfo rotinfo = univ_rotinfos[i];
                    Vector rotOrigin             = coords[rotinfo.bondedAtom.ID];
                    double rotAngle = torz[i] * scale;   // (maxRotAngle / tor_normInf);
                    if (rotAngle == 0)
                    {
                        continue;
                    }
                    Vector      rotAxis = coords[rotinfo.bond.atoms[1].ID] - coords[rotinfo.bond.atoms[0].ID];
                    Quaternion  rot     = new Quaternion(rotAxis, rotAngle);
                    MatrixByArr rotMat  = rot.RotationMatrix;
                    foreach (Atom atom in rotinfo.rotAtoms)
                    {
                        int    id    = atom.ID;
                        Vector coord = rotMat * (coords[id] - rotOrigin) + rotOrigin;
                        coords[id] = coord;
                    }
                }
                this._SaveCoordsToPdb(iter.ToString("0000") + ".pdb", coords);
            }
        }
Example #6
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);
            }
Example #7
0
            public Mode[] GetRtbModes()
            {
                if (_rtbmodes == null)
                {
                    Matrix   eigvec;
                    double[] eigval;
                    using (new Matlab.NamedLock(""))
                    {     // solve [eigvec, eigval] = eig(PHP, PMP)
                        { // PMPih = 1/sqrt(PMP)        where "ih" stands for "Inverse Half" -1/2
                            Matlab.PutMatrix("PMP", PMP);
                            Matlab.Execute("PMP = (PMP + PMP')/2;");
                            Matlab.Execute("[PMPih.V, PMPih.D] = eig(PMP); PMPih.D = diag(PMPih.D);");
                            Matlab.Execute("PMPih.Dih = 1.0 ./ sqrt(PMPih.D);");    // PMPih.Dih = PMPih.D ^ -1/2
                            if (HDebug.IsDebuggerAttached)
                            {
                                double err = Matlab.GetValue("max(abs(1 - PMPih.D .* PMPih.Dih .* PMPih.Dih))");
                                HDebug.AssertTolerance(0.00000001, err);
                            }
                            Matlab.Execute("PMPih = PMPih.V * diag(PMPih.Dih) * PMPih.V';");
                            if (HDebug.IsDebuggerAttached)
                            {
                                double err = Matlab.GetValue("max(max(abs(eye(size(PMP)) - (PMP * PMPih * PMPih))))");
                                HDebug.AssertTolerance(0.00000001, err);
                            }
                            Matlab.Execute("clear PMP;");
                        }

                        {   // to solve [eigvec, eigval] = eig(PHP, PMP)
                            // 1. H = PMP^-1/2 * PHP * PMP^-1/2
                            // 2. [V,D] = eig(H)
                            // 3. V = PMP^-1/2 * V
                            Matlab.PutMatrix("PHP", PHP);                                                       // put RTB Hess
                            Matlab.Execute("PHP = (PHP + PHP')/2;");
                            Matlab.Execute("PHP = PMPih * PHP * PMPih; PHP = (PHP + PHP')/2;");                 // mass-weighted Hess
                            Matlab.Execute("[V,D] = eig(PHP); D=diag(D);                        clear PHP;");   // mass-weighted modes, eigenvalues
                            Matlab.Execute("V = PMPih * V;                                      clear PMPih;"); // mass-reduced modes
                        }

                        eigvec = Matlab.GetMatrix("V");
                        eigval = Matlab.GetVector("D");
                        Matlab.Execute("clear;");
                    }

                    List <Mode> modes;
                    {   // sort by eigenvalues
                        int[] idx = eigval.HIdxSorted();
                        modes = new List <Mode>(idx.Length);
                        for (int i = 0; i < eigval.Length; i++)
                        {
                            Mode mode = new Mode
                            {
                                th     = i + 1,
                                eigval = eigval[idx[i]],
                                eigvec = eigvec.GetColVector(idx[i]),
                            };
                            modes.Add(mode);
                        }
                    }

                    _rtbmodes = modes.ToArray();
                }
                return(_rtbmodes);
            }
Example #8
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);
            }
Example #9
0
            public static Mode[] GetModeByTorsional(HessMatrix hessian, Vector masses, Matrix J
                                                    , HPack <Matrix> optoutJMJ = null // J' M J
                                                    , HPack <Matrix> optoutJM  = null // J' M
                                                    , Func <Matrix, Tuple <Matrix, Vector> > fnEigSymm = null
                                                    , Func <Matrix, Matrix, Matrix, Matrix> fnMul      = null
                                                    )
            {
                string opt;

                opt = "eig(JMJ^-1/2 * JHJ * JMJ^-1/2)";
                //opt = "mwhess->tor->eig(H)->cart->mrmode";
                if ((fnEigSymm != null) && (fnMul != null))
                {
                    opt = "fn-" + opt;
                }
                switch (opt)
                {
                case "mwhess->tor->eig(H)->cart->mrmode":
                    /// http://www.lct.jussieu.fr/manuels/Gaussian03/g_whitepap/vib.htm
                    /// http://www.lct.jussieu.fr/manuels/Gaussian03/g_whitepap/vib/vib.pdf
                    /// does not work properly.
                    HDebug.Assert(false);
                    using (new Matlab.NamedLock("GetModeByTor"))
                    {
                        int n = J.ColSize;
                        int m = J.RowSize;

                        //Matrix M = massmat; // univ.GetMassMatrix(3);
                        Vector[] toreigvecs = new Vector[m];
                        Vector[] tormodes   = new Vector[m];
                        double[] toreigvals = new double[m];
                        Mode[]   modes      = new Mode[m];
                        {
                            Matlab.Clear("GetModeByTor");
                            Matlab.PutMatrix("GetModeByTor.H", hessian);
                            Matlab.PutMatrix("GetModeByTor.J", J);
                            //Matlab.PutMatrix("GetModeByTor.M", M);
                            Matlab.PutVector("GetModeByTor.m", masses);                         // ex: m = [1,2,...,n]
                            Matlab.Execute("GetModeByTor.m3 = kron(GetModeByTor.m,[1;1;1]);");  // ex: m3 = [1,1,1,2,2,2,...,n,n,n]
                            Matlab.Execute("GetModeByTor.M = diag(GetModeByTor.m3);");
                            Matlab.Execute("GetModeByTor.m = diag(1 ./ sqrt(diag(GetModeByTor.M)));");
                            Matlab.Execute("GetModeByTor.mHm = GetModeByTor.m * GetModeByTor.H * GetModeByTor.m;");
                            Matlab.Execute("GetModeByTor.JmHmJ = GetModeByTor.J' * GetModeByTor.mHm * GetModeByTor.J;");
                            Matlab.Execute("[GetModeByTor.V, GetModeByTor.D] = eig(GetModeByTor.JmHmJ);");
                            Matlab.Execute("GetModeByTor.JV = GetModeByTor.m * GetModeByTor.J * GetModeByTor.V;");
                            Matrix V  = Matlab.GetMatrix("GetModeByTor.V");
                            Vector D  = Matlab.GetVector("diag(GetModeByTor.D)");
                            Matrix JV = Matlab.GetMatrix("GetModeByTor.JV");
                            Matlab.Clear("GetModeByTor");
                            for (int i = 0; i < m; i++)
                            {
                                toreigvecs[i]   = V.GetColVector(i);
                                toreigvals[i]   = D[i];
                                tormodes[i]     = JV.GetColVector(i);
                                modes[i]        = new Mode();
                                modes[i].eigval = toreigvals[i];
                                modes[i].eigvec = tormodes[i];
                                modes[i].th     = i;
                            }
                        }
                        return(modes);
                    }

                case "eig(JMJ^-1/2 * JHJ * JMJ^-1/2)":
                    /// Solve the problem of using eng(H,M).
                    ///
                    /// eig(H,M) => H.v = M.v.l
                    ///             H.(M^-1/2 . M^1/2).v = (M^1/2 . M^1/2).v.l
                    ///             M^-1/2 . H.(M^-1/2 . M^1/2).v = M^1/2 .v.l
                    ///             (M^-1/2 . H . M^-1/2) . (M^1/2.v) = (M^1/2.v).l
                    ///             (M^-1/2 . H . M^-1/2) . w = w.l
                    ///       where (M^1/2.v) = w
                    ///             v = M^-1/2 . w
                    ///       where M = V . D . V'
                    ///             M^-1/2 = V . (1/sqrt(D)) . V'
                    ///             M^-1/2 . M^-1/2 . M = (V . (1/sqrt(D)) . V') . (V . (1/sqrt(D)) . V') . (V . D . V')
                    ///                                 = V . (1/sqrt(D)) . (1/sqrt(D)) . D . V'
                    ///                                 = V . I . V'
                    ///                                 = I
                    using (new Matlab.NamedLock("GetModeByTor"))
                    {
                        int n = J.ColSize;
                        int m = J.RowSize;

                        //Matrix M = massmat; // univ.GetMassMatrix(3);
                        Vector[] toreigvecs = new Vector[m];
                        Vector[] tormodes   = new Vector[m];
                        double[] toreigvals = new double[m];
                        Mode[]   modes      = new Mode[m];
                        {
                            Matlab.Clear("GetModeByTor");
                            Matlab.PutMatrix("GetModeByTor.J", J.ToArray(), true);
                            //Matlab.PutMatrix("GetModeByTor.M", M      , true);
                            //Matlab.PutMatrix("GetModeByTor.H", hessian, true);
                            Matlab.PutSparseMatrix("GetModeByTor.H", hessian.GetMatrixSparse(), 3, 3);
                            if (HDebug.IsDebuggerAttached && hessian.ColSize < 10000)
                            {
                                Matlab.PutMatrix("GetModeByTor.Htest", hessian.ToArray(), true);
                                double dHessErr = Matlab.GetValue("max(max(abs(GetModeByTor.H - GetModeByTor.Htest)))");
                                Matlab.Execute("clear GetModeByTor.Htest");
                                HDebug.Assert(dHessErr == 0);
                            }
                            Matlab.PutVector("GetModeByTor.m", masses);                         // ex: m = [1,2,...,n]
                            Matlab.Execute("GetModeByTor.m3 = kron(GetModeByTor.m,[1;1;1]);");  // ex: m3 = [1,1,1,2,2,2,...,n,n,n]
                            Matlab.Execute("GetModeByTor.M = diag(GetModeByTor.m3);");

                            Matlab.Execute("GetModeByTor.JMJ = GetModeByTor.J' * GetModeByTor.M * GetModeByTor.J;");
                            Matlab.Execute("GetModeByTor.JHJ = GetModeByTor.J' * GetModeByTor.H * GetModeByTor.J;");
                            Matlab.Execute("[GetModeByTor.V, GetModeByTor.D] = eig(GetModeByTor.JMJ);");
                            Matlab.Execute("GetModeByTor.jmj = GetModeByTor.V * diag(1 ./ sqrt(diag(GetModeByTor.D))) * GetModeByTor.V';"); // jmj = sqrt(JMJ)
                            //Matlab.Execute("max(max(abs(JMJ*jmj*jmj - eye(size(JMJ)))));"); // for checking
                            //Matlab.Execute("max(max(abs(jmj*JMJ*jmj - eye(size(JMJ)))));"); // for checking
                            //Matlab.Execute("max(max(abs(jmj*jmj*JMJ - eye(size(JMJ)))));"); // for checking

                            Matlab.Execute("[GetModeByTor.V, GetModeByTor.D] = eig(GetModeByTor.jmj * GetModeByTor.JHJ * GetModeByTor.jmj);");
                            Matlab.Execute("GetModeByTor.D = diag(GetModeByTor.D);");
                            Matlab.Execute("GetModeByTor.V = GetModeByTor.jmj * GetModeByTor.V;");
                            Matlab.Execute("GetModeByTor.JV = GetModeByTor.J * GetModeByTor.V;");
                            Matrix V  = Matlab.GetMatrix("GetModeByTor.V", true);
                            Vector D  = Matlab.GetVector("GetModeByTor.D");
                            Matrix JV = Matlab.GetMatrix("GetModeByTor.JV", true);
                            if (optoutJMJ != null)
                            {
                                optoutJMJ.value = Matlab.GetMatrix("GetModeByTor.JMJ", true);
                            }
                            if (optoutJM != null)
                            {
                                optoutJM.value = Matlab.GetMatrix("GetModeByTor.J' * GetModeByTor.M", true);
                            }
                            Matlab.Clear("GetModeByTor");
                            for (int i = 0; i < m; i++)
                            {
                                toreigvecs[i]   = V.GetColVector(i);
                                toreigvals[i]   = D[i];
                                tormodes[i]     = JV.GetColVector(i);
                                modes[i]        = new Mode();
                                modes[i].eigval = toreigvals[i];
                                modes[i].eigvec = tormodes[i];
                                modes[i].th     = i;
                            }
                        }
                        return(modes);
                    }

                case "fn-eig(JMJ^-1/2 * JHJ * JMJ^-1/2)":
                    /// Solve the problem of using eng(H,M).
                    ///
                    /// eig(H,M) => H.v = M.v.l
                    ///             H.(M^-1/2 . M^1/2).v = (M^1/2 . M^1/2).v.l
                    ///             M^-1/2 . H.(M^-1/2 . M^1/2).v = M^1/2 .v.l
                    ///             (M^-1/2 . H . M^-1/2) . (M^1/2.v) = (M^1/2.v).l
                    ///             (M^-1/2 . H . M^-1/2) . w = w.l
                    ///       where (M^1/2.v) = w
                    ///             v = M^-1/2 . w
                    ///       where M = V . D . V'
                    ///             M^-1/2 = V . (1/sqrt(D)) . V'
                    ///             M^-1/2 . M^-1/2 . M = (V . (1/sqrt(D)) . V') . (V . (1/sqrt(D)) . V') . (V . D . V')
                    ///                                 = V . (1/sqrt(D)) . (1/sqrt(D)) . D . V'
                    ///                                 = V . I . V'
                    ///                                 = I
                {
                    int n = J.ColSize;
                    int m = J.RowSize;

                    //Matrix M = massmat; // univ.GetMassMatrix(3);
                    Vector[] toreigvecs = new Vector[m];
                    Vector[] tormodes   = new Vector[m];
                    double[] toreigvals = new double[m];
                    Mode[]   modes      = new Mode[m];
                    {
                        Matrix H = hessian; HDebug.Assert(hessian.ColSize == hessian.RowSize);
                        Matrix M = Matrix.Zeros(hessian.ColSize, hessian.RowSize); HDebug.Assert(3 * masses.Size == M.ColSize, M.ColSize == M.RowSize);
                        for (int i = 0; i < M.ColSize; i++)
                        {
                            M[i, i] = masses[i / 3];
                        }
                        Matrix Jt = J.Tr();

                        Matrix JMJ = fnMul(Jt, M, J);       // JMJ = J' * M * J
                        Matrix JHJ = fnMul(Jt, H, J);       // JHJ = J' * H * J
                        Matrix V; Vector D; {               // [V, D] = eig(JMJ)
                            var VD = fnEigSymm(JMJ);
                            V = VD.Item1;
                            D = VD.Item2;
                        }
                        Matrix jmj; {                       // jmj = sqrt(JMJ)
                            Vector isD = new double[D.Size];
                            for (int i = 0; i < isD.Size; i++)
                            {
                                isD[i] = 1 / Math.Sqrt(D[i]);
                            }
                            jmj = fnMul(V, LinAlg.Diag(isD), V.Tr());
                        }
                        {                                   // [V, D] = eig(jmj * JHJ * jmj)
                            Matrix jmj_JHJ_jmj = fnMul(jmj, JHJ, jmj);
                            var    VD          = fnEigSymm(jmj_JHJ_jmj);
                            V = VD.Item1;
                            D = VD.Item2;
                        }
                        V = fnMul(jmj, V, null);            // V = jmj * V
                        Matrix JV = fnMul(J, V, null);      // JV = J * V
                        if (optoutJMJ != null)
                        {
                            optoutJMJ.value = JMJ;
                        }
                        if (optoutJM != null)
                        {
                            optoutJM.value = fnMul(Jt, M, null);     // J' * M
                        }
                        for (int i = 0; i < m; i++)
                        {
                            toreigvecs[i]   = V.GetColVector(i);
                            toreigvals[i]   = D[i];
                            tormodes[i]     = JV.GetColVector(i);
                            modes[i]        = new Mode();
                            modes[i].eigval = toreigvals[i];
                            modes[i].eigvec = tormodes[i];
                            modes[i].th     = i;
                        }
                    }
                    //if(Debug.IsDebuggerAttached)
                    //{
                    //    Mode[] tmodes = GetModeByTorsional(hessian, masses, J);
                    //    Debug.Assert(modes.Length ==  tmodes.Length);
                    //    for(int i=0; i<modes.Length; i++)
                    //    {
                    //        Debug.AssertTolerance(0.00001, modes[i].eigval - tmodes[i].eigval);
                    //        Debug.AssertTolerance(0.00001, modes[i].eigvec - tmodes[i].eigvec);
                    //    }
                    //}
                    return(modes);
                }

                case "eig(JHJ,JMJ)":
                    /// Generalized eigendecomposition does not guarantee that the eigenvalue be normalized.
                    /// This becomes a problem when a B-factor (determined using eig(H,M)) is compared with another B-factor (determined using eig(M^-1/2 H M^-1/2)).
                    /// This problem is being solved using case "eig(JMJ^-1/2 * JHJ * JMJ^-1/2)"
                    using (new Matlab.NamedLock("GetModeByTor"))
                    {
                        int n = J.ColSize;
                        int m = J.RowSize;

                        //Matrix M = massmat; // univ.GetMassMatrix(3);
                        Matrix JMJ;
                        {
                            Matlab.PutMatrix("GetModeByTor.J", J);
                            //Matlab.PutMatrix("GetModeByTor.M", M);
                            Matlab.PutVector("GetModeByTor.m", masses);                         // ex: m = [1,2,...,n]
                            Matlab.Execute("GetModeByTor.m3 = kron(GetModeByTor.m,[1;1;1]);");  // ex: m3 = [1,1,1,2,2,2,...,n,n,n]
                            Matlab.Execute("GetModeByTor.M = diag(GetModeByTor.m3);");
                            Matlab.Execute("GetModeByTor.JMJ = GetModeByTor.J' * GetModeByTor.M * GetModeByTor.J;");
                            JMJ = Matlab.GetMatrix("GetModeByTor.JMJ");
                            Matlab.Clear("GetModeByTor");
                        }
                        Matrix JHJ;
                        {
                            Matlab.PutMatrix("GetModeByTor.J", J);
                            Matlab.PutMatrix("GetModeByTor.H", hessian);
                            Matlab.Execute("GetModeByTor.JHJ = GetModeByTor.J' * GetModeByTor.H * GetModeByTor.J;");
                            JHJ = Matlab.GetMatrix("GetModeByTor.JHJ");
                            Matlab.Clear("GetModeByTor");
                        }
                        Vector[] toreigvecs = new Vector[m];
                        Vector[] tormodes   = new Vector[m];
                        double[] toreigvals = new double[m];
                        Mode[]   modes      = new Mode[m];
                        {
                            Matlab.PutMatrix("GetModeByTor.JHJ", JHJ);
                            Matlab.PutMatrix("GetModeByTor.JMJ", JMJ);
                            Matlab.PutMatrix("GetModeByTor.J", J);
                            Matlab.Execute("[GetModeByTor.V, GetModeByTor.D] = eig(GetModeByTor.JHJ, GetModeByTor.JMJ);");
                            Matlab.Execute("GetModeByTor.D = diag(GetModeByTor.D);");
                            Matlab.Execute("GetModeByTor.JV = GetModeByTor.J * GetModeByTor.V;");
                            Matrix V  = Matlab.GetMatrix("GetModeByTor.V");
                            Vector D  = Matlab.GetVector("GetModeByTor.D");
                            Matrix JV = Matlab.GetMatrix("GetModeByTor.JV");
                            Matlab.Clear("GetModeByTor");
                            for (int i = 0; i < m; i++)
                            {
                                toreigvecs[i]   = V.GetColVector(i);
                                toreigvals[i]   = D[i];
                                tormodes[i]     = JV.GetColVector(i);
                                modes[i]        = new Mode();
                                modes[i].eigval = toreigvals[i];
                                modes[i].eigvec = tormodes[i];
                                modes[i].th     = i;
                            }
                        }
                        return(modes);
                    }
                }
                return(null);
            }
Example #10
0
        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
            });
        }