Пример #1
0
            public static HessMatrix GetHessElec(IList <Vector> coords, IEnumerable <Universe.Nonbonded14> nonbonded14s, HessMatrix hessian, double ee)
            {
                int size = coords.Count;

                if (hessian == null)
                {
                    hessian = HessMatrixSparse.ZerosSparse(size * 3, size * 3);
                }

                foreach (Universe.Nonbonded14 nonbonded14 in nonbonded14s)
                {
                    Universe.Atom atom0 = nonbonded14.atoms[0];
                    Universe.Atom atom1 = nonbonded14.atoms[1];
                    int           idx0  = atom0.ID; if (coords[idx0] == null)
                    {
                        continue;
                    }
                    int idx1 = atom1.ID; if (coords[idx1] == null)
                    {
                        continue;
                    }
                    double pch0 = atom0.Charge;
                    double pch1 = atom1.Charge;
                    TermElec(coords, pch0, pch1, ee, hessian, idx0, idx1);
                    TermElec(coords, pch0, pch1, ee, hessian, idx1, idx0);
                }

                return(hessian);
            }
Пример #2
0
            static public void MV(HessMatrixSparse M, Vector V, Vector mv, Vector bvec, Vector bmv)
            {
                HDebug.Exception(V.Size == M.RowSize);
                HDebug.Exception(mv.Size == M.ColSize); //Vector mv = new double[M.ColSize];
                HDebug.Exception(bvec.Size == 3);       //Vector bvec = new double[3];
                HDebug.Exception(bmv.Size == 3);        //Vector bmv = new double[3];
                foreach (ValueTuple <int, int, MatrixByArr> bc_br_bval in M.EnumBlocks())
                {
                    int bc   = bc_br_bval.Item1;
                    int br   = bc_br_bval.Item2;
                    var bmat = bc_br_bval.Item3;
                    bvec[0] = V[br * 3 + 0];
                    bvec[1] = V[br * 3 + 1];
                    bvec[2] = V[br * 3 + 2];
                    HTLib2.LinAlg.MV(bmat, bvec, bmv);
                    mv[bc * 3 + 0] += bmv[0];
                    mv[bc * 3 + 1] += bmv[1];
                    mv[bc * 3 + 2] += bmv[2];
                }

                if (HDebug.Selftest())
                {
                    Matlab.Clear();
                    Matlab.PutSparseMatrix("M", M.GetMatrixSparse(), 3, 3);
                    Matlab.PutVector("V", V);
                    Matlab.Execute("MV = M*V;");
                    Matlab.PutVector("MV1", mv);
                    Vector err     = Matlab.GetVector("MV-MV1");
                    double err_max = err.ToArray().HAbs().Max();
                    HDebug.Assert(err_max < 0.00000001);
                }
            }
Пример #3
0
            public static HessMatrix GetHessAngle
                (IList <Vector> coords, IEnumerable <Universe.Angle> angles, bool useUreybrad, double?K_theta, double?K_ub, HessMatrix hessian
                , Matrix pwspr
                , Action <Universe.Atom, Vector, Universe.Atom, Vector, Universe.Atom, Vector, double, double> collector
                )
            {
                int size = coords.Count;

                if (hessian == null)
                {
                    hessian = HessMatrixSparse.ZerosSparse(size * 3, size * 3);
                }

                foreach (Universe.Angle angle in angles)
                {
                    int idx0 = angle.atoms[0].ID; if (coords[idx0] == null)
                    {
                        continue;
                    }
                    int idx1 = angle.atoms[1].ID; if (coords[idx1] == null)
                    {
                        continue;
                    }
                    int idx2 = angle.atoms[2].ID; if (coords[idx2] == null)
                    {
                        continue;
                    }
                    double lK_theta = (K_theta != null)? K_theta.Value : angle.Ktheta;
                    HDebug.Assert(lK_theta >= 0);
                    SecondTerm(coords, lK_theta, hessian, idx0, idx1, idx2);

                    double lK_ub = 0;
                    if (useUreybrad)
                    {
                        HDebug.Assert(angle.Kub >= 0);
                        lK_ub = (K_ub != null)? K_ub.Value : angle.Kub;
                        FirstTerm(coords, lK_ub, hessian, idx0, idx2);

                        if (pwspr != null)
                        {
                            pwspr[idx0, idx1] += lK_ub;
                            pwspr[idx1, idx0] += lK_ub;
                        }
                    }

                    if (collector != null)
                    {
                        collector
                            (angle.atoms[0], coords[idx0]
                            , angle.atoms[1], coords[idx1]
                            , angle.atoms[2], coords[idx2]
                            , lK_theta, lK_ub);
                    }
                }

                return(hessian);
            }
Пример #4
0
            static public Vector MV(HessMatrixSparse M, Vector V)
            {
                Vector mv   = new double[M.ColSize];
                Vector bvec = new double[3];
                Vector bmv  = new double[3];

                MV(M, V, mv, bvec, bmv);
                return(mv);
            }
Пример #5
0
        public static HessMatrix GetMulImpl(ILinAlg ila, bool warning, params HessMatrix[] mats)
        {
            if (ila != null)
            {
                if (HDebug.Selftest())
                {
                    Matrix h0 = new double[, ] {
                        { 0, 1, 2, 3, 4, 5 }
                        , { 1, 2, 3, 4, 5, 6 }
                        , { 2, 3, 4, 5, 6, 7 }
                        , { 3, 4, 5, 6, 7, 8 }
                        , { 4, 5, 6, 7, 8, 9 }
                        , { 5, 6, 7, 8, 9, 0 }
                    };
                    HessMatrix h1 = HessMatrixDense.FromMatrix(h0);
                    HessMatrix h2 = HessMatrixSparse.FromMatrix(h0);
                    Matrix     t0 = Matrix.GetMul(Matrix.GetMul(h1, h1), h1);
                    {
                        Matrix t1 = GetMulImpl(ila, false, h1, h1, h1); double d1 = (t0 - t1).HAbsMax(); HDebug.Assert(0 == d1);
                        Matrix t2 = GetMulImpl(ila, false, h1, h1, h2); double d2 = (t0 - t2).HAbsMax(); HDebug.Assert(0 == d2);
                        Matrix t3 = GetMulImpl(ila, false, h1, h2, h1); double d3 = (t0 - t3).HAbsMax(); HDebug.Assert(0 == d3);
                        Matrix t4 = GetMulImpl(ila, false, h1, h2, h2); double d4 = (t0 - t4).HAbsMax(); HDebug.Assert(0 == d4);
                        Matrix t5 = GetMulImpl(ila, false, h2, h1, h1); double d5 = (t0 - t5).HAbsMax(); HDebug.Assert(0 == d5);
                        Matrix t6 = GetMulImpl(ila, false, h2, h1, h2); double d6 = (t0 - t6).HAbsMax(); HDebug.Assert(0 == d6);
                        Matrix t7 = GetMulImpl(ila, false, h2, h2, h1); double d7 = (t0 - t7).HAbsMax(); HDebug.Assert(0 == d7);
                        Matrix t8 = GetMulImpl(ila, false, h2, h2, h2); double d8 = (t0 - t8).HAbsMax(); HDebug.Assert(0 == d8);
                    }
                    {
                        Matrix t1 = GetMulImpl(null, false, h1, h1, h1); double d1 = (t0 - t1).HAbsMax(); HDebug.Assert(0 == d1);
                        Matrix t2 = GetMulImpl(null, false, h1, h1, h2); double d2 = (t0 - t2).HAbsMax(); HDebug.Assert(0 == d2);
                        Matrix t3 = GetMulImpl(null, false, h1, h2, h1); double d3 = (t0 - t3).HAbsMax(); HDebug.Assert(0 == d3);
                        Matrix t4 = GetMulImpl(null, false, h1, h2, h2); double d4 = (t0 - t4).HAbsMax(); HDebug.Assert(0 == d4);
                        Matrix t5 = GetMulImpl(null, false, h2, h1, h1); double d5 = (t0 - t5).HAbsMax(); HDebug.Assert(0 == d5);
                        Matrix t6 = GetMulImpl(null, false, h2, h1, h2); double d6 = (t0 - t6).HAbsMax(); HDebug.Assert(0 == d6);
                        Matrix t7 = GetMulImpl(null, false, h2, h2, h1); double d7 = (t0 - t7).HAbsMax(); HDebug.Assert(0 == d7);
                        Matrix t8 = GetMulImpl(null, false, h2, h2, h2); double d8 = (t0 - t8).HAbsMax(); HDebug.Assert(0 == d8);
                    }
                }
            }

            HessMatrix mul = null;

            foreach (HessMatrix mat in mats)
            {
                if (mul == null)
                {
                    mul = mat;
                }
                else
                {
                    mul = GetMulImpl(mul, mat, ila, warning);
                }
            }
            return(mul);
        }
Пример #6
0
            public static HessMatrix GetHessVdw(IList <Vector> coords, IEnumerable <Universe.Nonbonded14> nonbonded14s, double?Epsilon, string opt, HessMatrix hessian)
            {
                int size = coords.Count;

                if (hessian == null)
                {
                    hessian = HessMatrixSparse.ZerosSparse(size * 3, size * 3);
                }

                foreach (Universe.Nonbonded14 nonbonded14 in nonbonded14s)
                {
                    Universe.Atom atom0 = nonbonded14.atoms[0];
                    Universe.Atom atom1 = nonbonded14.atoms[1];
                    int           idx0  = atom0.ID; if (coords[idx0] == null)
                    {
                        continue;
                    }
                    int idx1 = atom1.ID; if (coords[idx1] == null)
                    {
                        continue;
                    }
                    double lEpsilon;
                    if (Epsilon != null)
                    {
                        lEpsilon = Epsilon.Value;
                    }
                    else
                    {
                        switch (opt)
                        {
                        case "gromacs":
                        {
                            var    nbndpar0 = atom0.ConvertGromacsToCharmm;
                            var    nbndpar1 = atom1.ConvertGromacsToCharmm;
                            double eps0_14  = nbndpar0.eps_14; eps0_14 = (double.IsNaN(eps0_14) == false) ? eps0_14 : nbndpar0.eps;
                            double eps1_14  = nbndpar1.eps_14; eps1_14 = (double.IsNaN(eps1_14) == false) ? eps1_14 : nbndpar1.eps;
                            lEpsilon = Math.Sqrt(eps0_14 * eps1_14);
                        }
                        break;

                        default:
                        {
                            double eps0_14 = atom0.eps_14; eps0_14 = (double.IsNaN(eps0_14) == false) ? eps0_14 : atom0.epsilon;
                            double eps1_14 = atom1.eps_14; eps1_14 = (double.IsNaN(eps1_14) == false) ? eps1_14 : atom1.epsilon;
                            lEpsilon = Math.Sqrt(eps0_14 * eps1_14);
                        }
                        break;
                        }
                    }
                    FourthTerm(coords, lEpsilon, hessian, idx0, idx1);
                    FourthTerm(coords, lEpsilon, hessian, idx1, idx0);
                }

                return(hessian);
            }
Пример #7
0
            public static HessMatrix GetHessImproper
                (IList <Vector> coords, IEnumerable <Universe.Improper> impropers, double?K_psi, HessMatrix hessian
                , Action <Universe.Atom, Vector, Universe.Atom, Vector, Universe.Atom, Vector, Universe.Atom, Vector, double, double> collector
                , bool useArnaud96 = false
                )
            {
                int size = coords.Count;

                if (hessian == null)
                {
                    hessian = HessMatrixSparse.ZerosSparse(size * 3, size * 3);
                }

                double sqrt2 = Math.Sqrt(2);

                foreach (Universe.Improper improper in impropers)
                {
                    int idx0 = improper.atoms[0].ID; if (coords[idx0] == null)
                    {
                        continue;
                    }
                    int idx1 = improper.atoms[1].ID; if (coords[idx1] == null)
                    {
                        continue;
                    }
                    int idx2 = improper.atoms[2].ID; if (coords[idx2] == null)
                    {
                        continue;
                    }
                    int idx3 = improper.atoms[3].ID; if (coords[idx3] == null)
                    {
                        continue;
                    }
                    double lK_psi = (K_psi != null)? K_psi.Value : improper.Kpsi;
                    double n      = sqrt2; // make (K_chi * n^2 / 2 == K_chi) when calling ThirdTermN(IList<Vector> caArray, double K_phi, double n)

                    lK_psi = lK_psi * 2;
                    n      = 1;
                    HDebug.Assert(lK_psi >= 0);
                    ThirdTermN(coords, lK_psi, n, hessian, idx0, idx1, idx2, idx3, useArnaud96: useArnaud96);

                    if (collector != null)
                    {
                        collector
                            (improper.atoms[0], coords[idx0]
                            , improper.atoms[1], coords[idx1]
                            , improper.atoms[2], coords[idx2]
                            , improper.atoms[3], coords[idx3]
                            , lK_psi, n);
                    }
                }

                return(hessian);
            }
Пример #8
0
            public static HessMatrix GetHessVdw(IList <Vector> coords, IEnumerable <Universe.AtomPack> pairs, double?Epsilon, string opt, HessMatrix hessian)
            {
                int size = coords.Count;

                if (hessian == null)
                {
                    hessian = HessMatrixSparse.ZerosSparse(size * 3, size * 3);
                }

                foreach (Universe.AtomPack pair in pairs)
                {
                    Universe.Atom atom0 = pair.atoms.First();
                    Universe.Atom atom1 = pair.atoms.Last();
                    int           idx0  = atom0.ID; if (coords[idx0] == null)
                    {
                        continue;
                    }
                    int idx1 = atom1.ID; if (coords[idx1] == null)
                    {
                        continue;
                    }
                    double lEpsilon;
                    if (Epsilon != null)
                    {
                        lEpsilon = Epsilon.Value;
                    }
                    else
                    {
                        switch (opt)
                        {
                        case "gromacs":
                        {
                            double eps0 = atom0.ConvertGromacsToCharmm.eps;
                            double eps1 = atom1.ConvertGromacsToCharmm.eps;
                            lEpsilon = Math.Sqrt(eps0 * eps1);
                        }
                        break;

                        default:
                        {
                            double eps0 = atom0.epsilon;
                            double eps1 = atom1.epsilon;
                            lEpsilon = Math.Sqrt(eps0 * eps1);
                        }
                        break;
                        }
                    }
                    FourthTerm(coords, lEpsilon, hessian, idx0, idx1);
                    FourthTerm(coords, lEpsilon, hessian, idx1, idx0);
                }

                return(hessian);
            }
Пример #9
0
 public IMatrixSparse <MatrixByArr> GetMatrixSparse()
 {
     if (this is HessMatrixSparse)
     {
         return((this as HessMatrixSparse).GetMatrixSparse());
     }
     if (this is HessMatrixDense)
     {
         return(HessMatrixSparse.FromMatrix(this).GetMatrixSparse());
     }
     if (this is HessMatrixLayeredArray)
     {
         return(this as IMatrixSparse <MatrixByArr>);
     }
     throw new NotImplementedException();
 }
Пример #10
0
            public static HessMatrix GetHessBond
                (IList <Vector> coords, IEnumerable <Universe.Bond> bonds, double?K_r, HessMatrix hessian, Matrix pwspr
                , Action <Universe.Atom, Vector, Universe.Atom, Vector, double> collector
                )
            {
                int size = coords.Count;

                if (hessian == null)
                {
                    hessian = HessMatrixSparse.ZerosSparse(size * 3, size * 3);
                }

                foreach (Universe.Bond bond in bonds)
                {
                    int idx0 = bond.atoms[0].ID; if (coords[idx0] == null)
                    {
                        continue;
                    }
                    int idx1 = bond.atoms[1].ID; if (coords[idx1] == null)
                    {
                        continue;
                    }
                    double lK_r = (K_r != null)? K_r.Value : bond.Kb;
                    HDebug.Assert(lK_r >= 0);
                    FirstTerm(coords, lK_r, hessian, idx0, idx1);

                    if (pwspr != null)
                    {
                        pwspr[idx0, idx1] += lK_r;
                        pwspr[idx1, idx0] += lK_r;
                    }

                    if (collector != null)
                    {
                        collector
                            (bond.atoms[0], coords[idx0]
                            , bond.atoms[1], coords[idx1]
                            , lK_r);
                    }
                }

                return(hessian);
            }
Пример #11
0
            public static HessMatrix GetHess(Universe univ)
            {
                Vector[] coords = univ.GetCoords();

                HessMatrix hessian_spr = HessMatrixSparse.ZerosSparse(univ.size * 3, univ.size * 3);

                Universe.Nonbondeds_v1 nonbondeds = new Universe.Nonbondeds_v1(univ.atoms, univ.size, 12);
                nonbondeds.UpdateNonbondeds(coords, 0);
                hessian_spr = STeM.GetHessBond(coords, univ.bonds, null, hessian: hessian_spr); HDebug.Verify(Hess.CheckHessDiag(hessian_spr, 0.000001, "non-computable exception while generating STeM hess_spr with bond"));
                hessian_spr = STeM.GetHessAngle(coords, univ.angles, true, null, null, hessian: hessian_spr); HDebug.Verify(Hess.CheckHessDiag(hessian_spr, 0.000001, "non-computable exception while generating STeM hess_spr with angle"));
                hessian_spr = STeM.GetHessImproper(coords, univ.impropers, null, hessian: hessian_spr); HDebug.Verify(Hess.CheckHessDiag(hessian_spr, 0.000001, "non-computable exception while generating STeM hess_spr with improper"));
                hessian_spr = STeM.GetHessDihedral(coords, univ.dihedrals, null, null, hessian: hessian_spr); HDebug.Verify(Hess.CheckHessDiag(hessian_spr, 0.000001, "non-computable exception while generating STeM hess_spr with dihedral"));
                hessian_spr = STeM.GetHessVdw(coords, univ.nonbonded14s.GetEnumerable(), null, null, hessian: hessian_spr); HDebug.Verify(Hess.CheckHessDiag(hessian_spr, 0.000001, "non-computable exception while generating STeM hess_spr with vdw14"));
                hessian_spr = STeM.GetHessElec(coords, univ.nonbonded14s.GetEnumerable(), hessian: hessian_spr); HDebug.Verify(Hess.CheckHessDiag(hessian_spr, 0.000001, "non-computable exception while generating STeM hess_spr with elec14"));
                hessian_spr = STeM.GetHessVdw(coords, nonbondeds.GetEnumerable(), null, null, hessian: hessian_spr); HDebug.Verify(Hess.CheckHessDiag(hessian_spr, 0.000001, "non-computable exception while generating STeM hess_spr with vdw"));
                hessian_spr = STeM.GetHessElec(coords, nonbondeds.GetEnumerable(), hessian: hessian_spr); HDebug.Verify(Hess.CheckHessDiag(hessian_spr, 0.000001, "non-computable exception while generating STeM hess_spr with elec"));
                //hessian_spr = GetHessSprElec(coords, nonbondeds                                   , hessian: hessian_spr); Debug.Verify(Hess.CheckHessDiag(hessian_spr));
                //hessian_spr = GetHessSprVdw(coords, nonbondeds                                    , hessian: hessian_spr); Debug.Verify(Hess.CheckHessDiag(hessian_spr));
                hessian_spr = Hess.CorrectHessDiag(hessian_spr);                                                           HDebug.Verify(Hess.CheckHessDiag(hessian_spr, 0.000001, "non-computable exception while generating STeM hess_spr"));

                return(hessian_spr);
            }
Пример #12
0
        public static HessMatrixSparse ZerosSparse(int colsize, int rowsize)
        {
            if (ZerosSparse_selftest)
            {
                ZerosSparse_selftest = false;
                HessMatrixSparse tmat  = ZerosSparse(300, 300);
                bool             bzero = true;
                for (int c = 0; c < tmat.ColSize; c++)
                {
                    for (int r = 0; r < tmat.ColSize; r++)
                    {
                        if (tmat[c, r] != 0)
                        {
                            bzero = false;
                        }
                    }
                }
                HDebug.Assert(bzero);
            }

            HessMatrixSparse mat = new HessMatrixSparse(colsize, rowsize);

            return(mat);
        }
                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
                    )
                {
                    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 = HessMatrixSparse.ZerosSparse(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 != null && options.Contains("pinv(D)"))
                                {
                                    string msg = Matlab.Execute("BinvDC = (C' / D) * C;", true);
                                    if (msg != "")
                                    {
                                        Matlab.Execute("BinvDC = C' * pinv(D) * C;");
                                    }
                                }
                                else
                                {
                                    Matlab.Execute("BinvDC = (C' / D) * C;");
                                }
                            }                                                                                       if (process_disp_console)
                            {
                                System.Console.Write("X");
                            }
                            /// » whos
                            ///   Name         Size                 Bytes  Class     Attributes
                            ///                                                                                 //   before compressing C matrix
                            ///   C         1359x507              5512104  double                               //   C         1359x1545            16797240  double
                            ///   CC        1359x507               198464  double    sparse                     //   CC        1359x1545              206768  double    sparse
                            ///   D         1359x1359            14775048  double                               //   D         1359x1359            14775048  double
                            ///   DD        1359x1359              979280  double    sparse                     //   DD        1359x1359              979280  double    sparse
                            ///   ans          1x1                      8  double
                            ///
                            /// » tic; for i=1:30; A=(C' / D) * C; end; toc         dense  * dense  * dense  => 8.839463 seconds. (win)
                            /// Elapsed time is 8.839463 seconds.
                            /// » tic; for i=1:30; AA=(CC' / DD) * CC; end; toc     sparse * sparse * sparse => 27.945534 seconds.
                            /// Elapsed time is 27.945534 seconds.
                            /// » tic; for i=1:30; AAA=(C' / DD) * C; end; toc      sparse * dense  * sparse => 29.136144 seconds.
                            /// Elapsed time is 29.136144 seconds.
                            /// »
                            /// » tic; for i=1:30; A=(C' / D) * C; end; toc         dense  * dense  * dense  => 8.469071 seconds. (win)
                            /// Elapsed time is 8.469071 seconds.
                            /// » tic; for i=1:30; AA=(CC' / DD) * CC; end; toc     sparse * sparse * sparse => 28.309953 seconds.
                            /// Elapsed time is 28.309953 seconds.
                            /// » tic; for i=1:30; AAA=(C' / DD) * C; end; toc      sparse * dense  * sparse => 28.586375 seconds.
                            /// Elapsed time is 28.586375 seconds.
                            //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)
                            {
                                double[,] arr = Matlab.GetMatrix("BinvDC", true);
                                BB_invDD_CC   = HessMatrixDense.FromMatrix(arr);
                                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 = HessMatrixSparse.ZerosSparse(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 = HessMatrixSparse.ZerosSparse(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.SetBlock(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);
                }
Пример #14
0
        public static HessMatrix GetHessAnm(IList <Vector> coords, IEnumerable <Tuple <int, int, double> > enumKij)
        {
            if (GetHessAnm_selftest)
            {
                GetHessAnm_selftest = false;
                Vector[] tcoords = new Vector[]
                {
                    new Vector(0, 0, 0),
                    new Vector(1, 0, 0),
                    new Vector(0, 2, 0),
                    new Vector(0, 0, 3),
                    new Vector(4, 5, 0),
                    new Vector(0, 6, 7),
                    new Vector(8, 0, 9),
                    new Vector(-1, -1, -1),
                };
                Matrix tKij = Matrix.Ones(8, 8);
                for (int i = 0; i < 8; i++)
                {
                    tKij[i, i] = 0;
                }
                HessMatrix hess0 = GetHessAnm_debug(tcoords, tKij);
                HessMatrix hess1 = GetHessAnm(tcoords, tKij.HEnumNonZeros());
                HDebug.Assert((hess0 - hess1).HAbsMax() == 0);
            }
            //Debug.Assert(AnmHessianSelfTest());

            int        n    = coords.Count;
            HessMatrix hess = null;

            if (n < 100)
            {
                hess = HessMatrixDense.ZerosDense(n * 3, n * 3);
            }
            else
            {
                hess = HessMatrixSparse.ZerosSparse(n * 3, n * 3);
            }
            int numset = 0;

            foreach (var kij in enumKij)
            {
                int    i    = kij.Item1;
                int    j    = kij.Item2;
                double k_ij = kij.Item3;
                {
                    if (i == j)
                    {
                        HDebug.Assert(k_ij == 0);
                        continue;
                    }
                    if (coords[j] == null)
                    {
                        continue;
                    }
                    Vector vec_ij  = coords[j] - coords[i];
                    Vector unit_ij = vec_ij.UnitVector();
                    HDebug.Assert(double.IsNaN(k_ij) == false);
                    if (k_ij == 0)
                    {
                        continue;
                    }
                    MatrixByArr hessij = new double[3, 3];
                    hessij[0, 0] = -k_ij * unit_ij[0] * unit_ij[0];
                    hessij[0, 1] = -k_ij * unit_ij[0] * unit_ij[1];
                    hessij[0, 2] = -k_ij * unit_ij[0] * unit_ij[2];
                    hessij[1, 0] = -k_ij * unit_ij[1] * unit_ij[0];
                    hessij[1, 1] = -k_ij * unit_ij[1] * unit_ij[1];
                    hessij[1, 2] = -k_ij * unit_ij[1] * unit_ij[2];
                    hessij[2, 0] = -k_ij * unit_ij[2] * unit_ij[0];
                    hessij[2, 1] = -k_ij * unit_ij[2] * unit_ij[1];
                    hessij[2, 2] = -k_ij * unit_ij[2] * unit_ij[2];
                    hess.SetBlock(i, j, hessij);
                    MatrixByArr hessii = hess.GetBlock(i, i) - hessij;
                    hess.SetBlock(i, i, hessii);
                    numset++;
                }
            }

            return(hess);
        }
Пример #15
0
            public static CTesthess ReadHess
                (Xyz xyz
                , string outputpath
                , Dictionary <string, string[]> optOutSource  // =null
                , Func <int, int, HessMatrix> HessMatrixZeros // =null
                )
            {
                int size = xyz.atoms.Length;

                #region format: output.txt
                ///      ######################################################################
                ///    ##########################################################################
                ///   ###                                                                      ###
                ///  ###            TINKER  ---  Software Tools for Molecular Design            ###
                ///  ##                                                                          ##
                ///  ##                        Version 6.2  February 2013                        ##
                ///  ##                                                                          ##
                ///  ##               Copyright (c)  Jay William Ponder  1990-2013               ##
                ///  ###                           All Rights Reserved                          ###
                ///   ###                                                                      ###
                ///    ##########################################################################
                ///      ######################################################################
                ///
                ///
                ///  Atoms with an Unusual Number of Attached Atoms :
                ///
                ///  Type           Atom Name      Atom Type       Expected    Found
                ///
                ///  Valence        1496-NR2           69              2         3
                ///  Valence        2438-FE           107              6         5
                ///
                ///  Diagonal Hessian Elements for Each Atom :
                ///
                ///       Atom                 X               Y               Z
                ///
                ///          1            1445.9830       1358.3447       1484.8642
                ///          2             212.9895        294.4584        604.5062
                ///          3             187.1986        751.6727        125.0336
                ///          4             813.4799        132.1743        151.5707
                ///        ...
                ///       2507             178.7277        479.7434        243.4103
                ///       2508             969.8813        977.2507       1845.6726
                ///       2509             390.1648        232.0577       1029.6844
                ///       2510             322.3674        337.8749        996.8230
                ///
                ///  Sum of Diagonal Hessian Elements :          5209042.9060
                ///
                ///  Hessian Matrix written to File :  test.hes
                #endregion
                Tuple <int, double, double, double>[] outDiagHessElems = new Tuple <int, double, double, double> [size];
                double?outSumDiagHessElem = null;
                string outHessMatFile     = null;
                string outHessFormat      = null;
                {
                    string step = "";
                    foreach (string _line in HFile.ReadLines(outputpath))
                    {
                        string line = _line.Trim();
                        if (line.Length == 0)
                        {
                            continue;
                        }
                        if (line.Trim().StartsWith("#"))
                        {
                            continue;
                        }
                        if (line.Contains(" :"))
                        {
                            if (line.Contains("Atoms with an Unusual Number of Attached Atoms"))
                            {
                                step = "";                  continue;
                            }
                            else if (line.Contains("Diagonal Hessian Elements for Each Atom"))
                            {
                                step = "hess diagonal";     continue;
                            }
                            else if (line.Contains("Sum of Diagonal Hessian Elements"))
                            {
                                step = "sum hess diagonal";
                            }
                            else if (line.Contains("Hessian Matrix written to File"))
                            {
                                step = "full hess file";
                            }
                            else if (line.Contains("Hessian Sparse Matrix written to File"))
                            {
                                step = "sparse hess file";
                            }
                            else if (line.Contains("Select Smaller Size for Sparse Hessian Matrix"))
                            {
                                continue;
                            }
                            else
                            {
                                HDebug.Assert(false);
                                continue;
                            }
                        }
                        switch (step)
                        {
                        case "":
                            continue;

                        case "hess diagonal":
                        {
                            string[] tokens = line.Split().HRemoveAll("");
                            if (tokens[0] == "Atom")
                            {
                                continue;
                            }
                            int    Atom = int.Parse(tokens[0]);         // ; if(   int.TryParse(tokens[0], out Atom) == false) continue;
                            double X    = double.Parse(tokens[1]);      // ; if(double.TryParse(tokens[1], out    X) == false) continue;
                            double Y    = double.Parse(tokens[2]);      // ; if(double.TryParse(tokens[2], out    Y) == false) continue;
                            double Z    = double.Parse(tokens[3]);      // ; if(double.TryParse(tokens[3], out    Z) == false) continue;
                            HDebug.Assert(outDiagHessElems[Atom - 1] == null);
                            outDiagHessElems[Atom - 1] = new Tuple <int, double, double, double>(Atom, X, Y, Z);
                        }
                            continue;

                        case "sum hess diagonal":
                        {
                            string[] tokens = line.Split().HRemoveAll("");
                            double   sum    = double.Parse(tokens.Last());    // if(double.TryParse(tokens.Last(), out sum) == false) continue;
                            outSumDiagHessElem = sum;
                        }
                            step = "";
                            continue;

                        case   "full hess file": outHessFormat = "full matrix"; goto case "hess file";

                        case "sparse hess file": outHessFormat = "sparse matrix"; goto case "hess file";

                        case "hess file":
                        {
                            string[] tokens         = line.Split().HRemoveAll("");
                            string   outputpath_dir = HFile.GetFileInfo(outputpath).Directory.FullName;
                            outHessMatFile = outputpath_dir + "\\" + tokens.Last();
                        }
                            step = "";
                            continue;

                        default:
                            HDebug.Assert(false);
                            step = "";
                            continue;
                        }
                    }
                }
                #region Format: test.hes
                /// Diagonal Hessian Elements  (3 per Atom)
                ///
                ///   1445.9830   1358.3447   1484.8642    212.9895    294.4584    604.5062
                ///    187.1986    751.6727    125.0336    813.4799    132.1743    151.5707
                ///   1167.7472   1188.3459   1162.5475    268.8291    498.0188    143.2438
                ///   ...
                /// Off-diagonal Hessian Elements for Atom     1 X
                ///     23.0878     14.6380   -214.0545     96.9308   -186.7740   -205.1460
                ///   -208.7035    -28.9630   -788.9124     39.6748    126.4491   -190.5074
                ///   ...
                /// Off-diagonal Hessian Elements for Atom     1 Y
                ///    -64.1616     97.2697   -292.3813    264.1922   -184.4701   -728.8687
                ///   -109.9103     15.4168   -152.5717    -11.7733     18.8369   -188.4875
                ///   ...
                /// Off-diagonal Hessian Elements for Atom     1 Z
                ///   -155.9409    219.8782   -610.0622    -10.0041    -62.8209   -156.1112
                ///     77.0829    -14.2127   -166.0525     53.1834    -97.4207   -347.9315
                ///   ...
                /// Off-diagonal Hessian Elements for Atom     2 X
                ///   -106.5166    185.8395     19.7546    -10.0094     25.8072     -8.1335
                ///     35.8501    -64.8320      3.8761    -13.8893      9.4266      0.1312
                ///   ...
                ///
                ///   ...
                ///
                /// Off-diagonal Hessian Elements for Atom  2508 X
                ///    488.4590    -69.2721   -338.4824   -155.1656    253.3732   -297.4214
                ///   -164.8301   -191.3769
                /// Off-diagonal Hessian Elements for Atom  2508 Y
                ///     74.0161   -149.1060   -273.4863    176.4975   -170.6527   -341.1639
                ///   -263.6141
                /// Off-diagonal Hessian Elements for Atom  2508 Z
                ///    304.9942    223.7496   -851.3028   -242.9481   -310.7953   -821.2532
                /// Off-diagonal Hessian Elements for Atom  2509 X
                ///    198.4498   -331.6530     78.8172     17.3909    -30.0512
                /// Off-diagonal Hessian Elements for Atom  2509 Y
                ///   -227.5916     25.7235     74.5131    -53.2690
                /// Off-diagonal Hessian Elements for Atom  2509 Z
                ///     46.7873     20.7615   -168.0704
                /// Off-diagonal Hessian Elements for Atom  2510 X
                ///    252.6853    247.2963
                /// Off-diagonal Hessian Elements for Atom  2510 Y
                ///    343.6797
                #endregion
                HessMatrix hess;
                {
                    if (HessMatrixZeros != null)
                    {
                        hess = HessMatrixZeros(size * 3, size * 3);
                    }
                    else
                    {
                        switch (outHessFormat)
                        {
                        case "full matrix": hess = HessMatrixDense.ZerosDense(size * 3, size * 3); break;

                        case "sparse matrix": hess = HessMatrixSparse.ZerosSparse(size * 3, size * 3); break;

                        default:              hess = null;                                             break;
                        }
                    }
                    //HDebug.SetEpsilon(hess);
                    string step    = "";
                    int    diagidx = -1;
                    int    offidx1 = -1;
                    int    offidx2 = -1;

                    /// string[] lines = HFile.ReadAllLines(outHessMatFile);
                    /// GC.WaitForFullGCComplete();
                    /// object[] tokenss = new object[lines.Length];
                    ///
                    /// Parallel.For(0, lines.Length, delegate(int i)
                    /// //for(int i=0; i<lines.Length; i++)
                    /// {
                    ///     string line = lines[i];
                    ///     string[] stokens = line.Trim().Split().RemoveAll("");
                    ///     if(stokens.Length != 0)
                    ///     {
                    ///         double[] dtokens = new double[stokens.Length];
                    ///         for(int j=0; j<stokens.Length; j++)
                    ///             if(double.TryParse(stokens[j], out dtokens[j]) == false)
                    ///             {
                    ///                 tokenss[i] = stokens;
                    ///                 goto endfor;
                    ///             }
                    ///         tokenss[i] = dtokens;
                    ///     }
                    /// endfor: ;
                    /// });

                    /// System.IO.StreamReader matreader = HFile.OpenText(outHessMatFile);
                    /// while(matreader.EndOfStream == false)
                    /// for(int i=0; i<lines.Length; i++)
                    /// foreach(string line in lines)
                    foreach (string line in HFile.HEnumAllLines(outHessMatFile))
                    {
                        ///     string line = lines[i];
                        ///     string line = matreader.ReadLine();
                        string[] tokens = line.Trim().Split().HRemoveAll("");
                        if (tokens.Length == 0)
                        {
                            continue;
                        }
                        ///     if(tokenss[i] == null)
                        ///         continue;
                        ///     string[] stokens = (tokenss[i] as string[]);
                        if (tokens[0] == "Diagonal" && tokens[1] == "Hessian" && tokens[2] == "Elements")
                        {
                            step = "Diagonal"; diagidx = 0; continue;
                        }
                        if (tokens[0] == "Off-diagonal" && tokens[1] == "Hessian" && tokens[2] == "Elements")
                        {
                            step = "Off-diagonal"; offidx1++; offidx2 = offidx1 + 1; continue;
                        }
                        if (tokens[0] == "Off-diagonal" && tokens[1] == "sparse" && tokens[2] == "Hessian" &&
                            tokens[3] == "Indexes/Elements" && tokens[4] == "for" && tokens[5] == "Atom")
                        {
                            step    = "Off-diagonal sparse";
                            offidx1 = (int.Parse(tokens[6]) - 1) * 3;
                            switch (tokens[7])
                            {
                            case "X": break;

                            case "Y": offidx1 += 1; break;

                            case "Z": offidx1 += 2; break;

                            default: throw new HException();
                            }
                            continue;
                        }

                        ///     double[] dtokens = (tokenss[i] as double[]);
                        ///     tokens = new string[20];
                        ///     for(int i=0; i*12<line.Length; i++)
                        ///         tokens[i] = line.Substring(i*12, 12).Trim();
                        ///     tokens = tokens.HRemoveAll("").ToArray();
                        ///     tokens = tokens.HRemoveAll(null).ToArray();

                        switch (step)
                        {
                        case "Diagonal":
                        {
                            ///                 foreach(double val in dtokens)
                            foreach (string token in tokens)
                            {
                                HDebug.Assert(token.Last() != ' ');
                                double val = double.Parse(token);
                                HDebug.Assert(hess[diagidx, diagidx] == 0);
                                hess[diagidx, diagidx] = val;
                                diagidx++;
                            }
                        }
                            continue;

                        case "Off-diagonal":
                        {
                            ///                 foreach(double val in dtokens)
                            foreach (string token in tokens)
                            {
                                HDebug.Assert(token.Last() != ' ');
                                //double val = double.Parse(token);
                                double val;
                                bool   succ = double.TryParse(token, out val);
                                if (succ == false)
                                {
                                    HDebug.Assert(false);
                                    goto case "exception 0";
                                }
                                if (size < 3000)
                                {
                                    HDebug.Assert(hess[offidx1, offidx2] == 0);
                                    HDebug.Assert(hess[offidx2, offidx1] == 0);
                                }
                                if (val != 0)
                                {
                                    hess[offidx1, offidx2] = val;
                                    hess[offidx2, offidx1] = val;
                                }
                                offidx2++;
                            }
                        }
                            continue;

                        case "Off-diagonal sparse":
                        {
                            HDebug.Assert(tokens.Length % 2 == 0);
                            for (int i = 0; i < tokens.Length; i += 2)
                            {
                                HDebug.Assert(tokens[i].Last() != ' ');
                                HDebug.Assert(tokens[i + 1].Last() != ' ');
                                //double val = double.Parse(token);
                                double val;
                                bool   succ = true;
                                succ &= int.TryParse(tokens[i], out offidx2); offidx2--;
                                succ &= double.TryParse(tokens[i + 1], out val);
                                if (succ == false)
                                {
                                    HDebug.Assert(false);
                                    goto case "exception 0";
                                }
                                if (size < 3000)
                                {
                                    HDebug.Assert(hess[offidx1, offidx2] == 0);
                                    HDebug.Assert(hess[offidx2, offidx1] == 0);
                                }
                                if (val != 0)
                                {
                                    hess[offidx1, offidx2] = val;
                                    hess[offidx2, offidx1] = val;
                                }
                            }
                        }
                            continue;

                        default:
                            HDebug.Assert(false);
                            goto case "exception 1";

                        case "exception 0":
                            throw new HException("incomplete hessian file (0)");

                        case "exception 1":
                            throw new HException("incomplete hessian file (1)");
                        }
                        throw new HException("incomplete hessian file (2)");
                    }
                    /// matreader.Close();

                    if (HDebug.IsDebuggerAttached && size < 3000)
                    {
                        //for(int c=0; c<size*3; c++)
                        //    for(int r=0; r<size*3; r++)
                        //        if(hess[c, r] == double.Epsilon)
                        //            throw new Exception("incomplete hessian file (3)");
                        //
                        //for(int c=0; c<size*3; c++)
                        //{
                        //    double sum = 0;
                        //    double max = double.NegativeInfinity;
                        //    for(int r=0; r<size*3; r++)
                        //    {
                        //        max = Math.Max(max, hess[c, r]);
                        //        sum += hess[c, r];
                        //        HDebug.Assert(hess[c, r] != double.Epsilon);
                        //    }
                        //    HDebug.Assert(Math.Abs(sum) < max/1000);
                        //    HDebug.AssertTolerance(0.1, sum);
                        //}

                        Hess.CheckHessDiag(hess, 0.1, null);

                        for (int i = 0; i < size; i++)
                        {
                            HDebug.Assert(outDiagHessElems[i].Item1 == i + 1);
                            HDebug.AssertTolerance(0.000001, outDiagHessElems[i].Item2 - hess[i * 3 + 0, i * 3 + 0]);
                            HDebug.AssertTolerance(0.000001, outDiagHessElems[i].Item3 - hess[i * 3 + 1, i * 3 + 1]);
                            HDebug.AssertTolerance(0.000001, outDiagHessElems[i].Item4 - hess[i * 3 + 2, i * 3 + 2]);
                        }
                    }
                }

                if (optOutSource != null)
                {
                    optOutSource.Add("test.hes", HFile.HEnumAllLines(outHessMatFile).ToArray());
                }

                return(new CTesthess
                {
                    hess = hess,
                    xyz = xyz,
                });
            }
Пример #16
0
        public static HessMatrix GetHessAnm(IList <Vector> coords, IList <double> cutoffs, string options = "")
        {
            if (coords.Count > 10000)
            {
                HDebug.ToDo("System size is too big. Use EnumHessAnmSpr() and other GetHessAnm()");
            }

            //Debug.Assert(AnmHessianSelfTest());

            HDebug.Assert(coords.Count == cutoffs.Count);

            double[] cutoffs2 = new double[cutoffs.Count];
            for (int i = 0; i < cutoffs.Count; i++)
            {
                cutoffs2[i] = cutoffs[i] * cutoffs[i];
            }

            double Epsilon = 0;// double.Epsilon;

            int        n    = coords.Count;
            HessMatrix hess = null;

            if (n < 100)
            {
                hess = HessMatrixDense.ZerosDense(n * 3, n * 3);
            }
            else
            {
                hess = HessMatrixSparse.ZerosSparse(n * 3, n * 3);
            }
            Action <int> comp_hess_i = delegate(int i)
            {
                if (coords[i] == null)
                {
                    return;
                }
                //continue;
                for (int j = 0; j < n; j++)
                {
                    if (i == j)
                    {
                        continue;
                    }
                    if (coords[j] == null)
                    {
                        continue;
                    }
                    Vector vec_ij  = coords[j] - coords[i];
                    double dist2   = vec_ij.Dist2;
                    double cutoff2 = Math.Max(cutoffs2[i], cutoffs2[j]);
                    if (dist2 > cutoff2)
                    {
                        if (Epsilon == 0)
                        {
                            continue;
                        }
                        HDebug.Assert(hess[i * 3 + 0, j * 3 + 0] == 0); hess[i * 3 + 0, j *3 + 0] = Epsilon;
                        HDebug.Assert(hess[i * 3 + 0, j * 3 + 1] == 0); hess[i * 3 + 0, j *3 + 1] = Epsilon;
                        HDebug.Assert(hess[i * 3 + 0, j * 3 + 2] == 0); hess[i * 3 + 0, j *3 + 2] = Epsilon;
                        HDebug.Assert(hess[i * 3 + 1, j * 3 + 0] == 0); hess[i * 3 + 1, j *3 + 0] = Epsilon;
                        HDebug.Assert(hess[i * 3 + 1, j * 3 + 1] == 0); hess[i * 3 + 1, j *3 + 1] = Epsilon;
                        HDebug.Assert(hess[i * 3 + 1, j * 3 + 2] == 0); hess[i * 3 + 1, j *3 + 2] = Epsilon;
                        HDebug.Assert(hess[i * 3 + 2, j * 3 + 0] == 0); hess[i * 3 + 2, j *3 + 0] = Epsilon;
                        HDebug.Assert(hess[i * 3 + 2, j * 3 + 1] == 0); hess[i * 3 + 2, j *3 + 1] = Epsilon;
                        HDebug.Assert(hess[i * 3 + 2, j * 3 + 2] == 0); hess[i * 3 + 2, j *3 + 2] = Epsilon;
                        continue;
                    }
                    Vector unit_ij = vec_ij.UnitVector();
                    double k_ij = 1; double val;
                    val = k_ij * unit_ij[0] * unit_ij[0]; hess[i * 3 + 0, j *3 + 0] = Epsilon - val; hess[i * 3 + 0, i *3 + 0] += val;  // hess[i*3+0, j*3+0] = Epsilon - k_ij * unit_ij[0]*unit_ij[0]; hess[i*3+0, i*3+0] += k_ij * unit_ij[0]*unit_ij[0];
                    val = k_ij * unit_ij[0] * unit_ij[1]; hess[i * 3 + 0, j *3 + 1] = Epsilon - val; hess[i * 3 + 0, i *3 + 1] += val;  // hess[i*3+0, j*3+1] = Epsilon - k_ij * unit_ij[0]*unit_ij[1]; hess[i*3+0, i*3+1] += k_ij * unit_ij[0]*unit_ij[1];
                    val = k_ij * unit_ij[0] * unit_ij[2]; hess[i * 3 + 0, j *3 + 2] = Epsilon - val; hess[i * 3 + 0, i *3 + 2] += val;  // hess[i*3+0, j*3+2] = Epsilon - k_ij * unit_ij[0]*unit_ij[2]; hess[i*3+0, i*3+2] += k_ij * unit_ij[0]*unit_ij[2];
                    val = k_ij * unit_ij[1] * unit_ij[0]; hess[i * 3 + 1, j *3 + 0] = Epsilon - val; hess[i * 3 + 1, i *3 + 0] += val;  // hess[i*3+1, j*3+0] = Epsilon - k_ij * unit_ij[1]*unit_ij[0]; hess[i*3+1, i*3+0] += k_ij * unit_ij[1]*unit_ij[0];
                    val = k_ij * unit_ij[1] * unit_ij[1]; hess[i * 3 + 1, j *3 + 1] = Epsilon - val; hess[i * 3 + 1, i *3 + 1] += val;  // hess[i*3+1, j*3+1] = Epsilon - k_ij * unit_ij[1]*unit_ij[1]; hess[i*3+1, i*3+1] += k_ij * unit_ij[1]*unit_ij[1];
                    val = k_ij * unit_ij[1] * unit_ij[2]; hess[i * 3 + 1, j *3 + 2] = Epsilon - val; hess[i * 3 + 1, i *3 + 2] += val;  // hess[i*3+1, j*3+2] = Epsilon - k_ij * unit_ij[1]*unit_ij[2]; hess[i*3+1, i*3+2] += k_ij * unit_ij[1]*unit_ij[2];
                    val = k_ij * unit_ij[2] * unit_ij[0]; hess[i * 3 + 2, j *3 + 0] = Epsilon - val; hess[i * 3 + 2, i *3 + 0] += val;  // hess[i*3+2, j*3+0] = Epsilon - k_ij * unit_ij[2]*unit_ij[0]; hess[i*3+2, i*3+0] += k_ij * unit_ij[2]*unit_ij[0];
                    val = k_ij * unit_ij[2] * unit_ij[1]; hess[i * 3 + 2, j *3 + 1] = Epsilon - val; hess[i * 3 + 2, i *3 + 1] += val;  // hess[i*3+2, j*3+1] = Epsilon - k_ij * unit_ij[2]*unit_ij[1]; hess[i*3+2, i*3+1] += k_ij * unit_ij[2]*unit_ij[1];
                    val = k_ij * unit_ij[2] * unit_ij[2]; hess[i * 3 + 2, j *3 + 2] = Epsilon - val; hess[i * 3 + 2, i *3 + 2] += val;  // hess[i*3+2, j*3+2] = Epsilon - k_ij * unit_ij[2]*unit_ij[2]; hess[i*3+2, i*3+2] += k_ij * unit_ij[2]*unit_ij[2];
                }
            };

            if (options.Split(';').Contains("parallel"))
            {
                System.Threading.Tasks.Parallel.For(0, n, comp_hess_i);
            }
            else
            {
                for (int i = 0; i < n; i++)
                {
                    comp_hess_i(i);
                }
            }

            return(hess);
        }
Пример #17
0
            public static bool SelfTest_1AAC()
            {
                Pdb.Atom[] atoms_ca = new Pdb.Atom[]
                {
                    #region 1AAC text of CA atoms
                    Pdb.Atom.FromString("ATOM      2  CA  ASP A   1      25.378 -18.141  21.012  1.00 23.28           C  "),
                    Pdb.Atom.FromString("ATOM     10  CA  LYS A   2      24.390 -18.799  17.407  1.00 12.32           C  "),
                    Pdb.Atom.FromString("ATOM     19  CA  ALA A   3      25.772 -15.617  15.840  1.00 10.31           C  "),
                    Pdb.Atom.FromString("ATOM     24  CA  THR A   4      28.837 -13.442  16.439  1.00  9.47           C  "),
                    Pdb.Atom.FromString("ATOM     31  CA  ILE A   5      28.913  -9.665  15.865  1.00  7.94           C  "),
                    Pdb.Atom.FromString("ATOM     39  CA  PRO A   6      31.906  -8.243  13.886  1.00  8.02           C  "),
                    Pdb.Atom.FromString("ATOM     46  CA  SER A   7      31.049  -4.632  14.810  1.00  7.70           C  "),
                    Pdb.Atom.FromString("ATOM     52  CA  GLU A   8      28.768  -3.589  17.658  1.00 10.01           C  "),
                    Pdb.Atom.FromString("ATOM     73  CA  PRO A  10      26.932   0.412  12.498  1.00  7.09           C  "),
                    Pdb.Atom.FromString("ATOM     80  CA  PHE A  11      29.488   1.217   9.844  1.00  6.81           C  "),
                    Pdb.Atom.FromString("ATOM     91  CA  ALA A  12      29.431   2.815   6.390  1.00  6.76           C  "),
                    Pdb.Atom.FromString("ATOM     96  CA  ALA A  13      28.012   1.036   3.320  1.00  8.60           C  "),
                    Pdb.Atom.FromString("ATOM    101  CA  ALA A  14      31.392   1.654   1.659  1.00 11.18           C  "),
                    Pdb.Atom.FromString("ATOM    106  CA  GLU A  15      33.092  -0.407   4.404  1.00  9.76           C  "),
                    Pdb.Atom.FromString("ATOM    115  CA  VAL A  16      31.115  -3.590   3.763  1.00 12.85           C  "),
                    Pdb.Atom.FromString("ATOM    122  CA  ALA A  17      33.429  -6.584   3.205  1.00 20.32           C  "),
                    Pdb.Atom.FromString("ATOM    127  CA  ASP A  18      34.080  -7.894  -0.306  1.00 27.64           C  "),
                    Pdb.Atom.FromString("ATOM    135  CA  GLY A  19      31.708 -10.634  -1.313  1.00 26.92           C  "),
                    Pdb.Atom.FromString("ATOM    139  CA  ALA A  20      29.393  -9.683   1.528  1.00 19.57           C  "),
                    Pdb.Atom.FromString("ATOM    144  CA  ILE A  21      25.881 -11.238   1.583  1.00 11.70           C  "),
                    Pdb.Atom.FromString("ATOM    152  CA  VAL A  22      23.847  -8.061   1.553  1.00  7.77           C  "),
                    Pdb.Atom.FromString("ATOM    159  CA  VAL A  23      20.196  -7.501   2.410  1.00  6.37           C  "),
                    Pdb.Atom.FromString("ATOM    166  CA  ASP A  24      19.093  -3.982   1.466  1.00  6.66           C  "),
                    Pdb.Atom.FromString("ATOM    174  CA  ILE A  25      16.500  -2.121   3.513  1.00  7.21           C  "),
                    Pdb.Atom.FromString("ATOM    182  CA  ALA A  26      14.398   0.375   1.556  1.00  8.41           C  "),
                    Pdb.Atom.FromString("ATOM    187  CA  LYS A  27      10.724   1.489   1.214  1.00  9.80           C  "),
                    Pdb.Atom.FromString("ATOM    201  CA  MET A  28      10.147   0.295   4.838  1.00  8.69           C  "),
                    Pdb.Atom.FromString("ATOM    209  CA  LYS A  29      10.882  -3.362   4.004  1.00  9.09           C  "),
                    Pdb.Atom.FromString("ATOM    223  CA  TYR A  30      13.753  -5.845   4.132  1.00  6.32           C  "),
                    Pdb.Atom.FromString("ATOM    235  CA  GLU A  31      14.275  -6.364   0.381  1.00  9.00           C  "),
                    Pdb.Atom.FromString("ATOM    244  CA  THR A  32      15.144 -10.026   0.769  1.00  7.30           C  "),
                    Pdb.Atom.FromString("ATOM    251  CA  PRO A  33      12.722 -11.107   3.546  1.00  8.68           C  "),
                    Pdb.Atom.FromString("ATOM    258  CA  GLU A  34      13.757 -14.780   3.406  1.00  9.28           C  "),
                    Pdb.Atom.FromString("ATOM    267  CA  LEU A  35      17.468 -15.255   2.972  1.00  7.34           C  "),
                    Pdb.Atom.FromString("ATOM    275  CA  HIS A  36      19.181 -18.672   2.822  1.00  6.97           C  "),
                    Pdb.Atom.FromString("ATOM    285  CA  VAL A  37      22.841 -18.828   3.840  1.00  7.29           C  "),
                    Pdb.Atom.FromString("ATOM    292  CA  LYS A  38      25.361 -21.456   5.044  1.00  9.55           C  "),
                    Pdb.Atom.FromString("ATOM    306  CA  VAL A  39      26.828 -21.965   8.529  1.00  9.09           C  "),
                    Pdb.Atom.FromString("ATOM    313  CA  GLY A  40      29.717 -19.533   8.887  1.00  8.81           C  "),
                    Pdb.Atom.FromString("ATOM    317  CA  ASP A  41      28.343 -16.891   6.520  1.00  8.19           C  "),
                    Pdb.Atom.FromString("ATOM    325  CA  THR A  42      28.196 -13.227   7.468  1.00  7.95           C  "),
                    Pdb.Atom.FromString("ATOM    332  CA  VAL A  43      24.989 -11.395   6.512  1.00  6.02           C  "),
                    Pdb.Atom.FromString("ATOM    339  CA  THR A  44      25.158  -7.607   6.224  1.00  5.34           C  "),
                    Pdb.Atom.FromString("ATOM    346  CA  TRP A  45      22.054  -5.421   6.244  1.00  4.51           C  "),
                    Pdb.Atom.FromString("ATOM    360  CA  ILE A  46      22.453  -1.974   4.623  1.00  5.55           C  "),
                    Pdb.Atom.FromString("ATOM    368  CA  ASN A  47      19.890   0.774   5.248  1.00  6.52           C  "),
                    Pdb.Atom.FromString("ATOM    376  CA  ARG A  48      19.350   2.559   1.939  1.00 10.21           C  "),
                    Pdb.Atom.FromString("ATOM    387  CA  GLU A  49      16.823   5.111   3.196  1.00 12.44           C  "),
                    Pdb.Atom.FromString("ATOM    396  CA  ALA A  50      16.764   8.058   5.564  1.00 13.39           C  "),
                    Pdb.Atom.FromString("ATOM    401  CA  MET A  51      14.386   6.508   8.133  1.00 12.52           C  "),
                    Pdb.Atom.FromString("ATOM    409  CA  PRO A  52      16.509   4.566  10.725  1.00  9.20           C  "),
                    Pdb.Atom.FromString("ATOM    416  CA  HIS A  53      16.032   0.778  10.889  1.00  6.43           C  "),
                    Pdb.Atom.FromString("ATOM    426  CA  ASN A  54      17.658  -2.107  12.766  1.00  5.06           C  "),
                    Pdb.Atom.FromString("ATOM    434  CA  VAL A  55      17.296  -5.891  13.052  1.00  5.44           C  "),
                    Pdb.Atom.FromString("ATOM    441  CA  HIS A  56      15.979  -7.379  16.316  1.00  4.53           C  "),
                    Pdb.Atom.FromString("ATOM    451  CA  PHE A  57      15.920 -11.061  17.243  1.00  5.94           C  "),
                    Pdb.Atom.FromString("ATOM    462  CA  VAL A  58      13.932 -11.794  20.435  1.00  7.60           C  "),
                    Pdb.Atom.FromString("ATOM    469  CA  ALA A  59      15.316 -13.765  23.405  1.00  7.37           C  "),
                    Pdb.Atom.FromString("ATOM    474  CA  GLY A  60      16.074 -17.393  22.787  1.00  9.00           C  "),
                    Pdb.Atom.FromString("ATOM    478  CA  VAL A  61      16.521 -17.029  18.997  1.00  8.51           C  "),
                    Pdb.Atom.FromString("ATOM    485  CA  LEU A  62      20.244 -16.290  18.543  1.00  9.65           C  "),
                    Pdb.Atom.FromString("ATOM    493  CA  GLY A  63      21.156 -16.644  22.197  1.00 10.26           C  "),
                    Pdb.Atom.FromString("ATOM    497  CA  GLU A  64      19.729 -16.413  25.651  1.00  9.18           C  "),
                    Pdb.Atom.FromString("ATOM    506  CA  ALA A  65      19.129 -12.671  25.468  1.00  8.86           C  "),
                    Pdb.Atom.FromString("ATOM    511  CA  ALA A  66      17.408 -10.687  22.723  1.00  7.22           C  "),
                    Pdb.Atom.FromString("ATOM    516  CA  LEU A  67      19.808  -9.283  20.128  1.00  9.01           C  "),
                    Pdb.Atom.FromString("ATOM    524  CA  LYS A  68      18.504  -5.777  19.473  1.00 10.06           C  "),
                    Pdb.Atom.FromString("ATOM    533  CA  GLY A  69      20.805  -4.416  16.788  1.00  8.06           C  "),
                    Pdb.Atom.FromString("ATOM    537  CA  PRO A  70      21.868  -0.715  16.656  1.00  8.23           C  "),
                    Pdb.Atom.FromString("ATOM    544  CA  MET A  71      19.807   1.769  14.640  1.00  8.56           C  "),
                    Pdb.Atom.FromString("ATOM    552  CA  MET A  72      21.337   2.189  11.156  1.00  8.26           C  "),
                    Pdb.Atom.FromString("ATOM    560  CA  LYS A  73      21.086   5.638   9.601  1.00  9.59           C  "),
                    Pdb.Atom.FromString("ATOM    574  CA  LYS A  74      21.097   6.084   5.777  1.00  9.46           C  "),
                    Pdb.Atom.FromString("ATOM    588  CA  GLU A  75      23.892   4.149   4.097  1.00  9.45           C  "),
                    Pdb.Atom.FromString("ATOM    602  CA  GLN A  76      24.997   2.451   7.267  1.00  6.02           C  "),
                    Pdb.Atom.FromString("ATOM    611  CA  ALA A  77      25.416  -1.310   7.631  1.00  5.75           C  "),
                    Pdb.Atom.FromString("ATOM    616  CA  TYR A  78      25.448  -3.978  10.318  1.00  4.90           C  "),
                    Pdb.Atom.FromString("ATOM    628  CA  SER A  79      26.700  -7.612  10.117  1.00  5.13           C  "),
                    Pdb.Atom.FromString("ATOM    634  CA  LEU A  80      26.024 -10.884  11.899  1.00  5.65           C  "),
                    Pdb.Atom.FromString("ATOM    642  CA  THR A  81      27.969 -14.123  11.320  1.00  6.53           C  "),
                    Pdb.Atom.FromString("ATOM    649  CA  PHE A  82      25.693 -17.171  11.780  1.00  5.24           C  "),
                    Pdb.Atom.FromString("ATOM    660  CA  THR A  83      27.363 -20.163  13.449  1.00  6.79           C  "),
                    Pdb.Atom.FromString("ATOM    667  CA  GLU A  84      24.599 -22.785  13.726  1.00  6.27           C  "),
                    Pdb.Atom.FromString("ATOM    676  CA  ALA A  85      21.975 -24.045  11.260  1.00  7.61           C  "),
                    Pdb.Atom.FromString("ATOM    681  CA  GLY A  86      18.324 -23.142  11.886  1.00  7.35           C  "),
                    Pdb.Atom.FromString("ATOM    685  CA  THR A  87      15.680 -20.519  11.055  1.00  8.50           C  "),
                    Pdb.Atom.FromString("ATOM    692  CA  TYR A  88      16.009 -17.145  12.731  1.00  7.35           C  "),
                    Pdb.Atom.FromString("ATOM    704  CA  ASP A  89      13.191 -14.620  12.557  1.00  7.28           C  "),
                    Pdb.Atom.FromString("ATOM    712  CA  TYR A  90      13.740 -10.922  13.122  1.00  5.26           C  "),
                    Pdb.Atom.FromString("ATOM    724  CA  HIS A  91      11.902  -7.619  12.935  1.00  4.80           C  "),
                    Pdb.Atom.FromString("ATOM    734  CA  CYS A  92      12.663  -3.894  13.049  1.00  5.44           C  "),
                    Pdb.Atom.FromString("ATOM    740  CA  THR A  93      12.228  -2.579  16.647  1.00  6.60           C  "),
                    Pdb.Atom.FromString("ATOM    747  CA  PRO A  94      10.460   0.815  15.821  1.00  7.51           C  "),
                    Pdb.Atom.FromString("ATOM    754  CA  HIS A  95       8.594  -0.728  12.857  1.00  7.46           C  "),
                    Pdb.Atom.FromString("ATOM    764  CA  PRO A  96       7.518  -4.286  13.932  1.00  7.59           C  "),
                    Pdb.Atom.FromString("ATOM    771  CA  PHE A  97       5.480  -4.778  10.739  1.00  7.30           C  "),
                    Pdb.Atom.FromString("ATOM    782  CA  MET A  98       8.923  -5.104   8.994  1.00  6.57           C  "),
                    Pdb.Atom.FromString("ATOM    790  CA  ARG A  99       9.707  -8.821   9.391  1.00  7.91           C  "),
                    Pdb.Atom.FromString("ATOM    808  CA  GLY A 100      12.343 -11.105   7.827  1.00  6.39           C  "),
                    Pdb.Atom.FromString("ATOM    812  CA  LYS A 101      14.085 -14.438   8.459  1.00  7.31           C  "),
                    Pdb.Atom.FromString("ATOM    826  CA  VAL A 102      17.523 -15.900   7.870  1.00  6.58           C  "),
                    Pdb.Atom.FromString("ATOM    833  CA  VAL A 103      17.552 -19.658   7.157  1.00  7.20           C  "),
                    Pdb.Atom.FromString("ATOM    840  CA  VAL A 104      21.061 -21.012   7.897  1.00  7.28           C  "),
                    Pdb.Atom.FromString("ATOM    847  CA  GLU A 105      21.699 -24.347   6.221  1.00 13.74           C  "),
                    #endregion
                };
                Pdb.Atom[] atoms_r6 = new Pdb.Atom[]
                {
                    Pdb.Atom.FromString("ATOM     42  CB  PRO A   6      31.929  -8.271  12.386  1.00  7.98           C  "),
                    Pdb.Atom.FromString("ATOM     43  CG  PRO A   6      30.972  -9.378  12.022  1.00  9.48           C  "),
                    Pdb.Atom.FromString("ATOM     44  CD  PRO A   6      29.880  -9.313  13.099  1.00  8.27           C  "),
                };

                {
                    HessMatrix hess = GetHessCa(atoms_ca.ListCoord());

                    InfoPack extra = new InfoPack();
                    //Vector bfactors = ENM.BFactorFromHessian(hess, null, 6, extra);
                    Vector bfactors          = Hess.GetBFactor(hess, null, 6, extra);
                    Vector eigvals           = (double[])extra["eigenvalues"];
                    int[]  idxsorted_eigvals = eigvals.ToArray().HAbs().HIdxSorted();
                    for (int i = 0; i < 6; i++)
                    {
                        eigvals[idxsorted_eigvals[i]] = 0;
                    }
                    for (int i = 0; i < eigvals.Size; i++)
                    {
                        if (eigvals[i] < 0)
                        {
                            // return false, if there exists negative eigenvalue
                            HDebug.Assert(false);
                            return(false);
                        }
                    }
                }
                {
                    List <Pdb.Atom> atoms = new List <Pdb.Atom>();
                    atoms.AddRange(atoms_ca);
                    atoms.AddRange(atoms_r6);
                    HDebug.Assert(atoms[5].resSeq == 6);

                    List <int> idxs_ca = new List <int>(); for (int i = 0; i < atoms_ca.Length; i++)
                    {
                        idxs_ca.Add(i);
                    }
                    List <int> idxs_r6 = new List <int>(); for (int i = atoms_ca.Length; i < atoms.Count; i++)
                    {
                        idxs_r6.Add(i);
                    }
                    idxs_r6.InsertRange(0, new int[] { 3, 4, 5 });

                    List <Tuple <int, int> > list12 = new List <Tuple <int, int> >();
                    for (int i = 1; i < idxs_ca.Count; i++)
                    {
                        list12.Add(new Tuple <int, int>(idxs_ca[i - 1], idxs_ca[i]));
                    }
                    for (int i = 3; i < idxs_r6.Count; i++)
                    {
                        list12.Add(new Tuple <int, int>(idxs_r6[i - 1], idxs_r6[i]));
                    }

                    List <Tuple <int, int, int> > list123 = new List <Tuple <int, int, int> >();
                    for (int i = 2; i < idxs_ca.Count; i++)
                    {
                        list123.Add(new Tuple <int, int, int>(idxs_ca[i - 2], idxs_ca[i - 1], idxs_ca[i]));
                    }
                    for (int i = 3; i < idxs_r6.Count; i++)
                    {
                        list123.Add(new Tuple <int, int, int>(idxs_r6[i - 2], idxs_r6[i - 1], idxs_r6[i]));
                    }

                    List <Tuple <int, int, int, int> > list1234 = new List <Tuple <int, int, int, int> >();
                    for (int i = 3; i < idxs_ca.Count; i++)
                    {
                        list1234.Add(new Tuple <int, int, int, int>(idxs_ca[i - 3], idxs_ca[i - 2], idxs_ca[i - 1], idxs_ca[i]));
                    }
                    for (int i = 3; i < idxs_r6.Count; i++)
                    {
                        list1234.Add(new Tuple <int, int, int, int>(idxs_r6[i - 3], idxs_r6[i - 2], idxs_r6[i - 1], idxs_r6[i]));
                    }

                    List <Tuple <int, int> > listNonbond = new List <Tuple <int, int> >();
                    for (int i = 0; i < idxs_ca.Count; i++)
                    {
                        for (int j = i + 4; j < idxs_ca.Count; j++)
                        {
                            listNonbond.Add(new Tuple <int, int>(idxs_ca[i], idxs_ca[j]));
                        }
                    }
                    for (int i = 0; i < idxs_r6.Count; i++)
                    {
                        for (int j = i + 4; j < idxs_r6.Count; j++)
                        {
                            listNonbond.Add(new Tuple <int, int>(idxs_r6[i], idxs_r6[j]));
                        }
                    }

                    List <Vector> coords  = atoms.ListCoord();
                    HessMatrix    hessian = HessMatrixSparse.ZerosSparse(atoms.Count * 3, atoms.Count * 3);

                    double Epsilon = 0.36;
                    double K_r     = 100 * Epsilon;
                    double K_theta = 20 * Epsilon;
                    double K_phi1  = 1 * Epsilon;
                    double K_phi3  = 0.5 * Epsilon;
                    for (int i = 0; i < list12.Count; i++)
                    {
                        FirstTerm(coords, K_r, hessian, list12[i].Item1, list12[i].Item2);
                    }
                    for (int i = 0; i < list123.Count; i++)
                    {
                        SecondTerm(coords, K_theta, hessian, list123[i].Item1, list123[i].Item2, list123[i].Item3);
                    }
                    for (int i = 0; i < list1234.Count; i++)
                    {
                        ThirdTerm(coords, K_phi1, K_phi3, hessian, list1234[i].Item1, list1234[i].Item2, list1234[i].Item3, list1234[i].Item4);
                    }
                    for (int i = 0; i < listNonbond.Count; i++)
                    {
                        FourthTerm(coords, Epsilon, hessian, listNonbond[i].Item1, listNonbond[i].Item2);
                    }

                    InfoPack extra = new InfoPack();
                    //Vector bfactors = ENM.BFactorFromHessian(hessian, null, 6, extra);
                    Vector bfactors          = Hess.GetBFactor(hessian, null, 6, extra);
                    Vector eigvals           = (double[])extra["eigenvalues"];
                    int[]  idxsorted_eigvals = eigvals.ToArray().HAbs().HIdxSorted();
                    for (int i = 0; i < 6; i++)
                    {
                        eigvals[idxsorted_eigvals[i]] = 0;
                    }
                    for (int i = 0; i < eigvals.Size; i++)
                    {
                        if (eigvals[i] < 0)
                        {
                            // return false, if there exists negative eigenvalue
                            HDebug.Assert(false);
                            return(false);
                        }
                    }
                }
                //{
                //    Debug.Assert(atoms_ca[5].resSeq == 6);
                //    Pdb.Atom[] atoms_resi6 = new Pdb.Atom[]
                //        {
                //            atoms_ca[5],
                //            Pdb.Atom.FromString("ATOM     42  CB  PRO A   6      31.929  -8.271  12.386  1.00  7.98           C  "),
                //            Pdb.Atom.FromString("ATOM     43  CG  PRO A   6      30.972  -9.378  12.022  1.00  9.48           C  "),
                //            Pdb.Atom.FromString("ATOM     44  CD  PRO A   6      29.880  -9.313  13.099  1.00  8.27           C  "),
                //        };
                //    Matrix hess_ca = GetHessCa(atoms_ca.ListCoord());
                //    Matrix hess_resi6 = GetHessCa(atoms_resi6.ListCoord());
                //
                //    int size_ca = atoms_ca.Length;
                //    int size_r6 = atoms_resi6.Length - 1;
                //    Matrix hess = new double[(size_ca+size_r6)*3,(size_ca+size_r6)*3];
                //    for(int c = 0; c < hess.ColSize; c++)
                //        for(int r = 0; r < hess.RowSize; r++)
                //            hess[c, r] = double.NaN;
                //    for(int c = 0; c < hess_ca.ColSize; c++)
                //        for(int r = 0; r < hess_ca.RowSize; r++)
                //            hess[c, r] = hess_ca[c, r];
                //    for(int c = 0; c < hess_resi6.ColSize; c++)
                //        for(int r = 0; r < hess_resi6.RowSize; r++)
                //        {
                //                 if(c <  3 && r <  3) { int c0=5      *3+ c   ; int r0=5      *3+ r   ; Debug.Assert(double.IsNaN(hess[c0, r0]) ==false); hess[c0, r0] = hess_resi6[c, r]; }
                //            else if(c <  3 && r >= 3) { int c0=5      *3+ c   ; int r0=size_ca*3+(r-3); Debug.Assert(double.IsNaN(hess[c0, r0]) == true); hess[c0, r0] = hess_resi6[c, r]; }
                //            else if(c >= 3 && r <  3) { int c0=size_ca*3+(c-3); int r0=5      *3+ r   ; Debug.Assert(double.IsNaN(hess[c0, r0]) == true); hess[c0, r0] = hess_resi6[c, r]; }
                //            else if(c >= 3 && r >= 3) { int c0=size_ca*3+(c-3); int r0=size_ca*3+(r-3); Debug.Assert(double.IsNaN(hess[c0, r0]) == true); hess[c0, r0] = hess_resi6[c, r]; }
                //            else Debug.Assert(false);
                //        }
                //    for(int j = size_ca * 3; j < (size_ca + size_r6) * 3; j++)
                //    {
                //        for(int i = 0; i < 5*3; i++)
                //        {
                //            Debug.Assert(double.IsNaN(hess[i, j]) == true); hess[i, j] = 0;
                //            Debug.Assert(double.IsNaN(hess[j, i]) == true); hess[j, i] = 0;
                //        }
                //        for(int i = 6*3; i < size_ca * 3; i++)
                //        {
                //            Debug.Assert(double.IsNaN(hess[i, j]) == true); hess[i, j] = 0;
                //            Debug.Assert(double.IsNaN(hess[j, i]) == true); hess[j, i] = 0;
                //        }
                //    }
                //    for(int c = 0; c < hess.ColSize; c++)
                //        for(int r = 0; r < hess.RowSize; r++)
                //            Debug.Assert(double.IsNaN(hess[c, r]) == false);
                //
                //    InfoPack extra = new InfoPack();
                //    Vector bfactors = ENM.BFactorFromHessian(hess, null, 6, extra);
                //    Vector eigvals = (double[])extra["eigenvalues"];
                //    int[] idxsorted_eigvals = eigvals.ToArray().Abs().IdxSorted();
                //    for(int i = 0; i < 6; i++) eigvals[idxsorted_eigvals[i]] = 0;
                //    for(int i = 0; i < eigvals.Size; i++)
                //        if(eigvals[i] < 0)
                //        {
                //            // return false, if there exists negative eigenvalue
                //            Debug.Assert(false);
                //            return false;
                //        }
                //}

                return(true);
            }
Пример #18
0
        static HessMatrix GetMulImpl(HessMatrix left, HessMatrix right, ILinAlg ila, bool warning)
        {
            if (HDebug.Selftest())
            {
                Matrix h1 = new double[, ] {
                    { 0, 1, 2, 3, 4, 5 }
                    , { 1, 2, 3, 4, 5, 6 }
                    , { 2, 3, 4, 5, 6, 7 }
                    , { 3, 4, 5, 6, 7, 8 }
                    , { 4, 5, 6, 7, 8, 9 }
                    , { 5, 6, 7, 8, 9, 0 }
                };
                HessMatrix h2    = HessMatrixSparse.FromMatrix(h1);
                Matrix     h11   = Matrix.GetMul(h1, h1);
                HessMatrix h22   = HessMatrix.GetMulImpl(h2, h2, null, false);
                Matrix     hdiff = h11 - h22;
                HDebug.AssertToleranceMatrix(0, hdiff);
            }
            if ((left is HessMatrixDense) && (right is HessMatrixDense))
            {
                if (ila != null)
                {
                    return(new HessMatrixDense {
                        hess = ila.Mul(left, right)
                    });
                }
                if (warning)
                {
                    HDebug.ToDo("Check (HessMatrixDense * HessMatrixDense) !!!");
                }
            }

            Dictionary <int, Dictionary <int, Tuple <int, int, MatrixByArr> > > left_ic_rows = new Dictionary <int, Dictionary <int, Tuple <int, int, MatrixByArr> > >();

            foreach (var ic_row in left.EnumRowBlocksAll())
            {
                left_ic_rows.Add(ic_row.Item1, ic_row.Item2.HToDictionaryWithKeyItem2());
            }

            Dictionary <int, Dictionary <int, Tuple <int, int, MatrixByArr> > > right_ir_cols = new Dictionary <int, Dictionary <int, Tuple <int, int, MatrixByArr> > >();

            foreach (var ir_col in right.EnumColBlocksAll())
            {
                right_ir_cols.Add(ir_col.Item1, ir_col.Item2.HToDictionaryWithKeyItem1());
            }

            HessMatrix mul = null;

            if ((left is HessMatrixDense) && (right is HessMatrixDense))
            {
                mul = HessMatrixDense.ZerosDense(left.ColSize, right.RowSize);
            }
            else
            {
                mul = HessMatrixSparse.ZerosSparse(left.ColSize, right.RowSize);
            }
            for (int ic = 0; ic < left.ColBlockSize; ic++)
            {
                var left_row = left_ic_rows[ic];
                if (left_row.Count == 0)
                {
                    continue;
                }
                for (int ir = 0; ir < right.RowBlockSize; ir++)
                {
                    var right_col = right_ir_cols[ir];
                    if (right_col.Count == 0)
                    {
                        continue;
                    }
                    foreach (var left_ck in left_row)
                    {
                        int ik = left_ck.Key;
                        HDebug.Assert(ic == left_ck.Value.Item1);
                        HDebug.Assert(ik == left_ck.Value.Item2);
                        if (right_col.ContainsKey(ik))
                        {
                            var right_kr = right_col[ik];
                            HDebug.Assert(ik == right_kr.Item1);
                            HDebug.Assert(ir == right_kr.Item2);
                            MatrixByArr mul_ckr = mul.GetBlock(ic, ir) + left_ck.Value.Item3 * right_kr.Item3;
                            mul.SetBlock(ic, ir, mul_ckr);
                        }
                    }
                }
            }

            return(mul);
        }
Пример #19
0
        public static HessMatrixSparse FromMatrix(Matrix mat, bool parallel = false)
        {
            if (mat is HessMatrixSparse)
            {
                return((mat as HessMatrixSparse).CloneT());
            }

            HDebug.Assert(mat.ColSize % 3 == 0);
            HDebug.Assert(mat.RowSize % 3 == 0);
            HessMatrixSparse hess = ZerosSparse(mat.ColSize, mat.RowSize);

            {
                HessMatrixDense dense = new HessMatrixDense {
                    hess = mat
                };

                Action <Tuple <int, int> > func = delegate(Tuple <int, int> bc_br)
                {
                    int bc = bc_br.Item1;
                    int br = bc_br.Item2;
                    if (dense.HasBlock(bc, br) == false)
                    {
                        return;
                    }

                    var bval = dense.GetBlock(bc, br);
                    lock (hess)
                        hess.SetBlock(bc, br, bval);
                };
                if (parallel)
                {
                    Parallel.ForEach(dense.EnumIndicesAll(), func);
                }
                else
                {
                    foreach (var bc_br_bval in dense.EnumIndicesAll())
                    {
                        func(bc_br_bval);
                    }
                }
            }

            if (HDebug.IsDebuggerAttached)
            {
                // old version
                HessMatrixSparse dhess = ZerosSparse(mat.ColSize, mat.RowSize);
                int colsize            = mat.ColSize;
                int rowsize            = mat.RowSize;
                for (int c = 0; c < colsize; c++)
                {
                    for (int r = 0; r < rowsize; r++)
                    {
                        if (mat[c, r] != 0)
                        {
                            dhess[c, r] = mat[c, r];
                        }
                    }
                }
                HDebug.Assert(HessMatrixSparseEqual(hess, dhess));

                if (HDebug.IsDebuggerAttached && ((mat.ColSize / 3) < 3000))
                {
                    double maxAbsDiff = mat.HAbsMaxDiffWith(hess);
                    HDebug.Assert(maxAbsDiff == 0);
                }
            }

            return(hess);
        }
Пример #20
0
            public static HessMatrix GetHessDihedral
                (IList <Vector> coords, IEnumerable <Universe.Dihedral> dihedrals, double?K_chi, double?n, HessMatrix hessian
                , Action <Universe.Atom, Vector, Universe.Atom, Vector, Universe.Atom, Vector, Universe.Atom, Vector, double, double> collector
                , bool useAbsSpr   = false
                , bool useArnaud96 = false
                )
            {
                int size = coords.Count;

                if (hessian == null)
                {
                    hessian = HessMatrixSparse.ZerosSparse(size * 3, size * 3);
                }

                foreach (Universe.Dihedral dihedral in dihedrals)
                {
                    int idx0 = dihedral.atoms[0].ID; if (coords[idx0] == null)
                    {
                        continue;
                    }
                    int idx1 = dihedral.atoms[1].ID; if (coords[idx1] == null)
                    {
                        continue;
                    }
                    int idx2 = dihedral.atoms[2].ID; if (coords[idx2] == null)
                    {
                        continue;
                    }
                    int idx3 = dihedral.atoms[3].ID; if (coords[idx3] == null)
                    {
                        continue;
                    }
                    double lK_chi = (K_chi != null)? K_chi.Value : dihedral.Kchi;
                    double ln     = (n != null)? n.Value     : dihedral.n;
                    if (useAbsSpr)
                    {
                        /// https://www.charmm.org/ubbthreads/ubbthreads.php?ubb=showflat&Number=24521
                        /// ==========================================================================
                        /// Dear all, Recently I found a parameter file for some carbohydrates, like
                        /// NAG and FUC, which described the dihedral angle as following:
                        ///
                        /// OC CC CTS CTS -1.2007 1 0.0
                        /// OC CC CTS CTS -0.3145 2 0.0
                        /// OC CC CTS CTS -0.0618 3 0.0
                        /// CA OSL SL O2L 0.0000 3 0.0
                        /// CA CA OSL SL 0.0000 3 0.0
                        ///
                        /// In some entries the values of the Kchi for the dihedral angle are 0 or
                        /// negatives. But this value usually is a positive. I understand that the
                        /// kchi value reflect the flexibility of the dihedral, so what do the
                        /// negatives here mean? Thanks a million.
                        /// --------------------------------------------------------------------------
                        /// May I ask where you found these parameters?
                        ///
                        /// Although the negative values violate the convention, they are not
                        /// incorrect. Switching the sign of the amplitude is mathematically
                        /// equivalent to reversing the phase. (See the class I potential energy
                        /// function, as discussed in any paper or textbook on the subject.) In other
                        /// words, -1.2 1 0 is equivalent to 1.2 1 180. CHARMM handles this correctly.
                        /// ==========================================================================
                        /// htna:
                        /// Still "taking absolute value" is not a good choice, but because there is
                        /// no option that I can taek, maybe this is OK in this situation, in order
                        /// to avoid negative springs.
                        lK_chi = Math.Abs(lK_chi);
                    }
                    HDebug.Assert(lK_chi >= 0);
                    ThirdTermN(coords, lK_chi, ln, hessian, idx0, idx1, idx2, idx3, useArnaud96: useArnaud96);

                    if (collector != null)
                    {
                        collector
                            (dihedral.atoms[0], coords[idx0]
                            , dihedral.atoms[1], coords[idx1]
                            , dihedral.atoms[2], coords[idx2]
                            , dihedral.atoms[3], coords[idx3]
                            , lK_chi, ln);
                    }
                }

                return(hessian);
            }