예제 #1
0
        public static Mode[] GetModes(MatrixByArr hess, string cachepath = null)
        {
            Vector[] eigvec;
            double[] eigval;
            if (cachepath != null && HFile.Exists(cachepath))
            {
                HSerialize.Deserialize(cachepath, null, out eigval, out eigvec);
            }
            else
            {
                HDebug.Verify(NumericSolver.Eig(hess, out eigvec, out eigval));
                HSerialize.SerializeDepreciated(cachepath, null, eigval, eigvec);
            }

            List <Mode> modes;

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

            return(modes.ToArray());
        }
예제 #2
0
        public static bool GetModesSelftest()
        {
            if (GetModesSelftest_DoTest == false)
            {
                return(true);
            }
            GetModesSelftest_DoTest = false;

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

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

            Pdb pdb = Pdb.FromFile(pdbpath);

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

            Matrix modes;
            Vector freqs;

            GetModes(hess, out modes, out freqs);

            return(true);
        }
예제 #3
0
            public static string[] LinesFromFile(string path, bool loadLatest)
            {
                string loadpath = path;

                if (loadLatest)
                {
                    System.IO.FileInfo   fileinfo  = HFile.GetFileInfo(path);
                    System.IO.FileInfo[] fileinfos = fileinfo.Directory.GetFiles(fileinfo.Name + "*");
                    if (fileinfos.Length != 0)
                    {
                        List <string> filepaths = new List <string>();
                        foreach (System.IO.FileInfo lfileinfo in fileinfos)
                        {
                            filepaths.Add(lfileinfo.FullName);
                        }
                        filepaths.Sort();
                        loadpath = filepaths.Last();
                    }
                }
                if (HFile.Exists(loadpath) == false)
                {
                    return(null);
                }
                string[] lines = HFile.ReadAllLines(loadpath);
                return(lines);
            }
예제 #4
0
        public static Pdb FromPdbidCache(string pdbid, string cachepath)
        {
            Pdb pdb;

            if (HFile.Exists(cachepath))
            {
                pdb = FromPdbid(pdbid);
                pdb.ToFile(cachepath);
            }
            pdb = FromFile(cachepath);
            return(pdb);
        }
예제 #5
0
        public static Pdb FromPdbid
            (string pdbid
            , string cachebase  // null or @"K:\PdbUnzippeds\$PDBID$.pdb"
            , bool?download     // null or false
            )
        {
            if (cachebase == null)
            {
                cachebase = @"K:\PdbUnzippeds\$PDBID$.pdb";
            }
            if (download == null)
            {
                download = false;
            }

            string pdbpath = cachebase.Replace("$PDBID$", pdbid);

            if (HFile.Exists(pdbpath))
            {
                var pdb  = Pdb.FromFile(pdbpath);
                var last = pdb.elements.Last();
                if (last is Pdb.End)
                {
                    return(pdb);
                }
                if (last.line.Length == 80)
                {
                    return(pdb);
                }

                if (download.Value)
                {   // redownload
                    pdb = Pdb.FromPdbid(pdbid);
                    pdb.ToFile(pdbpath);
                }
                return(pdb);
            }
            else if (download.Value)
            {
                Pdb pdb = Pdb.FromPdbid(pdbid);
                if (pdb != null)
                {
                    pdb.ToFile(pdbpath);
                    return(pdb);
                }
            }
            return(null);
        }
예제 #6
0
        public static bool GetBFactorSelfTest(string pdbpath, double cutoff, double corr, int round, InfoPack extra)
        {
            if (HFile.Exists(pdbpath) == false)
            {
                return(false);
            }

            Pdb pdb = Pdb.FromFile(pdbpath);

            for (int i = 0; i < pdb.atoms.Length; i++)
            {
                HDebug.Assert(pdb.atoms[0].altLoc == pdb.atoms[i].altLoc);
                HDebug.Assert(pdb.atoms[0].chainID == pdb.atoms[i].chainID);
            }
            List <Pdb.Atom> atoms = new List <Pdb.Atom>();

            for (int i = 0; i < pdb.atoms.Length; i++)
            {
                Pdb.Atom atom = pdb.atoms[i];
                if (atom.name.Trim().ToUpper() == "CA")
                {
                    atoms.Add(atom);
                }
            }
            List <Vector> coords  = atoms.ListCoord();
            Matrix        hess    = Hess.GetHessAnm(coords, cutoff);
            InfoPack      lextra  = new InfoPack();
            Vector        bfactor = GetBFactor(hess, 0.00000001, null, lextra);

            if (extra != null)
            {
                extra["num_zero_eigvals"] = lextra["num_zero_eigvals"];
                extra["eigenvalues"]      = lextra["eigenvalues"];
            }

            double corr_comp = pdb.CorrBFactor(atoms.ListName(), atoms.ListResSeq(), bfactor.ToArray());

            corr_comp = Math.Round(corr_comp, round);
            HDebug.Assert(corr == corr_comp);
            return(corr == corr_comp);
        }
예제 #7
0
            public static void ElementsToFile(string path, bool saveAsNext, IList <Element> elements)
            {
                string writepath = path;

                if (saveAsNext)
                {
                    int idx = 2;
                    while (HFile.Exists(writepath))
                    {
                        writepath = string.Format("{0}_{1}", path, idx);
                        idx++;
                    }
                }

                List <string> lines = new List <string>();

                foreach (Element element in elements)
                {
                    lines.Add(element.line);
                }
                HFile.WriteAllLines(writepath, lines);
            }
예제 #8
0
        public static Anisou[] FromHessian(Mode[] modesMassWeighted, double[] mass, double scale = 10000 *1000
                                           , string cachepath = null
                                           )
        {
            if (cachepath != null && HFile.Exists(cachepath))
            {
                List <Anisou> lstanisou;
                HDebug.Verify(HSerialize.Deserialize(cachepath, null, out lstanisou));
                return(lstanisou.ToArray());
            }

            int size = modesMassWeighted.Size();

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

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

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

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

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

            return(anisous);
        }
예제 #9
0
        public static bool GetHessAnmSelfTest()
        {
            if (HDebug.Selftest() == false)
            {
                return(true);
            }

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

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

            Pdb pdb = Pdb.FromFile(pdbpath);

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

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

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

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

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

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

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

            Matlab.Execute("clear;");

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

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

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

            return(true);
        }
예제 #10
0
            public static CPdbxyz Pdbxyz
                (Pdb pdb
                , Tinker.Prm prm
                , string tempbase      //=null
                , string parameters    //=null
                , string tinkerversion //="6.2.1"
                , params string[] keys
                )
            {
                var    tmpdir   = HDirectory.CreateTempDirectory(tempbase);
                string currpath = HEnvironment.CurrentDirectory;

                Tinker.Xyz xyz;
                string[]   seq;
                string[]   capture;
                {
                    HEnvironment.CurrentDirectory = tmpdir.FullName;
                    {
                        foreach (var respath_filename in GetResourcePaths("6.2.1", "pdbxyz"))
                        {
                            string respath  = respath_filename.Item1;
                            string filename = respath_filename.Item2;
                            HResource.CopyResourceTo <Tinker>(respath, filename);
                        }
                    }
                    pdb.ToFile("prot.pdb");
                    prm.ToFile("prot.prm");
                    string keypath = null;
                    if ((keys != null) && (keys.Length > 0))
                    {
                        keypath = "prot.key";
                        HFile.WriteAllLines(keypath, keys);
                    }

                    {
                        //bool ComputeAnalyticalGradientVector    = true;
                        //bool ComputeNumericalGradientVector     = false;
                        //bool OutputBreakdownByGradientComponent = false;
                        string command = "";
                        command += "pdbxyz.exe";
                        command += " prot.pdb";
                        command += " prot.prm";
                        if (keypath != null)
                        {
                            command += " -k " + keypath;
                        }
                        command += " > output.txt";
                        List <string> errors   = new List <string>();
                        int           exitcode = HProcess.StartAsBatchSilent(null, null, errors, command);
                        capture = HFile.ReadAllLines("output.txt");
                        capture = capture.HAddRange(errors.ToArray());
                        xyz     = Tinker.Xyz.FromFile("prot.xyz", false);

                        if (HFile.Exists("prot.seq"))
                        {
                            seq = HFile.ReadAllLines("prot.seq");
                        }
                        else
                        {
                            seq = null;
                        }
                    }
                }
                HEnvironment.CurrentDirectory = currpath;
                try{ tmpdir.Delete(true); } catch {}

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

            int size = mass.Length;

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

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

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

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

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

            return(anisous);
        }
예제 #12
0
            public static ONewton Newton(string tinkerpath
                                         , Tinker.Xyz xyz
                                         , Tinker.Xyz.Atom.Format xyz_atoms_format
                                         , Tinker.Prm prm
                                         , string tempbase
                                         , string copytemp                    // = null
                                         , string param
                                                                              //, string precondition               // = "A"  // Precondition via Auto/None/Diag/Block/SSOR/ICCG [A] :  A
                                                                              //, double gradCriterion              // = 0.01 // Enter RMS Gradient per Atom Criterion [0.01] : 0.001
                                         , IList <Tinker.Xyz.Atom> atomsToFix // = null
                                         , bool pause                         // = false
                                         , params string[] keys
                                         )
            {
                if (HDebug.IsDebuggerAttached && atomsToFix != null)
                {
                    Dictionary <int, Tinker.Xyz.Atom> xyzatoms = xyz.atoms.ToIdDictionary();
                    foreach (var atom in atomsToFix)
                    {
                        HDebug.Assert(object.ReferenceEquals(atom, xyzatoms[atom.Id]));
                    }
                }
                Tinker.Xyz minxyz;
                string[]   minlog;
                using (var temp = new HTempDirectory(tempbase, copytemp))
                {
                    temp.EnterTemp();

                    if (tinkerpath == null)
                    {
                        string resbase = "HTLib2.Bioinfo.HTLib2.Bioinfo.External.Tinker.Resources.tinker_6_2_06.";
                        HResource.CopyResourceTo <Tinker>(resbase + "newton.exe", "newton.exe");
                        tinkerpath = "newton.exe";
                    }
                    xyz.ToFile("prot.xyz", false);
                    prm.ToFile("prot.prm");
                    List <string> keylines = new List <string>(keys);
                    if (atomsToFix != null)
                    {
                        foreach (var atom in atomsToFix)
                        {
                            Vector coord          = atom.Coord;
                            double force_constant = 10000; // force constant in kcal/Å2 for the harmonic restraint potential
                            string keyline        = string.Format("RESTRAIN-POSITION     {0}  {1}  {2}  {3}  {4}", atom.Id, coord[0], coord[1], coord[2], force_constant);
                            keylines.Add(keyline);
                        }
                    }
                    HFile.WriteAllLines("prot.key", keylines);
                    // Precondition via Auto/None/Diag/Block/SSOR/ICCG [A] :  A
                    // Enter RMS Gradient per Atom Criterion [0.01] : 0.001
                    //bool pause = false;
                    string command = tinkerpath;
                    command += string.Format("  prot.xyz  prot.prm");
                    command += string.Format("  -k  prot.key");
                    command += string.Format("  {0}", param);
                    HProcess.StartAsBatchInConsole("newton.bat", pause
                                                   , "time /t  >> prot.log"
                                                   , command //+" >> prot.log"
                                                   , "time /t  >> prot.log"
                                                   );
                    HDebug.Assert(HFile.Exists("prot.xyz_2"));
                    HDebug.Assert(HFile.Exists("prot.xyz_3") == false);
                    minxyz = Tinker.Xyz.FromFile("prot.xyz_2", false, xyz_atoms_format);
                    minlog = HFile.ReadAllLines("prot.log");
                    temp.QuitTemp();
                }

                return(new ONewton
                {
                    minxyz = minxyz,
                    minlog = minlog
                });
            }
예제 #13
0
            public static CNamd2 Namd2
                (IList <string> pdb_lines
                , IList <string> psf_lines
                , IList <string> prm_lines
                , string tempbase           // = null
                , string namd2version       // = "2.8"
                , string option             // = "+p3"
                , IList <string> infiles    = null
                , IList <string> outfiles   = null
                , IList <string> conf_lines = null
                )
            {
                string[] lines = null;
                if ((conf_lines != null) && (conf_lines.Count > 0))
                {
                    lines = conf_lines.ToArray();
                }
                else
                {
                    // http://www.msg.ucsf.edu/local/programs/Vega/pages/tu_namdmin.htm
                    lines = new string[]
                    { "numsteps                10000              " // minimization steps
                      //{ "numsteps                1000               " // minimization steps
                      , "minimization            on                 "
                      , "dielectric              1.0                "
                      , "coordinates             prot.pdb           " // coordinate file
                      , "outputname              output             " // output file: prot.coor
                      , "outputEnergies          1000               "
                      , "binaryoutput            no                 "
                      , "DCDFreq                 1000               "
                      , "restartFreq             1000               "
                      , "structure               prot.psf           " // psf file
                      , "paraTypeCharmm          on                 "
                      , "parameters              prot.prm           " // parameter file
                      //, "parameters              par_all22_vega.inp "
                      , "exclude                 scaled1-4          "
                      , "1-4scaling              1.0                "
                      , "switching               on                 "
                      , "switchdist              8.0                "
                      , "cutoff                  22.0               " //, "cutoff                  12.0               "
                      , "pairlistdist            23.5               " //, "pairlistdist            13.5               "
                      , "margin                  0.0                "
                      , "stepspercycle           20                 "
                      , "fixedAtoms              on                 " // fix atoms
                      , "fixedAtomsCol           O                  " // select fixing atoms from O
                    };
                }

                var    tmpdir   = HDirectory.CreateTempDirectory(tempbase);
                string currpath = HEnvironment.CurrentDirectory;

                HEnvironment.CurrentDirectory = tmpdir.FullName;
                string[] coor_lines = null;
                double   coor_rmsd  = double.NaN;

                {
                    {
                        //foreach(var respath_filename in GetResourcePaths("2.8", "psfgen"))
                        foreach (var respath_filename in GetResourcePaths(namd2version, "namd2"))
                        {
                            string respath  = respath_filename.Item1;
                            string filename = respath_filename.Item2;
                            HResource.CopyResourceTo <Tinker>(respath, filename);
                        }
                    }

                    Vector[] coords0 = Pdb.FromLines(pdb_lines).atoms.ListCoord().ToArray();
                    System.IO.File.WriteAllLines("prot.pdb", pdb_lines);
                    System.IO.File.WriteAllLines("prot.psf", psf_lines);
                    System.IO.File.WriteAllLines("prot.prm", prm_lines);
                    System.IO.File.WriteAllLines("prot.conf", lines);

                    if (option == null)
                    {
                        option = "";
                    }
                    string command = string.Format("namd2 {0} prot.conf", option);
                    HProcess.StartAsBatchInConsole(null, false, command);

                    if (HFile.Exists("output.coor"))
                    {
                        coor_lines = HFile.ReadAllLines("output.coor");
                        Vector[] coords1  = Pdb.FromLines(coor_lines).atoms.ListCoord().ToArray();
                        Vector[] coords1x = Align.MinRMSD.Align(coords0, coords1);
                        coor_rmsd = Align.MinRMSD.GetRMSD(coords0, coords1x);
                    }
                }
                HEnvironment.CurrentDirectory = currpath;
                try{ tmpdir.Delete(true); } catch {}

                if (coor_lines == null)
                {
                    return(null);
                }

                return(new CNamd2
                {
                    coor_lines = coor_lines,
                    coor_rmsd = coor_rmsd,
                });
            }
예제 #14
0
            public static Top FromFile(string path, List <string> defines)
            {
                List <string> lines = new List <string>(HFile.ReadAllLines(path));

                List <LineElement> elements = new List <LineElement>();
                //List<Tuple<string,List<LineElement>>> elementgroup = new List<Tuple<string, List<LineElement>>>();
                //Dictionary<int,Atom> atoms = new Dictionary<int, Atom>();
                //List<Bond> bonds = new List<Bond>();
                //List<Pair> pairs = new List<Pair>();
                //List<Angle> angles = new List<Angle>();
                string type = null;

                while (lines.Count > 0)
                //for(int i=0; i<lines.Length; i++)
                {
                    string line = lines[0];
                    lines.RemoveAt(0);
                    //LineElement element = new LineElement(lines[i]);
                    string typei = LineElement.GetType(line);
                    if (typei != null)
                    {
                        type = typei;
                        //elementgroup.Add(new Tuple<string, List<LineElement>>(type, new List<LineElement>()));
                        continue;
                    }

                    {
                        line = line.Trim();
                        if (line.EndsWith("\\"))
                        {
                            while (lines.Count > 0)
                            {
                                line = line + "\n" + lines[0].Trim();
                                lines.RemoveAt(0);
                                if (line.EndsWith("\\") == false)
                                {
                                    break;
                                }
                            }
                            //line = "";
                            //for(; i<lines.Length; i++)
                            //{
                            //    string lline = lines[i].Trim();
                            //    line = line + lline + "\n";
                            //    if(lline.EndsWith("\\") == false)
                            //        break;
                            //}
                        }
                        line = (line.IndexOf(';') == -1) ? line.Trim() : line.Substring(0, line.IndexOf(';')).Trim();
                        if (line.Length == 0)
                        {
                            continue;
                        }
                        if (line[0] == '*')
                        {
                            continue;
                        }
                        if (line.StartsWith("#define"))
                        {
                            string define = line.Replace("#define", "").Trim();
                            defines.Add(define);
                            continue;
                        }
                        if (line.StartsWith("#include"))
                        {
                            string includepath;
                            {
                                includepath = line.Replace("#include", "").Trim().Replace("\"", "").Trim();
                                if (HFile.Exists(includepath) == false)
                                {
                                    includepath = @"C:\Program Files (x86)\Gromacs\share\gromacs\top\"
                                                  + line.Replace("#include", "").Trim().Replace("\"", "").Trim();
                                }
                                if (HFile.Exists(includepath) == false)
                                {
                                    includepath = HDirectory.GetParent(path).FullName + "\\" //path.Substring(0, path.LastIndexOf('/')+1)
                                                  + line.Replace("#include", "").Trim().Replace("\"", "").Trim();
                                }
                                HDebug.Assert(HFile.Exists(includepath));
                            }
                            Top includetop = FromFile(includepath, defines);
                            elements.AddRange(includetop.elements);
                            type = null;
                            continue;
                        }
                        if (line.StartsWith("#ifdef"))
                        {
                            FromFile_ifdef(defines, lines, line);
                            continue;
                        }
                        if (line.StartsWith("#"))
                        {
                            HDebug.Assert(false);
                        }
                        if (type == "moleculetype")
                        {
                            LineElement element = new Moleculetype(line, path); elements.Add(element); continue;
                        }
                        if (type == "atoms")
                        {
                            LineElement element = new Atom(line, path); elements.Add(element); continue;
                        }
                        if (type == "bonds")
                        {
                            LineElement element = new Bond(line, path); elements.Add(element); continue;
                        }
                        if (type == "pairs")
                        {
                            LineElement element = new Pair(line, path); elements.Add(element); continue;
                        }
                        if (type == "angles")
                        {
                            LineElement element = new Angle(line, path); elements.Add(element); continue;
                        }
                        if (type == "dihedrals")
                        {
                            LineElement element = new Dihedral(line, path); elements.Add(element); continue;
                        }
                        if (type == "cmap")
                        {
                            LineElement element = new Cmap(line, path); elements.Add(element); continue;
                        }
                        if (type == "position_restraints")
                        {
                            LineElement element = new Position_restraints(line, path); elements.Add(element); continue;
                        }
                        if (type == "system")
                        {
                            LineElement element = new System(line, path); elements.Add(element); continue;
                        }
                        if (type == "molecules")
                        {
                            LineElement element = new Molecules(line, path); elements.Add(element); continue;
                        }

                        if (type == "defaults")
                        {
                            LineElement element = new Defaults(line, path); elements.Add(element); continue;
                        }
                        if (type == "atomtypes")
                        {
                            LineElement element = new Atomtypes(line, path); elements.Add(element); continue;
                        }
                        if (type == "pairtypes")
                        {
                            LineElement element = new Pairtypes(line, path); elements.Add(element); continue;
                        }
                        if (type == "bondtypes")
                        {
                            LineElement element = new Bondtypes(line, path); elements.Add(element); continue;
                        }
                        if (type == "constrainttypes")
                        {
                            LineElement element = new Constrainttypes(line, path); elements.Add(element); continue;
                        }
                        if (type == "angletypes")
                        {
                            LineElement element = new Angletypes(line, path); elements.Add(element); continue;
                        }
                        if (type == "dihedraltypes")
                        {
                            LineElement element = new Dihedraltypes(line, path); elements.Add(element); continue;
                        }
                        if (type == "implicit_genborn_params")
                        {
                            LineElement element = new Implicit_genborn_params(line, path); elements.Add(element); continue;
                        }
                        if (type == "cmaptypes")
                        {
                            LineElement element = new Cmaptypes(line, path); elements.Add(element); continue;
                        }
                        if (type == "settles")
                        {
                            LineElement element = new Settles(line, path); elements.Add(element); continue;
                        }
                        if (type == "exclusions")
                        {
                            LineElement element = new Exclusions(line, path); elements.Add(element); continue;
                        }

                        HDebug.Assert(false);
                    }
                }

                Top top = new Top();

                top.elements = elements.ToArray();

                return(top);
            }
예제 #15
0
            public static HessInfoCoarseResiIter GetHessCoarseResiIter
                (Hess.HessInfo hessinfo
                , Vector[] coords
                , FuncGetIdxKeepListRemv GetIdxKeepListRemv
                , ILinAlg ila
                , double thres_zeroblk = 0.001
                , IterOption iteropt   = IterOption.Matlab_experimental
                , string[] options     = null
                )
            {
                bool rediag = true;

                HessMatrix H = null;

                List <int>[] lstNewIdxRemv = null;
                int          numca         = 0;

                double[] reMass   = null;
                object[] reAtoms  = null;
                Vector[] reCoords = null;
                Tuple <int[], int[][]> idxKeepRemv = null;

                //System.Console.WriteLine("begin re-indexing hess");
                {
                    object[] atoms = hessinfo.atoms;
                    idxKeepRemv = GetIdxKeepListRemv(atoms, coords);
                    int[]   idxKeep  = idxKeepRemv.Item1;
                    int[][] idxsRemv = idxKeepRemv.Item2;
                    {
                        List <int> check = new List <int>();
                        check.AddRange(idxKeep);
                        foreach (int[] idxRemv in idxsRemv)
                        {
                            check.AddRange(idxRemv);
                        }
                        check = check.HToHashSet().ToList();
                        if (check.Count != coords.Length)
                        {
                            throw new Exception("the re-index contains the duplicated atoms or the missing atoms");
                        }
                    }
                    List <int> idxs = new List <int>();
                    idxs.AddRange(idxKeep);
                    foreach (int[] idxRemv in idxsRemv)
                    {
                        idxs.AddRange(idxRemv);
                    }
                    HDebug.Assert(idxs.Count == idxs.HToHashSet().Count);

                    H        = hessinfo.hess.ReshapeByAtom(idxs);
                    numca    = idxKeep.Length;
                    reMass   = hessinfo.mass.ToArray().HSelectByIndex(idxs);
                    reAtoms  = hessinfo.atoms.ToArray().HSelectByIndex(idxs);
                    reCoords = coords.HSelectByIndex(idxs);

                    int nidx = idxKeep.Length;
                    lstNewIdxRemv = new List <int> [idxsRemv.Length];
                    for (int i = 0; i < idxsRemv.Length; i++)
                    {
                        lstNewIdxRemv[i] = new List <int>();
                        foreach (var idx in idxsRemv[i])
                        {
                            lstNewIdxRemv[i].Add(nidx);
                            nidx++;
                        }
                    }
                    HDebug.Assert(nidx == lstNewIdxRemv.Last().Last() + 1);
                    HDebug.Assert(nidx == idxs.Count);
                }
                GC.Collect(0);
                HDebug.Assert(numca == H.ColBlockSize - lstNewIdxRemv.HListCount().Sum());

                //if(bool.Parse("false"))
                {
                    if (bool.Parse("false"))
                    #region
                    {
                        int[]      idxKeep  = idxKeepRemv.Item1;
                        int[][]    idxsRemv = idxKeepRemv.Item2;
                        Pdb.Atom[] pdbatoms = hessinfo.atomsAsUniverseAtom.ListPdbAtoms();
                        Pdb.ToFile(@"C:\temp\coarse-keeps.pdb", pdbatoms.HSelectByIndex(idxKeep), false);
                        if (HFile.Exists(@"C:\temp\coarse-graining.pdb"))
                        {
                            HFile.Delete(@"C:\temp\coarse-graining.pdb");
                        }
                        foreach (int[] idxremv in idxsRemv.Reverse())
                        {
                            List <Pdb.Element> delatoms = new List <Pdb.Element>();
                            foreach (int idx in idxremv)
                            {
                                if (pdbatoms[idx] == null)
                                {
                                    continue;
                                }
                                string   line    = pdbatoms[idx].GetUpdatedLine(coords[idx]);
                                Pdb.Atom delatom = Pdb.Atom.FromString(line);
                                delatoms.Add(delatom);
                            }
                            Pdb.ToFile(@"C:\temp\coarse-graining.pdb", delatoms.ToArray(), true);
                        }
                    }
                    #endregion

                    if (bool.Parse("false"))
                    #region
                    {
                        // export matrix to matlab, so the matrix can be checked in there.
                        int[] idxca  = HEnum.HEnumCount(numca).ToArray();
                        int[] idxoth = HEnum.HEnumFromTo(numca, coords.Length - 1).ToArray();
                        Matlab.Register(@"C:\temp\");
                        Matlab.PutSparseMatrix("H", H.GetMatrixSparse(), 3, 3);
                        Matlab.Execute("figure; spy(H)");
                        Matlab.Clear();
                    }
                    #endregion

                    if (bool.Parse("false"))
                    #region
                    {
                        HDirectory.CreateDirectory(@"K:\temp\$coarse-graining\");
                        {   // export original hessian matrix
                            List <int> cs = new List <int>();
                            List <int> rs = new List <int>();
                            foreach (ValueTuple <int, int, MatrixByArr> bc_br_bval in hessinfo.hess.EnumBlocks())
                            {
                                cs.Add(bc_br_bval.Item1);
                                rs.Add(bc_br_bval.Item2);
                            }
                            Matlab.Clear();
                            Matlab.PutVector("cs", cs.ToArray());
                            Matlab.PutVector("rs", rs.ToArray());
                            Matlab.Execute("hess = sparse(cs+1, rs+1, ones(size(cs)));");
                            Matlab.Execute("hess = float(hess);");
                            Matlab.Execute("figure; spy(hess)");
                            Matlab.Execute("cs = int32(cs+1);");
                            Matlab.Execute("rs = int32(rs+1);");
                            Matlab.Execute(@"save('K:\temp\$coarse-graining\hess-original.mat', 'cs', 'rs', '-v6');");
                            Matlab.Clear();
                        }
                        {   // export reshuffled hessian matrix
                            List <int> cs = new List <int>();
                            List <int> rs = new List <int>();
                            foreach (ValueTuple <int, int, MatrixByArr> bc_br_bval in H.EnumBlocks())
                            {
                                cs.Add(bc_br_bval.Item1);
                                rs.Add(bc_br_bval.Item2);
                            }
                            Matlab.Clear();
                            Matlab.PutVector("cs", cs.ToArray());
                            Matlab.PutVector("rs", rs.ToArray());
                            Matlab.Execute("H = sparse(cs+1, rs+1, ones(size(cs)));");
                            Matlab.Execute("H = float(H);");
                            Matlab.Execute("figure; spy(H)");
                            Matlab.Execute("cs = int32(cs+1);");
                            Matlab.Execute("rs = int32(rs+1);");
                            Matlab.Execute(@"save('K:\temp\$coarse-graining\hess-reshuffled.mat', 'cs', 'rs', '-v6');");
                            Matlab.Clear();
                        }
                    }
                    #endregion

                    if (bool.Parse("false"))
                    #region
                    {
                        int[] idxca  = HEnum.HEnumCount(numca).ToArray();
                        int[] idxoth = HEnum.HEnumFromTo(numca, coords.Length - 1).ToArray();

                        HessMatrix A = H.SubMatrixByAtoms(false, idxca, idxca);
                        HessMatrix B = H.SubMatrixByAtoms(false, idxca, idxoth);
                        HessMatrix C = H.SubMatrixByAtoms(false, idxoth, idxca);
                        HessMatrix D = H.SubMatrixByAtoms(false, idxoth, idxoth);
                        Matlab.Clear();
                        Matlab.PutSparseMatrix("A", A.GetMatrixSparse(), 3, 3);
                        Matlab.PutSparseMatrix("B", B.GetMatrixSparse(), 3, 3);
                        Matlab.PutSparseMatrix("C", C.GetMatrixSparse(), 3, 3);
                        Matlab.PutSparseMatrix("D", D.GetMatrixSparse(), 3, 3);
                        Matlab.Clear();
                    }
                    #endregion
                }

                List <HessCoarseResiIterInfo> iterinfos = null;
                {
                    object[] atoms = reAtoms; // reAtoms.HToType(null as Universe.Atom[]);
                    CGetHessCoarseResiIterImpl info = null;
                    switch (iteropt)
                    {
                    case IterOption.ILinAlg_20150329: info = GetHessCoarseResiIterImpl_ILinAlg_20150329(H, lstNewIdxRemv, thres_zeroblk, ila, false);                    break;

                    case IterOption.ILinAlg: info = GetHessCoarseResiIterImpl_ILinAlg(H, lstNewIdxRemv, thres_zeroblk, ila, false);                             break;

                    case IterOption.Matlab: info = GetHessCoarseResiIterImpl_Matlab(atoms, H, lstNewIdxRemv, thres_zeroblk, ila, false, options);              break;

                    case IterOption.Matlab_experimental: info = GetHessCoarseResiIterImpl_Matlab_experimental(atoms, H, lstNewIdxRemv, thres_zeroblk, ila, false, options); break;

                    case IterOption.Matlab_IterLowerTri: info = GetHessCoarseResiIterImpl_Matlab_IterLowerTri(atoms, H, lstNewIdxRemv, thres_zeroblk, ila, false, options); break;

                    case IterOption.LinAlg_IterLowerTri: info = GetHessCoarseResiIterImpl_LinAlg_IterLowerTri.Do(atoms, H, lstNewIdxRemv, thres_zeroblk, ila, false, options); break;
                    }
                    ;
                    H         = info.H;
                    iterinfos = info.iterinfos;
                }
                //{
                //    var info = GetHessCoarseResiIterImpl_Matlab(H, lstNewIdxRemv, thres_zeroblk);
                //    H = info.H;
                //}
                GC.Collect(0);

                if (HDebug.IsDebuggerAttached)
                {
                    int   nidx  = 0;
                    int[] ikeep = idxKeepRemv.Item1;
                    foreach (int idx in ikeep)
                    {
                        bool equal = object.ReferenceEquals(hessinfo.atoms[idx], reAtoms[nidx]);
                        if (equal == false)
                        {
                            HDebug.Assert(false);
                        }
                        HDebug.Assert(equal);
                        nidx++;
                    }
                }

                if (rediag)
                {
                    H = H.CorrectHessDiag();
                }
                //System.Console.WriteLine("finish fixing diag");

                return(new HessInfoCoarseResiIter
                {
                    hess = H,
                    mass = reMass.HSelectCount(numca),
                    atoms = reAtoms.HSelectCount(numca),
                    coords = reCoords.HSelectCount(numca),
                    numZeroEigval = 6,
                    iterinfos = iterinfos,
                });
            }
예제 #16
0
        public static PdbInfo[] GetPdbInfo(params string[] pdbids)
        {
            Dictionary <string, PdbInfo> pdbinfos = new Dictionary <string, PdbInfo>();
            int VER = 0;

            string cachepath = RootPath + @"cache\GetPdbInfo.data";

            if (HFile.Exists(cachepath))
            {
                HSerialize.Deserialize(cachepath, VER, out pdbinfos);
                if (pdbinfos == null)
                {
                    pdbinfos = new Dictionary <string, PdbInfo>();
                }
            }

            bool updated = false;

            for (int i = 0; i < pdbids.Length; i++)
            {
                string pdbid = pdbids[i];

                if (pdbinfos.ContainsKey(pdbid) == false)
                {
                    pdbinfos.Add(pdbid, null);
                }

                if (pdbinfos[pdbid] != null)
                {
                    continue;
                }

                updated = true;
                //continue;

                List <string> pdblines = GetPdbLines(pdbid);
                if (pdblines == null)
                {
                    pdblines = GetPdbLines(pdbid, forceToRedownload: true);
                }
                HDebug.Assert(pdblines != null);
                if (pdblines == null)
                {
                    System.Console.WriteLine(pdbid + " is not processed");
                    continue;
                }

                PdbInfo pdbinfo = GetPdbInfo(pdbid, pdblines);
                pdbinfos[pdbid] = pdbinfo;

                if (i % 10 == 0)
                {
                    System.Console.WriteLine(pdbid + " is processed. There are " + (pdbids.Length - i).ToString() + " unprocessed pdbs.");
                }

                if (i % 200 == 0)
                {
                    HSerialize.Serialize(cachepath, VER, pdbinfos);
                    updated = false;
                    System.Console.WriteLine("serialize cache");
                }
            }
            //GetPdbInfo(pdbinfos);

            if (updated)
            {
                HSerialize.Serialize(cachepath, VER, pdbinfos);
            }

            return(pdbinfos.HSelectByKeys(pdbids));
        }
예제 #17
0
        public static CPsfgenExt PsfgenExt
            (IList <Tuple <string, string, Pdb.IAtom[]> > lstSegFileAtoms
            , string[] toplines
            , string[] parlines
            , Pdb alignto
            , string[] psfgen_lines
            , IList <string> minimize_conf_lines = null
            , HOptions options = null
            )
        {
            if (options == null)
            {
                options = new HOptions((string)null);
            }
            string tempbase       = @"C:\temp\";
            string psfgen_workdir = null;
            string topname        = "prot.top";
            string parname        = "prot.par";

            List <string> psf_lines = null;
            List <string> pdb_lines = null;

            using (var temp = new HTempDirectory(tempbase, null))
            {
                temp.EnterTemp();

                HFile.WriteAllLines(topname, toplines);
                HFile.WriteAllLines(parname, parlines);

                if ((HFile.Exists("prot.pdb") == false) || (HFile.Exists("prot.psf") == false))
                {
                    var psfgen = Namd.RunPsfgen
                                     (lstSegFileAtoms, tempbase, null, "2.10"
                                     , new string[] { topname }
                                     , new string[] {}
                                     , topname
                                     , psfgen_lines: psfgen_lines
                                     , psfgen_workdir: psfgen_workdir
                                     , options: options
                                     );

                    psf_lines = psfgen.psf_lines;
                    pdb_lines = psfgen.pdb_lines;
                    if (alignto != null)
                    {
                        HDebug.Exception("check!!!");
                        ////////////////////////////
                        Pdb prot = Pdb.FromLines(pdb_lines);
                        prot      = PsfgenExt_AlignTo(prot, alignto);
                        pdb_lines = prot.ToLines().ToList();
                    }
                    HFile.WriteAllLines("prot.pdb", pdb_lines);
                    HFile.WriteAllLines("prot.psf", psf_lines);
                }

                if (options.Contains("nomin") == false)
                {
                    if ((HFile.Exists("protmin.coor") == false) || (HFile.Exists("protmin.pdb") == false))
                    {
                        List <string> psfgen_pdb_lines = System.IO.File.ReadLines("prot.pdb").ToList();
                        List <string> psfgen_psf_lines = System.IO.File.ReadLines("prot.psf").ToList();

                        List <string> prm_lines = System.IO.File.ReadLines(parname).ToList();
                        string        Namd2_opt = null;
                        if (options.HSelectStartsWith("minimize option:").Length >= 1)
                        {
                            Namd2_opt = options.HSelectStartsWith("minimize option:").First().Replace("minimize option:", "");
                        }
                        var minpdb = Namd.Run.Namd2
                                         (psfgen_pdb_lines
                                         , psfgen_psf_lines
                                         , prm_lines
                                         , tempbase
                                         , "2.10"
                                         , ((Namd2_opt == null) ? "+p3" : Namd2_opt)
                                         , conf_lines: minimize_conf_lines
                                         );
                        HFile.WriteAllLines("protmin.coor", minpdb.coor_lines);

                        Pdb prot0 = Pdb.FromLines(psfgen_pdb_lines);
                        Pdb prot1 = Pdb.FromLines(minpdb.coor_lines);
                        HDebug.Exception(prot0.atoms.Length == prot1.atoms.Length);
                        HDebug.Exception(prot0.elements.Length == prot1.elements.Length);
                        // update conformation to minimized conformation
                        for (int i = 0; i < prot0.elements.Length; i++)
                        {
                            if (prot0.elements[i].GetType() != prot1.elements[i].GetType())
                            {
                                throw new HException("prot0.elements[i].GetType() != prot1.elements[i].GetType()");
                            }
                            if ((prot0.elements[i] is Pdb.IAtom) == false)
                            {
                                continue;
                            }
                            Pdb.IAtom iatom0 = prot0.elements[i] as Pdb.IAtom;
                            Pdb.IAtom iatom1 = prot1.elements[i] as Pdb.IAtom;
                            Vector    coord0 = iatom0.coord;
                            Vector    coord1 = iatom1.coord;
                            double    dist   = (coord0 - coord1).Dist;
                            if (iatom0.occupancy != 0)
                            {
                                if (dist != 0)
                                {
                                    throw new HException("iatom0.coord - iatom1.coord != 0");
                                }
                            }
                            if (dist != 0)
                            {
                                if (iatom0 is Pdb.Atom)
                                {
                                    string   nline0 = (iatom0 as Pdb.Atom).GetUpdatedLine(coord1);
                                    Pdb.Atom natom0 = Pdb.Atom.FromString(nline0);
                                    prot0.elements[i] = natom0;
                                    continue;
                                }
                                if (iatom0 is Pdb.Hetatm)
                                {
                                    string     nline0 = (iatom0 as Pdb.Hetatm).GetUpdatedLine(coord1);
                                    Pdb.Hetatm natom0 = Pdb.Hetatm.FromString(nline0);
                                    prot0.elements[i] = natom0;
                                    continue;
                                }
                            }
                        }
                        if ((prot0.elements[0] is Pdb.Remark) && (prot1.elements[0] is Pdb.Remark))
                        {
                            prot0.elements[0] = Pdb.Remark.FromString(prot1.elements[0].line);
                        }
                        prot0.ToFile("protmin.pdb");
                        pdb_lines = System.IO.File.ReadLines("protmin.pdb").ToList();
                    }
                }

                //{
                //    Pdb confpdb = GetConfPdb(options);
                //    var psf    = Namd.Psf.FromFile("prot.psf");
                //    var prm    = Namd.Prm.FromFile(parname);
                //    List<string> log = new List<string>();
                //    Universe  univ = Universe.BuilderNamd.Build(psf, prm, confpdb, true, new TextLogger(log));
                //    return univ;
                //}
                temp.QuitTemp();
            }

            return(new CPsfgenExt
            {
                psflines = psf_lines,
                pdblines = pdb_lines,
            });
        }
                public static Tuple <double, double, double[]> GetQuality
                    (string pathcache
                    , Universe univ
                    , Func <Hess.HessInfo> GetHessInfo
                    , double GetHessCoarseResiIter_thres_zeroblk
                    )
                {
                    if (HFile.Exists(pathcache) == false)
                    {
                        double   corr  = double.NaN;
                        double   wovlp = double.NaN;
                        double[] ovlps = new double[]
                        {
                            double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                            double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                        };

                        try
                        {
                            Hess.HessInfo hessinfo = GetHessInfo();

                            Mode[] camodes_orig;
                            {
                                int[]  idxca              = (hessinfo.atoms as Universe.Atom[]).ListPdbAtomName(true).HIdxEqual("CA");
                                Matrix cahess             = Hess.GetHessCoarseBlkmat(hessinfo.hess, idxca, "inv");
                                Mode[] lcamodes           = Hess.GetModesFromHess(cahess, la);
                                var    camodes_nzero_zero = lcamodes.SeparateTolerants();
                                if (bool.Parse("false"))
                                {
                                    camodes_nzero_zero = lcamodes.SeparateTolerantsByCountSigned(6);
                                }                                                                                            /// manually fix 3LKY, 4EDL
                                if (camodes_nzero_zero.Item2.Length != 6)
                                {
                                    throw new HException("# zero-eigval != 6");
                                }
                                camodes_orig = camodes_nzero_zero.Item1;
                            }
                            GC.Collect();
                            Vector cabfactor_orig = camodes_orig.GetBFactor().ToArray();

                            Mode[] camodes_iter;
                            {
                                var    cahess             = Hess.GetHessCoarseResiIter_BlockWise(hessinfo, univ.GetCoords(), la, 18, 500, GetHessCoarseResiIter_thres_zeroblk);
                                Mode[] lcamodes           = Hess.GetModesFromHess(cahess.hess, la);
                                var    camodes_nzero_zero = lcamodes.SeparateTolerantsByCountSigned(6);
                                if (camodes_nzero_zero.Item2.Length != 6)
                                {
                                    throw new HException("# zero-eigval != 6");
                                }
                                camodes_iter = camodes_nzero_zero.Item1;
                            }
                            GC.Collect();
                            Vector cabfactor_iter = camodes_iter.GetBFactor().ToArray();

                            corr = HBioinfo.BFactor.Corr(cabfactor_orig, cabfactor_iter);
                            var lwovlp = HBioinfo.OverlapWeightedByEigval(camodes_orig, camodes_iter, la, false, "corresponding index");
                            wovlp = lwovlp.woverlap;
                            ovlps = new double[]
                            {
                                lwovlp.overlaps[0], lwovlp.overlaps[1], lwovlp.overlaps[2], lwovlp.overlaps[3], lwovlp.overlaps[4],
                                lwovlp.overlaps[5], lwovlp.overlaps[6], lwovlp.overlaps[7], lwovlp.overlaps[8], lwovlp.overlaps[9],
                            };
                        }
                        catch (Exception e)
                        {
                            if (e.Message != "# zero-eigval != 6")
                            {
                                throw;
                            }
                        }

                        HSerialize.SerializeText(pathcache, new double[]
                                                 { corr, wovlp,
                                                   ovlps[0], ovlps[1], ovlps[2], ovlps[3], ovlps[4],
                                                   ovlps[5], ovlps[6], ovlps[7], ovlps[8], ovlps[9], });
                    }

                    {
                        double[] buff;
                        HSerialize.DeserializeText(pathcache, out buff);
                        double   corr  = buff[0];
                        double   wovlp = buff[1];
                        double[] ovlps = new double[] { buff[2], buff[3], buff[4], buff[5], buff[6]
                                                        , buff[7], buff[8], buff[9], buff[10], buff[11] };
                        if (double.IsNaN(corr))
                        {
                            HDebug.Assert(false);
                        }
                        return(new Tuple <double, double, double[]>(corr, wovlp, ovlps));
                    }
                }
                public static void Main
                    (string[] args
                    , string[] hesstypes
                    , double[] threszeroblks
                    )
                {
                    string cachebase = @"K:\cache\CoarseGraining-20150111\proteins-177\";
                    string lockbase  = cachebase + @"lock\"; if (HDirectory.Exists(lockbase) == false)
                    {
                        HDirectory.CreateDirectory(lockbase);
                    }

                    Dictionary <string, List <Tuple <double, double, double[]> > > data = new Dictionary <string, List <Tuple <double, double, double[]> > >();

                    foreach (string pdbid in pdbids)
                    {
                        if (locks.ContainsKey(pdbid) == false)
                        {
                            var filelock = HFile.LockFile(lockbase + pdbid);
                            if (filelock == null)
                            {
                                System.Console.WriteLine("{0} is locked", pdbid);
                                continue;
                            }
                            locks.Add(pdbid, filelock);
                        }

                        string pathbase = cachebase + pdbid + @"\";
                        // load univ
                        var pdb0 = Pdb.FromFile(pathbase + "xry-struc.pdb");
                        var xyz0 = Tinker.Xyz.FromFile(pathbase + "xry-struc.xyz", false);
                        var xyz1 = Tinker.Xyz.FromFile(pathbase + "min-struc-charmm22.xyz", false);
                        var prm  = Tinker.Prm.FromFile(cachebase + "charmm22.prm");
                        if (HFile.Exists(pathbase + "min-struc-charmm22-screened.xyz") == false)
                        {
                            var newton = Tinker.Run.Newton
                                             (xyz1, prm, tempbase
                                             , null       // copytemp
                                             , "A 0.0001" // param
                                             , null       // atomsToFix
                                             , false
                                             , "CUTOFF 9", "TAPER"
                                             );
                            newton.minxyz.ToFile(pathbase + "min-struc-charmm22-screened.xyz", false);
                        }
                        var      xyz2      = Tinker.Xyz.FromFile(pathbase + "min-struc-charmm22-screened.xyz", false);
                        Universe univ      = Universe.BuilderTinker.Build(xyz1, prm, pdb0, xyz0, 0.001);
                        Universe univ_scrn = Universe.BuilderTinker.Build(xyz2, prm, pdb0, xyz0, 0.001);

                        if (HDebug.IsDebuggerAttached)
                        {
                            var grad  = Tinker.Run.Testgrad(xyz1, prm, tempbase);
                            var forc  = grad.anlyts.GetForces(xyz1.atoms);
                            var mforc = forc.Dist().Max();
                            HDebug.Assert(mforc < 0.1);

                            grad = Tinker.Run.Testgrad(xyz2, prm, tempbase, new string[] { "CUTOFF 9", "TAPER" }
                                                       , optOutSource: null
                                                       );
                            forc  = grad.anlyts.GetForces(xyz1.atoms);
                            mforc = forc.Dist().Max();
                            HDebug.Assert(mforc < 0.1);
                        }

                        System.Console.Write(pdbid + " : ");
                        foreach (string hesstype in hesstypes)
                        {
                            foreach (double threszeroblk in threszeroblks)
                            {
                                double GetHessCoarseResiIter_thres_zeroblk        = threszeroblk;
                                Tuple <double, double, double[]> corr_wovlp_ovlps = GetQuality(pathbase, univ, univ_scrn, hesstype, GetHessCoarseResiIter_thres_zeroblk);
                                if (corr_wovlp_ovlps == null)
                                {
                                    System.Console.Write(hesstype + "(Unknown exception                                                            ),    ");
                                    continue;
                                }
                                System.Console.Write(hesstype + "(");
                                System.Console.Write("thod " + threszeroblk + " : ");
                                System.Console.Write("corr {0,6:0.0000}, ", corr_wovlp_ovlps.Item1);
                                System.Console.Write("wovlp {0,6:0.0000} : ", corr_wovlp_ovlps.Item2);
                                System.Console.Write("{0}),    ", corr_wovlp_ovlps.Item3.HToStringSeparated("{0,4:0.00}", ","));

                                string datakey = hesstype + "-" + threszeroblk;
                                if (data.ContainsKey(datakey) == false)
                                {
                                    data.Add(datakey, new List <Tuple <double, double, double[]> >());
                                }
                                data[datakey].Add(corr_wovlp_ovlps);
                            }
                        }
                        System.Console.WriteLine();
                    }

                    System.Console.WriteLine("=================================================================================================");
                    System.Console.Write("avg  : ");
                    foreach (string hesstype in hesstypes)
                    {
                        foreach (double threszeroblk in threszeroblks)
                        {
                            string datakey = hesstype + "-" + threszeroblk;
                            List <Tuple <double, double, double[]> > datai = data[datakey];

                            double[]   lst_corr  = datai.HListItem1().ToArray();
                            double[]   lst_wovlp = datai.HListItem2().ToArray();
                            double[][] lst_ovlps = datai.HListItem3().ToArray();

                            double   corr  = lst_corr.HRemoveAll(double.NaN).Average();
                            double   wovlp = lst_wovlp.HRemoveAll(double.NaN).Average();
                            double[] ovlps = new double[10];
                            for (int i = 0; i < 10; i++)
                            {
                                double[] lst_ovlpsi = new double[lst_ovlps.Length];
                                for (int j = 0; j < lst_ovlps.Length; j++)
                                {
                                    lst_ovlpsi[j] = lst_ovlps[j][i];
                                }
                                ovlps[i] = lst_ovlpsi.HRemoveAll(double.NaN).Average();
                            }

                            System.Console.Write(hesstype + "(");
                            System.Console.Write("thod " + threszeroblk + " : ");
                            System.Console.Write("corr {0,6:0.0000}, ", corr);
                            System.Console.Write("wovlp {0,6:0.0000} : ", wovlp);
                            System.Console.Write("{0}),    ", ovlps.HToStringSeparated("{0,4:0.00}", ","));
                        }
                    }
                    System.Console.WriteLine();
                    System.Console.Write("min  : ");
                    foreach (string hesstype in hesstypes)
                    {
                        foreach (double threszeroblk in threszeroblks)
                        {
                            string datakey = hesstype + "-" + threszeroblk;
                            List <Tuple <double, double, double[]> > datai = data[datakey];

                            double[]   lst_corr  = datai.HListItem1().ToArray();
                            double[]   lst_wovlp = datai.HListItem2().ToArray();
                            double[][] lst_ovlps = datai.HListItem3().ToArray();

                            double   corr  = lst_corr.HRemoveAll(double.NaN).Min();
                            double   wovlp = lst_wovlp.HRemoveAll(double.NaN).Min();
                            double[] ovlps = new double[10];
                            for (int i = 0; i < 10; i++)
                            {
                                double[] lst_ovlpsi = new double[lst_ovlps.Length];
                                for (int j = 0; j < lst_ovlps.Length; j++)
                                {
                                    lst_ovlpsi[j] = lst_ovlps[j][i];
                                }
                                ovlps[i] = lst_ovlpsi.HRemoveAll(double.NaN).Min();
                            }

                            System.Console.Write(hesstype + "(");
                            System.Console.Write("thod " + threszeroblk + " : ");
                            System.Console.Write("corr {0,6:0.0000}, ", corr);
                            System.Console.Write("wovlp {0,6:0.0000} : ", wovlp);
                            System.Console.Write("{0}),    ", ovlps.HToStringSeparated("{0,4:0.00}", ","));
                        }
                    }
                    System.Console.WriteLine();
                    System.Console.Write("#miss: ");
                    foreach (string hesstype in hesstypes)
                    {
                        foreach (double threszeroblk in threszeroblks)
                        {
                            string datakey = hesstype + "-" + threszeroblk;
                            List <Tuple <double, double, double[]> > datai = data[datakey];

                            double[]   lst_corr  = datai.HListItem1().ToArray();
                            double[]   lst_wovlp = datai.HListItem2().ToArray();
                            double[][] lst_ovlps = datai.HListItem3().ToArray();

                            int   cnt_corr  = lst_corr.Length - lst_corr.HRemoveAll(double.NaN).Length;
                            int   cnt_wovlp = lst_wovlp.Length - lst_wovlp.HRemoveAll(double.NaN).Length;
                            int[] cnt_ovlps = new int[10];
                            for (int i = 0; i < 10; i++)
                            {
                                double[] lst_ovlpsi = new double[lst_ovlps.Length];
                                for (int j = 0; j < lst_ovlps.Length; j++)
                                {
                                    lst_ovlpsi[j] = lst_ovlps[j][i];
                                }
                                cnt_ovlps[i] = lst_ovlpsi.Length - lst_ovlpsi.HRemoveAll(double.NaN).Length;
                            }

                            System.Console.Write(hesstype + "(");
                            System.Console.Write("thod " + threszeroblk + " : ");
                            System.Console.Write("corr {0,6}, ", cnt_corr);
                            System.Console.Write("wovlp {0,6} : ", cnt_wovlp);
                            System.Console.Write("{0}),    ", cnt_ovlps.HToStringSeparated("{0,4}", ","));
                        }
                    }
                    System.Console.WriteLine();
                }
예제 #20
0
            public static OMinimize Minimize(string minimizepath
                                             , Tinker.Xyz xyz
                                             , Tinker.Xyz.Atom.Format xyz_atoms_format
                                             , Tinker.Prm prm
                                             , string tempbase
                                             , string copytemp                    // = null
                                             , string param
                                             , IList <Tinker.Xyz.Atom> atomsToFix // = null
                                             , bool pause                         // = false
                                             , params string[] keys
                                             )
            {
                if (HDebug.IsDebuggerAttached && atomsToFix != null)
                {
                    Dictionary <int, Tinker.Xyz.Atom> xyzatoms = xyz.atoms.ToIdDictionary();
                    foreach (var atom in atomsToFix)
                    {
                        HDebug.Assert(object.ReferenceEquals(atom, xyzatoms[atom.Id]));
                    }
                }
                Tinker.Xyz minxyz;
                string[]   minlog;
                using (var temp = new HTempDirectory(tempbase, copytemp))
                {
                    temp.EnterTemp();
                    xyz.ToFile("prot.xyz", false);
                    prm.ToFile("prot.prm");
                    List <string> keylines = new List <string>();
                    //if(grdmin != null)
                    //{
                    //    string keyline = string.Format("GRDMIN                {0}", grdmin.Value);
                    //    keylines.Add(keyline);
                    //}
                    if (atomsToFix != null)
                    {
                        foreach (var atom in atomsToFix)
                        {
                            Vector coord          = atom.Coord;
                            double force_constant = 10000; // force constant in kcal/Å2 for the harmonic restraint potential
                            string keyline        = string.Format("RESTRAIN-POSITION     {0}  {1}  {2}  {3}  {4}", atom.Id, coord[0], coord[1], coord[2], force_constant);
                            keylines.Add(keyline);
                        }
                    }
                    if (keys != null)
                    {
                        keylines.AddRange(keys);
                    }
                    HFile.WriteAllLines("prot.key", keylines);
                    // Enter RMS Gradient per Atom Criterion [0.01] :
                    string command = minimizepath;
                    command += "  prot.xyz  prot.prm";
                    command += "  -k  prot.key  <  param.txt";

                    HFile.WriteAllLines("param.txt", param.HSplit());

                    //command += string.Format("  >> prot.log");
                    HProcess.StartAsBatchInConsole("minimize.bat", pause
                                                   , "time /t >> prot.log"
                                                   , command
                                                   , "time /t >> prot.log"
                                                   );
                    HDebug.Assert(HFile.Exists("prot.xyz_2"));
                    HDebug.Assert(HFile.Exists("prot.xyz_3") == false);
                    minxyz = Tinker.Xyz.FromFile("prot.xyz_2", false, xyz.atoms_format);
                    minlog = HFile.ReadAllLines("prot.log");
                    temp.QuitTemp();
                }

                return(new OMinimize
                {
                    minxyz = minxyz,
                    minlog = minlog
                });
            }