private void btnProcess_Click(object sender, EventArgs e)
        {
            string fName = richTextBox1.Text;

            if (!File.Exists(fName))
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow, "couldn`t find a file: " + fName);
                return;
            }

            try
            {
                xlApp         = new Microsoft.Office.Interop.Excel.Application();
                xlApp.Visible = true;
                wb            = xlApp.Workbooks.Open(fName, Type.Missing, false);
                ws            = wb.Sheets[1];
            }
            catch (Exception)
            {
                CloseAll();
            }


            List <Tuple <int, SunElevationTestDataRecord> > lRecords = new List <Tuple <int, SunElevationTestDataRecord> >();
            int    rowIdx        = 2;
            double dDataTimeRead = 0.0d;

            while (true)
            {
                DateTime dtVal;
                SunElevationTestDataRecord currRec = new SunElevationTestDataRecord();

                System.Windows.Forms.Application.DoEvents();

                try
                {
                    Range rngDT = ws.Cells[rowIdx, 1];
                    var   dDataTimeReadValue = rngDT.Value2;
                    if (dDataTimeReadValue == null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "date-time value at row " + rowIdx + " is empty. Stopping reading.");
                        CloseAll();
                        break;
                    }
                    dDataTimeRead = (double)(dDataTimeReadValue);
                    if (dDataTimeRead == 0.0d)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "date-time value at row " + rowIdx + " is empty. Stopping reading.");
                        CloseAll();
                        break;
                    }
                }
                catch (Exception ex)
                {
                    //CloseAll();
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         ex.Message + Environment.NewLine + "for date-time value at row " + rowIdx);
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));
                    rowIdx++;
                    continue;
                }
                dtVal      = DateTime.FromOADate(dDataTimeRead);
                currRec.Dt = dtVal;



                double latVal = 0.0d;
                try
                {
                    Range rngLat    = ws.Cells[rowIdx, 2];
                    var   rngLatVal = rngLat.Value2;
                    if (rngLatVal == null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "latitude value at row " + rowIdx + " is empty");
                        //rowIdx++;
                        //continue;
                    }
                    else
                    {
                        latVal         = (double)(rngLatVal);
                        currRec.latDec = latVal;
                    }
                }
                catch (Exception ex)
                {
                    //CloseAll();
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         ex.Message + Environment.NewLine + "for latitude value at row " + rowIdx);
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));
                    rowIdx++;
                    continue;
                }



                double lonVal = 0.0d;
                try
                {
                    Range rngLon    = ws.Cells[rowIdx, 3];
                    var   rngLonVal = rngLon.Value2;
                    if (rngLonVal == null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "longitude value at row " + rowIdx + " is empty");
                        //rowIdx++;
                        //continue;
                    }
                    else
                    {
                        lonVal         = (double)(rngLonVal);
                        currRec.lonDec = lonVal;
                    }
                }
                catch (Exception ex)
                {
                    //CloseAll();
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         ex.Message + Environment.NewLine + "for longitude value at row " + rowIdx);
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));
                    rowIdx++;
                    continue;
                }



                double sunAltTestVal = 0.0d;
                try
                {
                    Range rngSunAltTest    = ws.Cells[rowIdx, 4];
                    var   rngSunAltTestVal = rngSunAltTest.Value2;
                    if (rngSunAltTestVal == null)
                    {
                        theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                             "testing sun elevation value at row " + rowIdx + " is empty");
                        //rowIdx++;
                        //continue;
                    }
                    else
                    {
                        sunAltTestVal       = (double)(rngSunAltTestVal);
                        currRec.SunElevTest = sunAltTestVal;
                    }
                }
                catch (Exception ex)
                {
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                         ex.Message + Environment.NewLine + "for read sun elevation value at row " + rowIdx);
                    theLogWindow = ServiceTools.LogAText(theLogWindow, "=====================");
                    //CloseAll();
                    lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));
                    rowIdx++;
                    continue;
                }



                ThreadSafeOperations.SetText(lblLoadingStatus, "loading " + rowIdx + " row", false);

                lRecords.Add(new Tuple <int, SunElevationTestDataRecord>(rowIdx, currRec));

                rowIdx++;
            }



            List <double> lDeviations = new List <double>();
            string        outFName    = Path.GetDirectoryName(fName) + "\\" + Path.GetFileNameWithoutExtension(fName) + "-output.txt";

            ServiceTools.logToTextFile(outFName, SunElevationTestDataRecord.TableFieldsHeader() + Environment.NewLine, true);

            foreach (Tuple <int, SunElevationTestDataRecord> tpl in lRecords)
            {
                rowIdx = tpl.Item1;
                SunElevationTestDataRecord currRec = tpl.Item2;

                if (currRec.WhetherAllValuesHasBeenRead)
                {
                    SPA spaCalc = new SPA(currRec.Dt.Year, currRec.Dt.Month, currRec.Dt.Day, currRec.Dt.Hour,
                                          currRec.Dt.Minute, currRec.Dt.Second, (float)currRec.lonDec, (float)currRec.latDec,
                                          (float)SPAConst.DeltaT(currRec.Dt));
                    int res = spaCalc.spa_calculate();
                    AzimuthZenithAngle sunPositionSPAext = new AzimuthZenithAngle(spaCalc.spa.azimuth,
                                                                                  spaCalc.spa.zenith);
                    currRec.SunElevCalc = sunPositionSPAext.ElevationAngle;

                    lDeviations.Add(currRec.SunElevCalc - currRec.SunElevTest);

                    ServiceTools.logToTextFile(outFName, currRec.ToString() + Environment.NewLine, true);
                }
                else
                {
                    ServiceTools.logToTextFile(outFName, currRec.ToString() + Environment.NewLine, true);
                }
            }


            HistogramDataAndProperties histData = new HistogramDataAndProperties(DenseVector.OfEnumerable(lDeviations), 20);
            HistogramCalcAndShowForm   histForm = new HistogramCalcAndShowForm("", defaultProperties);

            histForm.HistToRepresent = histData;
            histForm.Show();
            histForm.Represent();


            CloseAll();
        }
Пример #2
0
        // private List<bool> bgwFinished = new List<bool>();
        public void CollectPositioningData()
        {
#if DEBUG
            int concurrentFilesProcessingCount = 1;
#else
            int concurrentFilesProcessingCount = 2;
            try
            {
                concurrentFilesProcessingCount = Convert.ToInt32(defaultProperties["MaxConcurrentFilesProcessingCount"]);
            }
            catch (Exception ex)
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                     "ERROR! exception thrown: " + ex.Message + Environment.NewLine +
                                                     "MaxConcurrentFilesProcessingCount value can`t be read. " + Environment.NewLine +
                                                     "Using default value = " + concurrentFilesProcessingCount);
            }
#endif



            theLogWindow = ServiceTools.LogAText(theLogWindow, "started on " + DateTime.UtcNow.ToString("s"));


            string        strImagesDir = ParentForm.richTextBox1.Text;
            DirectoryInfo imagesDir    = new DirectoryInfo(strImagesDir);

            if (!imagesDir.Exists)
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                     "Операция не выполнена. Не найдена директория:" + Environment.NewLine + strImagesDir +
                                                     Environment.NewLine, true);
                return;
            }


            // оказалось, что маска - case-insensitive
            lImagesFileInfos = new List <FileInfo>(imagesDir.GetFiles("*.jpg", SearchOption.TopDirectoryOnly));

            List <FileInfo> lImagesFileInfoWithExistingSunDiskInfo = lImagesFileInfos.ConvertAll <FileInfo>(fInfoSrc =>
            {
                string sunDiskInfoFileName = fInfoSrc.DirectoryName + "\\" +
                                             Path.GetFileNameWithoutExtension(fInfoSrc.FullName) + "-SunDiskInfo.xml";
                if (File.Exists(sunDiskInfoFileName))
                {
                    return(fInfoSrc);
                }
                else
                {
                    return(null);
                }
            });
            lImagesFileInfoWithExistingSunDiskInfo.RemoveAll(fInfo => fInfo == null);

            theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                 "files already processed before: " + lImagesFileInfoWithExistingSunDiskInfo.Count);

            lImagesFileInfos.RemoveAll(fInfo => lImagesFileInfoWithExistingSunDiskInfo.Contains(fInfo));
            int filesCountToProcess        = lImagesFileInfos.Count;
            int filesCountAlreadyProcessed = lImagesFileInfoWithExistingSunDiskInfo.Count;

            lImagesFileInfos.AddRange(lImagesFileInfoWithExistingSunDiskInfo);



            //List<BackgroundWorker> bgwList = new List<BackgroundWorker>();
            //for (int i = 0; i < 2; i++)
            //{
            //    //bgwFinished.Add(true);
            //    //bgwList.Add(null);
            //}

            int currDataIdx = 1;

            foreach (FileInfo finfo in lImagesFileInfos)
            {
                //int currentBgwID = -1;
                while ((cbgBgwList.Count >= concurrentFilesProcessingCount) && (!hasToStopCollecting))
                {
                    Application.DoEvents();
                    Thread.Sleep(0);
                }

                //while ((bgwFinished.Sum(boolVal => (boolVal) ? ((int)0) : ((int)1)) == bgwFinished.Count) && (!hasToStopCollecting))
                //{
                //    Application.DoEvents();
                //    Thread.Sleep(0);
                //}
                if (hasToStopCollecting)
                {
                    break;
                }

                //for (int i = 0; i < concurrentFilesProcessingCount; i++)
                //{
                theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                     "" + currDataIdx + " / " + filesCountToProcess + " (+ " + filesCountAlreadyProcessed +
                                                     " processed before)");
                theLogWindow = ServiceTools.LogAText(theLogWindow, Environment.NewLine + "starting: " + finfo.Name);


                //object[] BGWorker2Args = new object[] { finfo, defaultProperties, currentBgwID };
                object[] BGWorker2Args = new object[] { finfo, defaultProperties };

                BackgroundWorker currBgw = new BackgroundWorker();
                // bgwList[currentBgwID] = currBgw;
                currBgw.DoWork             += currBgw_DoWork;
                currBgw.RunWorkerCompleted += currBgw_RunWorkerCompleted;
                currBgw.RunWorkerAsync(BGWorker2Args);

                cbgBgwList.Add(finfo.FullName);

                if (filesCountToProcess > 0)
                {
                    int progress = Convert.ToInt32(100.0d * (double)currDataIdx / (double)filesCountToProcess);
                    ThreadSafeOperations.UpdateProgressBar(ParentForm.pbUniversalProgressBar, progress);
                    Interlocked.Increment(ref currDataIdx);
                }
            }


            while (cbgBgwList.Count > 0)
            {
                Application.DoEvents();
                Thread.Sleep(0);
            }

            if (hasToStopCollecting)
            {
                return;
            }



            // сохраним на будущее
            string   strMedianPerc5StatsXMLFileName = (string)defaultProperties["DefaultMedianPerc5StatsXMLFile"];
            FileInfo MedianPerc5StatsXMLFileInfo    = new FileInfo(strMedianPerc5StatsXMLFileName);
            string   strMedianPerc5StatsXMLFilePath = MedianPerc5StatsXMLFileInfo.DirectoryName;
            strMedianPerc5StatsXMLFilePath += (strMedianPerc5StatsXMLFilePath.Last() == '\\') ? ("") : ("\\");
            string computedDeviationsXMLfilesPath = strMedianPerc5StatsXMLFilePath + "azimuth-dev-stats\\";
            if (!ServiceTools.CheckIfDirectoryExists(computedDeviationsXMLfilesPath))
            {
                theLogWindow = ServiceTools.LogAText(theLogWindow,
                                                     "couldn`t locate or create directory " + computedDeviationsXMLfilesPath);
                return;
            }

            string computedAzimuthDeviationsXMLFile = computedDeviationsXMLfilesPath + "PreComputedSunAnglesDeviationsData.xml";

            List <AngleSunDeviationCalcResult> lResList =
                new List <AngleSunDeviationCalcResult>(cbAnglesSunDeviationCalcResults);
            ServiceTools.WriteObjectToXML(lResList, computedAzimuthDeviationsXMLFile);
            ServiceTools.WriteDictionaryToXml(defaultProperties, defaultPropertiesXMLfileName, false);


            // теперь посчитаем статистику
            List <AngleSunDeviationCalcResult> azimuthResults = new List <AngleSunDeviationCalcResult>(lResList);
            List <AngleSunDeviationCalcResult> zenithResults  = new List <AngleSunDeviationCalcResult>(lResList);
            azimuthResults.RemoveAll(
                azimuthSunDeviationCalcResult =>
                ((!azimuthSunDeviationCalcResult.calculationSucceeded) ||
                 (!azimuthSunDeviationCalcResult.AzimuthDeviationCanBeComputed)));
            zenithResults.RemoveAll(
                sunDeviationCalcResult =>
                ((!sunDeviationCalcResult.calculationSucceeded) ||
                 (!sunDeviationCalcResult.ZenithDeviationCanBeComputed)));

            List <double> azimuthDevValues =
                azimuthResults.ConvertAll <double>(
                    azimuthSunDeviationCalcResult => azimuthSunDeviationCalcResult.computedAzimuthDeviationDeg);

            List <double> zenithDevValues =
                zenithResults.ConvertAll <double>(
                    azimuthSunDeviationCalcResult => azimuthSunDeviationCalcResult.computedZenithDeviationDeg);


            ServiceTools.ExecMethodInSeparateThread(ParentForm, delegate()
            {
                HistogramDataAndProperties histAzimuthData =
                    new HistogramDataAndProperties(DenseVector.OfEnumerable(azimuthDevValues), 100);
                HistogramCalcAndShowForm hAzimuthForm = new HistogramCalcAndShowForm("azimuth sun angle deviations (deg.)",
                                                                                     defaultProperties);
                hAzimuthForm.HistToRepresent = histAzimuthData;
                hAzimuthForm.Show();
                hAzimuthForm.Represent();
            });



            ServiceTools.ExecMethodInSeparateThread(ParentForm, delegate()
            {
                HistogramDataAndProperties histZenithData =
                    new HistogramDataAndProperties(DenseVector.OfEnumerable(zenithDevValues), 100);
                HistogramCalcAndShowForm hZenithForm = new HistogramCalcAndShowForm("zenith sun angle deviations (deg.)",
                                                                                    defaultProperties);
                hZenithForm.HistToRepresent = histZenithData;
                hZenithForm.Show();
                hZenithForm.Represent();
            });



            ThreadSafeOperations.UpdateProgressBar(ParentForm.pbUniversalProgressBar, 0);
        }