Example #1
0
        public void OnlyInSnapshot1_is_empty_if_both_snapshotss_contain_one_identical_file_in_same_dir()
        {
            Snapshot   snapshot1   = new Snapshot();
            HDirectory hDirectory1 = new HDirectory("Dir1");

            hDirectory1.Files.AddRange(new[]
            {
                new HFile {
                    Name = "File1", Hash = new byte[] { 0x01, 0x02, 0x03 }
                }
            });
            snapshot1.Directories.AddRange(new[] { hDirectory1 });

            Snapshot   snapshot2   = new Snapshot();
            HDirectory hDirectory2 = new HDirectory("Dir1");

            hDirectory2.Files.AddRange(new[]
            {
                new HFile {
                    Name = "File1", Hash = new byte[] { 0x01, 0x02, 0x03 }
                }
            });
            snapshot2.Directories.AddRange(new[] { hDirectory2 });

            SnapshotComparer comparer = new SnapshotComparer(snapshot1, snapshot2);

            comparer.Compare();

            Assert.That(comparer.OnlyInSnapshot1, Is.EqualTo(new string[0]));
        }
        private void CompareChildDirectories(HDirectory directory1, HDirectory directory2, string rootPath)
        {
            List <HDirectory> subDirectories1 = directory1.Directories.ToList();
            List <HDirectory> subDirectories2 = directory2.Directories.ToList();

            foreach (HDirectory subDirectory1 in subDirectories1)
            {
                HDirectory subDirectory2 = subDirectories2.FirstOrDefault(x => x.Name == subDirectory1.Name);

                if (subDirectory2 == null)
                {
                    onlyInSnapshot1.Add(rootPath + subDirectory1.Name + "/");
                }
                else
                {
                    subDirectories2.Remove(subDirectory2);

                    string rootPath1 = rootPath + subDirectory1.Name + "/";

                    CompareChildFiles(subDirectory1, subDirectory2, rootPath1);
                    CompareChildDirectories(subDirectory1, subDirectory2, rootPath1);
                }
            }

            foreach (HDirectory subDirectory2 in subDirectories2)
            {
                onlyInSnapshot2.Add(rootPath + subDirectory2.Name + "/");
            }
        }
Example #3
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);
            }
        public void Add(HDirectory directory)
        {
            JsonDirectoryWriter topDirectoryWriter = directoryStack.Peek();
            JsonDirectoryWriter newDirectoryWriter = topDirectoryWriter.WriteStartDirectory(directory.Name);

            newDirectoryWriter.WriteEnd();
        }
        public JsonDirectory(HDirectory xDirectory)
        {
            if (xDirectory == null)
            {
                throw new ArgumentNullException(nameof(xDirectory));
            }

            Name = xDirectory.Name;

            if (xDirectory.Directories == null)
            {
                Directories = null;
            }
            else
            {
                Directories = xDirectory.Directories
                              .Select(x => new JsonDirectory(x))
                              .ToList();
            }

            if (xDirectory.Files == null)
            {
                Files = null;
            }
            else
            {
                Files = xDirectory.Files
                        .Select(x => new JsonFile(x))
                        .ToList();
            }
        }
Example #6
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);
            }
        public static HItem PlaceInto(this HItem hItem, string parentName)
        {
            HDirectory parentDirectory = new HDirectory
            {
                Name = parentName
            };

            hItem.Parent = parentDirectory;

            return(parentDirectory);
        }
        public void Add(HFile file)
        {
            if (directoryStack.Count == 0)
            {
                throw new Exception("There is no directory added that can be used as parent for this file.");
            }

            HDirectory topDirectory = directoryStack.Peek();

            topDirectory.Files.Add(file);
        }
Example #9
0
        public void Add(HFile file)
        {
            if (directoryStack.Count == 0)
            {
                throw new Exception("There is no directory added.");
            }

            HDirectory topDirectory = directoryStack.Peek();

            topDirectory.Files.Add(file);
        }
 public void AddAndOpen(HDirectory directory)
 {
     if (directoryStack.Count == 0)
     {
         directoryStack.Push(jsonSnapshotWriter);
     }
     else
     {
         JsonDirectoryWriter topDirectoryWriter = directoryStack.Peek();
         JsonDirectoryWriter newDirectoryWriter = topDirectoryWriter.WriteStartDirectory(directory.Name);
         directoryStack.Push(newDirectoryWriter);
     }
 }
        public void HavingDirectoryWithMatchingName_WhenChecked_ThenMatches()
        {
            // pattern: file-or-dir-1
            // path:    /file-or-dir-1 (dir)

            HDirectory hDirectory = new HDirectory
            {
                Name = "file-or-dir-1"
            };

            bool actual = blackPath.Matches(hDirectory);

            Assert.That(actual, Is.True);
        }
        private void CompareChildFiles(HDirectory directory1, HDirectory directory2, string rootPath)
        {
            HItemCollection <HFile> files1           = directory1.Files;
            HItemCollection <HFile> files2           = directory2.Files;
            List <HFile>            onlyInDirectory2 = files2.ToList();

            foreach (HFile file1 in files1)
            {
                List <HFile> file2Matches = files2
                                            .Where(x => x.Name == file1.Name || ByteArrayCompare.AreEqual(x.Hash, file1.Hash))
                                            .ToList();

                if (file2Matches.Count == 0)
                {
                    onlyInSnapshot1.Add(rootPath + file1.Name);
                }
                else
                {
                    foreach (HFile file2 in file2Matches)
                    {
                        ItemComparison itemComparison = new ItemComparison
                        {
                            RootPath = rootPath,
                            Item1    = file1,
                            Item2    = file2
                        };

                        bool sameName    = file1.Name == file2.Name;
                        bool sameContent = ByteArrayCompare.AreEqual(file1.Hash, file2.Hash);

                        if (!sameName && sameContent)
                        {
                            differentNames.Add(itemComparison);
                        }

                        if (sameName && !sameContent)
                        {
                            differentContent.Add(itemComparison);
                        }

                        onlyInDirectory2.Remove(file2);
                    }
                }
            }

            foreach (HFile file2 in onlyInDirectory2)
            {
                onlyInSnapshot2.Add(rootPath + file2.Name);
            }
        }
 public void Add(HDirectory directory)
 {
     if (directoryStack.Count == 0)
     {
         Snapshot.Name = directory.Name;
         Snapshot.Files.AddRange(directory.Files);
         Snapshot.Directories.AddRange(directory.Directories);
         Snapshot.Error = directory.Error;
     }
     else
     {
         HDirectory topDirectory = directoryStack.Peek();
         topDirectory.Directories.Add(directory);
     }
 }
        private static void DisplayDirectory(HDirectory hDirectory, int index)
        {
            string indent = new string(' ', index);

            foreach (HDirectory subdirectory in hDirectory.Directories)
            {
                Console.WriteLine(indent + subdirectory.Name);
                DisplayDirectory(subdirectory, index + 1);
            }

            foreach (HFile xFile in hDirectory.Files)
            {
                Console.WriteLine(indent + xFile.Name);
            }
        }
        private static void DisplayDirectory(HDirectory hDirectory, int index)
        {
            string indent = new(' ', index * 2);

            foreach (HDirectory xSubdirectory in hDirectory.Directories)
            {
                Console.WriteLine(indent + xSubdirectory.Name);
                DisplayDirectory(xSubdirectory, index + 1);
            }

            foreach (HFile xFile in hDirectory.Files)
            {
                Console.Write(indent + xFile.Name);
                CustomConsole.WriteLine(ConsoleColor.DarkGray, " [" + xFile.Hash + "]");
            }
        }
        private void SaveDirectory(JsonAnalysisExport jsonAnalysisExport, HDirectory directory)
        {
            jsonAnalysisExport.AddAndOpen(directory);

            foreach (HDirectory subDirectory in directory.Directories)
            {
                SaveDirectory(jsonAnalysisExport, subDirectory);
            }

            foreach (HFile file in directory.Files)
            {
                jsonAnalysisExport.Add(file);
            }

            jsonAnalysisExport.CloseDirectory();
        }
Example #17
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);
            }
        public void HavingDirectoryWithMatchingNamePlacedInPath_WhenChecked_ThenMatches()
        {
            // pattern: item-1/
            // path:    /dir-2/item-1 (dir)

            HDirectory hDirectory = new HDirectory
            {
                Name   = "item-1",
                Parent = new HDirectory
                {
                    Name = "dir-2"
                }
            };

            bool actual = blackPath.Matches(hDirectory);

            Assert.That(actual, Is.True);
        }
        public static JDirectory ToJDirectory(this HDirectory directory)
        {
            if (directory == null)
            {
                throw new ArgumentNullException(nameof(directory));
            }

            return(new JDirectory
            {
                Name = directory.Name,
                Directories = directory.Directories?
                              .Select(x => x.ToJDirectory())
                              .ToList(),
                Files = directory.Files?
                        .Select(x => x.ToJFile())
                        .ToList()
            });
        }
        public void HavingDirectoryWithMatchingNamePlacedInPath_WhenChecked_ThenDoesNotMatch()
        {
            // pattern: /file-or-dir-1
            // path:    /dir-2/file-or-dir-1 (dir)

            HDirectory hDirectory = new HDirectory
            {
                Name   = "file-or-dir-1",
                Parent = new HDirectory
                {
                    Name = "dir-2"
                }
            };

            bool actual = blackPath.Matches(hDirectory);

            Assert.That(actual, Is.False);
        }
        private static void Read(ICollection <Tuple <string, HFile> > files, HDirectory hDirectory, string parentPath)
        {
            if (hDirectory.Files != null)
            {
                foreach (HFile xFile in hDirectory.Files)
                {
                    string filePath = Path.Combine(parentPath, xFile.Name);
                    files.Add(new Tuple <string, HFile>(filePath, xFile));
                }
            }

            if (hDirectory.Directories != null)
            {
                foreach (HDirectory xSubDirectory in hDirectory.Directories)
                {
                    string subdirectoryPath = Path.Combine(parentPath, xSubDirectory.Name);
                    Read(files, xSubDirectory, subdirectoryPath);
                }
            }
        }
Example #22
0
            public static Top FromPdb(string pdbpath
                                      , string ff    = "charmm27"
                                      , string water = "none"
                                      , HPack <Pdb> optout_confout = null
                                      )
            {
                Top top;

                FileInfo      pdbinfo  = new FileInfo(pdbpath);
                string        currdir  = HEnvironment.CurrentDirectory;
                DirectoryInfo temproot = HDirectory.CreateTempDirectory();

                HEnvironment.CurrentDirectory = temproot.FullName;
                {
                    HFile.Copy(pdbinfo.FullName, "protein.pdb");

                    RunPdb2gmx(f: "protein.pdb"
                               , o: "confout.pdb"
                               , p: "topol.top"
                               , q: "clean.pdb"
                               , ff: ff
                               , water: water
                               , merge: "all"
                               , lineStderr: null
                               , lineStdout: null
                               );

                    top = Top.FromFile("topol.top");
                    if (optout_confout != null)
                    {
                        optout_confout.value = Pdb.FromFile("confout.pdb");
                    }
                }
                HEnvironment.CurrentDirectory = currdir;
                Thread.Sleep(100);
                try{ temproot.Delete(true); } catch (Exception) {}

                return(top);
            }
        public static HDirectory ToHDirectory(this JDirectory jDirectory)
        {
            HDirectory directory = new HDirectory
            {
                Name = jDirectory.Name
            };

            List <HDirectory> directories = jDirectory.GetHDirectories();

            if (directories != null)
            {
                directory.Directories.AddRange(directories);
            }

            List <HFile> files = jDirectory.GetHFiles();

            if (files != null)
            {
                directory.Files.AddRange(files);
            }

            return(directory);
        }
        public HDirectory ToHDirectory()
        {
            HDirectory directory = new HDirectory
            {
                Name = Name
            };

            List <HDirectory> directories = GetHDirectories();

            if (directories != null)
            {
                directory.Directories.AddRange(directories);
            }

            List <HFile> files = GetHFiles();

            if (files != null)
            {
                directory.Files.AddRange(files);
            }

            return(directory);
        }
Example #25
0
        public void OnlyInSnapshot1_contains_the_name_of_the_file_if_only_snapshot1_has_one_file_in_dir()
        {
            Snapshot   snapshot1   = new Snapshot();
            HDirectory hDirectory1 = new HDirectory("Dir1");

            hDirectory1.Files.AddRange(new[]
            {
                new HFile {
                    Name = "File1", Hash = new byte[] { 0x01, 0x02, 0x03 }
                }
            });
            snapshot1.Directories.AddRange(new[] { hDirectory1 });

            Snapshot   snapshot2   = new Snapshot();
            HDirectory hDirectory2 = new HDirectory("Dir1");

            snapshot2.Directories.AddRange(new[] { hDirectory2 });

            SnapshotComparer comparer = new SnapshotComparer(snapshot1, snapshot2);

            comparer.Compare();

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

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

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

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

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

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

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

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

                return(new CNamd2
                {
                    coor_lines = coor_lines,
                    coor_rmsd = coor_rmsd,
                });
            }
Example #28
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,
                });
            }
Example #29
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,
                });
            }
 public void AddAndOpen(HDirectory directory)
 {
     Add(directory);
     directoryStack.Push(directory);
 }