Ejemplo n.º 1
0
        public static void ToFile(string filepath
                                  , Element[] elements
                                  , bool append //= false
                                  , IList <string> additionalHeaders = null
                                  )
        {
            List <string> lines = new List <string>();

            if (additionalHeaders != null)
            {
                lines.AddRange(additionalHeaders);
            }
            lines.Add("MODEL        1                                                                  ");
            lines.AddRange(elements.ToLines());
            lines.Add("ENDMDL                                                                          ");
            if (append == false)
            {
                HFile.WriteAllLines(filepath, lines);
            }
            else
            {
                StringBuilder text = new StringBuilder();
                foreach (string line in lines)
                {
                    text.AppendLine(line);
                }
                HFile.AppendAllText(filepath, text.ToString());
            }
        }
Ejemplo n.º 2
0
            public static CTestgrad Testgrad(string testgradpath
                                             , Tinker.Xyz xyz
                                             , Tinker.Prm prm
                                             , string tempbase                            //=null
                                             , string[] keys
                                             , Dictionary <string, string[]> optOutSource // = null
                                             )
            {
                var       tmpdir   = HDirectory.CreateTempDirectory(tempbase);
                string    currpath = HEnvironment.CurrentDirectory;
                CTestgrad testgrad;

                {
                    HEnvironment.CurrentDirectory = tmpdir.FullName;
                    if (testgradpath == null)
                    {
                        string resbase = "HTLib2.Bioinfo.HTLib2.Bioinfo.External.Tinker.Resources.tinker_6_2_06.";
                        HResource.CopyResourceTo <Tinker>(resbase + "testgrad.exe", "testgrad.exe");
                        testgradpath = "testgrad.exe";
                    }
                    xyz.ToFile("test.xyz", false);
                    prm.ToFile("test.prm");
                    string keypath = null;
                    if (keys != null && keys.Length > 0)
                    {
                        keypath = "test.key";
                        HFile.WriteAllLines(keypath, keys);
                    }
                    testgrad = TestgradImpl(testgradpath, "test.xyz", "test.prm", keypath, optOutSource);
                }
                HEnvironment.CurrentDirectory = currpath;
                try{ tmpdir.Delete(true); } catch {}
                return(testgrad);
            }
Ejemplo n.º 3
0
            public void ToFile(string filepath)
            {
                string[] lines = new string[elements.Length];
                for (int i = 0; i < elements.Length; i++)
                {
                    lines[i] = elements[i].line;
                }

                HFile.WriteAllLines(filepath, lines);
            }
Ejemplo n.º 4
0
            public static CTesthess Testhess
                (string testhesspath
                , Tinker.Xyz xyz
                , Tinker.Prm prm
                , string tempbase                             //=null
                , string[] keys
                , Dictionary <string, string[]> optOutSource  // =null
                , Func <int, int, HessMatrix> HessMatrixZeros // =null
                )
            {
                var       tmpdir   = HDirectory.CreateTempDirectory(tempbase);
                string    currpath = HEnvironment.CurrentDirectory;
                CTesthess testhess;

                {
                    HEnvironment.CurrentDirectory = tmpdir.FullName;
                    if (testhesspath == null)
                    {
                        string resbase = "HTLib2.Bioinfo.HTLib2.Bioinfo.External.Tinker.Resources.tinker_6_2_01.";
                        HResource.CopyResourceTo <Tinker>(resbase + "testhess.exe", "testhess.exe");
                        testhesspath = "testhess.exe";
                    }
                    xyz.ToFile("test.xyz", false);
                    prm.ToFile("test.prm");
                    string keypath = null;
                    if ((keys != null) && (keys.Length > 0))
                    {
                        keypath = "test.key";
                        HFile.WriteAllLines(keypath, keys);
                    }
                    testhess     = Testhess(testhesspath, "test.xyz", "test.prm", keypath, optOutSource, HessMatrixZeros);
                    testhess.xyz = xyz;
                    testhess.prm = prm;
                }
                HEnvironment.CurrentDirectory = currpath;
                try{ tmpdir.Delete(true); } catch {}

                string test_eig = "true";

                if (test_eig == "false")
                {
                    Vector D;
                    using (new Matlab.NamedLock(""))
                    {
                        Matlab.PutSparseMatrix("testeig.H", testhess.hess.GetMatrixSparse(), 3, 3);
                        Matlab.Execute("testeig.H = (testeig.H + testeig.H')/2;");
                        Matlab.Execute("[testeig.V, testeig.D] = eig(full(testeig.H));");
                        Matlab.Execute("testeig.D = diag(testeig.D);");
                        D = Matlab.GetVector("testeig.D");
                        Matlab.Execute("clear testeig;");
                    }
                }

                return(testhess);
            }
Ejemplo n.º 5
0
 public static void CopyPdb(string pathbase, params string[] pdbids)
 {
     if (pathbase.EndsWith("\\") == false)
     {
         pathbase += "\\";
     }
     foreach (string pdbid in pdbids)
     {
         string        pdbpath  = pathbase + pdbid.ToUpper() + ".pdb";
         List <string> pdblines = GetPdbLines(pdbid);
         HFile.WriteAllLines(pdbpath, pdblines);
     }
 }
Ejemplo n.º 6
0
 public static void WriteMdp(string mdppath
                             , string integrator               // = "steep"
                             , double emtol                    // = 5    // Stop minimization when the maximum force < 1.0 kJ/mol/nm
                             , double emstep = 0.01            // Energy step size
                             , long nsteps   = 500000          // Maximum number of (minimization) steps to perform
                                                               // Parameters describing how to find the neighbors of each atom and how to calculate the interactions
                             , int nstlist            = 1      // Frequency to update the neighbor list and long range forces
                             , string ns_type         = "grid" // Method to determine neighbor list (simple, grid)
                             , double rlist           = 1.0    // Cut-off for making neighbor list (short range forces) ; htna 1.0-1.2
                             , string coulombtype     = "Shift"
                             , double rcoulomb        = 1.0
                             , double rcoulomb_switch = 0.0
                             , string vdwtype         = "Shift"
                             , double rvdw            = 1.0
                             , double rvdw_switch     = 0.0
                             )
 {
     string[] lines = new string[]
     {
         "; Parameters describing what to do, when to stop and what to save                                                               ",
         "integrator      = $$integrator$$                                                                                                             ",
         "emtol           = $$emtol$$              ; Stop minimization when the maximum force < 1.0 kJ/mol/nm                                          ",
         "emstep          = $$emstep$$             ; Energy step size                                                                                  ",
         "nsteps          = $$nsteps$$             ; Maximum number of (minimization) steps to perform                                                 ",
         "                                         ; Parameters describing how to find the neighbors of each atom and how to calculate the interactions",
         "nstlist         = $$nstlist$$            ; Frequency to update the neighbor list and long range forces                                       ",
         "ns_type         = $$ns_type$$            ; Method to determine neighbor list (simple, grid)                                                  ",
         "rlist           = $$rlist$$              ; Cut-off for making neighbor list (short range forces) ; htna 1.0-1.2                              ",
         "coulombtype     = $$coulombtype$$                                                                                                            ",
         "rcoulomb        = $$rcoulomb$$                                                                                                               ",
         "rcoulomb_switch = $$rcoulomb_switch$$                                                                                                        ",
         "vdwtype         = $$vdwtype$$                                                                                                                ",
         "rvdw            = $$rvdw$$                                                                                                                   ",
         "rvdw_switch     = $$rvdw_switch$$                                                                                                            ",
     }
     .HReplace("$$integrator$$     ", integrator)
     .HReplace("$$emtol$$          ", emtol)
     .HReplace("$$emstep$$         ", emstep)
     .HReplace("$$nsteps$$         ", nsteps)
     .HReplace("$$nstlist$$        ", nstlist)
     .HReplace("$$ns_type$$        ", ns_type)
     .HReplace("$$rlist$$          ", rlist)
     .HReplace("$$coulombtype$$    ", coulombtype)
     .HReplace("$$rcoulomb$$       ", rcoulomb)
     .HReplace("$$rcoulomb_switch$$", rcoulomb_switch)
     .HReplace("$$vdwtype$$        ", vdwtype)
     .HReplace("$$rvdw$$           ", rvdw)
     .HReplace("$$rvdw_switch$$    ", rvdw_switch)
     ;
     HFile.WriteAllLines(mdppath, lines);
 }
Ejemplo n.º 7
0
            public static Xyz Intxyz(string intpath, string tempbase = null)
            {
                string[] intlines = HFile.ReadAllLines(intpath);
                Xyz      xyz;
                var      tmpdir   = HDirectory.CreateTempDirectory(tempbase);
                string   currpath = HEnvironment.CurrentDirectory;

                {
                    HEnvironment.CurrentDirectory = tmpdir.FullName;
                    HFile.WriteAllLines("test.int", intlines);
                    Intxyz("test.int");
                    xyz = Xyz.FromFile("test.xyz", true);
                }
                HEnvironment.CurrentDirectory = currpath;
                try{ tmpdir.Delete(true); } catch {}
                return(xyz);
            }
Ejemplo n.º 8
0
        public static void ToFile(string filepath
                                  , List <Atom> atoms
                                  , List <Vector>[] coordss
                                  , List <double>[] bfactorss
                                  )
        {
            List <string> lines = new List <string>();
            int           size  = atoms.Count;

            for (int iensemble = 0; iensemble < coordss.Length; iensemble++)
            {
                List <Vector> coords   = coordss[iensemble];
                List <double> bfactors = bfactorss[iensemble];
                HDebug.Assert(size == coords.Count);
                //lines.Add("MODEL        1                                                                  ");
                lines.Add(Pdb.Model.FromModelSerial(iensemble + 1).line);
                for (int i = 0; i < size; i++)
                {
                    Atom atom = atoms[i];
                    {
                        if (coordss != null)
                        {
                            double x = coords[i][0];
                            double y = coords[i][1];
                            double z = coords[i][2];
                            atom = Atom.FromString(atom.GetUpdatedLine(x, y, z));
                        }
                        if (bfactors != null)
                        {
                            atom = Atom.FromString(atom.GetUpdatedLineTempFactor(bfactors[i]));
                        }
                        lines.Add(atom.line);
                    }
                }
                lines.Add(Pdb.Endmdl.From().line);
                //lines.Add("ENDMDL                                                                          ");
            }
            HFile.WriteAllLines(filepath, lines);
        }
Ejemplo n.º 9
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);
            }
Ejemplo n.º 10
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
                });
            }
Ejemplo n.º 11
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,
            });
        }
Ejemplo n.º 12
0
        /// https://www.charmmtutorial.org/index.php/Full_example

        public static string[] Hessian
            (IEnumerable <string> toplines
            , IEnumerable <string> parlines
            , IEnumerable <string> psflines
            , IEnumerable <string> crdlines
            )
        {
            string tempbase = @"C:\temp\";

            string[] mincrdlines;

            using (var temp = new HTempDirectory(tempbase, null))
            {
                temp.EnterTemp();
                string topname    = "top.rtf"; HFile.WriteAllLines(topname, toplines);
                string parname    = "par.prm"; HFile.WriteAllLines(parname, parlines);
                string psfname    = "target.psf"; HFile.WriteAllLines(psfname, psflines);
                string crdname    = "target.crd"; HFile.WriteAllLines(crdname, crdlines);
                string mincrdname = "target-minimized.crd";

                string conf_inp = @"* Minimize PDB
* Minimize PDB
*

! read topology and parameter file
read rtf   card name top.rtf
read param card name par.prm
! read the psf and coordinate file
read psf  card name target.psf
read coor card name target.crd

! set up shake
shake bonh param sele all end

! set up electrostatics, since we're not using PME, set up switching
! electrostatics
nbond inbfrq -1 elec fswitch vdw vswitch cutnb 16. ctofnb 12. ctonnb 10.

energy

coor copy comp


! mini sd nstep 100
! mini abnr nstep 1000 nprint 10000 tolg 0.0000
! ! mini abnr nstep 1000 nprint 100 tolg 0.01
! ! mini abnr nstep 10000000 nprint 100 tolg 0.00
! ! mini abnr nstep   1000000  nprint 100 tolg 10.00    ! target-min-step1-tolg-10_00.crd
! ! mini abnr nstep   1000000  nprint 100 tolg 1.00     ! target-min-step2-tolg-1_00.crd
! ! mini abnr nstep   1000000  nprint 100 tolg 0.10
! ! mini sd nstep 10000                                 ! target-min-step3-sd10000.crd
! ! mini abnr nstep   1000000  nprint 100 tolg 0.01     ! target-min-step4-tolg-0_01.crd
! ! mini abnr nstep   10000  nprint 100 tolg 0.0001     ! target-min-step5-tolg-0_0001.crd
! ! mini abnr nstep   10000  nprint 100 tolg 0.000001   ! target-min-step6-tolg-0_000001.crd
! ! mini abnr nstep   10000  nprint 100 tolg 0.000000     ! target-min-step7-tolg-0_000000.crd
! 
! 
! coor rms
! 
! ioform extended
! 
! write coor card name target-minimized.crd
! * Initial minimization, no PME.
! *

! VIBRAN NMOD 20 ATOM FSWITCH rdie eps 4.0 VDW VSHIFT cutnb 13.0 ctofnb 12.0 CTONNB 8.0
! 
! DIMB ITERations 500 TOLErance 0.04 PARDim 200 IUNMode 21 DWIN
! 
! WRITe SECOnd-derivatives card

! BOMLEV -2
! VIBRAN
! DIAG ENTRopy

! VIBRan NMODes 500
! DIAG
! print norm vector dipole

!mini abnr nstep   100  nprint 100 tolg 0.000000     ! target-min-step7-tolg-0_000000.crd
BOMLEV -2
open unit 1 write form name " + " \"second.dat\" " + @" 
REDUce CMPAct
vibran
!diag
write second card unit 1
close unit 1

!calc natom3 ?NATOM *3
!vibran nmode @natom3
!diag
!print norm

!bomlev - 2
!VIBRan NMOD 300
!DIAGonalize


!https://www.charmm.org/charmm/documentation/by-version/c42b1/params/doc/vibran/

stop



";
                conf_inp = conf_inp.Replace("$$topname$$", topname)
                           .Replace("$$parname$$", parname)
                           .Replace("$$psfname$$", psfname)
                           .Replace("$$crdname$$", crdname)
                           .Replace("$$mincrdname$$", mincrdname)
                ;
                HFile.WriteAllText("conf.inp", conf_inp);

                System.Console.WriteLine("Run the following command at " + temp + " :");
                System.Console.WriteLine("      $ charmm < conf.inp");
                System.Console.WriteLine("   or $ mpd&");
                System.Console.WriteLine("      $ mpirun -n 38 charmm_M < conf.inp");
                System.Console.WriteLine("Then, copy second.dat to " + temp);

                while (true)
                {
                    bool next = HConsole.ReadValue <bool>("Ready for next? ", false, null, false, true);
                    if (next)
                    {
                        if (HFile.ExistsAll(mincrdname))
                        {
                            mincrdlines = HFile.ReadAllLines(mincrdname);
                            /// second.dat has the following format
                            ///
                            /// num-atoms
                            /// pot-energy
                            /// atom1-xforce  atom1-yforce atom1-zforce
                            /// atom2-xforce  atom2-yforce atom2-zforce
                            ///         ...
                            /// atomn-xforce  atomn-yforce atomn-zforce
                            /// upper- or lower-diag elem 1
                            /// upper- or lower-diag elem 2
                            ///   ....
                            /// upper- or lower-diag elem 3n*3n/2
                            /// atom1-xcoord  atom1-ycoord atom1-zcoord
                            /// atom2-xcoord  atom2-ycoord atom2-zcoord
                            ///         ...
                            /// atomn-xcoord  atomn-ycoord atomn-zcoord
                            ///
                            break;
                        }
                        System.Console.WriteLine("DO, copy target.psf and target.crd to " + temp);
                    }
                }

                temp.QuitTemp();
            }
            return(mincrdlines);
        }
Ejemplo n.º 13
0
        /// https://www.charmmtutorial.org/index.php/Full_example

        public static string[] MinimizeCrd
            (IEnumerable <string> toplines
            , IEnumerable <string> parlines
            , IEnumerable <string> psflines
            , IEnumerable <string> crdlines
            , string conf_inp_mini
            )
        {
            string tempbase = @"C:\temp\";

            if (conf_inp_mini == null)
            {
                conf_inp_mini = @"
mini sd nstep 100
mini abnr nstep 1000 nprint 10000 tolg 0.0001
! mini abnr nstep 1000 nprint 100 tolg 0.01
! mini abnr nstep 10000000 nprint 100 tolg 0.00
! mini abnr nstep   1000000  nprint 100 tolg 10.00    ! target-min-step1-tolg-10_00.crd
! mini abnr nstep   1000000  nprint 100 tolg 1.00     ! target-min-step2-tolg-1_00.crd
! mini abnr nstep   1000000  nprint 100 tolg 0.10
! mini sd nstep 10000                                 ! target-min-step3-sd10000.crd
! mini abnr nstep   1000000  nprint 100 tolg 0.01     ! target-min-step4-tolg-0_01.crd
! mini abnr nstep   10000  nprint 100 tolg 0.0001     ! target-min-step5-tolg-0_0001.crd
! mini abnr nstep   10000  nprint 100 tolg 0.000001   ! target-min-step6-tolg-0_000001.crd
! mini abnr nstep   10000  nprint 100 tolg 0.000000     ! target-min-step7-tolg-0_000000.crd
";
            }

            string[] mincrdlines;

            using (var temp = new HTempDirectory(tempbase, null))
            {
                temp.EnterTemp();
                string topname    = "top.rtf"; HFile.WriteAllLines(topname, toplines);
                string parname    = "par.prm"; HFile.WriteAllLines(parname, parlines);
                string psfname    = "target.psf"; HFile.WriteAllLines(psfname, psflines);
                string crdname    = "target.crd"; HFile.WriteAllLines(crdname, crdlines);
                string mincrdname = "target-minimized.crd";

                string conf_inp = @"* Minimize PDB
*

! read topology and parameter file
read rtf   card name $$topname$$
read param card name $$parname$$
! read the psf and coordinate file
read psf  card name $$psfname$$
read coor card name $$crdname$$

! set up shake
shake bonh param sele all end

! set up electrostatics, since we're not using PME, set up switching
! electrostatics
nbond inbfrq -1 elec fswitch vdw vswitch cutnb 16. ctofnb 12. ctonnb 10.

energy

coor copy comp

" + conf_inp_mini + @"

coor rms

ioform extended

write coor card name $$mincrdname$$
* Initial minimization, no PME.
*

stop


";
                conf_inp = conf_inp.Replace("$$topname$$", topname)
                           .Replace("$$parname$$", parname)
                           .Replace("$$psfname$$", psfname)
                           .Replace("$$crdname$$", crdname)
                           .Replace("$$mincrdname$$", mincrdname)
                ;
                HFile.WriteAllText("conf.inp", conf_inp);

                System.Console.WriteLine("Run the following command at " + temp + " :");
                System.Console.WriteLine("      $ charmm < conf.inp");
                System.Console.WriteLine("   or $ mpd&");
                System.Console.WriteLine("      $ mpirun -n 38 charmm_M < conf.inp");
                System.Console.WriteLine("Then, copy target-minimized.crd to " + temp);

                while (true)
                {
                    bool next = HConsole.ReadValue <bool>("Ready for next? ", false, null, false, true);
                    if (next)
                    {
                        if (HFile.ExistsAll(mincrdname))
                        {
                            mincrdlines = HFile.ReadAllLines(mincrdname);
                            break;
                        }
                        System.Console.WriteLine("DO, copy target.psf and target.crd to " + temp);
                    }
                }

                temp.QuitTemp();
            }
            return(mincrdlines);
        }
Ejemplo n.º 14
0
        public static SPsfCrd BuildPsfCrd
            (IEnumerable <string> toplines
            , IEnumerable <string> parlines
            , IEnumerable <string> pdblines
            )
        {
            string tempbase = @"C:\temp\";

            SPsfCrd psfcrd;

            using (var temp = new HTempDirectory(tempbase, null))
            {
                temp.EnterTemp();
                string topname = "top.rtf"; HFile.WriteAllLines(topname, toplines);
                string parname = "par.prm"; HFile.WriteAllLines(parname, parlines);

                string tgtname = "target"; HFile.WriteAllLines(tgtname + ".pdb", pdblines);

                string Setup_inp = @"* Run Segment Through CHARMM
*

! read topology and parameter files

read rtf  card name $$topname$$
read para card name $$parname$$

! Read sequence from the PDB coordinate file
open unit 1 card read name $$tgtname$$.pdb
read sequ pdb unit 1

! now generate the PSF and also the IC table (SETU keyword)
generate setu a-pro first NTER last CTER

rewind unit 1

! set bomlev to -1 to avois sying on lack of hydrogen coordinates
bomlev -1
read coor pdb unit 1
! them put bomlev back up to 0
bomlev 0

close unit 1

! prints out number of atoms that still have undefined coordinates.
define test select segid a-pro .and. ( .not. hydrogen ) .and. ( .not. init ) show end

ic para
ic fill preserve
ic build
hbuild sele all end

! write out the protein structure file (psf) and
! the coordinate file in pdb and crd format.

write psf card name $$tgtname$$.psf
* PSF
*

write coor card name $$tgtname$$.crd
* Coords
*

stop

"
                                   .Replace("$$topname$$", topname)
                                   .Replace("$$parname$$", parname)
                                   .Replace("$$tgtname$$", tgtname);
                HFile.WriteAllText("Setup.inp", Setup_inp);

                System.Console.WriteLine("Run the following command at " + temp + " :");
                System.Console.WriteLine("      $ charmm < Setup.inp");
                System.Console.WriteLine("   or $ mpd&");
                System.Console.WriteLine("      $ mpirun -n 38 charmm_M < Setup.inp");
                System.Console.WriteLine("Then, copy target.psf and target.crd to " + temp);

                while (true)
                {
                    bool next = HConsole.ReadValue <bool>("Ready for next? ", false, null, false, true);
                    if (next)
                    {
                        if (HFile.ExistsAll("target.crd", "target.psf"))
                        {
                            string[] crdlines = HFile.ReadAllLines("target.crd");
                            string[] psflines = HFile.ReadAllLines("target.psf");
                            psfcrd = new SPsfCrd
                            {
                                crdlines = crdlines,
                                psflines = psflines,
                            };
                            break;
                        }
                        System.Console.WriteLine("DO, copy target.psf and target.crd to " + temp);
                    }
                }

                temp.QuitTemp();
            }

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

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

            for (int i = 0; i < size; i++)
            {
                Atom atom = atoms[i];
                if (atom == null)
                {
                    continue;
                }
                {
                    if (coords != null)
                    {
                        double x = coords[i][0];
                        double y = coords[i][1];
                        double z = coords[i][2];
                        atom = Atom.FromString(atom.GetUpdatedLine(x, y, z));
                    }
                    if (bfactors != null)
                    {
                        atom = Atom.FromString(atom.GetUpdatedLineTempFactor(bfactors[i]));
                    }
                    lines.Add(atom.line);
                }
                {
                    if (anisous != null)
                    {
                        MatrixByArr U = anisous[i];
                        if (anisouScale != null)
                        {
                            U = U * anisouScale.Value;
                        }
                        Anisou anisou = Anisou.FromAtom(atom, U.ToArray().HToInt());
                        string line   = anisou.line; //anisou.GetUpdatedU(anisous[i])
                        lines.Add(line);
                    }
                }
            }
            lines.Add("ENDMDL                                                                          ");
            //int idx = 0;
            //foreach(Element element in elements)
            //{
            //    string line = element.line;
            //    if(typeof(Atom).IsInstanceOfType(element))
            //    {
            //        double x = coords[idx][0];
            //        double y = coords[idx][1];
            //        double z = coords[idx][2];
            //        Atom atom = (Atom)element;
            //        line = atom.GetUpdatedLine(x, y, z);
            //        idx++;
            //    }
            //    lines.Add(line);
            //}
            if (append == false)
            {
                HFile.WriteAllLines(filepath, lines);
            }
            else
            {
                StringBuilder text = new StringBuilder();
                foreach (string line in lines)
                {
                    text.AppendLine(line);
                }
                HFile.AppendAllText(filepath, text.ToString());
            }
        }
Ejemplo n.º 16
0
        public void ToFile(string filepath, IList <Vector> coords = null, IList <double> bfactors = null, IList <MatrixByArr> anisous = null, double anisous_scale = 1, bool append = false)
        {
            List <string> lines = new List <string>();

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

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

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

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

                    lines.Add(atom.line);

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

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

            if (append == false)
            {
                HFile.WriteAllLines(filepath, lines);
            }
            else
            {
                StringBuilder text = new StringBuilder();
                foreach (string line in lines)
                {
                    text.AppendLine(line);
                }
                HFile.AppendAllText(filepath, text.ToString());
            }
        }
Ejemplo n.º 17
0
 public void ToFile(string filepath)
 {
     string[] lines = ToLines();
     HFile.WriteAllLines(filepath, lines);
 }
Ejemplo n.º 18
0
            public static CPsfgen Psfgen
                (IList <Tuple <string, string, Pdb.IAtom[]> > lstSegFileAtoms // segname, filename, pdbatoms
                , string tempbase                                             //=null
                , string parameters                                           //=null
                , string namdversion                                          //="2.8"
                , IList <string> infiles
                , IList <string> outfiles
                , string topology
                , IList <string> psfgen_lines = null
                , string psfgen_workdir       = null
                , HOptions options            = null
                )
            {
                if (options == null)
                {
                    options = new HOptions((string)null);
                }
                Dictionary <System.IO.FileInfo, string[]> infile_lines = new Dictionary <System.IO.FileInfo, string[]>();

                foreach (string infile in infiles)
                {
                    infile_lines.Add(HFile.GetFileInfo(infile), HFile.ReadAllLines(infile));
                }

                string currpath = HEnvironment.CurrentDirectory;

                System.IO.DirectoryInfo tmpdir = null;
                if (psfgen_workdir != null)
                {
                    HEnvironment.CurrentDirectory = psfgen_workdir;
                }
                else
                {
                    tmpdir = HDirectory.CreateTempDirectory(tempbase);
                    HEnvironment.CurrentDirectory = tmpdir.FullName;
                }

                string[] lines = null;
                if ((psfgen_lines != null) && (psfgen_lines.Count > 0))
                {
                    lines = psfgen_lines.ToArray();
                }
                else
                {
                    lines = GetPsfgenLines
                                (custom_pdbalias: null
                                , custom_patches: null
                                );
                }

                if (topology != null)
                {
                    lines = lines.ToArray().HReplace("$topology$", topology);
                }

                List <string> psf_lines;
                List <string> pdb_lines;

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

                    //  Dictionary<string, Tuple<string, Pdb.IAtom[]>> segname_filename_pdbatoms = new Dictionary<string, Tuple<string, Pdb.IAtom[]>>();
                    //  //if(pdbs.Length != 1) throw new ArgumentException();
                    //  for(int i=0; i<lstSegFilePdb.Count; i++)
                    //  {
                    //      string  segnameprefix = lstSegFilePdb[i].Item1; if( segnameprefix == null)  segnameprefix = string.Format("{0:00}", i);
                    //      string filenameprefix = lstSegFilePdb[i].Item2; if(filenameprefix == null) filenameprefix = string.Format("{0:00}", i);
                    //      Pdb    pdb            = lstSegFilePdb[i].Item3;
                    //      List<Pdb.IAtom> pdb_atoms = new List<Pdb.IAtom>();
                    //      pdb_atoms.AddRange(pdb.atoms);
                    //      pdb_atoms.AddRange(pdb.hetatms);
                    //      char[] chains = pdb_atoms.ListChainID().HToHashSet().ToArray();
                    //
                    //      HDebug.AssertIf(chains.Length> 1, segnameprefix.Length <= 5);
                    //      HDebug.AssertIf(chains.Length<=1, segnameprefix.Length <= 6);
                    //      foreach(char chain in chains)
                    //      {
                    //          Pdb.IAtom[] chain_atoms = pdb_atoms.SelectByChainID(chain).SelectByAltLoc().ToArray();
                    //          string suffix = null;
                    //          if(('a' <= chain) && (chain <= 'z')) suffix = string.Format("L{0}", chain);
                    //          if(('A' <= chain) && (chain <= 'Z')) suffix = string.Format("U{0}", chain);
                    //          if(('0' <= chain) && (chain <= '9')) suffix = string.Format("N{0}", chain);
                    //          string  segname =  segnameprefix + ((chains.Length <= 1) ? "" : suffix);
                    //          string filename = filenameprefix + ((chains.Length <= 1) ? "" : suffix);
                    //          segname_filename_pdbatoms.Add(segname, new Tuple<string,Pdb.IAtom[]>(filename, chain_atoms));
                    //      }
                    //  }

                    foreach (var finfo_line in infile_lines)
                    {
                        string   inname  = finfo_line.Key.Name;
                        string[] inlines = finfo_line.Value;
                        HFile.WriteAllLines(inname, inlines);
                    }

                    HashSet <string> segnames = new HashSet <string>();
                    int segindex = 0;
                    foreach (var seg_file_atoms in lstSegFileAtoms)
                    {
                        string      segname     = seg_file_atoms.Item1;
                        string      filename    = seg_file_atoms.Item2;
                        Pdb.IAtom[] chain_atoms = seg_file_atoms.Item3.SelectByAltLoc().ToArray();
                        HDebug.Exception(chain_atoms.ListChainID().HToHashSet().Count == 1);
                        if (segname == null)
                        {
                            while (segindex <= 9999)
                            {
                                if (segnames.Contains(segindex.ToString()) == false)
                                {
                                    segname = segindex.ToString();
                                    segnames.Add(segname);
                                    break;
                                }
                                segindex++;
                            }
                        }
                        if (filename == null)
                        {
                            filename = segname;
                        }

                        Pdb.ToFile
                            (filename + ".pdb"
                            , chain_atoms.HToType <Pdb.IAtom, Pdb.Element>()
                            , false
                            );

                        for (int i = 0; i < lines.Length; i++)
                        {
                            if (lines[i].Contains("$segname$"))
                            {
                                string insert = lines[i];
                                insert = insert.Replace("$segname$", segname);
                                insert = insert.Replace("$segfilename$", filename);
                                lines  = lines.HInsert(i, insert);
                                i++;
                            }
                        }
                    }

                    lines = lines.HRemoveAllContains("$segname$");

                    HFile.WriteAllLines("prot.inp", lines);
                    string command0 = string.Format("psfgen < prot.inp");
                    bool   pause    = options.Contains("psfgen pause");
                    HProcess.StartAsBatchInConsole(null, pause, command0);

                    psf_lines = System.IO.File.ReadLines("prot.psf").ToList();
                    pdb_lines = System.IO.File.ReadLines("prot.pdb").ToList();
                }
                HEnvironment.CurrentDirectory = currpath;
                if (tmpdir != null)
                {
                    try{ tmpdir.Delete(true); } catch {}
                }

                return(new CPsfgen
                {
                    psf_lines = psf_lines,
                    pdb_lines = pdb_lines,
                });
            }
Ejemplo n.º 19
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,
                });
            }
Ejemplo n.º 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
                });
            }
Ejemplo n.º 21
0
        public static void SavePse(string psepath
                                   , bool cartoon
                                   , bool line
                                   , string pngpath // null if not save png
                                   , params string[] pdbpaths)
        {
            string currpath = HEnvironment.CurrentDirectory;

            HEnvironment.CurrentDirectory = HFile.GetFileInfo(psepath).Directory.FullName;
            {
                Random rand    = new Random();
                string psename = HFile.GetFileInfo(psepath).Name;

                int      count     = pdbpaths.Length;
                string[] pdblnames = new string[count];
                string[] pdblpaths = new string[count];
                for (int i = 0; i < count; i++)
                {
                    var info = HFile.GetFileInfo(pdbpaths[i]);
                    pdblnames[i] = info.Name.Replace(".pdb", "").Replace(".PDB", "");
                    pdblpaths[i] = psepath + info.Name + rand.NextInt(99999).ToString(".rnd00000") + ".pdb";
                    HFile.Copy(pdbpaths[i], pdblpaths[i]);
                }

                string        pmlpath = psepath + rand.NextInt(99999).ToString(".rnd00000") + ".pml";
                List <string> pmltext = new List <string>();
                for (int i = 0; i < count; i++)
                {
                    pmltext.Add("load $$path$$, $$name$$;".Replace("$$path$$", pdblpaths[i]).Replace("$$name$$", pdblnames[i]));
                }
                if (cartoon)
                {
                    pmltext.Add("show cartoon;");
                }
                else
                {
                    pmltext.Add("hide cartoon");
                }
                if (line)
                {
                    pmltext.Add("show lines;");
                }
                else
                {
                    pmltext.Add("hide lines");
                }
                pmltext.Add("reset;");
                pmltext.Add("save $$psepath$$;".Replace("$$psepath$$", psepath));
                if (pngpath != null)
                {
                    pmltext.Add("png $$pngpath$$;".Replace("$$pngpath$$", pngpath));
                }
                pmltext.Add("quit;");

                HFile.WriteAllLines(pmlpath, pmltext);

                System.Diagnostics.Process pymol;
                pymol = System.Diagnostics.Process.Start(@"C:\Program Files (x86)\PyMOL\PyMOL\PymolWin.exe", pmlpath);
                pymol.WaitForExit();

                for (int i = 0; i < count; i++)
                {
                    HFile.Delete(pdblpaths[i]);
                }
                HFile.Delete(pmlpath);
            }
            HEnvironment.CurrentDirectory = currpath;
        }
Ejemplo n.º 22
0
            public static void WriteResult(string pdbid, List <Pdb.Atom>[] ensemble, List <Trans3[]> trajtrans, string pathroot)
            {
                List <Pdb.Atom> atoms = ensemble[0];

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

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

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

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

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

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

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

                    {
                        HFile.AppendAllLines(pmlpath, "quit");
                        string curdirectory = System.Environment.CurrentDirectory;
                        string pmldirectory = pmlpath.Substring(0, pmlpath.LastIndexOf('\\') + 1);
                        System.Environment.CurrentDirectory = pmldirectory;
                        System.Diagnostics.ProcessStartInfo pymolStartInfo = new System.Diagnostics.ProcessStartInfo(@"C:\Program Files (x86)\PyMOL\PyMOL\PymolWin.exe ", "\"" + pmlpath + "\"");
                        pymolStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
                        System.Diagnostics.Process pymol = System.Diagnostics.Process.Start(pymolStartInfo);
                        //pymol.win
                        pymol.WaitForExit();
                        System.Environment.CurrentDirectory = curdirectory;
                        HFile.WriteAllLines(pmlpath, lines);
                    }
                    {
                        List <string> lines_notheseus = new List <string>();
                        for (int i = 0; i < lines.Length; i++)
                        {
                            if (lines[i].Contains("theseus") == false)
                            {
                                lines_notheseus.Add(lines[i]);
                            }
                        }
                        HFile.WriteAllLines(pathroot + "align.notheseus.pml", lines);
                    }
                }
            }
Ejemplo n.º 23
0
            public static Vector[] MinimizeLBfgs(IList <Pdb.Atom> atoms
                                                 , IList <Vector> coords = null
                                                 , string ff             = null // -ff          string select  Force field, interactive by default. Use -h for information.
                                                                                //              "charmm27", ...
                                                 , string water      = null     // -water       enum   select  Water model to use: select, none, spc, spce, tip3p, tip4p or tip5p
                                                 , double mdp_emtol  = 0.001    // the minimization is converged when the maximum force is smaller than this value
                                                 , double mdp_emstep = 0.001    // initial step-size
                                                 )
            {
                Vector[] confout;
                {
                    string currdir = HEnvironment.CurrentDirectory;
                    System.IO.DirectoryInfo temproot = HDirectory.CreateTempDirectory();
                    HEnvironment.CurrentDirectory = temproot.FullName;
                    {
                        if (coords != null)
                        {
                            HDebug.Assert(atoms.Count == coords.Count);
                        }
                        Pdb.ToFile("conf.pdb", atoms, coords: coords
                                   , headers: new string[] { "CRYST1                                                                          " }
                                   );
                        HFile.WriteAllLines("grompp-nm.mdp"
                                            , new string[] { "; Parameters describing what to do, when to stop and what to save                                                                    "
                                                             , "integrator      = l-bfgs                                                                                                             "
                                                             , "emtol           = 0.001                                                                                                              "
                                                             , "emstep          = 0.001      ; Energy step size                                                                                      "
                                                             , "nsteps          = 5000000000 ; Maximum number of (minimization) steps to perform                                                              "
                                                             , "                             ; Parameters describing how to find the neighbors of each atom and how to calculate the interactions    "
                                                             , "nstlist         = 1          ; Frequency to update the neighbor list and long range forces                                           "
                                                             , "ns_type         = grid       ; Method to determine neighbor list (simple, grid)                                                      "
                                                             , "rlist           = 1.0        ; Cut-off for making neighbor list (short range forces) ; htna 1.0-1.2                                  "
                                                             , "coulombtype     = Shift                                                                                                              "
                                                             , "rcoulomb        = 1.0                                                                                                                "
                                                             , "rcoulomb_switch = 0.7                                                                                                                "
                                                             , "vdwtype         = Shift                                                                                                              "
                                                             , "rvdw            = 1.0                                                                                                                "
                                                             , "rvdw_switch     = 0.7                                                                                                                "
                                                             //,"                                                                                                                                     "
                                                             //,"                                                                                                                                     "
                                                             //,"nstxout         = 1; (100) [steps]  frequency to write coordinates to output trajectory file, the last coordinates are always written"
                                                             //,"nstvout         = 1; (100) [steps]  frequency to write velocities to output trajectory, the last velocities are always written       "
                                                             //,"nstfout         = 1; (  0) [steps]  frequency to write forces to output trajectory.                                                  "
                                            });

                        RunPdb2gmx(f: "conf.pdb"
                                   , o: "confout.pdb"
                                   , p: "topol.top"
                                   , i: "posre.itp"
                                   , n: "clean.ndx"
                                   , q: "clean.pdb"
                                   , ff: "charmm27"
                                   , water: "none"
                                   , merge: "all"
                                   , lineStderr: null
                                   , lineStdout: null
                                   );

                        RunGrompp(f: "grompp-nm.mdp"
                                  , p: "topol.top"
                                  , o: "topol-nm.tpr"
                                  , c: "confout.pdb"
                                  , lineStderr: null
                                  , lineStdout: null
                                  );


                        RunMdrun(s: "topol-nm.tpr"
                                 , c: "confout.pdb"
                                 , o: "traj.trr"
                                 , g: "md.log"
                                 //, mtx:"hessian.mtx"
                                 //, pf:"pullf.xvg"
                                 //, px:"pullx.xvg"
                                 //, nt:"3"
                                 , lineStderr: null
                                 , lineStdout: null
                                 );

                        Pdb pdbout = Pdb.FromFile("confout.pdb");
                        confout = pdbout.atoms.ListCoord().ToArray();
                    }
                    HEnvironment.CurrentDirectory = currdir;
                    Thread.Sleep(100);
                    try{ temproot.Delete(true); } catch (Exception) {}
                }

                HDebug.Assert(confout.Length == atoms.Count);
                return(confout);
            }
Ejemplo n.º 24
0
        /// https://www.charmmtutorial.org/index.php/Full_example

        public static SPsfCrd Solvate
            (IEnumerable <string> toplines
            , IEnumerable <string> parlines
            , IEnumerable <string> psflines_prot
            , IEnumerable <string> crdlines_prot
            , IEnumerable <string> crdlines_water
            )
        {
            string tempbase = @"C:\temp\";

            SPsfCrd psfcrd;

            using (var temp = new HTempDirectory(tempbase, null))
            {
                temp.EnterTemp();
                string topname           = "top.rtf"; HFile.WriteAllLines(topname, toplines);
                string parname           = "par.prm"; HFile.WriteAllLines(parname, parlines);
                string psfname_prot      = "prot.psf"; HFile.WriteAllLines(psfname_prot, psflines_prot);
                string crdname_prot      = "prot.crd"; HFile.WriteAllLines(crdname_prot, crdlines_prot);
                string crdname_water     = "water.crd"; HFile.WriteAllLines(crdname_water, crdlines_water);
                string psfname_protwater = "protwater.psf";
                string crdname_protwater = "protwater.crd";

                string conf_inp = @"* Run Segment Through CHARMM
*

! read topology and parameter files
read rtf  card name $$topname$$
read para card name $$parname$$

! read the psf and coordinate file
read psf  card name $$psfname_prot$$
read coor card name $$crdname_prot$$


! Read in water sequence
read sequence tip3 46656

! Generate new segment for the water
generate bwat noangle nodihedral

! Read the water PDB coordinates and append them to the protein
read coor card append name $$crdname_water$$

! Delete waters which overlap with protein
delete atom sort -
select .byres. (segid bwat .AND. type oh2 .and. -
((.not. (segid bwat .OR. hydrogen)) .around. 2.5)) end

! set headstr = rhdo with a crystal dimension of @greatervalue
set headstr = test xxx

! we want to do a quick-and-dirty minimization to remove bad contacts. Therefore, we should
! set up shake and the non-bond parameters again.
shake bonh param sele all end
nbond inbfrq -1 elec fswitch vdw vswitch cutnb 16. ctofnb 12. ctonnb 10.
mini sd nstep 100 nprint 1 tolgrd 100.0

! use Expanded I/O format
ioform extended

! since we've changed the structure by adding waters, we need to write out a new PSF
write psf card name $$psfname_protwater$$
* new_1cbn-18126-1-solv.psf
* solvation: @headstr
*

write coor card name $$crdname_protwater$$
* new_1cbn-18126-1-solv.crd
* solvation: @headstr
*

stop

".Replace("$$topname$$", topname)
                                  .Replace("$$parname$$", parname)
                                  .Replace("$$psfname_prot$$", psfname_prot)
                                  .Replace("$$crdname_prot$$", crdname_prot)
                                  .Replace("$$crdname_water$$", crdname_water)
                                  .Replace("$$psfname_protwater$$", psfname_protwater)
                                  .Replace("$$crdname_protwater$$", crdname_protwater)
                ;
                HFile.WriteAllText("conf.inp", conf_inp);

                System.Console.WriteLine("Run the following command at " + temp + " :");
                System.Console.WriteLine("      $ charmm < conf.inp");
                System.Console.WriteLine("   or $ mpd&");
                System.Console.WriteLine("      $ mpirun -n 38 charmm_M < conf.inp");
                System.Console.WriteLine("Then, copy " + psfname_protwater + " and " + crdname_protwater + " to " + temp);

                while (true)
                {
                    bool next = HConsole.ReadValue <bool>("Ready for next? ", false, null, false, true);
                    if (next)
                    {
                        if (HFile.ExistsAll(psfname_protwater, crdname_protwater))
                        {
                            string[] psflines_protwater = HFile.ReadAllLines(psfname_protwater);
                            string[] crdlines_protwater = HFile.ReadAllLines(crdname_protwater);
                            psfcrd = new SPsfCrd
                            {
                                psflines = psflines_protwater,
                                crdlines = crdlines_protwater,
                            };
                            break;
                        }
                        System.Console.WriteLine("DO, copy " + psfname_protwater + " and " + crdname_protwater + " to " + temp);
                    }
                }

                temp.QuitTemp();
            }
            return(psfcrd);
        }
Ejemplo n.º 25
0
            public static MixHessInfo GetHessMixModel(Universe univ, IList <Vector> coords, ILinAlg la
                                                      , IList <ResInfo> lstResAllAtom, FnGetHess GetHess, out string errmsg
                                                      , bool bGetIntmInfo, string strBkbnReso
                                                      )
            {
                FnGetHess lGetHess = delegate(Universe luniv, IList <Vector> lcoords, int[] lidxAll, int[] lidxBuffer, int[] lidxCoarse, int[] idxBackbone)
                {
                    // double check if all three indices are disjoint
                    HDebug.Assert(lidxAll.HUnion().Length == lidxAll.Length);
                    HDebug.Assert(lidxBuffer.HUnion().Length == lidxBuffer.Length);
                    HDebug.Assert(lidxCoarse.HUnion().Length == lidxCoarse.Length);
                    HDebug.Assert(lidxAll.HListCommonT(lidxBuffer).Count == 0);
                    HDebug.Assert(lidxBuffer.HListCommonT(lidxCoarse).Count == 0);
                    HDebug.Assert(lidxCoarse.HListCommonT(lidxAll).Count == 0);
                    if (HDebug.IsDebuggerAttached)
                    {
                        foreach (int idx in lidxAll)
                        {
                            HDebug.Assert(lcoords[idx] != null);
                        }
                        foreach (int idx in lidxBuffer)
                        {
                            HDebug.Assert(lcoords[idx] != null);
                        }
                        foreach (int idx in lidxCoarse)
                        {
                            HDebug.Assert(lcoords[idx] != null);
                        }
                    }

                    var hessinfo = GetHess(luniv, lcoords, lidxAll, lidxBuffer, lidxCoarse, idxBackbone);
                    return(hessinfo);
                };

                bool   bVerifySteps = false; // HDebug.IsDebuggerAttached;
                Vector bfactorFull  = null;

                if (bVerifySteps && HDebug.IsDebuggerAttached)
                {
                    int[] idxAll       = HEnum.HEnumCount(coords.Count).ToArray();
                    var   hessinfo     = lGetHess(univ, coords, idxAll, new int[0], new int[0], new int[0]);
                    var   modes        = hessinfo.GetModesMassReduced();
                    var   modesPosZero = modes.SeparateTolerants();
                    HDebug.Assert(modesPosZero.Item2.Length == 6);
                    bfactorFull = modesPosZero.Item1.GetBFactor().ToArray();
                }

                IList <Pdb.Atom> pdbatoms = univ.atoms.ListPdbAtoms();

                ResInfo[] resinfos = pdbatoms.ListResInfo(true);

                int[] idxCa;   // idxs of Ca atoms
                int[] idxBkbn; // idxs of backbone atoms
                int[] idxSele; // idxs of all atoms of lstResAllAtom (selected)
                int[] idxCntk; // idxs of all atoms contacting idxSele
                {
                    string[] nameBkbn;
                    switch (strBkbnReso)
                    {
                    case "NCaC": nameBkbn = new string[] { "N", "CA", "C" }; break;

                    case "NCaC-O": nameBkbn = new string[] { "N", "CA", "C", "O" }; break;

                    case "NCaC-OHn": nameBkbn = new string[] { "N", "CA", "C", "O", "HN" }; break;

                    case "NCaC-O-Ha": nameBkbn = new string[] { "N", "CA", "C", "O", "HA" }; break;

                    case "NCaC-OHn-HaCb": nameBkbn = new string[] { "N", "CA", "C", "O", "HN", "HA", "CB" }; break;

                    default: throw new NotImplementedException();
                    }

                    idxCa = univ.atoms.ListPdbAtoms().IdxByName(true, "CA");
                    //idxBkbn = univ.atoms.ListPdbAtoms().IdxByName(true, "N", "CA", "C", "O", "HA");
                    idxBkbn = univ.atoms.ListPdbAtoms().IdxByName(true, nameBkbn);

                    idxSele = resinfos.HIdxEqual(ResInfo.Equals, lstResAllAtom.ToArray());
                    Vector[] coordSele = coords.HSelectByIndex(idxSele);

                    int[]     idxCtof = coords.HIdxWithinCutoff(4.5, coordSele);
                    ResInfo[] resCtof = resinfos.HSelectByIndex(idxCtof);
                    resCtof = resCtof.HUnion();                                                 // remove redundant residues
                    resCtof = resCtof.HRemoveAll(lstResAllAtom.ToArray()).ToArray();            // remove active site residues
                    idxCntk = resinfos.HIdxEqual(ResInfo.Equals, resCtof);

                    bool plot = false;
                    if (plot)
                    #region verify by plotting
                    {
                        Pdb.ToFile(@"C:\temp\mix.pdb", pdbatoms, coords);
                        Pymol.Py.CgoOld.WriteBlank(@"C:\temp\mix.py", false);
                        Pymol.Py.CgoOld.WriteSphere(@"C:\temp\mix.py", "Ca", coords.HSelectByIndex(idxCa).HRemoveAllNull(), 0.3);
                        Pymol.Py.CgoOld.WriteSphere(@"C:\temp\mix.py", "backbone", coords.HSelectByIndex(idxBkbn).HRemoveAllNull(), 0.3);
                        Pymol.Py.CgoOld.WriteSphere(@"C:\temp\mix.py", "active", coordSele.HRemoveAllNull()
                                                    , 0.3
                                                    , red: 1, green: 0, blue: 0);
                        Pymol.Py.CgoOld.WriteSphere(@"C:\temp\mix.py", "connect", coords.HSelectByIndex(idxCntk).HRemoveAllNull()
                                                    , 0.3
                                                    , red: 0, green: 0, blue: 1);
                        HFile.WriteAllLines(@"C:\temp\mix.pml", new string[]
                        {
                            "load mix.pdb",
                            "run mix.py",
                            "reset",
                        });
                    }
                    #endregion
                }

                //idxBkbn = HEnum.HSequence(coords.Count).ToArray();
                int[]    idxFull      = idxSele.HUnionWith(idxCntk).HUnionWith(idxBkbn);
                Vector[] coordsFull   = coords.HCopyIdx(idxFull, null);
                var      hessinfoFull = lGetHess(univ, coordsFull
                                                 , idxAll: idxSele
                                                 , idxBuffer: idxCntk.HRemoveAll(idxSele)
                                                 , idxCoarse: idxBkbn.HRemoveAll(idxSele).HRemoveAll(idxCntk)
                                                 , idxBackbone: idxBkbn
                                                 );
                HDebug.Assert(hessinfoFull.hess.IsComputable() == false);
                //{
                //    var modes = hessinfoFull.GetModesMassReduced(false, la);
                //    var modesPosZero = modes.SeparateTolerants();
                //    Vector bf = modesPosZero.Item1.GetBFactor().ToArray();
                //    Vector nma = ext as Vector;
                //    double corr = BFactor.Corr(bf, nma);
                //}

                var hessinfoSub = hessinfoFull.GetSubHessInfo(idxFull);
                HDebug.Assert(hessinfoSub.hess.IsComputable() == true);
                if (HDebug.IsDebuggerAttached)
                {
                    Mode[] lmodes = hessinfoSub.GetModesMassReduced();
                    if (lmodes.SeparateTolerants().Item2.Length != 6)
                    {
                        HDebug.Assert(false);
                        //throw new Exception();
                    }
                }
                if (bVerifySteps && HDebug.IsDebuggerAttached)
                {
                    var    modes        = hessinfoSub.GetModesMassReduced();
                    var    modesPosZero = modes.SeparateTolerants();
                    Vector bf0          = modesPosZero.Item1.GetBFactor().ToArray();
                    Vector bf           = new double[coords.Count]; bf.SetValue(double.NaN);
                    for (int i = 0; i < idxFull.Length; i++)
                    {
                        bf[idxFull[i]] = bf0[i];
                    }
                    int[]  idxCax   = idxCa.HRemoveAll(idxSele).HRemoveAll(idxCntk);
                    double corr     = HBioinfo.BFactor.Corr(bf, bfactorFull, idxFull);
                    double corrCa   = HBioinfo.BFactor.Corr(bf, bfactorFull, idxCa);
                    double corrCax  = HBioinfo.BFactor.Corr(bf, bfactorFull, idxCax);
                    double corrBkbn = HBioinfo.BFactor.Corr(bf, bfactorFull, idxBkbn);
                    double corrSele = HBioinfo.BFactor.Corr(bf, bfactorFull, idxSele);
                    double corrCntk = HBioinfo.BFactor.Corr(bf, bfactorFull, idxCntk);
                }

                int[] idxMix;
                {
                    Universe.Atom[] mixAtoms    = hessinfoSub.atoms.HToType <object, Universe.Atom>();
                    Pdb.Atom[]      mixPdbAtoms = mixAtoms.ListPdbAtoms();
                    ResInfo[]       mixResinfos = mixPdbAtoms.ListResInfo(true);
                    int[]           mixIdxCa    = mixPdbAtoms.IdxByName(true, "CA");
                    int[]           mixIdxSele  = mixResinfos.HIdxEqual(ResInfo.Equals, lstResAllAtom.ToArray());
                    idxMix = mixIdxCa.HUnionWith(mixIdxSele).HSort();
                }

                HessMatrix hessMix = Hess.GetHessCoarseBlkmat(hessinfoSub.hess, idxMix, la);
                if (hessMix.IsComputable() == false)
                {
                    // hessSub (=hessinfoSub.hess) is computable, but hessMix become in-computable.
                    // This happens when 1. hessSub=[A,B;C,D] has more then 6 zero eigenvalues,
                    //                   2. the D matrix become singular,
                    //                   3. inv(D) is incomputable
                    //                   4. "A - B inv(D) C" becomes incomputable.
                    errmsg = "hess(Sele,Cntk,Bkbn)->hess(Sele,Ca) becomes incomputable";
                    return(null);
                }

                MixHessInfo hessinfoMix = new MixHessInfo
                {
                    hess          = hessMix,
                    mass          = hessinfoSub.mass.ToArray().HSelectByIndex(idxMix),
                    atoms         = hessinfoSub.atoms.ToArray().HSelectByIndex(idxMix),
                    coords        = hessinfoSub.coords.ToArray().HSelectByIndex(idxMix),
                    numZeroEigval = 6,
                };
                if (bGetIntmInfo)
                {
                    hessinfoMix.intmHessinfoAllMidBkbn = hessinfoSub;
                    hessinfoMix.intmAtomCa             = univ.atoms.ToArray().HSelectByIndex(idxCa);
                    hessinfoMix.intmAtomAll            = univ.atoms.ToArray().HSelectByIndex(idxSele);
                    hessinfoMix.intmAtomMid            = univ.atoms.ToArray().HSelectByIndex(idxCntk);
                    hessinfoMix.intmAtomBkbn           = univ.atoms.ToArray().HSelectByIndex(idxBkbn);
                }

                if (HDebug.IsDebuggerAttached)
                {
                    Mode[] lmodes = hessinfoMix.GetModesMassReduced();
                    if (lmodes.SeparateTolerants().Item2.Length != 6)
                    {
                        throw new Exception();
                    }
                }
                if (bVerifySteps && HDebug.IsDebuggerAttached)
                {
                    var    modes        = hessinfoMix.GetModesMassReduced();
                    var    modesPosZero = modes.SeparateTolerants();
                    Vector bf0          = modesPosZero.Item1.GetBFactor().ToArray();
                    Vector bf           = new double[coords.Count]; bf.SetValue(double.NaN);
                    for (int i = 0; i < idxMix.Length; i++)
                    {
                        bf[idxFull[idxMix[i]]] = bf0[i];
                    }
                    int[]  idxCax   = idxCa.HRemoveAll(idxSele).HRemoveAll(idxCntk);
                    double corr     = HBioinfo.BFactor.Corr(bf, bfactorFull, true);
                    double corrCa   = HBioinfo.BFactor.Corr(bf, bfactorFull, idxCa);
                    double corrCax  = HBioinfo.BFactor.Corr(bf, bfactorFull, idxCax);
                    double corrBkbn = HBioinfo.BFactor.Corr(bf, bfactorFull, idxBkbn);
                    double corrSele = HBioinfo.BFactor.Corr(bf, bfactorFull, idxSele);
                    double corrCntk = HBioinfo.BFactor.Corr(bf, bfactorFull, idxCntk);
                }

                errmsg = null;
                return(hessinfoMix);
            }