示例#1
0
        public void PlotMouseMove(LinearBarSeries lb, MapStatistics ms, OxyMouseEventArgs e)
        {
            if (lb.Points.Count != 0)
            {
                ms._endPoint1 = lb.InverseTransform(e.Position);
                if (ms._startPoint1.X != 0 || ms._startPoint1.Y != 0)
                {
                    ms._pm.Annotations.Clear();

                    var rectangle = new PolygonAnnotation();
                    rectangle.Layer           = AnnotationLayer.BelowAxes;
                    rectangle.StrokeThickness = 0.5;
                    rectangle.Stroke          = OxyColors.Red;
                    rectangle.Fill            = OxyColors.Transparent;
                    rectangle.LineStyle       = OxyPlot.LineStyle.Dot;

                    rectangle.Points.Add(new DataPoint(ms._startPoint1.X, ms._startPoint1.Y));
                    rectangle.Points.Add(new DataPoint(ms._endPoint1.X, ms._startPoint1.Y));
                    rectangle.Points.Add(new DataPoint(ms._endPoint1.X, ms._endPoint1.Y));
                    rectangle.Points.Add(new DataPoint(ms._startPoint1.X, ms._endPoint1.Y));

                    ms._pm.Annotations.Add(rectangle as Annotation);
                    ms._pm.InvalidatePlot(true);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Show daily visits
        /// </summary>
        /// <param name="sysName"></param>
        public void SystemTraffic()
        {
            TrafficButtonContent = "Show Influence";
            PlotModel.Series.Clear();
            PlotModel.Axes.Clear();

            LinearBarSeries l1 = new LinearBarSeries();

            // First extract the traffic record for the system
            dataAccess.GetDailyVisits();
            VisitHistory trafficRec = dataAccess.DeVisitsHistory[dataAccess.DeVisitsHistory.FindIndex(x => x.Visted[0].StarSystem == SelectedSystem)];

            foreach (var dailyTraffic in trafficRec.Visted)
            {
                l1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(dailyTraffic.timestamp.Date), dailyTraffic.Visits));
            }

            l1.BarWidth        = 20;
            l1.FillColor       = OxyColors.DarkBlue;
            l1.StrokeThickness = 1;
            l1.StrokeColor     = OxyColors.Red;
            PlotModel.Series.Add(l1);
            AddAxis("Visits");
            PlotModel.Title = string.Format("Traffic levels for {0}", SelectedSystem);
            PlotModel.InvalidatePlot(true);
        }
示例#3
0
 public void featurelayer_SelectionChanged(LinearBarSeries selectlb, MapStatistics ms, IFeatureLayer featurelayer)
 {
     if (featurelayer != null)
     {
         List <IFeature> featureList = featurelayer.Selection.ToFeatureList();
         if (featureList.Count != 0)
         {
             foreach (Feature feature in featurelayer.Selection.ToFeatureList())
             {
                 if (ms.value_X != "" || ms.value_Y != "")
                 {
                     double    X         = Convert.ToDouble(feature.DataRow[ms.value_X]);
                     double    Y         = Convert.ToDouble(feature.DataRow[ms.value_Y]);
                     DataPoint datapoint = new DataPoint(X, Y);
                     selectlb.Points.Add(datapoint);
                 }
             }
         }
         else
         {
             selectlb.Points.Clear();
         }
     }
     ms.plotView1.Refresh();
 }
示例#4
0
 public void PlotMouseDown(LinearBarSeries lb, MapStatistics ms, OxyMouseDownEventArgs e)
 {
     if (lb.Points.Count != 0)
     {
         DataPoint dd = new DataPoint(lb.InverseTransform(e.Position).X, lb.InverseTransform(e.Position).Y);
         ms._startPoint1 = dd;
     }
 }
示例#5
0
        public static void ToPNG(string fileName, string plotTitle, MeasurmentsData measData)
        {
            int resX = 1280;
            int resY = 1024;

            var delaysModel = new PlotModel {
                Title = plotTitle
            };

            delaysModel.Legends.Add(new Legend {
                LegendBackground = OxyColors.White, LegendBorder = OxyColors.Black
            });
            int i;

            foreach (var data in measData.Delays)
            {
                var line = new LineSeries {
                    Title = $"{data.Key}"
                };
                delaysModel.Series.Add(line);
                i = 0;
                line.Points.AddRange(data.Value.Select(x => new DataPoint(i++, x)));
            }

            var seqModel = new PlotModel {
                Title = "Sequence"
            };

            seqModel.Legends.Add(new Legend {
                LegendBackground = OxyColors.White, LegendBorder = OxyColors.Black
            });
            var indexedSeq = measData.Sequence.Select((x, idx) => (idx, x));

            foreach (var group in indexedSeq.GroupBy(x => x.x).OrderBy(x => x.Key))
            {
                var seqSeries = new LinearBarSeries {
                    Title = $"{group.Key}"
                };
                seqSeries.Points.AddRange(group.Select(x => new DataPoint(x.idx, 1)));
                seqModel.Series.Add(seqSeries);
            }

            using var delaysPngStream = new MemoryStream();
            using var seqPngStream    = new MemoryStream();

            PngExporter.Export(delaysModel, delaysPngStream, resX, resY / 2);
            PngExporter.Export(seqModel, seqPngStream, resX, resY / 2);

            using var b1     = new Bitmap(Image.FromStream(delaysPngStream));
            using var b2     = new Bitmap(Image.FromStream(seqPngStream));
            using var result = new Bitmap(resX, resY);
            using var g      = Graphics.FromImage(result);
            g.DrawImage(b1, 0, 0);
            g.DrawImage(b2, 0, resY / 2);
            result.Save(fileName);
        }
        /// <summary>
        /// Creates an example linear bar series with negative values.
        /// </summary>
        /// <returns>A linear bar series containing random points.</returns>
        private static LinearBarSeries CreateExampleLinearBarSeriesWithNegativeValues()
        {
            var linearBarSeries = new LinearBarSeries();
            var r = new Random(31);

            for (int x = 0; x <= 50; x++)
            {
                var y = -200 + r.Next(1000);
                linearBarSeries.Points.Add(new DataPoint(x, y));
            }
            return(linearBarSeries);
        }
示例#7
0
 public WavePlotter(Plot Canvas)
 {
     m_Model        = Canvas;
     m_WaveLimitBar = new LinearBarSeries()
     {
         BarWidth        = 0.01,
         StrokeColor     = System.Windows.Media.Colors.Red,
         FillColor       = System.Windows.Media.Colors.Red,
         StrokeThickness = 5
     };
     m_Model.Series.Add(m_WaveLimitBar);
 }
示例#8
0
 public void PlotMouseUp(LinearBarSeries selectlb, LinearBarSeries lb, MapStatistics ms, IFeatureLayer featurelayer)
 {
     if (ms._startPoint1.X != ms._startPoint1.Y)
     {
         List <int> indexs = SelectByRectangle(selectlb, lb, ms, featurelayer);
         featurelayer.Select(indexs);
         DataPoint zerodata = new DataPoint(0, 0);
         ms._startPoint1 = zerodata;
         ms._pm.Annotations.Clear();
         ms.plotView1.Model.InvalidatePlot(true);
     }
 }
        /// <summary>
        /// Creates an example linear bar series.
        /// </summary>
        /// <returns>A linear bar series containing random points.</returns>
        private static LinearBarSeries CreateExampleLinearBarSeries()
        {
            var linearBarSeries = new LinearBarSeries();
            var r = new Random(31);
            var y = r.Next(10, 30);

            for (int x = 0; x <= 50; x++)
            {
                linearBarSeries.Points.Add(new DataPoint(x, y));
                y += r.Next(-5, 5);
            }
            return(linearBarSeries);
        }
示例#10
0
        private void RefreshLCFrontPlot()
        {
            var plotModel = new PlotModel();

            var linearAxis1 = new LinearAxis();

            linearAxis1.Title    = "Intensity";
            linearAxis1.Position = AxisPosition.Left;
            plotModel.Axes.Add(linearAxis1);

            var linearAxis2 = new LinearAxis();

            linearAxis2.Title    = "Minutes";
            linearAxis2.Position = AxisPosition.Bottom;
            plotModel.Axes.Add(linearAxis2);



            var linearBarSeries = new LinearBarSeries();

            linearBarSeries.FillColor       = OxyColor.FromArgb(69, 76, 175, 80);
            linearBarSeries.StrokeThickness = 1;
            linearBarSeries.StrokeColor     = OxyColor.FromArgb(255, 76, 175, 80);


            plotModel.Series.Add(linearBarSeries);

            if (MyMS1.Count == 0)
            {
                return;
            }

            double intensitySum = 0;

            foreach (MSUltraLight ms in MyMS1)
            {
                double spectrumCurrent = ms.Ions.Sum(a => a.Item2);
                intensitySum += spectrumCurrent;
                linearBarSeries.Points.Add(new DataPoint(ms.CromatographyRetentionTime, spectrumCurrent));
            }

            LabelTICMS1.Content = intensitySum.ToString("e4", CultureInfo.InvariantCulture);
            LabelNoMS1.Content  = MyMS1.Count;
            LabelAvgTIC.Content = Math.Round(intensitySum / (double)MyMS1.Count, 2).ToString("e4", CultureInfo.InvariantCulture);


            MyPlotLCMSFront.Model = plotModel;
        }
示例#11
0
        public List <int> SelectByRectangle(LinearBarSeries selectlb, LinearBarSeries lb, MapStatistics ms, IFeatureLayer featurelayer)
        {
            selectlb.Points.Clear();
            featurelayer.ClearSelection();
            List <int> result = new List <int>();
            double     minX, minY, maxX, maxY;

            if (ms._startPoint1.X < ms._endPoint1.X)
            {
                minX = ms._startPoint1.X;
                maxX = ms._endPoint1.X;
            }
            else
            {
                minX = ms._endPoint1.X;
                maxX = ms._startPoint1.X;
            }

            if (ms._startPoint1.Y < ms._endPoint1.Y)
            {
                minY = ms._startPoint1.Y;
                maxY = ms._endPoint1.Y;
            }
            else
            {
                minY = ms._endPoint1.Y;
                maxY = ms._startPoint1.Y;
            }

            foreach (DataPoint item in lb.Points)
            {
                if (item.X < minX || item.X > maxX || item.Y < minY || item.Y > maxY)
                {
                    continue;
                }
                else
                {
                    int pointIndex = ms._pointDic1[item.ToString()];
                    result.Add(pointIndex);
                    selectlb.Points.Add(item);
                }
            }

            ms.plotView1.Refresh();
            return(result);
        }
示例#12
0
 public void DrawPlot(ComboBox cmbX, ComboBox cmbY, MapStatistics ms, LinearBarSeries lb, IFeatureLayer featurelayer)
 {
     foreach (Feature feature in featurelayer.DataSet.Features)
     {
         ms.plotView1.Refresh();
         double X = Convert.ToDouble(feature.DataRow[cmbX.Text]);
         double Y = Convert.ToDouble(feature.DataRow[cmbY.Text]);
         ms.value_X = cmbX.Text;
         ms.value_Y = cmbY.Text;
         DataPoint dataPoint = new DataPoint(X, Y);
         lb.Points.Add(dataPoint);
         if (!ms._pointDic1.ContainsKey(dataPoint.ToString()))
         {
             ms._pointDic1.Add(dataPoint.ToString(), feature.Fid);
         }
     }
     ms.plotView1.Refresh();
 }
        // #ToDO Improve Performance by pulling all Points at once and combining as necessary
        private void UpdateChart()
        {
            m_plotModel      = new PlotModel();
            m_plotController = new PlotController();

            m_plotModel.Title = "Event Occurrences";
            DateTimeAxis tAxis = new DateTimeAxis()
            {
                Minimum = DateTimeAxis.ToDouble(m_start),
                Maximum = DateTimeAxis.ToDouble(m_end)
            };

            m_plotModel.Axes.Add(tAxis);

            tAxis.AxisChanged += AxisChanged;

            foreach (IReader reader in m_readers)
            {
                LinearBarSeries     series = new LinearBarSeries();
                TimeSpan            bucket = (m_end - m_start) / 15.0;
                List <EventSummary> lst    = new List <EventSummary>();

                for (int i = 0; i < 15; i++)
                {
                    EventSummary pt = reader.GetEventSummary(m_start + i * bucket, m_start + (i + 1) * bucket);
                    lst.Add(pt);
                }
                series.Points.AddRange(lst.Select(item => new DataPoint(
                                                      DateTimeAxis.ToDouble(item.Tmin + 0.5 * (item.Tmax - item.Tmin)),
                                                      item.Count
                                                      )));

                series.BarWidth = 15;
                m_plotModel.Series.Add(series);
            }

            OnPropertyChanged(nameof(PlotModel));
            OnPropertyChanged(nameof(PlotController));
        }
示例#14
0
        public IndicatorArea(OxyAreaSettings settings, List <OxyArea> all_areas, object tag, OxyChartPainter owner) : base(settings, owner)
        {
            area_settings  = settings;
            this.all_areas = all_areas;
            Tag            = tag;

            date_time_axis_X.IsAxisVisible = area_settings.X_Axies_is_visible;
            date_time_axis_X.IsPanEnabled  = false;

            linear_axis_Y.IsAxisVisible = area_settings.Y_Axies_is_visible;
            linear_axis_Y.IsPanEnabled  = false;

            handy_bar_series = new LinearBarSeries()
            {
                FillColor  = OxyColor.FromArgb(160, 65, 157, 238),
                BarWidth   = 5,
                Selectable = false,
                Tag        = "SeriaNameBar"
            };

            handy_lines_series = new LineSeries()
            {
                Color = OxyColor.Parse("#FF33FF"),
                Tag   = "SeriaNameBar"
            };

            handy_scatter_series = new ScatterSeries()
            {
                MarkerFill        = OxyColors.Yellow,
                MarkerStroke      = OxyColors.Yellow,
                MarkerSize        = 1,
                MarkerType        = MarkerType.Circle,
                Selectable        = false,
                EdgeRenderingMode = EdgeRenderingMode.Adaptive,
                Tag = "SeriaScatter"
            };

            plot_model.Updated += Plot_model_Updated;
        }
示例#15
0
        /// <summary>
        /// Display theAverage Influence
        /// </summary>
        public void AverageInf()
        {
            PlotModel.Series.Clear();
            PlotModel.Axes.Clear();

            double prevDay = 0.0;

            LineSeries ls = new LineSeries();

            ls.Color = OxyColors.Blue;

            LinearBarSeries l1 = new LinearBarSeries();

            l1.NegativeFillColor = OxyColors.Red;
            l1.FillColor         = OxyColors.Green;

            PlotModel.Title = string.Format("Average Influence Across all Dark Echo Systems for the past {0} days", theResults.Count);

            foreach (var results in theResults)
            {
                if (prevDay == 0.0)
                {
                    prevDay = results.TotalInf;
                }

                l1.Points.Add(new DataPoint(DateTimeAxis.ToDouble(results.InfDate), (results.TotalInf - prevDay) * 10));

                ls.Points.Add(new DataPoint(DateTimeAxis.ToDouble(results.InfDate), results.TotalInf));
                prevDay = results.TotalInf;
            }

            PlotModel.Series.Add(ls);
            PlotModel.Series.Add(l1);
            AddAxis("Inf");
            PlotModel.InvalidatePlot(true);
        }
        public static async Task AnimateSeriesAsync(
            this PlotModel plotModel,
            LinearBarSeries series,
            AnimationSettings settings)
        {
            var points = series.GetAnimatablePoints();

            if (points.Count == 0)
            {
                return;
            }

            var duration = settings.Duration;

            if (duration == default(TimeSpan))
            {
                duration = TimeSpan.FromMilliseconds(DefaultAnimationDuration);
            }

            var easingFunction = settings.EasingFunction;

            if (easingFunction == null)
            {
                easingFunction = DefaultEasingFunction;
            }

            var animationFrameDurationInMs = (int)settings.FrameDuration.TotalMilliseconds;
            var minimumValue = settings.MinimumValue;

            var animationFrames = new List <AnimationFrame>();

            // Animation assumptions:
            //
            //   - Total duration: 300ms (in this example)
            //   - At least animate each horizontal value separately
            //   - First animate from left => right (70 % of the time)
            //   - Second animate from center => end (30 % of the time)
            //
            // |                                                  ^
            // |                                                  |
            // |               ___                                |
            // |               | |                                |  30 % of time
            // |   ___         | |                                |     90 ms
            // |   | |         | |                                |
            // |   | |   ___   | |                                |
            // |   | |   | |   | |                                |
            // |___|_|___|_|___|_|_____________________________   ^
            //
            // <---------------- 70 % of time ---------------->
            //                     (210 ms)

            var horizontalDuration = duration.TotalMilliseconds / 100 * settings.HorizontalPercentage;
            var verticalDuration   = duration.TotalMilliseconds / 100 * settings.VerticalPercentage;

            var animationFrameCount    = (int)(duration.TotalMilliseconds / animationFrameDurationInMs);
            var animationFrameDuration = TimeSpan.FromMilliseconds(animationFrameDurationInMs);

            if (!minimumValue.HasValue)
            {
                minimumValue = 0d;

                var defaultYAxis = plotModel.DefaultYAxis;
                if (defaultYAxis != null)
                {
                    if (defaultYAxis.Minimum > 0d)
                    {
                        minimumValue = defaultYAxis.Minimum;
                    }
                }
            }

            var minX   = (from point in points orderby point.X select point.X).Min();
            var maxX   = (from point in points orderby point.X select point.X).Max();
            var deltaX = maxX - minX;

            for (var i = 0; i < animationFrameCount; i++)
            {
                var animationFrame = new AnimationFrame
                {
                    Duration = animationFrameDuration
                };

                var currentTime = animationFrameDurationInMs * i;
                var percentage  = i * 100d / animationFrameCount;

                var horizontalPercentage = currentTime * 100d / horizontalDuration;
                if (horizontalPercentage > 100d)
                {
                    horizontalPercentage = 100d;
                }

                var currentDeltaX = deltaX / 100d * horizontalPercentage;
                var currentX      = minX + currentDeltaX;

                // Get the last visible point. It should not be based on the index (can be really different), but on the X position
                // since we want to draw a smooth animation
                var lastVisibleHorizontalPoint = 0;
                for (int j = 0; j < points.Count; j++)
                {
                    var x = points[j].FinalX;
                    if (x > currentX)
                    {
                        break;
                    }

                    lastVisibleHorizontalPoint = j;
                }

                for (var j = 0; j < points.Count; j++)
                {
                    var point = points[j];

                    var isVisible = false;
                    var x         = point.FinalX;
                    var y         = 0d;

                    if (j <= lastVisibleHorizontalPoint)
                    {
                        isVisible = true;
                        y         = point.FinalY;

                        // We know how long an y animation takes. We only have to calculate if this start time of this x animation
                        // is longer than verticalDuration ago
                        var localDeltaX      = point.FinalX - minX;
                        var localPercentageX = localDeltaX * 100d / deltaX;
                        var startTime        = horizontalDuration / 100 * localPercentageX;
                        var endTime          = startTime + verticalDuration;

                        if (endTime > currentTime)
                        {
                            var timeDeltaTotal   = endTime - startTime;
                            var timeDeltaCurrent = currentTime - startTime;
                            var subPercentage    = timeDeltaCurrent * 100d / timeDeltaTotal;

                            // This bar is part of the current animation, calculate the Y relative to 30 % of the time based on the current index
                            // Calculate the % that offset is based on totalTimeDelta

                            // Calculate point to animate from
                            var maxY   = point.FinalY;
                            var minY   = minimumValue.Value;
                            var deltaY = maxY - minY;

                            // We need to ease against percentage (between 0 and 1)
                            var ease          = easingFunction.Ease(subPercentage / 100);
                            var currentDeltaY = deltaY * ease;

                            y = minY + currentDeltaY;
                        }
                    }

                    animationFrame.AnimationPoints.Add(new AnimationPoint
                    {
                        IsVisible = isVisible,
                        X         = x,
                        Y         = y
                    });
                }

                animationFrames.Add(animationFrame);
            }

            animationFrames.InsertDelayAnimationFrame(settings.Delay);

            await plotModel.AnimateSeriesAsync(series, animationFrames);
        }
示例#17
0
        public override void BuildIndicatorSeries(IndicatorSeria indi_seria, List <decimal> data_points, TimeSpan time_frame_span)
        {
            var time_step_double = 1 / (1000 * 60 * 60 * 24 / time_frame_span.TotalMilliseconds);

            indi_seria.DataPoints = data_points;

            if (indi_seria.DataPoints == null || indi_seria.DataPoints.Count == 0)
            {
                return;
            }

            if (plot_view == null || plot_model == null)
            {
                return;
            }

            var main_chart = (CandleStickArea)all_areas.Find(x => x is CandleStickArea);

            lock (series_locker)
            {
                if (main_chart != null && (main_chart.axis_Y_type == "linear" || (string)Tag != "Prime"))
                {
                    if (indi_seria.IndicatorType == IndicatorChartPaintType.Column)
                    {
                        if (indi_seria.DataPoints.Count == indi_seria.IndicatorPoints.Count)
                        {
                            double last_point = (double)indi_seria.DataPoints.Last();

                            if (last_point == 0)
                            {
                                last_point = double.NaN;
                            }

                            indi_seria.IndicatorHistogramPoints[indi_seria.IndicatorHistogramPoints.Count - 1] = new DataPoint(items_oxy_candles.Last().X, last_point);
                        }
                        else if (indi_seria.DataPoints.Count == indi_seria.IndicatorPoints.Count + 1)
                        {
                            double last_point = (double)indi_seria.DataPoints.Last();

                            if (last_point == 0)
                            {
                                last_point = double.NaN;
                            }

                            indi_seria.IndicatorHistogramPoints.Add(new DataPoint(items_oxy_candles.Last().X, last_point));
                        }
                        else
                        {
                            indi_seria.IndicatorHistogramPoints.Clear();

                            List <DataPoint> points = new List <DataPoint>();

                            for (int i = 0; i < indi_seria.DataPoints.Count; i++)
                            {
                                double last_point = (double)indi_seria.DataPoints[i];

                                if (last_point == 0)
                                {
                                    last_point = double.NaN;
                                }

                                try
                                {
                                    points.Add(new DataPoint(items_oxy_candles[i].X, last_point));
                                }
                                catch { return; }
                            }

                            indi_seria.IndicatorHistogramPoints = points.ToList();
                        }



                        LinearBarSeries linear_bar_seria = new LinearBarSeries()
                        {
                            StrokeThickness     = 1,
                            StrokeColor         = OxyColor.FromArgb(255, 55, 219, 186),
                            FillColor           = OxyColor.FromArgb(69, 55, 219, 186),
                            NegativeFillColor   = OxyColor.FromArgb(69, 235, 96, 47),
                            NegativeStrokeColor = OxyColor.FromArgb(255, 235, 96, 47),
                            Tag = indi_seria.SeriaName
                        };


                        linear_bar_seria.Points.AddRange(indi_seria.IndicatorHistogramPoints);


                        if (linear_bar_series_list.Exists(x => (string)x.Tag == indi_seria.SeriaName))
                        {
                            linear_bar_series_list.Remove(linear_bar_series_list.Find(x => (string)x.Tag == indi_seria.SeriaName));
                        }

                        linear_bar_series_list.Add(linear_bar_seria);
                    }



                    if (indi_seria.IndicatorType == IndicatorChartPaintType.Line)
                    {
                        if (indi_seria.DataPoints.Count == indi_seria.IndicatorPoints.Count)
                        {
                            double last_point = (double)indi_seria.DataPoints.Last();

                            if (last_point == 0)
                            {
                                last_point = double.NaN;
                            }


                            indi_seria.IndicatorPoints[indi_seria.IndicatorPoints.Count - 1] = new DataPoint(items_oxy_candles.Last().X, last_point);

                            indi_seria.IndicatorPoints[indi_seria.IndicatorPoints.Count - 1] = new DataPoint(items_oxy_candles.Last().X, last_point);
                        }
                        else if (indi_seria.DataPoints.Count == indi_seria.IndicatorPoints.Count + 1)
                        {
                            double last_point = (double)indi_seria.DataPoints.Last();

                            if (last_point == 0)
                            {
                                last_point = double.NaN;
                            }


                            indi_seria.IndicatorPoints.Add(new DataPoint(items_oxy_candles.Last().X, last_point));
                        }
                        else
                        {
                            indi_seria.IndicatorPoints.Clear();

                            List <DataPoint> points = new List <DataPoint>();

                            for (int i = 0; i < indi_seria.DataPoints.Count; i++)
                            {
                                double last_point = (double)indi_seria.DataPoints[i];

                                if (last_point == 0)
                                {
                                    last_point = double.NaN;
                                }

                                try
                                {
                                    points.Add(new DataPoint(items_oxy_candles[i].X, last_point));
                                }
                                catch { return; }
                            }
                            ;

                            indi_seria.IndicatorPoints = points;
                        }


                        LineSeries line_seria = new LineSeries()
                        {
                            StrokeThickness = 1,
                            LineStyle       = LineStyle.Solid,
                            Color           = indi_seria.OxyColor,
                            Tag             = indi_seria.SeriaName
                        };

                        line_seria.Points.AddRange(indi_seria.IndicatorPoints);


                        if (lines_series_list.Exists(x => (string)x.Tag == indi_seria.SeriaName))
                        {
                            lines_series_list.Remove(lines_series_list.Find(x => (string)x.Tag == indi_seria.SeriaName));
                        }

                        lines_series_list.Add(line_seria);
                    }


                    if (indi_seria.IndicatorType == IndicatorChartPaintType.Point)
                    {
                        if (indi_seria.DataPoints.Count == indi_seria.IndicatorScatterPoints.Count)
                        {
                            double last_point = (double)indi_seria.DataPoints.Last();

                            if (last_point == 0)
                            {
                                last_point = double.NaN;
                            }

                            indi_seria.IndicatorScatterPoints[indi_seria.IndicatorScatterPoints.Count - 1] = new ScatterPoint(items_oxy_candles.Last().X, last_point);
                        }
                        else if (indi_seria.DataPoints.Count == indi_seria.IndicatorScatterPoints.Count + 1)
                        {
                            double last_point = (double)indi_seria.DataPoints.Last();

                            if (last_point == 0)
                            {
                                last_point = double.NaN;
                            }

                            indi_seria.IndicatorScatterPoints.Add(new ScatterPoint(items_oxy_candles.Last().X, last_point));
                        }
                        else
                        {
                            indi_seria.IndicatorScatterPoints.Clear();

                            List <ScatterPoint> points = new List <ScatterPoint>();

                            for (int i = 0; i < indi_seria.DataPoints.Count; i++)
                            {
                                double last_point = (double)indi_seria.DataPoints[i];

                                if (last_point == 0)
                                {
                                    last_point = double.NaN;
                                }

                                try
                                {
                                    points.Add(new ScatterPoint(items_oxy_candles[i].X, last_point));
                                }
                                catch { return; }
                            }
                            ;

                            indi_seria.IndicatorScatterPoints = points;
                        }

                        ScatterSeries scatter_seria = new ScatterSeries()
                        {
                            MarkerType            = MarkerType.Circle,
                            MarkerFill            = indi_seria.OxyColor,
                            MarkerSize            = 2,
                            MarkerStrokeThickness = 0,
                            Tag = indi_seria.SeriaName
                        };

                        scatter_seria.Points.AddRange(indi_seria.IndicatorScatterPoints);


                        if (scatter_series_list.Exists(x => (string)x.Tag == indi_seria.SeriaName))
                        {
                            scatter_series_list.Remove(scatter_series_list.Find(x => (string)x.Tag == indi_seria.SeriaName));
                        }

                        scatter_series_list.Add(scatter_seria);
                    }
                }
            }
        }
示例#18
0
using System;
using System.Drawing;
using System.IO;
using ImageFilter.Filters;
using ImageFilter.Noises;
using ImageFilter.Extensions;
using OxyPlot;
using OxyPlot.WindowsForms;
using OxyPlot.Axes;
using OxyPlot.Series;
using System.Collections.Generic;

namespace ImageFilter
{
    public class ImageLoader : IDisposable
    {
        #region Fields

        private bool isDisposed;

        #endregion

        #region Propeties

        public Image Image { get; set; }
        public string ImagePath { get; private set; }

        #endregion

        #region Methods

        public double CalculatePSNR(Image image)
        {
            var img1 = (Bitmap) Image;
            var img2 = (Bitmap) image;

            int width = image.Width;
            int height = image.Height;

            double psnrY = 0;
            using (var img1BMP = new ConcurrentBitmap(img1))
            {
                using (var img2BMP = new ConcurrentBitmap(img2))
                {
                    // For each line
                    for (var y = 0; y < height; y++)
                    {
                        // For each pixel
                        for (var x = 0; x < width; x++)
                        {
                            Color img1Color = img1BMP.GetPixel(x, y);

                            // Assumes that img2 is not in Y component
                            Color tmpColor = img2BMP.GetPixel(x, y);
                            var I = (int) (tmpColor.R * 0.299
                                           + tmpColor.G * 0.587
                                           + tmpColor.B * 0.114);

                            Color img2Color = Color.FromArgb(I, I, I);

                            psnrY += Math.Pow(img1Color.R - img2Color.R, 2);
                        }
                    }
                }
            }

            psnrY = 10 * Math.Log10(width * height * Math.Pow(Math.Pow(2, 8) - 1, 2) / psnrY);
            /*Console.WriteLine($"Y: {psnrY}");*/
            return psnrY;
        }

        public ImageLoader Load(string filePath)
        {
            var fileInfo = new FileInfo(filePath);

            if (!fileInfo.Exists)
            {
                throw new FileNotFoundException(filePath);
            }

            ImagePath = filePath;

            // Open a file stream

            using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                var stream = new MemoryStream();
                fileStream.CopyTo(stream);
                stream.Position = 0;

                Image = Image.FromStream(stream);
            }

            return this;
        }

        

        public ImageLoader Save(string filePath)
        {
            var dirInfo = new DirectoryInfo(Path.GetDirectoryName(filePath));

            if (!dirInfo.Exists)
            {
                dirInfo.Create();
            }

            Image.Save(filePath);

            return this;
        }

        public ImageLoader AddImage(Image I, double[,] img)
        {
            Bitmap one = (Bitmap) I;

            //Bitmap two = (Bitmap) img;

            Bitmap res = new Bitmap(one.Width, one.Height);

            int height = Image.Height;
            int width =  Image.Width;
            for (int y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    double blue;
                    double green;
                    double red = green = blue = 0;

                    Color colorOne = one.GetPixel(x, y);
                    int colorTwo = (int) img[y, x];//two.GetPixel(x, y);

                    red = colorOne.R + colorTwo;
                    green = colorOne.G + colorTwo;
                    blue = colorOne.B + colorTwo;

                    Color destinationColor = Color.FromArgb(
                                    Convert.ToByte(red.Clamp(0, 255)),
                                    Convert.ToByte(green.Clamp(0, 255)),
                                    Convert.ToByte(blue.Clamp(0, 255)));

                    res.SetPixel(x, y, destinationColor);
                }
            }
            Image = res;

            return this;
        }

        public ImageLoader Add128(double[,] I)
        {
            Bitmap image = (Bitmap) Image;
            Bitmap res = new Bitmap(Image.Width, Image.Height);
            int height = Image.Height;
            int width = Image.Width;
            for (int y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    double blue;
                    double green;
                    double red = green = blue = 0;

                    red = I[y, x];// 128;
                    blue = I[y, x];// + 128;
                    green = I[y, x];//

                    red += 128;
                    blue += 128;
                    green += 128;

                    Color destinationColor = Color.FromArgb(
                                    Convert.ToByte(red.Clamp(0, 255)),
                        Convert.ToByte(green.Clamp(0, 255)),
                                    Convert.ToByte(blue.Clamp(0, 255)));

                    res.SetPixel(x, y, destinationColor);
                }
            }
            Image = res;
            return this;
        }

        public ImageLoader AddNoise(INoise noise)
        {
            Image = noise.ProcessPicture(this);

            return this;
        }

        public ImageLoader AddBoxFilter(int size)
        {
            var boxFilter = new BoxFilter(size);
            Image = boxFilter.ProcessPicture(this);

            return this;
        }

        public ImageLoader AddGaussFilter(int size, double sigma)
        {
            var boxFilter = new GaussFilter(size, sigma);
            Image = boxFilter.ProcessPicture(this);

            return this;
        }

        public ImageLoader AddMedianFilter(int size)
        {
            var medianFilter = new MedianFilter(size);
            Image = medianFilter.ProcessPicture(this);

            return this;
        }

        public ImageLoader AddLaplacianFilter(double alpha)
        {
            var laplacianFilter = new LaplacianFilter(alpha);
            Image = laplacianFilter.ProcessPicture(this);

            return this;
        }
        public double[,] AddLaplacianFilterAlpha0()
        {
            var laplacianFilter = new LaplacianFilter(0);
            double[,] res = laplacianFilter.ProcessPictureAlpha0(this);

            return res;
        }
        public ImageLoader AddSobelFilter(string direction)
        {
            var sobelFilter = new SobelFilter(direction == "V" ? 1 : 0);

            Image = sobelFilter.ProcessPicture(this);

            return this;
        }

        public double[,] GetSobelFilterDouble(string direction)
        {
            var sobelFilter = new SobelFilter(direction == "V" ? 1 : 0);

            return sobelFilter.Get(this);
        }

        public double CalculateAvgLuminocity()
        {
            double luminocity = 0;
            Bitmap image = (Bitmap)Image;
            int height = image.Height;
            int width = image.Width;
            for (int y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    luminocity += image.GetPixel(x, y).R;
                }
            }

            return luminocity / (double) (height * width);
        }

        private SortedDictionary<int, int> GetFrequency()
        {
            Bitmap image = (Bitmap)Image;
            int height = image.Height;
            int width = image.Width;

            var result = new SortedDictionary<int, int>();
            for (int y = 0; y < height; y++)
            {
                for (var x = 0; x < width; x++)
                {
                    int Y = image.GetPixel(x, y).R;

                    if (result.ContainsKey(Y))
                    {
                        result[Y] = result[Y] + 1;
                    } else
                    {
                        result.Add(Y, 1);
                    }
                }
            }
            return result;
        }

        public void PlotHistogram(string name, string outputPath, FileInfo fileInfo)
        {
            PngExporter pngExporter = new PngExporter { Width = 1280, Height = 720, Background = OxyColors.White };

            var freq = GetFrequency();

            var x = freq.Values;
            var y = freq.Keys;

            var plotGauss = new PlotModel { Title = $"Histogram for {name}" };
            plotGauss.Axes.Add(new LinearAxis { Title = "x", Position = AxisPosition.Bottom });
            plotGauss.Axes.Add(new LinearAxis { Title = "y", Position = AxisPosition.Left });

            var barSeries = new LinearBarSeries
            {

            };

            foreach (var item in freq)
            {
                barSeries.Points.Add(new DataPoint(item.Key, item.Value));
            }

            plotGauss.Series.Add(barSeries);
            pngExporter.ExportToFile(plotGauss, $"{outputPath}/{fileInfo.Name}/histograms/{name}{fileInfo.Extension}");
        }

        #region Dispose

        ~ImageLoader()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);

            // Already cleaned up in dispose method, supress GC
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            if (isDisposed)
            {
                return;
            }

            if (disposing)
            {
                if (Image != null)
                {
                    Image.Dispose();
                    Image = null;
                }
            }

            isDisposed = true;
        }

        #endregion

        #endregion
    }
}
示例#19
0
        public void PlotLines(List <Wave> waves)
        {
            m_Model.Series.Clear();
            m_Model.InvalidatePlot(true);

            if (waves.Count != 0)
            {
                var minW = waves.Min(x => x.lambda) * 0.95;
                var maxW = waves.Max(x => x.lambda) * 1.05;

                m_Model.Axes[0].Minimum = minW;
                m_Model.Axes[0].Maximum = maxW;
            }

            if (m_Limits != null)
            {
                SetWaveLimits(m_Limits);
            }

            var index = 0;

            foreach (var groupedWave in waves.GroupBy(x => x.Order))
            {
                var waveSeries = new LinearBarSeries()
                {
                    BarWidth        = 0.0001,
                    StrokeThickness = 2,
                    StrokeColor     = OxyColor.Parse(ColorMap.GetColor(index)).ToColor()
                };

                ++index;

                waveSeries.ItemsSource = groupedWave.Select(x =>
                {
                    var dh = (x.dlambda * 1e-3) / 2.0;
                    return(new DataPoint(x.lambda, x.intensity));
                }).OrderBy(x => x.X).ToList();

                m_Model.Series.Add(waveSeries);
                m_Model.InvalidatePlot(true);
            }


            var lineSeries = new LineSeries()
            {
                LineStyle  = LineStyle.None,
                MarkerFill = OxyColors.Blue.ToColor(),
                MarkerSize = 5,
                MarkerType = MarkerType.Circle
            };

            lineSeries.YAxisKey = "WaveReflectivity";
            lineSeries.XAxisKey = "WaveKey";

            List <DataPoint> pointList = new List <DataPoint>();

            foreach (var wave in waves)
            {
                pointList.Add(new DataPoint(wave.lambda, wave.Efficiency));
            }
            lineSeries.ItemsSource = pointList;
            lineSeries.Items.Refresh();

            m_Model.Series.Add(lineSeries);
            m_Model.InvalidatePlot(true);
        }
        public LinearBarViewModel()
        {
            var pnls = new List <Pnl>();

            var random   = new Random(31);
            var dateTime = DateTime.Today.Add(TimeSpan.FromHours(9));

            for (var pointIndex = 0; pointIndex < 50; pointIndex++)
            {
                pnls.Add(new Pnl
                {
                    Time  = dateTime,
                    Value = -200 + random.Next(1000),
                });
                dateTime = dateTime.AddMinutes(1);
            }

            var minimum = pnls.Min(x => x.Value);
            var maximum = pnls.Max(x => x.Value);

            var plotModel = this.PlotModel;

            plotModel.Title = "Linear Bar Series Animation Demo";

            var series = new LinearBarSeries
            {
                Title           = "P & L",
                ItemsSource     = pnls,
                DataFieldX      = "Time",
                DataFieldY      = "Value",
                FillColor       = OxyColor.Parse("#454CAF50"),
                StrokeColor     = OxyColor.Parse("#4CAF50"),
                StrokeThickness = 1,
                BarWidth        = 5
            };

            plotModel.Series.Add(series);

            var annotation = new LineAnnotation
            {
                Type = LineAnnotationType.Horizontal,
                Y    = 0
            };

            plotModel.Annotations.Add(annotation);

            var dateTimeAxis = new DateTimeAxis
            {
                Position       = AxisPosition.Bottom,
                IntervalType   = DateTimeIntervalType.Hours,
                IntervalLength = 50
            };

            plotModel.Axes.Add(dateTimeAxis);

            var margin = (maximum - minimum) * 0.05;

            var valueAxis = new LinearAxis
            {
                Position = AxisPosition.Left,
                Minimum  = minimum - margin,
                Maximum  = maximum + margin,
            };

            plotModel.Axes.Add(valueAxis);
        }