Exemple #1
0
 //HashSet<Atom> _dbgatoms = (HDebug.IsDebuggerAttached ? new HashSet<Atom>() : null);
 public Atoms(Universe univ)
 {
     this.univ = univ;
 }
                public static void Main
                    (string[] args
                    , string[] hesstypes
                    , double[] threszeroblks
                    )
                {
                    string cachebase = @"K:\cache\CoarseGraining-20150111\proteins-177\";
                    string lockbase  = cachebase + @"lock\"; if (HDirectory.Exists(lockbase) == false)
                    {
                        HDirectory.CreateDirectory(lockbase);
                    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                            System.Console.Write(hesstype + "(");
                            System.Console.Write("thod " + threszeroblk + " : ");
                            System.Console.Write("corr {0,6}, ", cnt_corr);
                            System.Console.Write("wovlp {0,6} : ", cnt_wovlp);
                            System.Console.Write("{0}),    ", cnt_ovlps.HToStringSeparated("{0,4}", ","));
                        }
                    }
                    System.Console.WriteLine();
                }
Exemple #3
0
                public static void SelfTest()
                {
                    if (HDebug.Selftest() == false)
                    {
                        return;
                    }

                    string temppath            = @"K:\temp\";
                    string tinkerpath_testgrad = "\"" + @"C:\Program Files\Tinker\bin-win64-8.2.1\testgrad.exe" + "\"";
                    string tinkerpath_testhess = "\"" + @"C:\Program Files\Tinker\bin-win64-8.2.1\testhess.exe" + "\"";

                    var xyz  = Tinker.Xyz.FromLines(SelftestData.lines_1L2Y_xyz);
                    var prm  = Tinker.Prm.FromLines(SelftestData.lines_charmm22_prm);
                    var univ = Universe.Build(xyz, prm);

                    var testhess = Tinker.Run.Testhess(tinkerpath_testhess, xyz, prm, temppath
                                                       , HessMatrixZeros: HessMatrixLayeredArray.ZerosHessMatrixLayeredArray
                                                       );
                    var testgrad = Tinker.Run.Testgrad(tinkerpath_testgrad, xyz, prm, temppath);
                    var hessinfo = Hess.HessInfo.FromTinker(xyz, prm, testhess.hess);

                    var hessforcinfo = HessForc.Coarse.HessForcInfo.From(hessinfo);

                    hessforcinfo.forc = testgrad.anlyts.GetForces(xyz.atoms);
                    var coarseinfo_debug = HessForc.Coarse.GetCoarseHessForc
                                               (hessforcinfo
                                               , coords: hessinfo.coords
                                               , GetIdxKeepListRemv: GetIdxKeepListRemv
                                               , ila: null
                                               , thres_zeroblk: double.Epsilon
                                               , options: new string[] { "Debug" }
                                               );

                    var coarseinfo_simple = HessForc.Coarse.GetCoarseHessForc
                                                (hessforcinfo
                                                , coords: hessinfo.coords
                                                , GetIdxKeepListRemv: GetIdxKeepListRemv
                                                , ila: null
                                                , thres_zeroblk: double.Epsilon
                                                , options: new string[] { "SubSimple" }
                                                );
                    double absmax_simple = (coarseinfo_debug.hess - coarseinfo_simple.hess).HAbsMax();

                    HDebug.Assert(Math.Abs(absmax_simple) < 0.00000001);
                    double absmax_simple_forc = (coarseinfo_debug.forc.ToVector() - coarseinfo_simple.forc.ToVector()).ToArray().MaxAbs();

                    HDebug.Assert(Math.Abs(absmax_simple_forc) < 0.00000001);

                    var coarseinfo_1iter = HessForc.Coarse.GetCoarseHessForc
                                               (hessforcinfo
                                               , coords: hessinfo.coords
                                               , GetIdxKeepListRemv: GetIdxKeepListRemv
                                               , ila: null
                                               , thres_zeroblk: double.Epsilon
                                               , options: new string[] { "OneIter" }
                                               );
                    double absmax_1iter = (coarseinfo_debug.hess - coarseinfo_1iter.hess).HAbsMax();

                    HDebug.Assert(Math.Abs(absmax_1iter) < 0.00000001);
                    double absmax_1iter_forc = (coarseinfo_debug.forc.ToVector() - coarseinfo_1iter.forc.ToVector()).ToArray().MaxAbs();

                    HDebug.Assert(Math.Abs(absmax_1iter_forc) < 0.00000001);

                    var coarseinfo_iter = HessForc.Coarse.GetCoarseHessForc
                                              (hessforcinfo
                                              , coords: hessinfo.coords
                                              , GetIdxKeepListRemv: GetIdxKeepListRemv
                                              , ila: null
                                              , thres_zeroblk: double.Epsilon
                                              , options: null
                                              );
                    double absmax_iter = (coarseinfo_debug.hess - coarseinfo_iter.hess).HAbsMax();

                    HDebug.Assert(Math.Abs(absmax_iter) < 0.00000001);
                    double absmax_iter_forc = (coarseinfo_debug.forc.ToVector() - coarseinfo_iter.forc.ToVector()).ToArray().MaxAbs();

                    HDebug.Assert(Math.Abs(absmax_iter_forc) < 0.00000001);

                    double tolerance = 1.0E-6; // 0.00001;
                    var    coarseinfo_1iter_tolerant = HessForc.Coarse.GetCoarseHessForc
                                                           (hessforcinfo
                                                           , coords: hessinfo.coords
                                                           , GetIdxKeepListRemv: GetIdxKeepListRemv
                                                           , ila: null
                                                           , thres_zeroblk: tolerance
                                                           , options: new string[] { "OneIter" }
                                                           );
                    double absmax_1iter_tolerant = (coarseinfo_debug.hess - coarseinfo_1iter_tolerant.hess).HAbsMax();

                    HDebug.Assert(Math.Abs(absmax_1iter_tolerant) < tolerance * 10);
                    double absmax_1iter_tolerant_forc = (coarseinfo_debug.forc.ToVector() - coarseinfo_1iter_tolerant.forc.ToVector()).ToArray().MaxAbs();

                    HDebug.Assert(Math.Abs(absmax_1iter_tolerant_forc) < tolerance * 10);

                    var coarseinfo_iter_tolerant = HessForc.Coarse.GetCoarseHessForc
                                                       (hessforcinfo
                                                       , coords: hessinfo.coords
                                                       , GetIdxKeepListRemv: GetIdxKeepListRemv
                                                       , ila: null
                                                       , thres_zeroblk: tolerance
                                                       , options: null
                                                       );
                    double absmax_iter_tolerant = (coarseinfo_debug.hess - coarseinfo_iter_tolerant.hess).HAbsMax();

                    HDebug.Assert(Math.Abs(absmax_iter_tolerant) < tolerance * 10);
                    double absmax_iter_tolerant_forc = (coarseinfo_debug.forc.ToVector() - coarseinfo_iter_tolerant.forc.ToVector()).ToArray().MaxAbs();

                    HDebug.Assert(Math.Abs(absmax_iter_tolerant_forc) < tolerance * 10);

                    string tempfilepath = HFile.GetTempPath(temppath, "test_serialzation_CoarseHessForc.dat");

                    HSerialize.Serialize(tempfilepath, null, coarseinfo_iter_tolerant);
                    var    coarseinfo_iter_tolerant2 = HSerialize.Deserialize <HessForcInfo>(tempfilepath, null);
                    double absmax_iter_tolerant_file = (coarseinfo_iter_tolerant.hess - coarseinfo_iter_tolerant.hess).HAbsMax();

                    HDebug.Assert(Math.Abs(absmax_iter_tolerant_file) == 0);
                    double absmax_iter_tolerant_file_forc = (coarseinfo_iter_tolerant.forc.ToVector() - coarseinfo_iter_tolerant.forc.ToVector()).ToArray().MaxAbs();

                    HDebug.Assert(Math.Abs(absmax_iter_tolerant_file_forc) == 0);
                    HFile.Delete(tempfilepath);
                }
Exemple #4
0
                public static Quality GetQuality
                    (string pathcache
                    , Universe univ
                    , Func <Hess.HessInfo> GetHessInfo
                    , double GetHessCoarseResiIter_thres_zeroblk
                    )
                {
                    double corr        = double.NaN;
                    double wovlp       = double.NaN;
                    double sparsityall = double.NaN;
                    double sparsityca  = double.NaN;

                    double[] ovlps = new double[]
                    {
                        double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                        double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                    };
                    double[] eigvals = new double[]
                    {
                        double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                        double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                    };

                    try
                    {
                        Hess.HessInfo hessinfo     = GetHessInfo();
                        double        lsparsityall = 1 - hessinfo.hess.RatioUsedBlocks;

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

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

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

                    return(new Quality
                    {
                        corr = corr,
                        wovlp = wovlp,
                        sparsity_all = sparsityall,
                        sparsity_ca = sparsityca,
                        ovlps = ovlps,
                        eigvals = eigvals,
                    });
                }
                public static Tuple <double, double, double[]> GetQuality
                    (string pathcache
                    , Universe univ
                    , Func <Hess.HessInfo> GetHessInfo
                    , double GetHessCoarseResiIter_thres_zeroblk
                    )
                {
                    if (HFile.Exists(pathcache) == false)
                    {
                        double   corr  = double.NaN;
                        double   wovlp = double.NaN;
                        double[] ovlps = new double[]
                        {
                            double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                            double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                        };

                        try
                        {
                            Hess.HessInfo hessinfo = GetHessInfo();

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

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

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

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

                    {
                        double[] buff;
                        HSerialize.DeserializeText(pathcache, out buff);
                        double   corr  = buff[0];
                        double   wovlp = buff[1];
                        double[] ovlps = new double[] { buff[2], buff[3], buff[4], buff[5], buff[6]
                                                        , buff[7], buff[8], buff[9], buff[10], buff[11] };
                        if (double.IsNaN(corr))
                        {
                            HDebug.Assert(false);
                        }
                        return(new Tuple <double, double, double[]>(corr, wovlp, ovlps));
                    }
                }
Exemple #6
0
            public static Universe Build(Pdb pdb, Gromacs.Top top, ITextLogger logger)
            {
                Universe univ = new Universe();

                // atoms
                List <Top.Atom>          top_atoms         = top.elements.SelectSourceExtTop().ListAtom().SelectMatchToPdb(pdb.atoms);
                List <Top.Bond>          top_bonds         = top.elements.SelectSourceExtTop().ListType <Top.Bond>();
                List <Top.Pair>          top_pairs         = top.elements.SelectSourceExtTop().ListType <Top.Pair>(); ///Debug.ToDo("handle pairtype <= nbnd 1-4");
                List <Top.Angle>         top_angles        = top.elements.SelectSourceExtTop().ListType <Top.Angle>();
                List <Top.Dihedral>      top_dihedral      = top.elements.SelectSourceExtTop().ListType <Top.Dihedral>();
                List <Top.Atomtypes>     top_atomtypes     = top.elements.ListAtomtypes();
                List <Top.Bondtypes>     top_bondtypes     = top.elements.ListType <Top.Bondtypes>();
                List <Top.Angletypes>    top_angletypes    = top.elements.ListType <Top.Angletypes>();
                List <Top.Dihedraltypes> top_dihedraltypes = top.elements.ListType <Top.Dihedraltypes>();
                List <Top.Pairtypes>     top_pairtypes     = top.elements.ListType <Top.Pairtypes>();   ///Debug.ToDo("handle pairtype <= nbnd 1-4");

                {
                    ///Debug.ToDo("handle here");
                    List <Top.LineElement> elems = new List <Top.LineElement>(top.elements);
                    foreach (var elem in top_atoms)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    foreach (var elem in top_bonds)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    foreach (var elem in top_pairs)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    foreach (var elem in top_angles)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    foreach (var elem in top_dihedral)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    foreach (var elem in top_atomtypes)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    foreach (var elem in top_bondtypes)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    foreach (var elem in top_angletypes)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    foreach (var elem in top_dihedraltypes)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    foreach (var elem in top_pairtypes)
                    {
                        HDebug.Verify(elems.Remove(elem));
                    }
                    List <Top.LineElement> srcitp = new List <Top.LineElement>();
                    List <Top.LineElement> srctop = new List <Top.LineElement>();
                    for (int i = 0; i < elems.Count; i++)
                    {
                        if ((elems[i].source as string).EndsWith(".itp"))
                        {
                            srcitp.Add(elems[i]); elems[i] = null; continue;
                        }
                        if ((elems[i].source as string).EndsWith(".top"))
                        {
                            srctop.Add(elems[i]); elems[i] = null; continue;
                        }
                    }
                    elems = elems.HRemoveAllNull().ToList();
                    HDebug.Assert(elems.Count == 0);
                }

                Atoms atoms = new Atoms(univ);

                HDebug.Assert(pdb.atoms.Length == top_atoms.Count);
                for (int i = 0; i < top_atoms.Count; i++)
                {
                    //Debug.Assert(psf.atoms[i].AtomId == pdb.atoms[i].serial);
                    //string type0 = psf.atoms[i].AtomType;
                    //Atom atom = new Atom(psf.atoms[i], prm.FindNonbonded(type0, logger), pdb.atoms[i]);
                    //atom.Coord = pdb.atoms[i].coord;
                    //atoms.Add(atom);
                    Gromacs.Top.Atom atom = top_atoms[i];
                    HDebug.Assert(i + 1 == atom.cgnr);
                    HDebug.Assert(atom.cgnr == pdb.atoms[i].serial);
                    //Gromacs.Top.Atomtypes atomtype = top_atomtypes[atom.type];
                    List <Gromacs.Top.Atomtypes> atomtypes = FindTypes(top_atomtypes, atom.type);
                    HDebug.Assert(atomtypes.Count == 1);
                    Gromacs.Top.Atomtypes atomtype = atomtypes.Last();
                    //Debug.Assert(atom.charge == atomtype.charge);
                    //Debug.Assert(atom.mass   == atomtype.mass  );
                    Atom uatom = new Atom(atom.cgnr, atom.atom, atom.type, pdb.atoms[i].element.Trim()
                                          , atom.resnr, atom.residu
                                          , atom.charge, atom.mass
                                          , atomtype.epsilon, atomtype.sigma
                                          , double.NaN, double.NaN
                                          , atom, atomtype
                                          );
                    uatom.Coord = pdb.atoms[i].coord;
                    atoms.Add(uatom);
                }

                // bonds
                Bonds bonds = new Bonds();

                for (int i = 0; i < top_bonds.Count; i++)
                {
                    int idx0 = top_bonds[i].ai - 1; Atom atom0 = atoms[idx0]; string type0 = atom0.AtomType;
                    int idx1 = top_bonds[i].aj - 1; Atom atom1 = atoms[idx1]; string type1 = atom1.AtomType;
                    List <Gromacs.Top.Bondtypes> bondtypes = FindTypes(top_bondtypes, type0, type1);
                    //Debug.Assert(bondtypes.Count == 1);
                    Gromacs.Top.Bondtypes bondtype         = bondtypes.Last();
                    //Gromacs.Top.Bondtypes bondtype = top_bondtypes[Gromacs.Top.Bondtypes.GetStringKey(type0,type1)];
                    Bond bond = new Bond(atom0, atom1, bondtype.kb, bondtype.b0, bondtype);
                    bonds.Add(bond);
                    atom0.Bonds.Add(bond); atom0.Inter123.Add(atom1); atom0.Inter12.Add(atom1);
                    atom1.Bonds.Add(bond); atom1.Inter123.Add(atom0); atom1.Inter12.Add(atom0);
                }

                // angles
                Angles angles = new Angles();

                for (int i = 0; i < top_angles.Count; i++)
                {
                    int idx0 = top_angles[i].ai - 1; Atom atom0 = atoms[idx0]; string type0 = atom0.AtomType;
                    int idx1 = top_angles[i].aj - 1; Atom atom1 = atoms[idx1]; string type1 = atom1.AtomType;
                    int idx2 = top_angles[i].ak - 1; Atom atom2 = atoms[idx2]; string type2 = atom2.AtomType;
                    List <Gromacs.Top.Angletypes> angletypes = FindTypes(top_angletypes, type0, type1, type2);
                    //Debug.Assert(angletypes.Count == 1);
                    Gromacs.Top.Angletypes angletype         = angletypes.Last();
                    //Gromacs.Top.Angletypes angletype = top_angletypes[Gromacs.Top.Bondtypes.GetStringKey(type0, type1, type2)];
                    Angle angle = new Angle(atom0, atom1, atom2
                                            , angletype.cth, angletype.th0, angletype.cub, angletype.ub0
                                            , angletype
                                            );
                    angles.Add(angle);
                    atom0.Angles.Add(angle); atom0.Inter123.Add(atom1); atom0.Inter123.Add(atom2);
                    atom1.Angles.Add(angle); atom1.Inter123.Add(atom2); atom1.Inter123.Add(atom0);
                    atom2.Angles.Add(angle); atom2.Inter123.Add(atom0); atom2.Inter123.Add(atom1);
                }

                // dihedrals
                Dihedrals dihedrals = new Dihedrals();
                Impropers impropers = new Impropers();

                for (int i = 0; i < top_dihedral.Count; i++)
                {
                    int idx0 = top_dihedral[i].ai - 1; Atom atom0 = atoms[idx0]; string type0 = atom0.AtomType;
                    int idx1 = top_dihedral[i].aj - 1; Atom atom1 = atoms[idx1]; string type1 = atom1.AtomType;
                    int idx2 = top_dihedral[i].ak - 1; Atom atom2 = atoms[idx2]; string type2 = atom2.AtomType;
                    int idx3 = top_dihedral[i].al - 1; Atom atom3 = atoms[idx3]; string type3 = atom3.AtomType;
                    int funct = top_dihedral[i].funct;
                    List <Gromacs.Top.Dihedraltypes> dihedraltypes = FindTypes(top_dihedraltypes, type0, type1, type2, type3);
                    {
                        List <Gromacs.Top.Dihedraltypes> ldihedraltypes = new List <Top.Dihedraltypes>(dihedraltypes);
                        // select funct matching to its query
                        for (int j = 0; j < ldihedraltypes.Count;)
                        {
                            if (ldihedraltypes[j].func == funct)
                            {
                                j++;
                            }
                            else
                            {
                                ldihedraltypes.RemoveAt(j);
                            }
                        }
                        // if there are no matching query but improper, select the improper
                        if ((ldihedraltypes.Count == 0) && (dihedraltypes[0].func == 2))
                        {
                            ldihedraltypes.Add(dihedraltypes[0]);
                        }
                        dihedraltypes = new List <Top.Dihedraltypes>(ldihedraltypes);
                    }
                    //{
                    //    // if dihedral(func==9) and improper(func==2) are mixed
                    //    // select only improper
                    //    bool has_func_2 = false;
                    //    for(int j=0; j<dihedraltypes.Count; j++)
                    //        if(dihedraltypes[j].func == 2)
                    //            has_func_2 = true;
                    //    if(has_func_2)
                    //    {
                    //        for(int j=0; j<dihedraltypes.Count; )
                    //        {
                    //            if(dihedraltypes[j].func == 2)
                    //                j++;
                    //            else
                    //                dihedraltypes.RemoveAt(j);
                    //        }
                    //    }
                    //}
                    if (dihedraltypes[0].func == 9)
                    {
                        // dihedral
                        for (int j = 1; j < dihedraltypes.Count; j++)
                        {
                            HDebug.Assert(dihedraltypes[0].func == dihedraltypes[j].func);
                            HDebug.Assert(dihedraltypes[0].i.Trim() == dihedraltypes[j].i.Trim());
                            HDebug.Assert(dihedraltypes[0].j.Trim() == dihedraltypes[j].j.Trim());
                            HDebug.Assert(dihedraltypes[0].k.Trim() == dihedraltypes[j].k.Trim());
                            HDebug.Assert(dihedraltypes[0].l.Trim() == dihedraltypes[j].l.Trim());
                        }
                        Gromacs.Top.Dihedraltypes dihedraltype = dihedraltypes.Last();
                        Dihedral dihedral = new Dihedral(atom0, atom1, atom2, atom3
                                                         , dihedraltype.cp, dihedraltype.mult, dihedraltype.phi0
                                                         , dihedraltype
                                                         );
                        dihedrals.Add(dihedral);
                        atom0.Dihedrals.Add(dihedral); //atom0.Inter123.Add(atom1); atom0.Inter123.Add(atom2); atom0.Inter123.Add(atom3);
                        atom1.Dihedrals.Add(dihedral); //atom1.Inter123.Add(atom2); atom1.Inter123.Add(atom3); atom1.Inter123.Add(atom0);
                        atom2.Dihedrals.Add(dihedral); //atom2.Inter123.Add(atom3); atom2.Inter123.Add(atom0); atom2.Inter123.Add(atom1);
                        atom3.Dihedrals.Add(dihedral); //atom3.Inter123.Add(atom0); atom3.Inter123.Add(atom1); atom3.Inter123.Add(atom2);
                        continue;
                    }
                    if (dihedraltypes[0].func == 2)
                    {
                        // improper
                        for (int j = 1; j < dihedraltypes.Count; j++)
                        {
                            HDebug.Assert(dihedraltypes[0].func == dihedraltypes[j].func);
                            HDebug.Assert(dihedraltypes[0].i.Trim() == dihedraltypes[j].i.Trim());
                            HDebug.Assert(dihedraltypes[0].j.Trim() == dihedraltypes[j].j.Trim());
                            HDebug.Assert(dihedraltypes[0].k.Trim() == dihedraltypes[j].k.Trim());
                            HDebug.Assert(dihedraltypes[0].l.Trim() == dihedraltypes[j].l.Trim());
                        }
                        Gromacs.Top.Dihedraltypes impropertype = dihedraltypes.Last();
                        Improper improper = new Improper(atom0, atom1, atom2, atom3
                                                         , impropertype.cp, impropertype.phi0
                                                         , impropertype
                                                         );
                        impropers.Add(improper);
                        atom0.Impropers.Add(improper); //atom0.Inter123.Add(atom1); atom0.Inter123.Add(atom2); atom0.Inter123.Add(atom3);
                        atom1.Impropers.Add(improper); //atom1.Inter123.Add(atom2); atom1.Inter123.Add(atom3); atom1.Inter123.Add(atom0);
                        atom2.Impropers.Add(improper); //atom2.Inter123.Add(atom3); atom2.Inter123.Add(atom0); atom2.Inter123.Add(atom1);
                        atom3.Impropers.Add(improper); //atom3.Inter123.Add(atom0); atom3.Inter123.Add(atom1); atom3.Inter123.Add(atom2);
                        continue;
                    }
                    HDebug.Assert(false);


                    //Debug.Assert(dihedraltypes.Count == 1);
                    //
                    //for(int j=0; j<dihedraltypes.Count; j++)
                    //    if(dihedraltypes[j].func != 2)
                    //        dihedraltype = dihedraltypes[j];
                    //Debug.Assert(dihedraltype != null);
                    //List<Gromacs.Top.Dihedraltypes> dihedraltypes = top_dihedraltypes[Gromacs.Top.Dihedraltypes.GetStringKey(type0, type1, type2, type3)];
                }

                // 1-4 interactions
                for (int i = 0; i < atoms.Count; i++)
                {
                    HashSet <Atom> Inter14 = new HashSet <Atom>();
                    BuildInter1toN(atoms[i], 4, Inter14); // find all atoms for 1-4 interaction
                    Inter14.Remove(atoms[i]);             // remove self
                    foreach (Atom atom in atoms[i].Inter123)
                    {
                        Inter14.Remove(atom);             // remove all 1-2, 1-3 interactions
                    }
                    atoms[i].Inter14 = Inter14;
                }
                Nonbonded14s nonbonded14s = new Nonbonded14s();

                nonbonded14s.Build(atoms);

                //// nonbondeds
                //// do not make this list in advance, because it depends on the atom positions
                //Nonbondeds nonbondeds = new Nonbondeds();
                //nonbondeds.Build(atoms);


                //Universe univ = new Universe();
                univ.pdb = pdb;
                univ.refs.Add("top", top);
                univ.atoms     = atoms;
                univ.bonds     = bonds;
                univ.angles    = angles;
                univ.dihedrals = dihedrals;
                univ.impropers = impropers;
                //univ.nonbondeds   = nonbondeds  ;  // do not make this list in advance, because it depends on the atom positions
                univ.nonbonded14s = nonbonded14s;

                HDebug.Assert(univ.Verify());
                return(univ);
            }
Exemple #7
0
                public static MatrixByArr[,] GetJ(Universe univ, Vector[] coords, List <RotableInfo> rotInfos, Func <MatrixByArr, MatrixByArr> fnInv3x3 = null)
                {
                    if (fnInv3x3 == null)
                    {
                        fnInv3x3 = delegate(MatrixByArr A)
                        {
                            using (new Matlab.NamedLock("GetJ"))
                            {
                                return(LinAlg.Inv3x3(A));
                            }
                        }
                    }
                    ;

                    MatrixByArr I    = GetITa(univ.atoms.ToArray(), coords);
                    MatrixByArr invI = fnInv3x3(I);

                    Vector      R      = GetRa(univ.atoms.ToArray(), coords);
                    double      M      = GetMa(univ.atoms.ToArray());
                    Vector      MR     = GetMaRa(univ.atoms.ToArray(), coords);
                    MatrixByArr MRx    = GetSSMatrix(MR);
                    MatrixByArr MRxt   = MRx.Tr();
                    MatrixByArr III    = I - (1.0 / M) * MRx * MRxt; // { MI - 1/M * [MR]x * [MR]x^t }
                    MatrixByArr invIII = fnInv3x3(III);
                    //Vector MMR = GetMaMaRa(univ.atoms.ToArray());

                    int n = univ.atoms.Count;
                    int m = rotInfos.Count;

                    MatrixByArr[,] J = new MatrixByArr[n, m];
                    for (int a = 0; a < m; a++)
                    {
                        RotableInfo rotInfo = rotInfos[a];
                        Vector      Ra      = GetRa(rotInfo.rotAtoms, coords);
                        double      Ma      = GetMa(rotInfo.rotAtoms);
                        Vector      MaRa    = GetMaRa(rotInfo.rotAtoms, coords);
                        MatrixByArr Ia      = GetITa(rotInfo.rotAtoms, coords);

                        HDebug.Assert(rotInfo.rotAtoms.Contains(rotInfo.bondedAtom));
                        Vector sa = coords[rotInfo.bondedAtom.ID];
                        //Vector Sa = sa * rotInfos[a].rotAtoms.Length;
                        Vector ea;
                        {
                            HashSet <Atom> bondatoms = new HashSet <Atom>(rotInfo.bond.atoms);
                            bondatoms.Remove(rotInfo.bondedAtom);
                            HDebug.Assert(bondatoms.Count == 1);
                            HDebug.Assert(rotInfo.rotAtoms.Contains(bondatoms.First()) == false);
                            ea = (sa - coords[bondatoms.First().ID]).UnitVector();
                        }

                        Vector Aa;
                        {
                            Vector ea_Rasa = LinAlg.CrossProd3(ea, Ra - sa);
                            Vector IAa     = -LinAlg.MV(Ia, ea) + LinAlg.CrossProd3(Ma * R - MaRa, ea_Rasa);
                            Aa = LinAlg.MV(invI, IAa);
                        }
                        {
                            //Vector ea_MaRa_Masa = Vector.CrossProd3(ea, MaRa-Ma*sa);
                            //Vector ea_sa = Vector.CrossProd3(ea, sa);
                            Vector IAa = new double[3];
                            IAa += -LinAlg.MV(Ia, ea);
                            IAa += LinAlg.CrossProd3(MaRa, LinAlg.CrossProd3(ea, sa));
                            IAa += LinAlg.CrossProd3(MR, LinAlg.CrossProd3(ea, MaRa - Ma * sa)) / M;
                            Aa   = LinAlg.MV(invIII, IAa);
                        }
                        Vector ta = new double[3];
                        {
                            //Aa = new double[3]; // check "translational Eckart condition" only
                            //ta += (-1/M) * Vector.CrossProd3(Aa, MMR);
                            ta += (-1 / M) * LinAlg.CrossProd3(Aa, MR);
                            ta += (-1 / M) * LinAlg.CrossProd3(ea, MaRa - Ma * sa);
                        }

                        for (int i = 0; i < n; i++)
                        {
                            double mi  = univ.atoms[i].Mass;
                            Vector ri  = coords[univ.atoms[i].ID];
                            Vector Jia = new double[3];
                            //Jia += Vector.CrossProd3(Aa, ri*mi);
                            Jia    += LinAlg.CrossProd3(Aa, ri);
                            Jia    += ta;
                            J[i, a] = Jia.ToColMatrix();
                        }
                        foreach (Atom ira in rotInfo.rotAtoms)
                        {
                            int    i   = ira.ID;
                            Vector ri  = coords[univ.atoms[i].ID];
                            Vector Jia = LinAlg.CrossProd3(ea, ri - sa);
                            J[i, a] += Jia.ToColMatrix();
                        }

                        //if(Debug.IsDebuggerAttached)
                        //{
                        //    // check Eckart condition
                        //    // http://en.wikipedia.org/wiki/Eckart_conditions
                        //    //////////////////////////////////////////////////////////////////////
                        //    // 1. translational Eckart condition
                        //    //    sum{i=1..n}{mi * Jia} = 0
                        //    Vector mJ  = EckartConditionTrans(univ, J, a);
                        //    Debug.AssertTolerance(0.00000001, mJ);
                        //    // 2. rotational Eckart condition
                        //    //    sum{i=1..n}{mi * r0i x Jia} = 0,
                        //    //    where 'x' is the cross product
                        //    Vector mrJ = EckartConditionRotat(univ, coords, J, a);
                        //    Debug.AssertTolerance(0.00000001, mrJ);
                        //}
                    }
                    return(J);
                }
Exemple #8
0
                public unsafe static MatrixByArr GetJ(Universe univ, Vector[] coords, List <RotableInfo> rotInfos)
                {
                    HDebug.Assert(rotInfos.ListMolecule().HUnion().Length == 1);
                    Dictionary <Universe.Molecule, Dictionary <string, object> > moleMRI = new Dictionary <Universe.Molecule, Dictionary <string, object> >();

                    int         n = univ.atoms.Count;
                    int         m = rotInfos.Count;
                    MatrixByArr J = new double[3 * n, m];

                    double[] _Ja = new double[3 * n];
                    for (int a = 0; a < m; a++)
                    {
                        var mole = rotInfos[a].mole;
                        if (moleMRI.ContainsKey(rotInfos[a].mole) == false)
                        {
                            double      _M  = 0;
                            Vector      _R  = new double[3];
                            Vector      _MR = new double[3];
                            MatrixByArr _I  = new double[3, 3];
                            GetMaRaMaraITa(mole.atoms.ToArray(), coords, ref _M, ref _R, ref _MR, ref _I);
                            MatrixByArr _invI = LinAlg.Inv3x3(_I);

                            MatrixByArr _MRx    = GetSSMatrix(_MR);
                            MatrixByArr _MRxt   = _MRx.Tr();
                            MatrixByArr _III    = _I - (1.0 / _M) * _MRx * _MRxt; // { MI - 1/M * [MR]x * [MR]x^t }
                            MatrixByArr _invIII = LinAlg.Inv3x3(_III);

                            moleMRI.Add(mole, new Dictionary <string, object>());
                            moleMRI[mole].Add("invI", _invI);
                            moleMRI[mole].Add("invIII", _invIII);
                            moleMRI[mole].Add("MR", _MR);
                            moleMRI[mole].Add("R", _R);
                            moleMRI[mole].Add("M", _M);
                        }
                        MatrixByArr invI   = moleMRI[mole]["invI"] as MatrixByArr;
                        MatrixByArr invIII = moleMRI[mole]["invIII"] as MatrixByArr;
                        Vector      MR     = moleMRI[mole]["MR"] as Vector;
                        Vector      R      = moleMRI[mole]["R"] as Vector;
                        double      M      = (double)(moleMRI[mole]["M"]);



                        RotableInfo rotInfo = rotInfos[a];
                        double      Ma      = 0;
                        Vector      Ra      = new double[3];
                        Vector      MaRa    = new double[3];
                        MatrixByArr Ia      = new double[3, 3];
                        GetMaRaMaraITa(rotInfo.rotAtoms, coords, ref Ma, ref Ra, ref MaRa, ref Ia);

                        HDebug.Assert(rotInfo.rotAtoms.Contains(rotInfo.bondedAtom));
                        Vector sa = coords[rotInfo.bondedAtom.ID];
                        Vector ea;
                        {
                            Atom bondatom = null;
                            HDebug.Assert(rotInfo.bond.atoms.Length == 2);
                            if (rotInfo.bond.atoms[0] == rotInfo.bondedAtom)
                            {
                                bondatom = rotInfo.bond.atoms[1];
                            }
                            else
                            {
                                bondatom = rotInfo.bond.atoms[0];
                            }
                            HDebug.Assert(rotInfo.rotAtoms.Contains(bondatom) == false);
                            ea = (sa - coords[bondatom.ID]).UnitVector();
                        }

                        Vector Aa;
                        {
                            Vector ea_Rasa = LinAlg.CrossProd3(ea, Ra - sa);
                            Vector IAa     = -LinAlg.MV(Ia, ea) + LinAlg.CrossProd3(Ma * R - MaRa, ea_Rasa);
                            Aa = LinAlg.MV(invI, IAa);
                        }
                        {
                            //Vector ea_MaRa_Masa = Vector.CrossProd3(ea, MaRa-Ma*sa);
                            //Vector ea_sa = Vector.CrossProd3(ea, sa);
                            Vector IAa = new double[3];
                            IAa += -LinAlg.MV(Ia, ea);
                            IAa += LinAlg.CrossProd3(MaRa, LinAlg.CrossProd3(ea, sa));
                            IAa += LinAlg.CrossProd3(MR, LinAlg.CrossProd3(ea, MaRa - Ma * sa)) / M;
                            Aa   = LinAlg.MV(invIII, IAa);
                        }
                        Vector ta = new double[3];
                        {
                            //Aa = new double[3]; // check "translational Eckart condition" only
                            //ta += (-1/M) * Vector.CrossProd3(Aa, MMR);
                            ta += (-1 / M) * LinAlg.CrossProd3(Aa, MR);
                            ta += (-1 / M) * LinAlg.CrossProd3(ea, MaRa - Ma * sa);
                        }

                        fixed(double *Ja = _Ja)
                        {
                            //for(int i=0; i<n; i++)
                            foreach (Atom iaa in mole.atoms)
                            {
                                int    i   = iaa.ID;
                                double mi  = univ.atoms[i].Mass;
                                Vector ri  = coords[univ.atoms[i].ID];
                                Vector Jia = new double[3];
                                //Jia += Vector.CrossProd3(Aa, ri*mi);
                                Jia += LinAlg.CrossProd3(Aa, ri);
                                Jia += ta;
                                //J[i, a] = Jia.ToColMatrix();
                                Ja[i * 3 + 0] = Jia[0];
                                Ja[i * 3 + 2] = Jia[2];
                                Ja[i * 3 + 1] = Jia[1];
                            }
                            foreach (Atom ira in rotInfo.rotAtoms)
                            {
                                int    i   = ira.ID;
                                Vector ri  = coords[univ.atoms[i].ID];
                                Vector Jia = LinAlg.CrossProd3(ea, ri - sa);
                                //J[i, a] += Jia.ToColMatrix();
                                Ja[i * 3 + 0] += Jia[0];
                                Ja[i * 3 + 1] += Jia[1];
                                Ja[i * 3 + 2] += Jia[2];
                            }
                            //for(int i=0; i<n; i++)
                            foreach (Atom iaa in mole.atoms)
                            {
                                int i = iaa.ID;
                                J[i * 3 + 0, a] = Ja[i * 3 + 0];
                                J[i * 3 + 1, a] = Ja[i * 3 + 1];
                                J[i * 3 + 2, a] = Ja[i * 3 + 2];
                            }
                        }

                        if (HDebug.IsDebuggerAttached)
                        {
                            // check Eckart condition
                            // http://en.wikipedia.org/wiki/Eckart_conditions
                            //////////////////////////////////////////////////////////////////////
                            // 1. translational Eckart condition
                            //    sum{i=1..n}{mi * Jia} = 0
                            Vector mJ = new double[3];
                            //for(int i=0; i<n; i++)
                            foreach (Atom iaa in mole.atoms)
                            {
                                int    i  = iaa.ID;
                                double mi = univ.atoms[i].Mass;
                                //Vector Jia = J[i, a].ToVector();
                                Vector Jia = new double[3] {
                                    J[i * 3 + 0, a], J[i * 3 + 1, a], J[i * 3 + 2, a]
                                };
                                mJ += mi * Jia;
                            }
                            HDebug.AssertTolerance(0.00000001, mJ);
                            //////////////////////////////////////////////////////////////////////
                            // 1. rotational Eckart condition
                            //    sum{i=1..n}{mi * r0i x Jia} = 0,
                            //    where 'x' is the cross product
                            Vector mrJ = new double[3];
                            //for(int i=0; i<n; i++)
                            foreach (Atom iaa in mole.atoms)
                            {
                                int    i  = iaa.ID;
                                double mi = univ.atoms[i].Mass;
                                Vector ri = coords[univ.atoms[i].ID];
                                //Vector Jia = J[i, a].ToVector();
                                Vector Jia = new double[3] {
                                    J[i * 3 + 0, a], J[i * 3 + 1, a], J[i * 3 + 2, a]
                                };
                                mrJ += mi * LinAlg.CrossProd3(ri, Jia);
                            }
                            HDebug.AssertTolerance(0.0000001, mrJ);
                        }
                    }
                    return(J);
                }
 public MinimizeTNMImpl(Universe univ)
 {
     this.univ = univ;
 }
 public void logTrajectory(Universe univ, long iter, Vectors coords)
 {
 }
Exemple #11
0
 public void Isolate(Universe univ)
 {
     foreach (Bond bond        in new List <Bond>(Bonds))
     {
         foreach (Atom atom in bond.atoms)
         {
             if (atom != this)
             {
                 HDebug.Verify(atom.Bonds.Remove(bond));
             }
         }
         HDebug.Verify(Bonds.Remove(bond)); HDebug.Verify(univ.bonds.Remove(bond));
     }
     foreach (Angle angle       in new List <Angle>(Angles))
     {
         foreach (Atom atom in angle.atoms)
         {
             if (atom != this)
             {
                 HDebug.Verify(atom.Angles.Remove(angle));
             }
         }
         HDebug.Verify(Angles.Remove(angle)); HDebug.Verify(univ.angles.Remove(angle));
     }
     foreach (Dihedral dihedral    in new List <Dihedral>(Dihedrals))
     {
         foreach (Atom atom in dihedral.atoms)
         {
             if (atom != this)
             {
                 HDebug.Verify(atom.Dihedrals.Remove(dihedral));
             }
         }
         HDebug.Verify(Dihedrals.Remove(dihedral)); HDebug.Verify(univ.dihedrals.Remove(dihedral));
     }
     foreach (Improper improper    in new List <Improper>(Impropers))
     {
         foreach (Atom atom in improper.atoms)
         {
             if (atom != this)
             {
                 HDebug.Verify(atom.Impropers.Remove(improper));
             }
         }
         HDebug.Verify(Impropers.Remove(improper)); HDebug.Verify(univ.impropers.Remove(improper));
     }
     foreach (Nonbonded14 nonbonded14 in new List <Nonbonded14>(Nonbonded14s))
     {
         foreach (Atom atom in nonbonded14.atoms)
         {
             if (atom != this)
             {
                 HDebug.Verify(atom.Nonbonded14s.Remove(nonbonded14));
             }
         }
         HDebug.Verify(Nonbonded14s.Remove(nonbonded14)); HDebug.Verify(univ.nonbonded14s.Remove(nonbonded14));
     }
     //public List<Nonbonded> Nonbondeds = new List<Nonbonded>();
     foreach (Atom atom in new List <Atom>(Inter12))
     {
         HDebug.Assert(atom != this); HDebug.Verify(atom.Inter12.Remove(this)); HDebug.Verify(Inter12.Remove(atom));
     }
     foreach (Atom atom in new List <Atom>(Inter123))
     {
         HDebug.Assert(atom != this); HDebug.Verify(atom.Inter123.Remove(this)); HDebug.Verify(Inter123.Remove(atom));
     }
     foreach (Atom atom in new List <Atom>(Inter14))
     {
         HDebug.Assert(atom != this); HDebug.Verify(atom.Inter14.Remove(this)); HDebug.Verify(Inter14.Remove(atom));
     }
 }
Exemple #12
0
        public static MixHessInfo GetHessMixEAnm(Universe univ, IList <Vector> coords, ILinAlg la, IList <ResInfo> lstResAllAtom
                                                 , bool bAllowAllToCoarse, bool bOnlyCoarseConnBackbone
                                                 , Tuple <double, double> anmSprcstCutoffAll    // all-all
                                                 , Tuple <double, double> anmSprcstCutoffMix    // all/buffer-coarse
                                                 , Tuple <double, double> anmSprcstCutoffCoarse // coarse-coarse
                                                 , out string errmsg
                                                 , bool bGetIntmInfo, string strBkbnReso
                                                 )
        {
            double anmSprcstAll    = anmSprcstCutoffAll.Item1;
            double anmSprcstMix    = anmSprcstCutoffMix.Item1;
            double anmSprcstCoarse = anmSprcstCutoffCoarse.Item1;
            double anmCutoffAll    = anmSprcstCutoffAll.Item2;
            double anmCutoffMix    = anmSprcstCutoffMix.Item2;
            double anmCutoffCoarse = anmSprcstCutoffCoarse.Item2;

            HDebug.Assert(anmCutoffAll >= 0);
            HDebug.Assert(anmCutoffCoarse >= 0);
            MixModel.FnGetHess GetHess = delegate(Universe luniv, IList <Vector> lcoords, int[] idxAll, int[] idxBuffer, int[] idxCoarse, int[] idxBackbone)
            {
                int size = coords.Count;

                HashSet <int> setIdxAll      = idxAll.HToHashSet();
                HashSet <int> setIdxBuffer   = idxBuffer.HToHashSet();
                HashSet <int> setIdxCoarse   = idxCoarse.HToHashSet();
                HashSet <int> setIdxBackbone = idxBackbone.HToHashSet();

                Matrix anmKij = Matrix.Zeros(size, size);
                for (int c = 0; c < size; c++)
                {
                    if (lcoords[c] == null)
                    {
                        continue;
                    }
                    int typec = 0;
                    if (setIdxAll.Contains(c))
                    {
                        HDebug.Assert(typec == 0); typec = 1;
                    }
                    if (setIdxBuffer.Contains(c))
                    {
                        HDebug.Assert(typec == 0); typec = 2;
                    }
                    if (setIdxCoarse.Contains(c))
                    {
                        HDebug.Assert(typec == 0); typec = 3;
                    }
                    HDebug.Assert(typec != 0);

                    for (int r = c + 1; r < size; r++)
                    {
                        if (lcoords[r] == null)
                        {
                            continue;
                        }
                        int typer = 0;
                        if (setIdxAll.Contains(r))
                        {
                            HDebug.Assert(typer == 0); typer = 1;
                        }
                        if (setIdxBuffer.Contains(r))
                        {
                            HDebug.Assert(typer == 0); typer = 2;
                        }
                        if (setIdxCoarse.Contains(r))
                        {
                            HDebug.Assert(typer == 0); typer = 3;
                        }
                        HDebug.Assert(typer != 0);

                        double sprcst;
                        double cutoff;
                        int    type0  = Math.Min(typec, typer);
                        int    type1  = Math.Max(typec, typer);
                        int    type01 = type0 * 10 + type1;
                        switch (type01)
                        {
                        case 11: sprcst = anmSprcstAll; cutoff = anmCutoffAll; break;             // All    - All

                        case 12: sprcst = anmSprcstAll; cutoff = anmCutoffAll; break;             // All    - Buffer

                        case 22: sprcst = anmSprcstAll; cutoff = anmCutoffAll; break;             // Buffer - Buffer

                        case 33: sprcst = anmSprcstCoarse; cutoff = anmCutoffCoarse; break;       // Coarse - Coarse

                        case 23: sprcst = anmSprcstMix; cutoff = anmCutoffMix; break;             // Buffer - Coarse

                        case 13:                                                                  // All    - Buffer
                            if (bAllowAllToCoarse == false)
                            {
                                continue;
                            }
                            sprcst = anmSprcstMix;
                            cutoff = anmCutoffMix;
                            break;

                        default: throw new Exception();
                        }

                        HDebug.Assert(bOnlyCoarseConnBackbone == false); // "true" makes the result bad
                        if (bOnlyCoarseConnBackbone)
                        {
                            bool c_bkbn = setIdxBackbone.Contains(c);
                            bool r_bkbn = setIdxBackbone.Contains(r);
                            if (c_bkbn && r_bkbn)
                            {
                                // special treatment that in-between backbones use only coarse grained onnections.
                                sprcst = anmSprcstCoarse;
                                cutoff = anmCutoffCoarse;
                            }
                            else if ((type01 == 11) || (type01 == 12) || (type01 == 22))
                            {
                                // do nothing. use the above setting.
                            }
                            else
                            {
                                // all-to-coarse
                                HDebug.AssertOr(type01 == 13, type01 == 23);
                                if (type01 == 33)
                                {
                                    HDebug.Assert(type01 != 33); // should be treated by (c_bkbn && r_bkbn)
                                    throw new Exception("HDebug.Assert(type01 != 33)");
                                }
                                continue;
                            }
                        }
                        double cutoff2 = cutoff * cutoff;

                        double dist2 = (coords[c] - coords[r]).Dist2;
                        if (dist2 <= cutoff2)
                        {
                            anmKij[c, r] = sprcst;
                            anmKij[r, c] = sprcst;
                        }
                    }
                }

                var hessinfo = Hess.GetHessEAnm(luniv, lcoords, anmKij);
                return(hessinfo);
            };
            return(MixModel.GetHessMixModel(univ, coords, la, lstResAllAtom, GetHess, out errmsg, bGetIntmInfo, strBkbnReso));
        }
Exemple #13
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);
            }
Exemple #14
0
            public static Universe Build(Namd.Psf psf, Namd.Prm prm, Pdb pdb, bool?ignore_neg_occupancy, ITextLogger logger)
            {
                Universe univ = new Universe();

                // atoms
                Atoms atoms = new Atoms(univ);
                Dictionary <int, Atom> id_atom = new Dictionary <int, Atom>();

                Pdb.Atom[] pdb_atoms = pdb.atoms;
                HDebug.Assert(psf.atoms.Length == pdb_atoms.Length);
                for (int i = 0; i < psf.atoms.Length; i++)
                {
                    HDebug.Assert(pdb_atoms[i].try_serial == null || psf.atoms[i].AtomId == pdb_atoms[i].serial); // when num atoms in pdb is too large (>99999), it is marked as *****
                    string type0 = psf.atoms[i].AtomType;
                    Atom   atom  = new Atom(psf.atoms[i], prm.FindNonbonded(type0, logger), pdb_atoms[i]);
                    atom.Coord = pdb_atoms[i].coord;
                    {
                        if (ignore_neg_occupancy == null)
                        {
                            if (pdb_atoms[i].occupancy < 0)
                            {
                                throw new HException("unhandled negative occupancy during building universe");
                            }
                        }
                        else
                        {
                            if (ignore_neg_occupancy.Value && pdb_atoms[i].occupancy < 0)
                            {
                                continue;
                            }
                        }
                    }
                    atoms.Add(atom);
                    id_atom.Add(psf.atoms[i].AtomId, atom);
                }

                // bonds
                Bonds bonds = new Bonds();

                for (int i = 0; i < psf.bonds.GetLength(0); i++)
                {
                    int id0 = psf.bonds[i, 0]; if (id_atom.ContainsKey(id0) == false)
                    {
                        continue;
                    }
                    Atom atom0 = id_atom[id0]; string type0 = atom0.AtomType;
                    int  id1 = psf.bonds[i, 1]; if (id_atom.ContainsKey(id1) == false)
                    {
                        continue;
                    }
                    Atom atom1 = id_atom[id1]; string type1 = atom1.AtomType;
                    Bond bond = new Bond(atom0, atom1, prm.FindBond(type0, type1, logger));
                    bonds.Add(bond);
                    atom0.Bonds.Add(bond); atom0.Inter123.Add(atom1); atom0.Inter12.Add(atom1);
                    atom1.Bonds.Add(bond); atom1.Inter123.Add(atom0); atom1.Inter12.Add(atom0);
                }

                // angles
                Angles angles = new Angles();

                for (int i = 0; i < psf.angles.GetLength(0); i++)
                {
                    int id0 = psf.angles[i, 0]; if (id_atom.ContainsKey(id0) == false)
                    {
                        continue;
                    }
                    Atom atom0 = id_atom[id0]; string type0 = atom0.AtomType;
                    int  id1 = psf.angles[i, 1]; if (id_atom.ContainsKey(id1) == false)
                    {
                        continue;
                    }
                    Atom atom1 = id_atom[id1]; string type1 = atom1.AtomType;
                    int  id2 = psf.angles[i, 2]; if (id_atom.ContainsKey(id2) == false)
                    {
                        continue;
                    }
                    Atom atom2 = id_atom[id2]; string type2 = atom2.AtomType;
                    var  prm_angle = prm.FindAngle(type0, type1, type2, logger);
                    if (prm_angle == null)
                    {
                        HDebug.Assert(false);
                        logger.Log(string.Format
                                       ("try to add non-existing angle (({0}, prm {1})-({2}, prm {3})-({4}, prm {5})) in prm"
                                       , atom0, type0, atom1, type1, atom2, type2
                                       ));
                        continue;
                    }
                    Angle angle = new Angle(atom0, atom1, atom2, prm_angle);
                    angles.Add(angle);
                    atom0.Angles.Add(angle); atom0.Inter123.Add(atom1); atom0.Inter123.Add(atom2);
                    atom1.Angles.Add(angle); atom1.Inter123.Add(atom2); atom1.Inter123.Add(atom0);
                    atom2.Angles.Add(angle); atom2.Inter123.Add(atom0); atom2.Inter123.Add(atom1);
                }

                // dihedrals
                Dihedrals dihedrals = new Dihedrals();

                for (int i = 0; i < psf.dihedrals.GetLength(0); i++)
                {
                    int id0 = psf.dihedrals[i, 0]; if (id_atom.ContainsKey(id0) == false)
                    {
                        continue;
                    }
                    Atom atom0 = id_atom[id0]; string type0 = atom0.AtomType;
                    int  id1 = psf.dihedrals[i, 1]; if (id_atom.ContainsKey(id1) == false)
                    {
                        continue;
                    }
                    Atom atom1 = id_atom[id1]; string type1 = atom1.AtomType;
                    int  id2 = psf.dihedrals[i, 2]; if (id_atom.ContainsKey(id2) == false)
                    {
                        continue;
                    }
                    Atom atom2 = id_atom[id2]; string type2 = atom2.AtomType;
                    int  id3 = psf.dihedrals[i, 3]; if (id_atom.ContainsKey(id3) == false)
                    {
                        continue;
                    }
                    Atom atom3 = id_atom[id3]; string type3 = atom3.AtomType;
                    var  prm_dihedrals = prm.FindDihedral(type0, type1, type2, type3, logger);
                    if (prm_dihedrals.Length == 0)
                    {
                        HDebug.Assert(false);
                        logger.Log(string.Format
                                       ("try to add non-existing dihedral (({0}, prm {1})-({2}, prm {3})-({4}, prm {5})-({6}, prm {7})) in prm"
                                       , atom0, type0, atom1, type1, atom2, type2, atom3, type3
                                       ));
                        continue;
                    }
                    foreach (var prm_dihedral in prm_dihedrals)
                    {
                        Dihedral dihedral;
                        if (atom0.ID < atom3.ID)
                        {
                            dihedral = new Dihedral(atom0, atom1, atom2, atom3, prm_dihedral);
                        }
                        else
                        {
                            dihedral = new Dihedral(atom3, atom2, atom1, atom0, prm_dihedral);
                        }
                        dihedrals.Add(dihedral);
                        atom0.Dihedrals.Add(dihedral); //atom0.Inter123.Add(atom1); atom0.Inter123.Add(atom2); atom0.Inter123.Add(atom3);
                        atom1.Dihedrals.Add(dihedral); //atom1.Inter123.Add(atom2); atom1.Inter123.Add(atom3); atom1.Inter123.Add(atom0);
                        atom2.Dihedrals.Add(dihedral); //atom2.Inter123.Add(atom3); atom2.Inter123.Add(atom0); atom2.Inter123.Add(atom1);
                        atom3.Dihedrals.Add(dihedral); //atom3.Inter123.Add(atom0); atom3.Inter123.Add(atom1); atom3.Inter123.Add(atom2);
                    }
                }

                // impropers
                Impropers impropers = new Impropers();

                for (int i = 0; i < psf.impropers.GetLength(0); i++)
                {
                    int id0 = psf.impropers[i, 0]; if (id_atom.ContainsKey(id0) == false)
                    {
                        continue;
                    }
                    Atom atom0 = id_atom[id0]; string type0 = atom0.AtomType;
                    int  id1 = psf.impropers[i, 1]; if (id_atom.ContainsKey(id1) == false)
                    {
                        continue;
                    }
                    Atom atom1 = id_atom[id1]; string type1 = atom1.AtomType;
                    int  id2 = psf.impropers[i, 2]; if (id_atom.ContainsKey(id2) == false)
                    {
                        continue;
                    }
                    Atom atom2 = id_atom[id2]; string type2 = atom2.AtomType;
                    int  id3 = psf.impropers[i, 3]; if (id_atom.ContainsKey(id3) == false)
                    {
                        continue;
                    }
                    Atom     atom3 = id_atom[id3]; string type3 = atom3.AtomType;
                    Improper improper = new Improper(atom0, atom1, atom2, atom3, prm.FindImproper(type0, type1, type2, type3, logger));
                    impropers.Add(improper);
                    atom0.Impropers.Add(improper); //atom0.Inter123.Add(atom1); atom0.Inter123.Add(atom2); atom0.Inter123.Add(atom3);
                    atom1.Impropers.Add(improper); //atom1.Inter123.Add(atom2); atom1.Inter123.Add(atom3); atom1.Inter123.Add(atom0);
                    atom2.Impropers.Add(improper); //atom2.Inter123.Add(atom3); atom2.Inter123.Add(atom0); atom2.Inter123.Add(atom1);
                    atom3.Impropers.Add(improper); //atom3.Inter123.Add(atom0); atom3.Inter123.Add(atom1); atom3.Inter123.Add(atom2);
                }

                // 1-4 interactions
                for (int i = 0; i < atoms.Count; i++)
                {
                    HashSet <Atom> Inter14 = new HashSet <Atom>();
                    BuildInter1toN(atoms[i], 4, Inter14); // find all atoms for 1-4 interaction
                    Inter14.Remove(atoms[i]);             // remove self
                    foreach (Atom atom in atoms[i].Inter123)
                    {
                        Inter14.Remove(atom);             // remove all 1-2, 1-3 interactions
                    }
                    atoms[i].Inter14 = Inter14;
                }
                Nonbonded14s nonbonded14s = new Nonbonded14s();

                nonbonded14s.Build(atoms);

                //// nonbondeds
                //// do not make this list in advance, because it depends on the atom positions
                //Nonbondeds nonbondeds = new Nonbondeds();
                //nonbondeds.Build(atoms);


                //Universe univ = new Universe();
                univ.pdb = pdb;
                univ.refs.Add("psf", psf);
                univ.refs.Add("prm", prm);
                univ.atoms     = atoms;
                univ.bonds     = bonds;
                univ.angles    = angles;
                univ.dihedrals = dihedrals;
                univ.impropers = impropers;
                //univ.nonbondeds   = nonbondeds  ;  // do not make this list in advance, because it depends on the atom positions
                univ.nonbonded14s = nonbonded14s;

                HDebug.Assert(univ.Verify());
                return(univ);
            }