Beispiel #1
0
            public static void Align(string pdbpath1, string pdbpath2, string alignedpath2)
            {
                Pdb pdb1 = Pdb.FromFile(pdbpath1); List <Pdb.Atom> atoms1 = pdb1.atoms.SelectByChainID().SelectByAltLoc();
                Pdb pdb2 = Pdb.FromFile(pdbpath2); List <Pdb.Atom> atoms2 = pdb2.atoms.SelectByChainID().SelectByAltLoc();

                Align(atoms1, ref atoms2);

                Pdb.ToFile(alignedpath2, atoms2);
            }
Beispiel #2
0
 public static void SelfTest(string rootpath, string[] args)
 {
     {
         Pdb           pdb    = Pdb.FromFile(rootpath + @"\Sample\alanin.pdb");
         List <Vector> coords = pdb.atoms.ListCoord();
         coords[0] = new Vector(0, 1, 2);
         pdb.ToFile(rootpath + @"\Sample\alanin.updated.pdb", coords);
     }
     {
         Pdb pdb = Pdb.FromFile(rootpath + @"\Sample\1a6g.pdb");
         //pdb.CollectResidues();
     }
 }
Beispiel #3
0
        public static Pdb FromPdbid
            (string pdbid
            , string cachebase  // null or @"K:\PdbUnzippeds\$PDBID$.pdb"
            , bool?download     // null or false
            )
        {
            if (cachebase == null)
            {
                cachebase = @"K:\PdbUnzippeds\$PDBID$.pdb";
            }
            if (download == null)
            {
                download = false;
            }

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

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

                if (download.Value)
                {   // redownload
                    pdb = Pdb.FromPdbid(pdbid);
                    pdb.ToFile(pdbpath);
                }
                return(pdb);
            }
            else if (download.Value)
            {
                Pdb pdb = Pdb.FromPdbid(pdbid);
                if (pdb != null)
                {
                    pdb.ToFile(pdbpath);
                    return(pdb);
                }
            }
            return(null);
        }
Beispiel #4
0
            public static void GetEnergies(AlignData data1, IList <Vector> coords2
                                           , out double geo_rmsd, out double geo_enrg, out double geo_enrg_full, out double geo_enrg_anisou
                                           , Pdb pdb2, string pdb2outpath
                                           )
            {
                Trans3        trans        = GetTrans(data1.coords, coords2);
                List <Vector> coords2trans = new List <Vector>(trans.GetTransformed(coords2).ToArray());

                if (pdb2 != null && pdb2outpath != null)
                {
                    pdb2.ToFile(pdb2outpath, coords2);
                }

                geo_rmsd        = data1.GetRmsdFrom(coords2trans);
                geo_enrg        = data1.GetEnergyFromDiag(coords2trans);
                geo_enrg_full   = data1.GetEnergyFromFull(coords2trans);
                geo_enrg_anisou = data1.GetEnergyFromAnisou(coords2trans);
            }
Beispiel #5
0
            //public static Trans3 GetTrans(IList<Vector> C1, Matrix[] anisou1, IList<Vector> C2)
            //{
            //    int size = C1.Count;
            //    Tuple<Vector[], double[]>[] eigs1 = new Tuple<Vector[], double[]>[size];
            //    {
            //        for(int i=0; i<size; i++)
            //        {
            //            Vector[] eigvec;
            //            double[] eigval;
            //            Debug.Verify(NumericSolver.Eig(anisou1[i], out eigvec, out eigval));
            //            {   // normalize eigval and eigvec
            //                double l;
            //                l = eigvec[0].Dist; eigvec[0] /= l; eigval[0] *= (l*l); eigval[0] = Math.Pow(eigval[0], 2); Debug.Assert(eigval[0] >= 0);
            //                l = eigvec[1].Dist; eigvec[1] /= l; eigval[1] *= (l*l); eigval[1] = Math.Pow(eigval[1], 2); Debug.Assert(eigval[1] >= 0);
            //                l = eigvec[2].Dist; eigvec[2] /= l; eigval[2] *= (l*l); eigval[2] = Math.Pow(eigval[2], 2); Debug.Assert(eigval[2] >= 0);
            //            }
            //            {
            //                eigval[0] = 1 / eigval[0];
            //                eigval[1] = 1 / eigval[1];
            //                eigval[2] = 1 / eigval[2];
            //            }
            //            eigs1[i] = new Tuple<Vector[], double[]>(eigvec, eigval);
            //        }
            //    }
            //    return GetTrans(C1, eigs1, C2);
            //}

            public static void GetEnergies(AlignData data1, IList <Vector> coords2
                                           , out double pot_rmsd, out double pot_enrg, out double pot_enrg_full, out double pot_enrg_anisou
                                           , Pdb pdb2           = null
                                           , string pdb2outpath = null
                                           )
            {
                Anisou[]      anisous1     = data1.GetAnisous();
                Trans3        trans        = GetTrans(data1.coords, anisous1, coords2);
                List <Vector> coords2trans = new List <Vector>(trans.GetTransformed(coords2));

                if (pdb2 != null && pdb2outpath != null)
                {
                    pdb2.ToFile(pdb2outpath, coords2trans);
                }
                //data1.pdb.ToFile(pdb2outpath, coords2trans, anisous: anisous1.GetUs());

                pot_rmsd        = data1.GetRmsdFrom(coords2trans);
                pot_enrg        = data1.GetEnergyFromDiag(coords2trans);
                pot_enrg_full   = data1.GetEnergyFromFull(coords2trans);
                pot_enrg_anisou = data1.GetEnergyFromAnisou(coords2trans);
            }
Beispiel #6
0
        public static void ToFileAnimated(string filepath
                                          , IList <Atom> atoms
                                          , IList <Vector> velocities
                                          , IList <double> stepTimes = null
                                          , IList <Vector> coords    = null
                                          , IList <double> bfactors  = null
                                          , IList <Element> headers  = null
                                          , int?modelidx             = null
                                          )
        {
            if (coords == null)
            {
                coords = atoms.ListCoord();
            }
            if (stepTimes == null)
            {
                stepTimes = new double[] { 0.0, -0.1, -0.2, -0.3, -0.4, -0.5, -0.6, -0.7, -0.8, -0.9, -1.0,
                                           -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0,
                                           0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0,
                                           1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1, 0.0, }
            }
            ;

            bool append = false;

            for (int i = 0; i < stepTimes.Count; i++)
            {
                List <Vector> lcoords  = coords.PwAdd(velocities, stepTimes[i]);
                List <string> lheaders = null;
                if ((append == false) && (headers != null))
                {
                    lheaders = headers.ToLines();
                }
                Pdb.ToFile(filepath, atoms, coords: lcoords, append: append, headers: lheaders, bfactors: bfactors
                           , modelidx: modelidx
                           );
                append = true;
            }
        }
    }
Beispiel #7
0
        public void SaveCoordsToPdb(string path, Pdb pdb, Vector[] coords)
        {
            Pdb.Atom[]            pdbatoms   = pdb.atoms;
            Vector[]              pdbcoords  = new Vector[pdbatoms.Length];
            Dictionary <int, int> serial2idx = pdbatoms.ToDictionaryAsSerialToIndex();

            for (int ia = 0; ia < size; ia++)
            {
                Universe.Atom   uatom  = atoms[ia];
                List <Pdb.Atom> patoms = uatom.sources.HSelectByType((Pdb.Atom)null).ToList();
                if (patoms.Count >= 1)
                {
                    HDebug.Assert(patoms.Count == 1);
                    int serial = patoms[0].serial;
                    int idx    = serial2idx[serial];
                    HDebug.Assert(pdbatoms[idx].serial == serial);
                    HDebug.Assert(pdbcoords[idx] == null);
                    pdbcoords[idx] = coords[ia].Clone();
                }
                else
                {
                    HDebug.Assert();
                }
            }

            for (int i = 0; i < pdbcoords.Length; i++)
            {
                if (pdbcoords[i] == null)
                {
                    HDebug.Assert(false);
                    pdbcoords[i] = new double[3] {
                        double.NaN, double.NaN, double.NaN
                    };
                }
            }

            pdb.ToFile(path, pdbcoords);
        }
Beispiel #8
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,
                });
            }
Beispiel #9
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);
                    }
                }
            }
Beispiel #10
0
            public static CPdbxyz Pdbxyz
                (Pdb pdb
                , Tinker.Prm prm
                , string tempbase      //=null
                , string parameters    //=null
                , string tinkerversion //="6.2.1"
                , params string[] keys
                )
            {
                var    tmpdir   = HDirectory.CreateTempDirectory(tempbase);
                string currpath = HEnvironment.CurrentDirectory;

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

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

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

                return(new CPdbxyz
                {
                    xyz = xyz,
                    seq = seq,
                    capture = capture,
                });
            }
Beispiel #11
0
            public static HessInfoCoarseResiIter GetHessCoarseResiIter
                (Hess.HessInfo hessinfo
                , Vector[] coords
                , FuncGetIdxKeepListRemv GetIdxKeepListRemv
                , ILinAlg ila
                , double thres_zeroblk = 0.001
                , IterOption iteropt   = IterOption.Matlab_experimental
                , string[] options     = null
                )
            {
                bool rediag = true;

                HessMatrix H = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                return(new HessInfoCoarseResiIter
                {
                    hess = H,
                    mass = reMass.HSelectCount(numca),
                    atoms = reAtoms.HSelectCount(numca),
                    coords = reCoords.HSelectCount(numca),
                    numZeroEigval = 6,
                    iterinfos = iterinfos,
                });
            }
Beispiel #12
0
        public static void SelfTest(string rootpath, string[] args)
        {
            //{
            //    Pdb pdb = Pdb.FromFile(rootpath + @"\Sample\1a6g.pdb");
            //    HTLib2.Bioinfo.Universe.Build(pdb);
            //}
            GetPotential_SelfTest(rootpath, args);

            Universe univ = null;

            string sample = null;

            //sample = "1a6g_autopsf.unfolded";
            //sample = "1a6g_autopsf";
            switch (sample)
            {
            case "alanin":
            {
                List <ForceField.IForceField> frcflds = ForceField.GetMindyForceFields();
                double k         = 0.0001;
                double threshold = 0.001;
                //int iter = univ.Minimize_ConjugateGradient_v0(frcflds, k, threshold);
                int    randomPurturb = 0;      // no random purturbation
                bool[] atomsMovable  = null;   // update all atoms
                int    iter_conjgrad;
                {
                    Namd.Psf psf = Namd.Psf.FromFile(rootpath + @"\Sample\alanin.psf");
                    Pdb      pdb = Pdb.FromFile(rootpath + @"\Sample\alanin.pdb");
                    Namd.Prm prm = Namd.Prm.FromFileXPlor(rootpath + @"\Sample\alanin.params", new TextLogger());
                    univ = Universe.Build(psf, prm, pdb, false);

                    //frcflds = new List<ForceField.IForceField>();
                    //frcflds.Add(new ForceField.MindyBond());
                    //frcflds.Add(new ForceField.MindyAngle());
                    //frcflds.Add(new ForceField.MindyDihedral());
                    //frcflds.Add(new ForceField.MindyImproper());
                    //frcflds.Add(new ForceField.MindyNonbondedLennardJones());
                    //frcflds.Add(new ForceField.MindyNonbondedElectrostatic());

                    //iter_conjgrad = univ.Minimize_ConjugateGradient_v1(0, frcflds, k, 0.1, null, threshold, randomPurturb, atomsMovable, new MinimizeLogger_PrintEnergyForceMag(), null, null);

                    //frcflds = new List<ForceField.IForceField>();
                    //frcflds.Add(new ForceField.MindyBond());
                    //frcflds.Add(new ForceField.MindyAngle());
                    //frcflds.Add(new ForceField.MindyImproper());
                    //frcflds.Add(new ForceField.MindyNonbondedLennardJones());
                    //frcflds.Add(new ForceField.MindyNonbondedElectrostatic());

                    //iter_conjgrad = univ.Minimize_ConjugateGradient_v1(0, frcflds, k*0.1, 0.1, null, threshold, randomPurturb, atomsMovable, new MinimizeLogger_PrintEnergyForceMag(), null, null);

                    frcflds = new List <ForceField.IForceField>();
                    if (HDebug.False)
                    {
                        frcflds.Add(new ForceField.MindyBond());
                    }
                    else
                    {
                        frcflds.Add(new ForceField.PwBond());
                    }
                    if (HDebug.False)
                    {
                        frcflds.Add(new ForceField.MindyAngle());
                    }
                    else
                    {
                        frcflds.Add(new ForceField.PwAngle());
                    }
                    frcflds.Add(new ForceField.MindyDihedral());
                    if (HDebug.False)
                    {
                        frcflds.Add(new ForceField.MindyImproper());
                    }
                    else
                    {
                        frcflds.Add(new ForceField.PwImproper());
                    }
                    if (HDebug.False)
                    {
                        frcflds.Add(new ForceField.MindyNonbondedElectrostatic());
                    }
                    else
                    {
                        frcflds.Add(new ForceField.PwElec());
                    }
                    if (HDebug.False)
                    {
                        frcflds.Add(new ForceField.MindyNonbondedLennardJones());
                    }
                    else
                    {
                        frcflds.Add(new ForceField.PwVdw());
                    }

                    univ.LoadCoords(@"D:\xxxx.coords");
                    iter_conjgrad = univ.Minimize_ConjugateGradient_v1(0, frcflds, k, 0.01, null, threshold, randomPurturb, atomsMovable, new MinimizeLogger_PrintEnergyForceMag(), null, null);
                    univ.SaveCoords(@"D:\xxxx.coords");
                    System.Console.WriteLine("=======================================================================");
                    System.Console.WriteLine("=======================================================================");
                    System.Console.WriteLine("=======================================================================");
                }
                {
                    //Psf psf = Psf.FromFile(rootpath + @"\Sample\alanin.psf");
                    //Pdb pdb = Pdb.FromFile(rootpath + @"\Sample\alanin.pdb");
                    //Prm prm = Prm.FromFileXPlor(rootpath + @"\Sample\alanin.params", new TextLogger());
                    //univ = Universe.Build(psf, prm, pdb);

                    //frcflds = new List<ForceField.IForceField>();
                    //if(true) frcflds.Add(new ForceField.MindyBond()); else frcflds.Add(new ForceField.PwBond());
                    //if(true) frcflds.Add(new ForceField.MindyAngle()); else frcflds.Add(new ForceField.PwAngle());
                    //frcflds.Add(new ForceField.MindyDihedral());
                    //if(true) frcflds.Add(new ForceField.MindyImproper()); else frcflds.Add(new ForceField.PwImproper());
                    //if(true) frcflds.Add(new ForceField.MindyNonbondedElectrostatic()); else frcflds.Add(new ForceField.PwElec());
                    //if(true) frcflds.Add(new ForceField.MindyNonbondedLennardJones()); else frcflds.Add(new ForceField.PwVdw());
                    univ.atoms[0].Coord += new Vector(0.1, 0.1, 0.1);
                    //iter_conjgrad = univ.Minimize_ConjugateGradient_v1(0, frcflds, k, 0.001, null, threshold, randomPurturb, atomsMovable, new MinimizeLogger_PrintEnergyForceMag(), null, null);
                    iter_conjgrad = univ.Minimize_ConjugateGradient_AtomwiseUpdate(frcflds,
                                                                                   threshold: threshold,
                                                                                   k: k,
                                                                                   max_atom_movement: 0.001,
                                                                                   max_iteration: null,
                                                                                   atomsMovable: atomsMovable,
                                                                                   logger: new MinimizeLogger_PrintEnergyForceMag()
                                                                                   );
                }
                k = 0.0005;
                HDebug.Assert(false);
                //int iter_stepdsnt = univ.Minimize_SteepestDescent(frcflds, k, threshold, System.Console.Error);
            }
            break;

            case "1a6g_autopsf":
            {
                Namd.Psf psf = Namd.Psf.FromFile(rootpath + @"\Sample\1a6g_autopsf.psf");
                Pdb      pdb = Pdb.FromFile(rootpath + @"\Sample\1a6g_autopsf.pdb");
                Namd.Prm prm = Namd.Prm.FromFile(rootpath + @"\Sample\1a6g_autopsf.prm", new TextLogger());

                univ = Universe.Build(psf, prm, pdb, false);

                List <ForceField.IForceField> frcflds = ForceField.GetMindyForceFields();
                double threshold    = 0.001;
                string minimize_ver = "v1";
                switch (minimize_ver)
                {
                //case "v2":
                //    {
                //        double atom_max_move = 0.03;
                //        int iter_conjgrad = univ.Minimize_ConjugateGradient_v2(frcflds, atom_max_move, threshold, System.Console.Error);
                //        break;
                //    }
                case "v1":
                {
                    double k             = 0.0001;
                    int    randomPurturb = 0;              // no random purturbation
                    bool[] atomsMovable  = null;           // update all atoms
                    int    iter_conjgrad = univ.Minimize_ConjugateGradient_v1(0, frcflds, k, 0.1, null, threshold, randomPurturb, atomsMovable, new MinimizeLogger_PrintEnergyForceMag(), null, null);
                    break;
                }

                default:
                    goto case "v1";
                }
                //atom_max_move = 0.03;
                //int iter_stepdsnt = univ.Minimize_SteepestDescent(frcflds, atom_max_move, threshold, System.Console.Error);
            }
            break;

            case "1a6g_autopsf.unfolded":
            {
                Namd.Psf psf = Namd.Psf.FromFile(rootpath + @"\Sample\1a6g_autopsf.psf");
                Pdb      pdb = Pdb.FromFile(rootpath + @"\Sample\1a6g_autopsf.pdb");
                {
                    Random        rand   = new Random(1);
                    List <Vector> coords = pdb.atoms.ListCoord();

                    for (int i = 0; i < coords.Count; i++)
                    {
                        double x = i * 0.1 + rand.NextDouble() * 0.01;
                        double y = i * 0.1 + rand.NextDouble() * 0.01;
                        double z = i * 0.1 + rand.NextDouble() * 0.01;
                        coords[i] = new Vector(x, y, z);
                    }
                    pdb.ToFile(rootpath + @"\Sample\1a6g_autopsf.unfolded.pdb", coords);
                    pdb = Pdb.FromFile(rootpath + @"\Sample\1a6g_autopsf.unfolded.pdb");
                }
                Namd.Prm prm = Namd.Prm.FromFile(rootpath + @"\Sample\1a6g_autopsf.prm", new TextLogger());

                univ = Universe.Build(psf, prm, pdb, false);

                List <ForceField.IForceField> frcflds = ForceField.GetMindyForceFields();
                double threshold    = 0.01;
                string minimize_ver = "v1";
                switch (minimize_ver)
                {
                //case "v2":
                //    {
                //        double atom_max_move = 0.1;
                //        int iter_conjgrad = univ.Minimize_ConjugateGradient_v2(frcflds, atom_max_move, threshold, System.Console.Error);
                //        break;
                //    }
                case "v1":
                {
                    double k             = 0.0001;
                    int    randomPurturb = 100;
                    bool[] atomsMovable  = null;                // updates all atoms
                    int    iter_conjgrad = univ.Minimize_ConjugateGradient_v1(0, frcflds, k, 0.1, null, threshold, randomPurturb, atomsMovable, new MinimizeLogger_PrintEnergyForceMag(), null, null);
                    break;
                }

                default:
                    goto case "v1";
                }
                //atom_max_move = 0.03;
                //int iter_stepdsnt = univ.Minimize_SteepestDescent(frcflds, atom_max_move, threshold, System.Console.Error);
            }
            break;

            default:
                goto case "alanin";
            }
        }
Beispiel #13
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);
            }
Beispiel #14
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,
            });
        }
Beispiel #15
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);
            }