private Image <Bgr, byte> FillGraphImage(Size imgSize) { string curDirPath = Directory.GetCurrentDirectory() + "\\logs\\"; DirectoryInfo dirInfo = new DirectoryInfo(curDirPath); List <Dictionary <string, object> > lReadData = new List <Dictionary <string, object> >(); if (defaultGraphsTimeSpan) { graphsTimeSpan = new Tuple <DateTime, DateTime>(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow); } GraphVariablesTypes currVarType = GraphVariablesTypes.none; if (rbtnPressureGraph.Checked) { currVarType = GraphVariablesTypes.Pressure; } if (rbtnAirTempGraph.Checked) { currVarType = GraphVariablesTypes.AirTemp; } if (rbtnWaterTempGraph.Checked) { currVarType = GraphVariablesTypes.WaterTemp; } if (rbtnWindSpeedGraph.Checked) { currVarType = GraphVariablesTypes.WindSpeed; } if ((fRenderer == null) || (!prevGraphsTimeSpan.Equals(graphsTimeSpan) || currVarType != prevGraphVariable)) { fRenderer = new MultipleScatterAndFunctionsRepresentation(imgSize); switch (currVarType) { case GraphVariablesTypes.Pressure: { currValueColor = new Bgr(Color.Blue); break; } case GraphVariablesTypes.AirTemp: { currValueColor = new Bgr(Color.Red); break; } case GraphVariablesTypes.WaterTemp: { currValueColor = new Bgr(Color.RoyalBlue); break; } case GraphVariablesTypes.WindSpeed: { currValueColor = new Bgr(Color.Gray); break; } default: { currValueColor = new Bgr(Color.Blue); break; } } } else if (fRenderer != null) { if (fRenderer.TheImage.Size != imgSize) { fRenderer.ResizeCanvas(imgSize); } } if (!prevGraphsTimeSpan.Equals(graphsTimeSpan)) { IEnumerable <string> ncFileNames = Directory.EnumerateFiles(curDirPath, "IoffeVesselInfoStream-MeteoDataLog-*.nc", SearchOption.TopDirectoryOnly); foreach (string ncFileName in ncFileNames) { Tuple <DateTime, DateTime> currFileDateTimeRange = null; try { currFileDateTimeRange = ServiceTools.GetNetCDFfileTimeStampsRange(ncFileName); } catch (Exception ex) { #region report #if DEBUG ServiceTools.ExecMethodInSeparateThread(this, () => { theLogWindow = ServiceTools.LogAText(theLogWindow, "an exception has been thrown during file reading: " + Environment.NewLine + ncFileName + Environment.NewLine + "message: " + ex.Message + Environment.NewLine + ServiceTools.CurrentCodeLineDescription()); }); #else ServiceTools.ExecMethodInSeparateThread(this, () => { ServiceTools.logToTextFile(errorLogFilename, "an exception has been thrown during file reading: " + Environment.NewLine + ncFileName + Environment.NewLine + "message: " + ex.Message + Environment.NewLine + ServiceTools.CurrentCodeLineDescription(), true, true); }); #endif #endregion report } if (currFileDateTimeRange == null) { continue; } if ((currFileDateTimeRange.Item1 >= graphsTimeSpan.Item1) && (currFileDateTimeRange.Item1 <= graphsTimeSpan.Item2) || (currFileDateTimeRange.Item2 >= graphsTimeSpan.Item1) && (currFileDateTimeRange.Item2 <= graphsTimeSpan.Item2)) { Dictionary <string, object> dictFileData = null; try { dictFileData = NetCDFoperations.ReadDataFromFile(ncFileName); } catch (Exception ex) { #region report #if DEBUG ServiceTools.ExecMethodInSeparateThread(this, () => { theLogWindow = ServiceTools.LogAText(theLogWindow, "an exception has been thrown during file reading: " + Environment.NewLine + ncFileName + Environment.NewLine + "message: " + ex.Message + Environment.NewLine + ServiceTools.CurrentCodeLineDescription()); }); #else ServiceTools.ExecMethodInSeparateThread(this, () => { ServiceTools.logToTextFile(errorLogFilename, "an exception has been thrown during file reading: " + Environment.NewLine + ncFileName + Environment.NewLine + "message: " + ex.Message + Environment.NewLine + ServiceTools.CurrentCodeLineDescription(), true, true); }); #endif #endregion report } if (dictFileData != null) { lReadData.Add(dictFileData); } } } foreach (Dictionary <string, object> currFileDataDict in lReadData) { if (currFileDataDict == null) { continue; } string varNameDateTime = "DateTime"; List <long> currFileDateTimeLongTicksList = new List <long>((currFileDataDict[varNameDateTime] as long[])); List <DateTime> currFileDateTimeList = currFileDateTimeLongTicksList.ConvertAll(longVal => new DateTime(longVal)); string varNameMeteoData = "MeteoData"; List <MeteoData> currFileMeteoDataList = MeteoData.OfDenseMatrix(currFileDataDict[varNameMeteoData] as DenseMatrix); if (tsMeteoDataForGraphs == null) { try { tsMeteoDataForGraphs = new TimeSeries <MeteoData>(currFileMeteoDataList, currFileDateTimeList, true); } catch (Exception ex) { #region report #if DEBUG ServiceTools.ExecMethodInSeparateThread(this, () => { theLogWindow = ServiceTools.LogAText(theLogWindow, "couldn`t create timeseries: exception has been thrown" + Environment.NewLine + ServiceTools.CurrentCodeLineDescription() + Environment.NewLine + "message: " + ex.Message); }); #else ServiceTools.ExecMethodInSeparateThread(this, () => { ServiceTools.logToTextFile(errorLogFilename, "couldn`t create timeseries: exception has been thrown" + Environment.NewLine + ServiceTools.CurrentCodeLineDescription() + Environment.NewLine + "message: " + ex.Message, true, true); }); #endif #endregion report } } else { try { tsMeteoDataForGraphs.AddSubseriaData(currFileMeteoDataList, currFileDateTimeList, true); } catch (Exception ex) { #region report #if DEBUG ServiceTools.ExecMethodInSeparateThread(this, () => { theLogWindow = ServiceTools.LogAText(theLogWindow, "couldn`t create timeseries: exception has been thrown" + Environment.NewLine + ServiceTools.CurrentCodeLineDescription() + Environment.NewLine + "message: " + ex.Message); }); #else ServiceTools.ExecMethodInSeparateThread(this, () => { ServiceTools.logToTextFile(errorLogFilename, "couldn`t create timeseries: exception has been thrown" + Environment.NewLine + ServiceTools.CurrentCodeLineDescription() + Environment.NewLine + "message: " + ex.Message, true, true); }); #endif #endregion report } } } if (tsMeteoDataForGraphs == null) { return(null); } tsMeteoDataForGraphs.SortByTimeStamps(); tsMeteoDataForGraphs.RemoveDuplicatedTimeStamps(); DateTime utcNow = DateTime.UtcNow; if (defaultGraphsTimeSpan) { tsMeteoDataForGraphs.RemoveValues(dt => (utcNow - dt).TotalSeconds > 86400); } else { tsMeteoDataForGraphs.RemoveValues( dt => !((dt >= graphsTimeSpan.Item1) && (dt <= graphsTimeSpan.Item2))); } List <TimeSeries <MeteoData> > subSeriesBy1Minute = tsMeteoDataForGraphs.SplitByTimeSpan(new TimeSpan(0, 1, 0)); List <double> lSubSeriesEntriesCount = subSeriesBy1Minute.ConvertAll(subs => (double)subs.Count); DescriptiveStatistics statsCounts = new DescriptiveStatistics(lSubSeriesEntriesCount); aveMinuteEntriesCount = Convert.ToInt32(statsCounts.Mean); // = tsMeteoData.TimeStamps.ConvertAll(dt => (dt - maxDateTime).TotalSeconds); } List <MeteoData> meteoDataList = tsMeteoDataForGraphs.DataValues; DateTime maxDateTime = tsMeteoDataForGraphs.TimeStamps.Max(); if ((currVarType != prevGraphVariable) || !prevGraphsTimeSpan.Equals(graphsTimeSpan)) { double minVarValue = 0.0d; double maxVarValue = 1.0d; List <double> currVarToShowValues = new List <double>(); switch (currVarType) { case GraphVariablesTypes.Pressure: { currVarToShowValues = meteoDataList.ConvertAll(mdt => mdt.pressure); TimeSeries <double> currVarTS = new TimeSeries <double>(currVarToShowValues, tsMeteoDataForGraphs.TimeStamps); currVarTS.RemoveValues(dVal => dVal <= 900.0d); currVarToShowValues = new List <double>(currVarTS.DataValues); currFileSecondsList = currVarTS.TimeStamps.ConvertAll(dt => (dt - maxDateTime).TotalSeconds); fRenderer.yAxisValuesConversionToRepresentTicksValues = new Func <double, string>(dVal => dVal.ToString("F1")); break; } case GraphVariablesTypes.AirTemp: { currVarToShowValues = meteoDataList.ConvertAll(mdt => mdt.airTemperature); TimeSeries <double> currVarTS = new TimeSeries <double>(currVarToShowValues, tsMeteoDataForGraphs.TimeStamps); currVarTS.RemoveValues(dVal => ((dVal < -20.0d) || (dVal > 50.0d))); currVarToShowValues = new List <double>(currVarTS.DataValues); currFileSecondsList = currVarTS.TimeStamps.ConvertAll(dt => (dt - maxDateTime).TotalSeconds); fRenderer.yAxisValuesConversionToRepresentTicksValues = new Func <double, string>(dVal => dVal.ToString("F2")); break; } case GraphVariablesTypes.WaterTemp: { currVarToShowValues = meteoDataList.ConvertAll(mdt => mdt.waterTemperature); TimeSeries <double> currVarTS = new TimeSeries <double>(currVarToShowValues, tsMeteoDataForGraphs.TimeStamps); currVarTS.RemoveValues(dVal => ((dVal < -20.0d) || (dVal > 50.0d))); currVarToShowValues = new List <double>(currVarTS.DataValues); currFileSecondsList = currVarTS.TimeStamps.ConvertAll(dt => (dt - maxDateTime).TotalSeconds); fRenderer.yAxisValuesConversionToRepresentTicksValues = new Func <double, string>(dVal => dVal.ToString("F2")); break; } case GraphVariablesTypes.WindSpeed: { currVarToShowValues = meteoDataList.ConvertAll(mdt => mdt.windSpeed); TimeSeries <double> currVarTS = new TimeSeries <double>(currVarToShowValues, tsMeteoDataForGraphs.TimeStamps); currVarTS.RemoveValues(dVal => ((dVal < 0.0d) || (dVal > 50.0d))); currVarToShowValues = new List <double>(currVarTS.DataValues); currFileSecondsList = currVarTS.TimeStamps.ConvertAll(dt => (dt - maxDateTime).TotalSeconds); fRenderer.yAxisValuesConversionToRepresentTicksValues = new Func <double, string>(dVal => dVal.ToString("F1")); break; } default: return(null); } dvVarValues = DenseVector.OfEnumerable(currVarToShowValues); dvVarValues = dvVarValues.Conv(Extensions.StandardConvolutionKernels.gauss, aveMinuteEntriesCount * 10); } fRenderer.dvScatterFuncValues.Add(dvVarValues); fRenderer.dvScatterXSpace.Add(DenseVector.OfEnumerable(currFileSecondsList)); fRenderer.xAxisValuesConversionToRepresentTicksValues = (dValSec) => { DateTime currDT = tsMeteoDataForGraphs.TimeStamps.Max().AddSeconds(dValSec); return(currDT.ToString("yyyy-MM-dd" + Environment.NewLine + "HH:mm")); }; fRenderer.scatterLineColors.Add(currValueColor); fRenderer.scatterDrawingVariants.Add(SequencesDrawingVariants.polyline); fRenderer.xSpaceMin = currFileSecondsList.Min(); fRenderer.xSpaceMax = currFileSecondsList.Max(); fRenderer.overallFuncMin = dvVarValues.Min(); fRenderer.overallFuncMax = dvVarValues.Max(); fRenderer.fixSpecifiedMargins = true; fRenderer.Represent(); Image <Bgr, byte> retImg = fRenderer.TheImage; // расположим надпись string strSign = "current value: " + dvVarValues.Last().ToString("F2"); List <TextBarImage> textBarsCases = new List <TextBarImage>(); TextBarImage tbimTopLeftSign = new TextBarImage(strSign, retImg); tbimTopLeftSign.PtSurroundingBarStart = new Point(fRenderer.LeftServiceSpaceGapX + tbimTopLeftSign.textHalfHeight, fRenderer.TopServiceSpaceGapY + tbimTopLeftSign.textHalfHeight); textBarsCases.Add(tbimTopLeftSign); TextBarImage tbimBtmLeftSign = new TextBarImage(strSign, retImg); tbimBtmLeftSign.PtSurroundingBarStart = new Point(fRenderer.LeftServiceSpaceGapX + tbimBtmLeftSign.textHalfHeight, retImg.Height - fRenderer.BtmServiceSpaceGapY - tbimBtmLeftSign.textHalfHeight - tbimBtmLeftSign.textHeight * 2); textBarsCases.Add(tbimBtmLeftSign); TextBarImage tbimTopRightSign = new TextBarImage(strSign, retImg); tbimTopRightSign.PtSurroundingBarStart = new Point( retImg.Width - fRenderer.RightServiceSpaceGapX - tbimTopRightSign.textHalfHeight - tbimTopRightSign.textBarSize.Width, fRenderer.TopServiceSpaceGapY + tbimTopLeftSign.textHalfHeight); textBarsCases.Add(tbimTopRightSign); TextBarImage tbimBtmRightSign = new TextBarImage(strSign, retImg); tbimBtmRightSign.PtSurroundingBarStart = new Point( retImg.Width - fRenderer.RightServiceSpaceGapX - tbimBtmRightSign.textHalfHeight - tbimBtmRightSign.textBarSize.Width, retImg.Height - fRenderer.BtmServiceSpaceGapY - tbimBtmRightSign.textHalfHeight - tbimBtmRightSign.textHeight * 2); textBarsCases.Add(tbimBtmRightSign); textBarsCases.Sort((case1, case2) => (case1.SubImageInTextRect.CountNonzero().Sum() > case2.SubImageInTextRect.CountNonzero().Sum()) ? 1 : -1); MCvFont theFont = new MCvFont(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_PLAIN, 2.0d, 2.0d) { thickness = 2, }; // retImg.Draw(strSign, textBarsCases[0].ptTextBaselineStart, Emgu.CV.CvEnum.FontFace.HersheyPlain, 2.0d, new Bgr(Color.Green), 2); retImg.Draw(strSign, ref theFont, textBarsCases[0].ptTextBaselineStart, new Bgr(Color.Green)); retImg.Draw(textBarsCases[0].rectSurroundingBar, new Bgr(Color.Green), 2); prevGraphsTimeSpan = graphsTimeSpan; prevGraphVariable = currVarType; return(retImg); }
private void Represent() { Dictionary <string, object> dictDataToShow = NetCDFoperations.ReadDataFromFile(strLogFilename); long[] arrDateTimeTicksValues = new long[] { 0 }; if (dictDataToShow.Keys.Contains("DateTime")) { arrDateTimeTicksValues = (long[])(dictDataToShow["DateTime"]); } else if (dictDataToShow.Keys.Contains("Datetime")) { arrDateTimeTicksValues = (long[])(dictDataToShow["Datetime"]); } else { MessageBox.Show("Couldn`t acces the DateTime field of the file " + strLogFilename, "", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } DenseVector dvSecondsVector = DenseVector.Create(arrDateTimeTicksValues.Length, i => { DateTime dateTime1 = new DateTime(arrDateTimeTicksValues[i]); TimeSpan dt = dateTime1 - dateTime1.Date; return(dt.TotalSeconds); }); dmAccData = (DenseMatrix)dictDataToShow["AccelerometerData"]; if (sensorsHistoryRepresentingScale < 86400) { double lastDateTimeSecondsValue = dvSecondsVector[dvSecondsVector.Count - 1]; int searchingIndex = dvSecondsVector.Count - 1; for (int idx = dvSecondsVector.Count - 1; idx >= 0; idx--) { if (lastDateTimeSecondsValue - dvSecondsVector[idx] >= sensorsHistoryRepresentingScale) { searchingIndex = idx; break; } } dvSecondsVector = (DenseVector)dvSecondsVector.SubVector(searchingIndex, dvSecondsVector.Count - searchingIndex); dmAccData = (DenseMatrix)dmAccData.SubMatrix(searchingIndex, dvSecondsVector.Count, 0, dmAccData.ColumnCount); } #region filter input data noise List <DenseVector> dmAccDataFiltered = new List <DenseVector>(); Dictionary <string, DenseVector> dictCurrColumnFilteredData = new Dictionary <string, DenseVector>(); for (int col = 0; col < dmAccData.ColumnCount; col++) { DenseVector dvVectToFilter = (DenseVector)dmAccData.Column(col); dictCurrColumnFilteredData = DataAnalysis.SavGolFilter(dvVectToFilter, dvSecondsVector, 6, 6, 0, 6); dmAccDataFiltered.Add(dictCurrColumnFilteredData["values"]); //dmAccData.SetColumn(col, dictCurrColumnFilteredData["values"]); //dvSecondsVector = dictCurrColumnFilteredData["time"]; } dvSecondsVector = dictCurrColumnFilteredData["time"]; dmAccData = (DenseMatrix)DenseMatrix.OfColumns(dvSecondsVector.Count, dmAccData.ColumnCount, dmAccDataFiltered); #endregion filter input data noise // надо рассчитать углы отклонения отдельно - по сглаженным данным и по данным гироскопа DenseVector dvDataToShowDevAngleValue = (DenseVector)dmAccData.Column(6); if (cbFilterData.Checked) { List <double> ac = new List <double>(); } if (accDeviationAngleRenderer == null) { accDeviationAngleRenderer = new MultipleScatterAndFunctionsRepresentation(pbRepresentingDevAngle.Size); accDeviationAngleRenderer.dvScatterXSpace.Add(dvSecondsVector); accDeviationAngleRenderer.dvScatterFuncValues.Add(dvDataToShowDevAngleValue); accDeviationAngleRenderer.scatterLineColors.Add(new Bgr(Color.Blue)); accDeviationAngleRenderer.scatterDrawingVariants.Add(SequencesDrawingVariants.polyline); } else { if (accDeviationAngleRenderer.xSpaceMin != dvSecondsVector.Max() - sensorsHistoryRepresentingScale) { accDeviationAngleRenderer.xSpaceMin = dvSecondsVector.Max() - sensorsHistoryRepresentingScale; accDeviationAngleRenderer.dvScatterXSpace.Clear(); accDeviationAngleRenderer.dvScatterFuncValues.Clear(); accDeviationAngleRenderer.scatterLineColors.Clear(); accDeviationAngleRenderer.scatterDrawingVariants.Clear(); accDeviationAngleRenderer.dvScatterXSpace.Add(dvSecondsVector); accDeviationAngleRenderer.dvScatterFuncValues.Add(dvDataToShowDevAngleValue); accDeviationAngleRenderer.scatterLineColors.Add(new Bgr(Color.Blue)); accDeviationAngleRenderer.scatterDrawingVariants.Add(SequencesDrawingVariants.polyline); } } accDeviationAngleRenderer.xSpaceMin = dvSecondsVector.Max() - sensorsHistoryRepresentingScale; accDeviationAngleRenderer.Represent(); ThreadSafeOperations.UpdatePictureBox(pbRepresentingDevAngle, accDeviationAngleRenderer.TheImage.Bitmap); DenseVector dvDataToShowAccMagnitudeDev = DenseVector.Create(dmAccData.RowCount, i => { AccelerometerData currAccData = new AccelerometerData(dmAccData[i, 0], dmAccData[i, 1], dmAccData[i, 2]); AccelerometerData calibrationAccData = new AccelerometerData(dmAccData[i, 3], dmAccData[i, 4], dmAccData[i, 5]); return(currAccData.AccMagnitude - calibrationAccData.AccMagnitude); }); if (accDeviationMagnitudeRenderer == null) { accDeviationMagnitudeRenderer = new MultipleScatterAndFunctionsRepresentation(pbRepresentingDevMagnitude.Size); accDeviationMagnitudeRenderer.dvScatterXSpace.Add(dvSecondsVector); accDeviationMagnitudeRenderer.dvScatterFuncValues.Add(dvDataToShowAccMagnitudeDev); accDeviationMagnitudeRenderer.scatterLineColors.Add(new Bgr(Color.Blue)); accDeviationMagnitudeRenderer.scatterDrawingVariants.Add(SequencesDrawingVariants.polyline); } else { if (accDeviationMagnitudeRenderer.xSpaceMin != dvSecondsVector.Max() - sensorsHistoryRepresentingScale) { accDeviationMagnitudeRenderer.xSpaceMin = dvSecondsVector.Max() - sensorsHistoryRepresentingScale; accDeviationMagnitudeRenderer.dvScatterXSpace.Clear(); accDeviationMagnitudeRenderer.dvScatterFuncValues.Clear(); accDeviationMagnitudeRenderer.scatterLineColors.Clear(); accDeviationMagnitudeRenderer.scatterDrawingVariants.Clear(); accDeviationMagnitudeRenderer.dvScatterXSpace.Add(dvSecondsVector); accDeviationMagnitudeRenderer.dvScatterFuncValues.Add(dvDataToShowAccMagnitudeDev); accDeviationMagnitudeRenderer.scatterLineColors.Add(new Bgr(Color.Blue)); accDeviationMagnitudeRenderer.scatterDrawingVariants.Add(SequencesDrawingVariants.polyline); } } accDeviationMagnitudeRenderer.xSpaceMin = dvSecondsVector.Max() - sensorsHistoryRepresentingScale; accDeviationMagnitudeRenderer.Represent(); ThreadSafeOperations.UpdatePictureBox(pbRepresentingDevMagnitude, accDeviationMagnitudeRenderer.TheImage.Bitmap); AccelerometerData accCalibratedData = new AccelerometerData(dmAccData[0, 3], dmAccData[0, 4], dmAccData[0, 5]); double phiAngle = Math.Asin(accCalibratedData.xyProjectionMagnitude() / accCalibratedData.AccMagnitude); double tmpL = accCalibratedData.AccMagnitude * Math.Sin(phiAngle) * Math.Cos(phiAngle); double tmpLz = tmpL * Math.Sin(phiAngle); double tmpLx = tmpL * Math.Cos(phiAngle) * Math.Sqrt(1 + accCalibratedData.AccY * accCalibratedData.AccY / (accCalibratedData.AccX * accCalibratedData.AccX)); double tmpLy = tmpLx * accCalibratedData.AccY / accCalibratedData.AccX; AccelerometerData unitaryAccVectorZeroAngle = new AccelerometerData(tmpLx, tmpLy, tmpLz); unitaryAccVectorZeroAngle = unitaryAccVectorZeroAngle / unitaryAccVectorZeroAngle.AccMagnitude; AccelerometerData unitaryAccVectorCalibratedAcceleration = accCalibratedData / (accCalibratedData.AccMagnitude); DenseVector dvDataToShowAccDevDirection = DenseVector.Create(dmAccData.RowCount, i => { AccelerometerData currAccData = new AccelerometerData(dmAccData[i, 0], dmAccData[i, 1], dmAccData[i, 2]); AccelerometerData currAccDataProjectionPerpendicularToCalibratedAcc = currAccData - unitaryAccVectorCalibratedAcceleration * (currAccData * accCalibratedData / accCalibratedData.AccMagnitude); double retAngle = Math.Acos(currAccDataProjectionPerpendicularToCalibratedAcc * unitaryAccVectorZeroAngle / currAccDataProjectionPerpendicularToCalibratedAcc.AccMagnitude); AccelerometerData vectProduct = unitaryAccVectorZeroAngle ^ currAccDataProjectionPerpendicularToCalibratedAcc; if (vectProduct * unitaryAccVectorCalibratedAcceleration > 0) { //значит угол лежит в пределах от 0 до PI - ничего не делаем retAngle = retAngle + 0.0d; } else { //векторное произведение противоположно по направлению g0 - значит, угол лежит в диапазоне от Pi до 2Pi или от -PI до PI retAngle = -retAngle; } return(retAngle); }); if (accDeviationDirectionRenderer == null) { accDeviationDirectionRenderer = new MultipleScatterAndFunctionsRepresentation(pbRepresentingDevDirection.Size); accDeviationDirectionRenderer.dvScatterXSpace.Add(dvSecondsVector); accDeviationDirectionRenderer.dvScatterFuncValues.Add(dvDataToShowAccDevDirection); accDeviationDirectionRenderer.scatterLineColors.Add(new Bgr(Color.Blue)); accDeviationDirectionRenderer.scatterDrawingVariants.Add(SequencesDrawingVariants.polyline); } else { if (accDeviationDirectionRenderer.xSpaceMin != dvSecondsVector.Max() - sensorsHistoryRepresentingScale) { accDeviationDirectionRenderer.xSpaceMin = dvSecondsVector.Max() - sensorsHistoryRepresentingScale; accDeviationDirectionRenderer.dvScatterXSpace.Clear(); accDeviationDirectionRenderer.dvScatterFuncValues.Clear(); accDeviationDirectionRenderer.scatterLineColors.Clear(); accDeviationDirectionRenderer.scatterDrawingVariants.Clear(); accDeviationDirectionRenderer.dvScatterXSpace.Add(dvSecondsVector); accDeviationDirectionRenderer.dvScatterFuncValues.Add(dvDataToShowAccDevDirection); accDeviationDirectionRenderer.scatterLineColors.Add(new Bgr(Color.Blue)); accDeviationDirectionRenderer.scatterDrawingVariants.Add(SequencesDrawingVariants.polyline); } } accDeviationDirectionRenderer.xSpaceMin = dvSecondsVector.Max() - sensorsHistoryRepresentingScale; accDeviationDirectionRenderer.Represent(); ThreadSafeOperations.UpdatePictureBox(pbRepresentingDevDirection, accDeviationDirectionRenderer.TheImage.Bitmap); }
private void btnProcessAccelerationTimeSeries_Click(object sender, EventArgs e) { if ((bgwCalculate != null) && (bgwCalculate.IsBusy)) { bgwCalculate.CancelAsync(); return; } //simpleMultipleImagesShow imagesRepresentingForm = new simpleMultipleImagesShow(); //imagesRepresentingForm.Show(); DoWorkEventHandler bgwCalculate_DoWorkHandler = delegate(object currBGWsender, DoWorkEventArgs args) { BackgroundWorker selfWorker = currBGWsender as BackgroundWorker; //simpleMultipleImagesShow multImagesRepresentingForm = (simpleMultipleImagesShow)((args.Argument as object[])[0]); //Type theShowImagesType = multImagesRepresentingForm.GetType(); //MethodInfo thePicturePlacingMethodInfo = theShowImagesType.GetMethod("PlaceAPicture"); int imageRepresentingCounter = 0; DateTime dbgDT = new DateTime(2014, 7, 9, 9, 0, 0); dbgDT = dbgDT.AddMinutes(33); DateTime dtSeriesStart = accSubseries[0].StartTime; double tsOverallSeriesDurationMillisec = (accSubseries[accSubseries.Count - 1].EndTime - accSubseries[0].StartTime).TotalMilliseconds; string strToWrite = " fileName ; lat ; lon ; date ; time ; time(s) since start ; period(s) ; spectrum amplitude"; ServiceTools.logToTextFile(strOutputDirectory + "\\100sData-spectra-maximums.dat", strToWrite + Environment.NewLine, true); foreach (TimeSeries <double> accSubseria in accSubseries) { if (selfWorker.CancellationPending) { break; } int startindex = 0; while (true) { int endIndex; if (selfWorker.CancellationPending) { break; } TimeSeries <double> currTimeSeria = accSubseria.SubSeria(startindex, new TimeSpan(1000000000), out endIndex); //100s currTimeSeria = currTimeSeria.InterpolateSeria(new TimeSpan(500000)); currTimeSeria = currTimeSeria.ExtractDataDeviationValues(); //обработать и оценить наличие выраженных периодов Complex[] sourceSignalArray = currTimeSeria.DataRealValuesComplexArray(); Fourier.Forward(sourceSignalArray); //Transform.FourierForward(sourceSignalArray); List <Complex> FourierTransformedSignal = new List <Complex>(sourceSignalArray); List <double> FourierTransformedSignalAmplitudes = FourierTransformedSignal.ConvertAll <double>( cVal => ((double.IsNaN(cVal.Magnitude)) || (double.IsInfinity(cVal.Magnitude))) ? (0.0d) : (cVal.Magnitude)); List <double> FourierTransformedSignalPeriods = new List <double>(); for (int ind = 0; ind < FourierTransformedSignalAmplitudes.Count; ind++) { FourierTransformedSignalPeriods.Add(currTimeSeria.TotalSeriaDuration.TotalSeconds / (double)ind); } FourierTransformedSignalAmplitudes = new List <double>( FourierTransformedSignalAmplitudes.Zip <double, double, double>( FourierTransformedSignalPeriods, (amp, periodSec) => ((double.IsNaN(periodSec)) || (double.IsInfinity(periodSec))) ? (0.0d) : (amp))); FourierTransformedSignalPeriods = FourierTransformedSignalPeriods.ConvertAll <double>( dval => ((double.IsNaN(dval)) || (double.IsInfinity(dval))) ? (0.0d) : (dval)); //проанализируем этот участок - есть ли выраженные пики по амплитуде конкретных частот //найти максимум в спектре и выдать данные об этом максимуме в файл // сначала отфильтруем периоды меньше 1с - для данных по динамике судна они несущественны FourierTransformedSignalAmplitudes = new List <double>( FourierTransformedSignalAmplitudes.Zip <double, double, double>( FourierTransformedSignalPeriods, (amp, periodSec) => (periodSec <= 1.0d) ? (0.0d) : (amp))); FourierTransformedSignalPeriods = FourierTransformedSignalPeriods.ConvertAll <double>(dVal => (dVal <= 1.0d) ? (0.0d) : (dVal)); DescriptiveStatistics currAmpsStat = new DescriptiveStatistics(FourierTransformedSignalAmplitudes); List <double> lAmpsOutstanding = FourierTransformedSignalAmplitudes.ConvertAll <double>(dVal => { if (dVal / currAmpsStat.Mean >= 100.0d) { return(dVal); } return(0.0d); }); List <double> lPeriodsOutstanding = new List <double>(FourierTransformedSignalPeriods.Zip <double, double, double>(lAmpsOutstanding, (per, amp) => (amp == 0.0d) ? (0.0d) : (per))); if (lAmpsOutstanding.Sum() > 0.0d) { MultipleScatterAndFunctionsRepresentation renderer = new MultipleScatterAndFunctionsRepresentation(2048, 1536); renderer.dvScatterXSpace.Add(currTimeSeria.TimeStampsValuesSeconds); renderer.dvScatterFuncValues.Add(currTimeSeria.dvDoubleDataValues); renderer.scatterLineColors.Add(new Bgr(255, 50, 50)); renderer.scatterDrawingVariants.Add(SequencesDrawingVariants.polyline); renderer.dvScatterXSpace.Add(DenseVector.OfEnumerable(FourierTransformedSignalPeriods)); renderer.dvScatterFuncValues.Add(DenseVector.OfEnumerable(FourierTransformedSignalAmplitudes)); renderer.scatterLineColors.Add(new Bgr(50, 255, 50)); renderer.scatterDrawingVariants.Add(SequencesDrawingVariants.squares); renderer.dvScatterXSpace.Add(DenseVector.OfEnumerable(lPeriodsOutstanding)); renderer.dvScatterFuncValues.Add(DenseVector.OfEnumerable(lAmpsOutstanding)); renderer.scatterLineColors.Add(new Bgr(50, 50, 255)); renderer.scatterDrawingVariants.Add(SequencesDrawingVariants.circles); renderer.Represent(); if (strOutputDirectory != "") { double maxAmp = lAmpsOutstanding.Max(); int idx = lAmpsOutstanding.FindIndex(dval => dval == maxAmp); double maxAmpPeriod = lPeriodsOutstanding[idx]; GPSdata gpsMark = gpsSeriaData.GetMostClose(currTimeSeria.StartTime).Item2; string fName = currTimeSeria.StartTime.ToString("s").Replace(":", "-") + "-100sData-spectrum.jpg"; renderer.SaveToImage(strOutputDirectory + "\\" + fName, true); strToWrite = "" + fName + " ; "; strToWrite += gpsMark.LatDec + " ; "; strToWrite += gpsMark.LonDec + " ; "; strToWrite += currTimeSeria.StartTime.Date.ToString("yyyy-MM-dd") + " ; "; strToWrite += currTimeSeria.StartTime.ToString("HH-mm-ss") + " ; "; strToWrite += (currTimeSeria.StartTime - dtSeriesStart).TotalSeconds + " ; "; strToWrite += maxAmpPeriod.ToString() + " ; "; strToWrite += maxAmp.ToString() + " ; "; ServiceTools.logToTextFile(strOutputDirectory + "\\100sData-spectra-maximums.dat", strToWrite + Environment.NewLine, true); ThreadSafeOperations.SetText(lblStatusString, "processing: " + currTimeSeria.StartTime.ToString("s"), false); } } if ((currTimeSeria.StartTime >= dbgDT) || (currTimeSeria.EndTime >= dbgDT)) { startindex++; startindex--; } if (endIndex == accSubseria.Count - 1) { break; } Application.DoEvents(); selfWorker.ReportProgress(Convert.ToInt32(100.0d * (currTimeSeria.EndTime - dtSeriesStart).TotalMilliseconds / tsOverallSeriesDurationMillisec)); startindex += Convert.ToInt32((endIndex - startindex) / 2.0d); } } }; RunWorkerCompletedEventHandler bgwCalculate_CompletedHandler = delegate(object currBGWCompletedSender, RunWorkerCompletedEventArgs args) { ThreadSafeOperations.ToggleButtonState(btnProcessAccelerationTimeSeries, true, "Process acceleration timeseries", false); }; ProgressChangedEventHandler bgwCalculate_ProgressChanged = delegate(object bgwDataReaderSender, ProgressChangedEventArgs args) { ThreadSafeOperations.UpdateProgressBar(prbReadingProcessingData, args.ProgressPercentage); }; ThreadSafeOperations.ToggleButtonState(btnProcessAccelerationTimeSeries, true, "STOP", true); bgwCalculate = new BackgroundWorker(); bgwCalculate.WorkerSupportsCancellation = true; bgwCalculate.WorkerReportsProgress = true; bgwCalculate.DoWork += bgwCalculate_DoWorkHandler; bgwCalculate.RunWorkerCompleted += bgwCalculate_CompletedHandler; bgwCalculate.ProgressChanged += bgwCalculate_ProgressChanged; //object[] bgwCalculateArgs = new object[] { imagesRepresentingForm }; object[] bgwCalculateArgs = new object[] { }; bgwCalculate.RunWorkerAsync(bgwCalculateArgs); }