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

            List <Mode> modes;

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

            return(modes.ToArray());
        }
        private int SaveFiles(XDocument xDocument)
        {
            string response = "";
            string nameFolder;
            string nameFile;
            // DESERIALIZE.
            EnvioDTE xmlObjeto = HSerialize.ENVIODTE_To_Object(xDocument);

            if (xmlObjeto != null)
            {
                foreach (DTEDefType dte in xmlObjeto.SetDTE.DTE)
                {
                    DTEDefTypeDocumento document = (DTEDefTypeDocumento)dte.Item;
                    string[]            emisor   = document.Encabezado.Emisor.RUTEmisor.Split('-');
                    if (document.Encabezado.IdDoc.TipoDTE == global::DTEType.Item33 || document.Encabezado.IdDoc.TipoDTE == global::DTEType.Item34)
                    {
                        document.Encabezado.IdDoc.Folio = document.Encabezado.IdDoc.Folio.TrimStart(new char[] { '0' }); // REMOVE ZERO LEFT.
                        try
                        {
                            using (RegistroReclamoDteServiceEndpointService dateTimeDte = new RegistroReclamoDteServiceEndpointService(TokenSii))
                            {
                                int tipo = Convert.ToInt32(document.Encabezado.IdDoc.TipoDTE);
                                response = dateTimeDte.consultarFechaRecepcionSii(emisor.GetValue(0).ToString(),
                                                                                  emisor.GetValue(1).ToString(),
                                                                                  tipo.ToString(),
                                                                                  document.Encabezado.IdDoc.Folio);
                            }

                            if (response.Length != 0)
                            {
                                DateTime timeResponse = DateTime.Parse(string.Format(CultureInfo.InvariantCulture, "{0:D}", response));
                                // 2020\06\76470581-5
                                nameFolder = timeResponse.Year + @"\" + timeResponse.Month + @"\" + document.Encabezado.Receptor.RUTRecep;
                                // 15357870_33_8888
                                nameFile = document.Encabezado.Emisor.RUTEmisor + "__" + Convert.ToInt32(document.Encabezado.IdDoc.TipoDTE).ToString() + "__" + document.Encabezado.IdDoc.Folio;
                                SaveXmlInFolder(nameFolder, nameFile, dte);
                            }
                            else
                            {
                                // Errors. // dejar carpeta folder en 2020/5
                                nameFolder = document.Encabezado.IdDoc.FchEmis.Year + @"\" + document.Encabezado.IdDoc.FchEmis.Month;
                                nameFile   = document.Encabezado.Emisor.RUTEmisor + "__" + Convert.ToInt32(document.Encabezado.IdDoc.TipoDTE).ToString() + "__" + document.Encabezado.IdDoc.Folio;
                                SaveXmlInFolder(nameFolder + @"\Errors\", nameFile, dte);
                            }
                        }
                        catch (Exception)
                        {
                            // ERROR.
                            return(1);
                        }
                    }
                }
            }
            // SUCCESS.
            return(0);
        }
 private void SaveXmlInFolder(string nameFolder, string nameFile, DTEDefType dte)
 {
     try
     {
         string path = @"C:\Centralizador\Inbox\" + nameFolder;
         new CreateFile(path);
         File.WriteAllText(path + @"\" + nameFile + ".xml", HSerialize.DTE_To_Xml(dte));
     }
     catch (Exception)
     {
         throw;
     }
 }
Exemple #4
0
        public static Anisou[] FromHessian(Mode[] modesMassWeighted, double[] mass, double scale = 10000 *1000
                                           , string cachepath = null
                                           )
        {
            if (cachepath != null && HFile.Exists(cachepath))
            {
                List <Anisou> lstanisou;
                HDebug.Verify(HSerialize.Deserialize(cachepath, null, out lstanisou));
                return(lstanisou.ToArray());
            }

            int size = modesMassWeighted.Size();

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

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

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

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

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

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

            int size = mass.Length;

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

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

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

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

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

            return(anisous);
        }
Exemple #6
0
        public static PdbInfo[] GetPdbInfo(params string[] pdbids)
        {
            Dictionary <string, PdbInfo> pdbinfos = new Dictionary <string, PdbInfo>();
            int VER = 0;

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

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

            bool updated = false;

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

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

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

                updated = true;
                //continue;

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

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

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

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

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

            return(pdbinfos.HSelectByKeys(pdbids));
        }
Exemple #7
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);
                }
                public static Tuple <double, double, double[]> GetQuality
                    (string pathcache
                    , Universe univ
                    , Func <Hess.HessInfo> GetHessInfo
                    , double GetHessCoarseResiIter_thres_zeroblk
                    )
                {
                    if (HFile.Exists(pathcache) == false)
                    {
                        double   corr  = double.NaN;
                        double   wovlp = double.NaN;
                        double[] ovlps = new double[]
                        {
                            double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                            double.NaN, double.NaN, double.NaN, double.NaN, double.NaN,
                        };

                        try
                        {
                            Hess.HessInfo hessinfo = GetHessInfo();

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

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

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

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

                    {
                        double[] buff;
                        HSerialize.DeserializeText(pathcache, out buff);
                        double   corr  = buff[0];
                        double   wovlp = buff[1];
                        double[] ovlps = new double[] { buff[2], buff[3], buff[4], buff[5], buff[6]
                                                        , buff[7], buff[8], buff[9], buff[10], buff[11] };
                        if (double.IsNaN(corr))
                        {
                            HDebug.Assert(false);
                        }
                        return(new Tuple <double, double, double[]>(corr, wovlp, ovlps));
                    }
                }
        public async Task <List <Detalle> > GetCreditor(List <ResultInstruction> list)
        {
            ServiceEvento            dataEvento = new ServiceEvento(TokenSii);
            DteInfoRef               infoLastF  = null;
            List <Detalle>           detalles   = new List <Detalle>();
            Dictionary <string, int> dic        = Properties.Settings.Default.DicReem;
            int   c = 0;
            float porcent;
            List <Task <List <Detalle> > > tareas = new List <Task <List <Detalle> > >();

            tareas = list.Select(async instruction =>
            {
                try
                {
                    // GET PARTICIPANT DEBTOR
                    instruction.ParticipantDebtor = await Participant.GetParticipantByIdAsync(instruction.Debtor);
                    //REEMPLAZOS
                    if (dic.ContainsKey(instruction.ParticipantDebtor.Id.ToString()))
                    {
                        instruction.ParticipantNew = await Participant.GetParticipantByIdAsync(dic[instruction.ParticipantDebtor.Id.ToString()]);
                    }
                    // ROOT CLASS.
                    Detalle detalle = new Detalle(instruction.ParticipantDebtor.Rut, instruction.ParticipantDebtor.VerificationCode, instruction.ParticipantDebtor.BusinessName, instruction.Amount, instruction, true);
                    // GET INFO OF INVOICES.
                    List <DteInfoRef> dteInfos    = await DteInfoRef.GetInfoRefAsync(instruction, Conn, "F");
                    List <DteInfoRef> dteInfoRefs = new List <DteInfoRef>();
                    if (dteInfos != null)
                    {
                        foreach (DteInfoRef item in dteInfos)
                        {
                            if (string.Compare(item.Glosa, instruction.PaymentMatrix.NaturalKey, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                dteInfoRefs.Add(item);
                            }
                        }
                        // ATTACH FILES.
                        detalle.DteInfoRefs = dteInfoRefs;
                        // ATTACH PRINCIPAL DOC.
                        if (detalle.DteInfoRefs.Count >= 1)
                        {
                            infoLastF = detalle.DteInfoRefs.First(); // SHOW THE LAST DOC.
                            if (dteInfoRefs.First().DteFiles != null)
                            {
                                switch (detalle.DteInfoRefs.First().DteFiles.Count)
                                {
                                case 1:
                                    if (infoLastF.DteFiles[0].TipoXML == null)
                                    {
                                        detalle.DTEDef  = HSerialize.DTE_To_Object(infoLastF.DteFiles[0].Archivo);
                                        detalle.DTEFile = infoLastF.DteFiles[0].Archivo;
                                    }
                                    break;

                                default:
                                    {
                                        detalle.DTEDef  = HSerialize.DTE_To_Object(infoLastF.DteFiles.FirstOrDefault(x => x.TipoXML == "D").Archivo);
                                        detalle.DTEFile = infoLastF.DteFiles.FirstOrDefault(x => x.TipoXML == "D").Archivo;
                                        break;
                                    }
                                }
                            }
                            detalle.DteInfoRefLast = infoLastF;
                            detalle.NroInt         = infoLastF.NroInt;
                            detalle.FechaEmision   = infoLastF.Fecha.ToString();
                            detalle.Folio          = infoLastF.Folio;
                            detalle.MntNeto        = infoLastF.NetoAfecto;
                            detalle.MntIva         = infoLastF.IVA;
                            detalle.MntTotal       = infoLastF.Total;
                            // GET INFO FROM SII
                            if (infoLastF.EnviadoSII == 1 && infoLastF.AceptadoCliente == 0) // 1 Enviado / 0 No enviado
                            {
                                detalle.FechaRecepcion = infoLastF.FechaEnvioSII.ToString("dd-MM-yyyy");
                                // EVENTS FROM SII
                                DataEvento evento = await dataEvento.GetStatusDteAsync("Creditor", TokenSii, "33", detalle, UserParticipant);
                                if (evento != null)
                                {
                                    detalle.DataEvento    = evento;
                                    detalle.StatusDetalle = GetStatus(detalle);
                                }
                            }
                            if (detalle.StatusDetalle == StatusDetalle.Pending && infoLastF.AceptadoCliente == 1)
                            {
                                detalle.FechaRecepcion = infoLastF.FechaEnvioSII.ToString("dd-MM-yyyy");
                                detalle.StatusDetalle  = StatusDetalle.Accepted;
                            }
                            else if (detalle.StatusDetalle == StatusDetalle.Accepted && infoLastF.AceptadoCliente == 0)
                            {
                                DteFiles.UpdateFiles(Conn, detalle); // UPDATE DTE_DocCab SET infoLastF.EnviadoCliente = 1
                            }
                        }
                        // SEND DTE TO CEN.
                        if (detalle.StatusDetalle == StatusDetalle.Accepted && detalle.Instruction != null && detalle.Instruction.StatusBilled == Instruction.StatusBilled.NoFacturado)
                        {
                            ResultDte resultDte = await Dte.SendDteCreditorAsync(detalle, TokenCen, detalle.DTEFile);
                            if (resultDte != null)
                            {
                                detalle.Instruction.Dte          = resultDte;
                                detalle.Instruction.StatusBilled = Instruction.StatusBilled.Facturado;
                            }
                        }
                        detalle.ValidatorFlag = new HFlagValidator(detalle, true);
                    }
                    else
                    {
                        detalle.ValidatorFlag = new HFlagValidator()
                        {
                            Flag = LetterFlag.Clear
                        };
                    }
                    detalles.Add(detalle);
                    c++;
                    porcent = (float)(100 * c) / list.Count;
                    await ReportProgress(porcent, $"Processing 'Pay Instructions' {instruction.Id}-{instruction.PaymentMatrix.PublishDate.ToString("dd-MM-yyyy")}, wait please.  ({c}/{list.Count})");
                    return(detalles);
                }
                catch (Exception)
                {
                    return(null);

                    throw;
                }
            }).ToList();
            await Task.WhenAll(tareas);

            return(detalles.OrderBy(x => x.Instruction.Id).ToList());
        }
        public async Task <List <Detalle> > GetDebtor(List <Detalle> detalles, string p)
        {
            int            c                      = 0;
            ServiceEvento  dataEvento             = new ServiceEvento(TokenSii);
            List <Detalle> detallesFinal          = new List <Detalle>();
            List <Task <List <Detalle> > > tareas = new List <Task <List <Detalle> > >();

            tareas = detalles.Select(async item =>
            {
                DTEDefType xmlObjeto = null;
                string nameFile      = null;
                // GET XML FILE

                nameFile = p + $"\\{UserParticipant.Rut}-{UserParticipant.VerificationCode}\\{item.RutReceptor}-{item.DvReceptor}__{item.Tipo}__{item.Folio}.xml";

                if (File.Exists(nameFile))
                {
                    xmlObjeto = HSerialize.DTE_To_Object(nameFile);
                }
                // GET PARTICPANT INFO FROM CEN
                ResultParticipant participant = await Participant.GetParticipantByRutAsync(item.RutReceptor.ToString());
                if (participant != null && participant.Id > 0)
                {
                    item.IsParticipant     = true;
                    item.ParticipantMising = participant;
                }
                if (xmlObjeto != null)
                {
                    item.DTEDef = xmlObjeto;
                    if (item.IsParticipant)
                    {
                        // GET REFERENCE SEN.
                        DTEDefTypeDocumentoReferencia r = null;
                        GetReferenceCen doc             = new GetReferenceCen(item);
                        if (doc != null)
                        {
                            r = doc.DocumentoReferencia;
                        }
                        if (r != null && r.RazonRef != null)
                        {
                            // GET WINDOW.
                            ResultBillingWindow window = await BillingWindow.GetBillingWindowByNaturalKeyAsync(r);
                            // GET MATRIX.
                            if (window != null && window.Id > 0)
                            {
                                List <ResultPaymentMatrix> matrices = await PaymentMatrix.GetPaymentMatrixByBillingWindowIdAsync(window);
                                if (matrices != null && matrices.Count > 0)
                                {
                                    ResultPaymentMatrix matrix = matrices.FirstOrDefault(x => x.NaturalKey.Equals(r.RazonRef.Trim(), StringComparison.OrdinalIgnoreCase));
                                    if (matrix != null)
                                    {
                                        ResultInstruction instruction = await Instruction.GetInstructionDebtorAsync(matrix, participant, UserParticipant);
                                        if (instruction != null && instruction.Id > 0)
                                        {
                                            item.Instruction = instruction;
                                            item.Instruction.ParticipantCreditor = participant;
                                            item.Instruction.ParticipantDebtor   = UserParticipant;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // FLAGS IF EXISTS XML FILE
                item.ValidatorFlag = new HFlagValidator(item, false);
                // EVENTS FROM SII
                item.DataEvento = await dataEvento.GetStatusDteAsync2("Debtor", TokenSii, "33", item, UserParticipant);
                // STATUS DOC
                if (item.DataEvento != null)
                {
                    item.StatusDetalle = GetStatus(item);
                }
                // INSERT IN CEN
                if (item.StatusDetalle == StatusDetalle.Accepted && item.Instruction != null)
                {
                    // 1 No Facturado y cuando hay más de 1 dte informado 2 Facturado 3 Facturado
                    // con retraso Existe el DTE?
                    ResultDte doc = await Dte.GetDteAsync(item, false);
                    if (doc == null)
                    {
                        // Enviar el DTE
                        ResultDte resultDte = await Dte.SendDteDebtorAsync(item, TokenCen);
                        if (resultDte != null && resultDte.Folio > 0)
                        {
                            item.Instruction.Dte = resultDte;
                        }
                    }
                    else
                    {
                        item.Instruction.Dte = doc;
                    }
                }
                detallesFinal.Add(item);
                c++;
                float porcent = (float)(100 * c) / detalles.Count;
                await ReportProgress(porcent, $"Processing 'Pay Instructions' {item.Folio}, wait please.  ({c}/{detalles.Count})");
                return(detalles);
            }).ToList();
            await Task.WhenAll(tareas);

            return(detalles.OrderBy(x => x.FechaRecepcion).ToList());
        }
 public void LoadCoords(string path)
 {
     Vector[] coords;
     HSerialize.Deserialize(path, null, out coords);
     SetCoords(coords);
 }
 public void SaveCoords(string path, Vector[] coords)
 {
     HSerialize.Serialize(path, null, coords);
 }