예제 #1
0
        // ************************************************************************
        private void DrawPoints(params DrawInfo[] drawInfos)
        {
            Model.PlotModel.Series.Clear();

            foreach (var drawInfo in drawInfos)
            {
                if (drawInfo.DrawStyle == DrawStyle.Line)
                {
                    var s = new OxyPlot.Series.LineSeries {
                        Title = drawInfo.Name, MarkerType = MarkerType.Square, Color = drawInfo.Color
                    };
                    foreach (var pt in drawInfo.Points)
                    {
                        s.Points.Add(new DataPoint(pt.X, pt.Y));
                    }
                    Model.PlotModel.Series.Insert(0, s);
                }
                else if (drawInfo.DrawStyle == DrawStyle.Point)
                {
                    var s = new OxyPlot.Series.ScatterSeries {
                        Title = drawInfo.Name, MarkerType = MarkerType.Circle, MarkerSize = 2, MarkerFill = drawInfo.Color
                    };
                    foreach (var pt in drawInfo.Points)
                    {
                        s.Points.Add(new ScatterPoint(pt.X, pt.Y));
                    }
                    Model.PlotModel.Series.Insert(0, s);
                }
            }

            Model.PlotModel.PlotView?.InvalidatePlot();
        }
예제 #2
0
        public void PlotMirror(double w, double h)
        {
            var model = new PlotModel();

            model.PlotType = PlotType.Cartesian;

            OxyPlot.Series.ScatterSeries sser = new OxyPlot.Series.ScatterSeries()
            {
                MarkerType = MarkerType.Square,
                BinSize    = 2,
                MarkerSize = 0.75
            };

            sser.ItemsSource = m_Points;

            model.Series.Add(sser);
            model.Axes.Add(new OxyPlot.Axes.LinearAxis {
                Position = AxisPosition.Bottom, Maximum = w / 2.0, Minimum = -w / 2.0, Title = "x, [mm]"
            });
            model.Axes.Add(new OxyPlot.Axes.LinearAxis {
                Position = AxisPosition.Left, Maximum = h / 2.0, Minimum = -h / 2.0, Title = "y, [mm]"
            });
            model.Axes.Add(new OxyPlot.Axes.LinearColorAxis {
                Position = AxisPosition.Right,
                Palette  = OxyPalettes.Rainbow(200),
            });

            m_Canvas.Model = model;
            m_Canvas.InvalidatePlot(true);
        }
        public PlotModel ScatterPlot(IReadOnlyCollection <IdentData> data, Func <object, ScatterPoint> mapping, string title, string xTitle, OxyColor markerColor)
        {
            //series1.Mapping = item => new DataPoint(((MyType)item).Time,((MyType)item).Value)
            var model = ModelBaseConfig();

            model.Title = title;

            var s1 = new ScatterSeries
            {
                MarkerType            = MarkerType.Circle,
                MarkerStrokeThickness = 0,
                MarkerSize            = 1.0,
                MarkerFill            = markerColor,
                ItemsSource           = data,
                Mapping = mapping
            };

            var yAxis = new LinearAxis
            {
                Position           = AxisPosition.Left,
                Title              = "Mass Error (PPM)",
                MajorGridlineStyle = LineStyle.Solid,
                MajorStep          = 10.0,
                MinorStep          = 5.0,
                Minimum            = -20.0,
                Maximum            = 20.0,
                MinimumRange       = 40.0,
                FilterMinValue     = -20.0,
                FilterMaxValue     = 20.0
            };

            var xAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                Title    = xTitle
                           //Minimum = 1000,
                           //Maximum = 4600,
            };

            var xAxisCenter = new LinearAxis
            {
                Position = AxisPosition.Top,        // To let the other axis be locked to the bottom, and force this one to be horizontal
                PositionAtZeroCrossing = true,
                TickStyle         = TickStyle.None, // To change to show a value, need to do axis synchronization
                AxislineStyle     = LineStyle.Solid,
                AxislineThickness = 1.0,
                TextColor         = OxyColors.Undefined // Force invisible labels
            };

            model.Axes.Add(yAxis);
            model.Axes.Add(xAxis);
            model.Axes.Add(xAxisCenter);
            model.Series.Add(s1);
            return(model);
        }
        public PlotModel ScatterPlot(IReadOnlyCollection <IdentData> data, string xDataField, string yDataField, string title, string xTitle, OxyColor markerColor)
        {
            var model = ModelBaseConfig();

            model.Title = title;

            var s1 = new ScatterSeries
            {
                MarkerType            = MarkerType.Circle,
                MarkerStrokeThickness = 0,
                MarkerSize            = 1.0,
                MarkerFill            = markerColor,
                ItemsSource           = data,
                //DataFieldX = xDataField,
                //DataFieldY = yDataField,
                Mapping = item => new ScatterPoint(Convert.ToDouble(typeof(IdentData).GetProperty(xDataField)?.GetValue(item)), Convert.ToDouble(typeof(IdentData).GetProperty(yDataField)?.GetValue(item)))
            };

            var yAxis = new LinearAxis
            {
                Position           = AxisPosition.Left,
                Title              = "Mass Error (PPM)",
                MajorGridlineStyle = LineStyle.Solid,
                MajorStep          = 10.0,
                MinorStep          = 5.0,
                Minimum            = -20.0,
                Maximum            = 20.0,
                MinimumRange       = 40.0,
                FilterMinValue     = -20.0,
                FilterMaxValue     = 20.0
            };

            var xAxis = new LinearAxis
            {
                Position = AxisPosition.Bottom,
                Title    = xTitle
            };

            var xAxisCenter = new LinearAxis
            {
                Position = AxisPosition.Top,        // To let the other axis be locked to the bottom, and force this one to be horizontal
                PositionAtZeroCrossing = true,
                TickStyle         = TickStyle.None, // To change to show a value, need to do axis synchronization
                AxislineStyle     = LineStyle.Solid,
                AxislineThickness = 1.0,
                TextColor         = OxyColors.Undefined // Force invisible labels
            };

            model.Axes.Add(yAxis);
            model.Axes.Add(xAxis);
            model.Axes.Add(xAxisCenter);
            model.Series.Add(s1);
            return(model);
        }
        private OxyPlot.Series.ScatterSeries CreateSeries(List <double> CouchAng, List <double> GantryAng, int size)
        {
            var scatterSeries = new OxyPlot.Series.ScatterSeries();

            int CoordLength = CouchAng.Count;

            for (int iii = 0; iii < CoordLength; iii++)
            {
                var point = new ScatterPoint(CouchAng[iii], GantryAng[iii], size);
                scatterSeries.Points.Add(point);
            }
            return(scatterSeries);
        }
예제 #6
0
        private void CreateMdsChartModel()
        {
            var model = new PlotModel();

            var xAxis = new OxyPlot.Axes.LinearAxis
            {
                Position           = OxyPlot.Axes.AxisPosition.Bottom,
                MajorGridlineStyle = LineStyle.None
            };

            model.Axes.Add(xAxis);

            var yAxis = new OxyPlot.Axes.LinearAxis
            {
                Position           = OxyPlot.Axes.AxisPosition.Left,
                MajorGridlineStyle = LineStyle.None
            };

            model.Axes.Add(yAxis);

            var series = new OxyPlot.Series.ScatterSeries
            {
                ItemsSource = (Data.MdsCoords.Rows.Cast <filterReportDS.MdsCoordsRow>()
                               .Select(dr => new DataPoint(dr.X, dr.Y))),
                DataFieldX = "X",
                DataFieldY = "Y",
                MarkerType = MarkerType.Circle,
                MarkerSize = 2,
                MarkerFill = OxyColor.FromRgb(79, 129, 189)
            };

            model.Series.Add(series);

            foreach (filterReportDS.MdsCoordsRow dr in Data.MdsCoords.Rows)
            {
                var annotation = new OxyPlot.Annotations.TextAnnotation
                {
                    Text                    = dr.StrategyName,
                    TextPosition            = new DataPoint(dr.X, dr.Y),
                    TextHorizontalAlignment = OxyPlot.HorizontalAlignment.Center,
                    TextVerticalAlignment   = OxyPlot.VerticalAlignment.Top,
                    Font                    = "Segoe UI",
                    TextColor               = OxyColor.FromRgb(0, 0, 0),
                    StrokeThickness         = 0
                };

                model.Annotations.Add(annotation);
            }

            MdsChartModel = model;
        }
예제 #7
0
        private void PlotGraph()
        {
            PlotData = new PlotModel();
            var yAxis = new OxyPlot.Axes.LinearAxis {
                Position           = AxisPosition.Left,
                Title              = "Fiber Attenuation",
                MajorGridlineStyle = LineStyle.Solid,
                MinorGridlineStyle = LineStyle.None
            };
            var xAxis = new OxyPlot.Axes.LinearAxis {
                Position           = AxisPosition.Bottom,
                Title              = "Wavelengths (nm)",
                MajorGridlineStyle = LineStyle.Solid,
                MinorGridlineStyle = LineStyle.None
            };

            PlotData.Axes.Add(xAxis);
            PlotData.Axes.Add(yAxis);
            DataPoint[]    linePoints   = new DataPoint[loss.Count];
            ScatterPoint[] markerPoints = new ScatterPoint[loss.Count];
            for (int i = 0; i < loss.Count; i++)
            {
                if (markers.Contains(wavelengths[i]))
                {
                    markerPoints[i] = new ScatterPoint((double)wavelengths[i], (double)loss[i]);
                }
                else
                {
                    markerPoints[i] = new ScatterPoint((double)wavelengths[i], 0);
                }
                linePoints[i] = new DataPoint((double)wavelengths[i], (double)loss[i]);
            }



            var lineSeries = new OxyPlot.Series.LineSeries {
                StrokeThickness = 2,
                ItemsSource     = linePoints
            };
            var circleSeries = new OxyPlot.Series.ScatterSeries {
                MarkerSize = 3,
                MarkerType = MarkerType.Circle
            }; // W850 TO W1550 S10;

            circleSeries.Points.AddRange(markerPoints.Where(i => i.Y > 0));
            PlotData.Series.Add(lineSeries);
            PlotData.Series.Add(circleSeries);
            PlotData.InvalidatePlot(true);
        }
예제 #8
0
        private PlotModel CreatePlotModel()
        {
            var model = new PlotModel
            {
                Title = "Recent ECGs",
            };

            var xAxis = new LinearAxis
            {
                Title    = "Transit time",
                Unit     = "s",
                Position = AxisPosition.Bottom
            };

            model.Axes.Add(xAxis);
            var yAxis = new LinearAxis
            {
                Title = "Lost energy",
                Unit  = "kWh"
            };

            model.Axes.Add(yAxis);

            var scatterSeries = new ScatterSeries
            {
                MarkerFill = OxyColors.Gray
            };

            foreach (var datum in _graphData)
            {
                scatterSeries.Points.Add(new ScatterPoint(datum.TransitTime, datum.LostEnergy));
            }
            model.Series.Add(scatterSeries);

            var recentSeries = new ScatterSeries
            {
                MarkerFill = OxyColors.Blue,
                MarkerType = MarkerType.Circle
            };

            foreach (var datum in _recentGraphData)
            {
                recentSeries.Points.Add(new ScatterPoint(datum.TransitTime, datum.LostEnergy));
            }
            model.Series.Add(recentSeries);

            return(model);
        }
예제 #9
0
        private void DrawFunctions()
        {
            model.Series.Clear();

            var xMin = model.DefaultXAxis.ActualMinimum;
            var xMax = model.DefaultXAxis.ActualMaximum;

            for (int i = 0; i < parametersFunctions.Count; i++)
            {
                operatingFunction.SetParametersValues(parametersFunctions[i]);
                var series = new FunctionSeries(operatingFunction.FunctionValue, xMin, xMax, (xMax - xMin) / 1000);
                if (i == 0)
                {
                    series.Color = OxyColors.Blue;
                }
                else if (i == parametersFunctions.Count - 1)
                {
                    series.Color = OxyColors.Red;
                    series.Title = "результат";
                }
                else
                {
                    series.LineStyle = LineStyle.Dash;
                }
                model.Series.Add(series);
            }

            if (operatingDataSet.Count != 0)
            {
                var scatterSeries = new OxyPlot.Series.ScatterSeries {
                    MarkerType = MarkerType.Circle,
                    MarkerFill = OxyColors.DarkCyan
                };
                foreach (var point in operatingDataSet)
                {
                    scatterSeries.Points.Add(new ScatterPoint(point.X, point.Y, 3));
                }
                model.Series.Add(scatterSeries);
            }

            Plot.InvalidatePlot();
        }
예제 #10
0
        public void MakeScatterChart([ItemNotNull][JetBrains.Annotations.NotNull] List <CalculationOutcome> outcomes, [JetBrains.Annotations.NotNull] string pngfullName, [ItemNotNull][JetBrains.Annotations.NotNull] List <SeriesEntry> series)
        {
            _calculationProfiler.StartPart(Utili.GetCurrentMethodAndClass());
            var plotModel1 = new PlotModel
            {
                LegendBorderThickness = 0,
                LegendOrientation     = LegendOrientation.Horizontal,
                LegendPlacement       = LegendPlacement.Outside,
                LegendPosition        = LegendPosition.BottomCenter,
                DefaultFontSize       = FontSize,
                LegendFontSize        = FontSize,
                DefaultFont           = "Arial",
                LegendFont            = "Arial"
            };
            var ca = new CategoryAxis
            {
                Minimum  = 0.4,
                Title    = "Number of Persons",
                Position = AxisPosition.Bottom
            };

            ca.Title = Xaxislabel;
            ca.Labels.Add("0");
            ca.Labels.Add("1");
            ca.Labels.Add("2");
            ca.Labels.Add("3");
            ca.Labels.Add("4");
            ca.Labels.Add("5");
            ca.Labels.Add("6");
            ca.MaximumPadding = 0.02;
            plotModel1.Axes.Add(ca);

            var la = new LinearAxis
            {
                Minimum        = 0,
                Position       = AxisPosition.Left,
                Title          = Yaxislabel,
                MaximumPadding = 0.02
            };

            plotModel1.Axes.Add(la);

            var sc = new LineSeries
            {
                LineStyle       = LineStyle.Dash,
                MarkerFill      = OxyColors.SkyBlue,
                MarkerSize      = 5,
                MarkerType      = MarkerType.Circle,
                StrokeThickness = 3
            };

            AddNRWPoints(sc, 1);
            sc.Title = Averagelabel;
            plotModel1.Series.Add(sc);

            var energyIntensities = outcomes.Select(x => x.EnergyIntensity).Distinct().ToList();

            energyIntensities.Sort((x, y) => string.Compare(x, y, StringComparison.Ordinal));
            series.Sort((x, y) => string.Compare(x.Version, y.Version, StringComparison.Ordinal));
            OxyPalette p = OxyPalettes.Hue64;

            if (series.Count > 1)
            {
                p = OxyPalettes.HueDistinct(series.Count);
            }

            var i = 0;

            for (var index = 0; index < series.Count; index++)
            {
                var seriesEntry = series[index];
                var entrylist   = outcomes
                                  .Where(x => x.EnergyIntensity == seriesEntry.EnergyIntensity &&
                                         x.LPGVersion == seriesEntry.Version)
                                  .ToList();
                var sc1 = new ScatterSeries();
                foreach (var entry in entrylist)
                {
                    sc1.Points.Add(
                        new ScatterPoint(entry.NumberOfPersons + seriesEntry.Offset, entry.ElectricityDouble));
                }

                sc1.Title = seriesEntry.DisplayName;
                var oc = p.Colors[i++];
                sc1.MarkerStroke = OxyColor.FromAColor(128, oc);
                sc1.MarkerFill   = oc;
                if (index == 0)
                {
                    sc1.MarkerType = MarkerType.Diamond;
                }
                else
                {
                    sc1.MarkerType = MarkerType.Star;
                }
                sc1.MarkerStrokeThickness = 1;
                plotModel1.Series.Add(sc1);
            }
            PngExporter.Export(plotModel1, pngfullName, _width, _height, OxyColor.FromRgb(255, 255, 255), _dpi);
            _calculationProfiler.StopPart(Utili.GetCurrentMethodAndClass());
            //ChartPDFCreator.OxyPDFCreator.Run(plotModel1, pdfFullName);
        }
예제 #11
0
        public NetworkStatsWindow()
        {
            InitializeComponent();

            if (ChosenTask == TaskType.Approximation) // number of plots is dependent on type of task
            {
                PlotModels = new PlotModel[2];
            }
            else
            {
                PlotModels = new PlotModel[1];
            }
            #region error of epochs plot (two series - learning and test error) (set on 0 index of PlotModels)
            var epochErrorPlotModel = new PlotModel
            {
                Title           = "Error of epoch",
                IsLegendVisible = true,
            };
            //create learniing erro series
            var learningEpochErrorDataPoints = new List <DataPoint>();
            for (int i = 0; i < Creator.BestNetworkEpochHistory.Count; i++) // adding data
            {
                learningEpochErrorDataPoints.Add(new DataPoint(i, Creator.BestNetworkEpochHistory[i]));
            }
            var learningSeries = new OxyPlot.Series.LineSeries()
            {
                Title    = "Learning set error",
                Smooth   = false,
                LineJoin = LineJoin.Bevel,
            };
            learningSeries.ItemsSource = learningEpochErrorDataPoints;
            epochErrorPlotModel.Series.Add(learningSeries);
            //create test error series
            if (Creator.BestNetworkTestHistory != null)
            {
                var testEpochErrorDataPoints = new List <DataPoint>();
                for (int i = 0; i < Creator.BestNetworkTestHistory.Count; i++) // adding data
                {
                    testEpochErrorDataPoints.Add(new DataPoint(i, Creator.BestNetworkTestHistory[i]));
                }
                var testSeries = new OxyPlot.Series.LineSeries()
                {
                    Title    = "Test set error",
                    Smooth   = false,
                    LineJoin = LineJoin.Bevel,
                };
                testSeries.ItemsSource = testEpochErrorDataPoints;
                epochErrorPlotModel.Series.Add(testSeries);
            }
            //set plot
            PlotModels[0] = epochErrorPlotModel;
            #endregion

            if (ChosenTask == TaskType.Approximation)
            {
                var approximationFunctionPlotModel = new PlotModel
                {
                    Title           = "Network approximation function",
                    IsLegendVisible = true,
                };
                var approximationFunctionDataPoints = new List <DataPoint>();              //network outputs approximation
                for (int i = 0; i < Creator.ApproximationFunctionPoints.GetLength(0); i++) // adding data
                {
                    approximationFunctionDataPoints.Add(new DataPoint(Creator.ApproximationFunctionPoints[i, 0], Creator.ApproximationFunctionPoints[i, 1]));
                }
                var approximationSeries = new OxyPlot.Series.LineSeries()
                {
                    Title      = "Network approximation",
                    Selectable = false
                };
                approximationSeries.ItemsSource = approximationFunctionDataPoints;
                approximationFunctionPlotModel.Series.Add(approximationSeries);
                //set of 'real' points
                var testSet    = Creator.DataProvider.DataSet;
                var testPoints = new List <ScatterPoint>();    //network outputs approximation
                for (int i = 0; i < testSet.GetLength(0); i++) // adding data
                {
                    if (CurrentNetwork.IsBiasExisting)
                    {
                        testPoints.Add(new ScatterPoint(testSet[i].X[1], testSet[i].D[0], 1.5));
                    }
                    else
                    {
                        testPoints.Add(new ScatterPoint(testSet[i].X[0], testSet[i].D[0], 1.5));
                    }
                }
                var testSeries = new OxyPlot.Series.ScatterSeries()
                {
                    Title = "Test points",
                };
                testSeries.ItemsSource = testPoints;
                approximationFunctionPlotModel.Series.Add(testSeries);

                //set of learning points
                var learningSet    = Creator.DataProvider.LearnSet;
                var learningPoints = new List <ScatterPoint>();    //network outputs approximation
                int pointSize      = 2;
                for (int i = 0; i < learningSet.GetLength(0); i++) // adding data
                {
                    if (CurrentNetwork.IsBiasExisting)
                    {
                        learningPoints.Add(new ScatterPoint(learningSet[i].X[1], learningSet[i].D[0], pointSize));
                    }
                    else
                    {
                        learningPoints.Add(new ScatterPoint(learningSet[i].X[0], learningSet[i].D[0], pointSize));
                    }
                }
                var learningPointSeries = new OxyPlot.Series.ScatterSeries()
                {
                    Title = "Learning points",
                };
                learningPointSeries.ItemsSource = learningPoints;
                approximationFunctionPlotModel.Series.Add(learningPointSeries);
                //save created plot to plot models
                PlotModels[1] = approximationFunctionPlotModel;

                var colorBox = new TextBox
                {
                    Background      = new SolidColorBrush(Colors.SteelBlue),
                    BorderThickness = new Thickness(0)
                };

                NetworkStatsMainGrid.Children.Add(colorBox);
                Grid.SetColumn(colorBox, 4);
                Grid.SetColumnSpan(colorBox, 4);
                Grid.SetRow(colorBox, 1);
                Grid.SetRowSpan(colorBox, 3);
            }
            else if (ChosenTask == TaskType.Classification)
            {
                var classGrid = new UniformGrid
                {
                    Rows    = Creator.ClassificationFullResults.RowCount + 1,
                    Columns = Creator.ClassificationFullResults.ColumnCount + 1,
                };

                //No way to set Border on textblock defined in code behind; changing for TextBox is a way to make border but still it doesn't look like a table

                classGrid.Children.Add(new TextBox()
                {
                    BorderThickness = new Thickness(1), Text = "Class number", FontWeight = System.Windows.FontWeights.Bold, VerticalAlignment = System.Windows.VerticalAlignment.Center, TextAlignment = System.Windows.TextAlignment.Center, MinHeight = 50
                });
                for (int columnIndex = 0; columnIndex < Creator.ClassificationFullResults.ColumnCount; columnIndex++) //ceate column names as class number bolded
                {
                    classGrid.Children.Add(new TextBox()
                    {
                        BorderThickness = new Thickness(1), Text = columnIndex.ToString(), FontWeight = System.Windows.FontWeights.Bold, VerticalAlignment = System.Windows.VerticalAlignment.Center, TextAlignment = System.Windows.TextAlignment.Center, MinHeight = 50
                    });
                }
                for (int rowIndex = 0; rowIndex < Creator.ClassificationFullResults.RowCount; rowIndex++)
                {
                    classGrid.Children.Add(new TextBox()
                    {
                        BorderThickness = new Thickness(1), Text = rowIndex.ToString(), FontWeight = System.Windows.FontWeights.Bold, VerticalAlignment = System.Windows.VerticalAlignment.Center, TextAlignment = System.Windows.TextAlignment.Center, MinHeight = 50
                    });                                                                                                                                                                                                                                                                                        //add row name = class number bolded
                    for (int columnIndex = 0; columnIndex < Creator.ClassificationFullResults.ColumnCount; columnIndex++)
                    {
                        classGrid.Children.Add(new TextBox()
                        {
                            BorderThickness = new Thickness(1), Text = Creator.ClassificationFullResults[rowIndex, columnIndex].ToString(), VerticalAlignment = System.Windows.VerticalAlignment.Center, TextAlignment = System.Windows.TextAlignment.Center, MinHeight = 50
                        });
                    }
                }

                NetworkStatsMainGrid.Children.Add(classGrid);
                Grid.SetColumn(classGrid, 4);
                Grid.SetColumnSpan(classGrid, 4);
                Grid.SetRow(classGrid, 1);
                Grid.SetRowSpan(classGrid, 3);
            }
        }
        /// <summary>
        /// The mobility fit FitLine plot.
        /// </summary>
        /// <param name="fitline">
        /// The fitline.
        /// </param>
        /// <returns>
        /// The <see cref="PlotModel"/>.
        /// </returns>
        private PlotModel MobilityFitLinePlot(FitLine fitline)
        {
            IEnumerable<ContinuousXYPoint> fitPointList = fitline.FitPointCollection.Select(x => x.Point);
            IEnumerable<ContinuousXYPoint> outlierList = fitline.OutlierCollection.Select(x => x.Point);
            Func<object, ScatterPoint> fitPointMap = obj =>
            {
                ContinuousXYPoint point = (ContinuousXYPoint)obj;
                double size = 5;
                double color = 0;
                ScatterPoint sp = new ScatterPoint(point.X, point.Y, size, color);
                return sp;
            };

            Func<object, ScatterPoint> OutlierPointMap = obj =>
            {
                ContinuousXYPoint point = (ContinuousXYPoint)obj;
                double size = 5;
                double color = 1;
                ScatterPoint sp = new ScatterPoint(point.X, point.Y, size, color);
                return sp;
            };

            PlotModel model = new PlotModel();
            model.TitlePadding = 0;
            model.Title = "Mobility Fit FitLine";

            ScatterSeries fitPointSeries = new ScatterSeries
            {
                Mapping = fitPointMap,
                ItemsSource = fitPointList,
            };

            ScatterSeries outlierSeries = new ScatterSeries
            {
                Mapping = OutlierPointMap,
                ItemsSource = outlierList,
            };

            Func<object, DataPoint> lineMap = obj =>
            {
                ContinuousXYPoint point = (ContinuousXYPoint)obj;
                double x = point.X;
                double y = fitline.ModelPredictX2Y(x);
                DataPoint sp = new DataPoint(x, y);
                return sp;
            };

            LineSeries fitlineSeries = new LineSeries()
            {
                Mapping = lineMap,
                ItemsSource = fitPointList,
                Color = OxyColors.Purple
            };

            var yAxis = new LinearAxis()
            {
                Title = "IMS scan time (milliseconds)",
                MajorGridlineStyle = LineStyle.Solid,
                Position = AxisPosition.Left,

                //MajorStep = 100.0,
                //MinorStep = 50.0,
                //Minimum = 0,
                //Maximum = 360,
                //FilterMinValue = 0,
                //FilterMaxValue = 360,
            };

            var xAxis = new LinearAxis()
            {
                Title = "Pressure / (Temperature * Voltage) (1 / V))",
                Position = AxisPosition.Bottom,
                MajorGridlineStyle = LineStyle.Solid,
                //MajorStep = 100.0,
                //MinorStep = 50.0,
                //Minimum = 1000,
                //Maximum = 2000,
                //MinimumRange = 100.0,
                //FilterMinValue = 1000,
                //FilterMaxValue = 2000,
            };

            model.Axes.Add(yAxis);
            model.Axes.Add(xAxis);
            model.Series.Add(fitPointSeries);
            model.Series.Add(outlierSeries);
            model.Series.Add(fitlineSeries);
            return model;
        }
        /// <summary>
        /// The association hypothesis plot.
        /// </summary>
        /// <param name="hypothesis">
        /// The hypothesis.
        /// </param>
        /// <param name="datasetName">
        /// The dataset name.
        /// </param>
        /// <param name="targetDescriptor">
        /// The target descriptor.
        /// </param>
        /// <returns>
        /// The <see cref="PlotModel"/>.
        /// </returns>
        private PlotModel AssociationHypothesisPlot(AssociationHypothesis hypothesis, string datasetName, IImsTarget target, bool plotXAxisFromZero = false)
        {
            PlotModel model = new PlotModel();

            model.LegendBorderThickness = 0;
            model.LegendOrientation = LegendOrientation.Vertical;
            model.LegendPlacement = LegendPlacement.Inside;
            model.LegendPosition = LegendPosition.LeftTop;

            model.TitlePadding = 0;
            model.Title = "Optimal Association Hypothesis Plot";
            model.Subtitle = string.Format("Target: {0}, dataset: {1}", target.TargetDescriptor, datasetName) ;

            model.Axes.Add(
                new LinearAxis
                    {
                        Title = "IMS arrival time (milliseconds)",
                        MajorGridlineStyle = LineStyle.Solid,
                        Position = AxisPosition.Left,
                    });

            model.Axes.Add(
                new LinearAxis
                    {
                        Title = "P/(T*V) with P and T nondimensionalized (1/V)",
                        Position = AxisPosition.Bottom,
                        MajorGridlineStyle = LineStyle.Solid,
                    });

            // Add all the points
            IEnumerable<ObservedPeak> onTrackPeaks = hypothesis.OnTrackObservations;
            IEnumerable<ObservedPeak> offTrackPeaks = hypothesis.AllObservations.Where(x => !hypothesis.IsOnTrack(x));

            Func<ObservedPeak, ScatterPoint> fitPointMap = obj =>
            {
                ObservedPeak observation = obj;
                ContinuousXYPoint xyPoint = observation.ToContinuousXyPoint(false, 0);
                double size = MapToPointSize(observation);
                ScatterPoint sp = new ScatterPoint(xyPoint.X, xyPoint.Y, size);
                return sp;
            };

            var ontrackSeries= new ScatterSeries
            {
                Title = "[Peaks On Tracks]",
                MarkerFill = OxyColors.BlueViolet,
                MarkerType = MarkerType.Circle
            };

            var offtrackSeries= new ScatterSeries
            {
                Title = "[Peaks Off Tracks]",
                MarkerFill = OxyColors.Red,
                MarkerType = MarkerType.Circle
            };

            ontrackSeries.Points.AddRange(onTrackPeaks.Select(x => fitPointMap(x)));

            offtrackSeries.Points.AddRange(offTrackPeaks.Select(x => fitPointMap(x)));

            model.Series.Add(ontrackSeries);

            model.Series.Add(offtrackSeries);

            var allTracks = hypothesis.Tracks;

            // Add the tracks as linear axes
            int count = 1;
            foreach (var track in allTracks)
            {
                FitLine fitline = track.FitLine;
                LineAnnotation annotation = new LineAnnotation();
                annotation.Slope = fitline.Slope;
                annotation.Intercept = fitline.Intercept;
                annotation.TextPadding = 3;
                annotation.TextMargin = 2;
                annotation.Text = string.Format("Conformer {0} - mz: {1:F2}; ccs: {2:F2}, Isotopic Score: {3:F3}; Track Probability: {4:F2}; R2: {5:F5};",
                    count, track.AverageMzInDalton, track.GetMobilityInfoForTarget(target).CollisionCrossSectionArea, track.TrackStatistics.IsotopicScore, track.TrackProbability, track.FitLine.RSquared);
                count++;
                model.Annotations.Add(annotation);
                //Func<object, DataPoint> lineMap = obj =>
                //{
                //    ObservedPeak observation = (ObservedPeak)obj;
                //    ContinuousXYPoint xyPoint = observation.ToContinuousXyPoint();
                //    double x = xyPoint.X;
                //    double y = fitline.ModelPredictX2Y(x);
                //    DataPoint sp = new DataPoint(x, y);
                //    return sp;
                //};

                //model.Series.Add(new LineSeries()
                //{
                //    Mapping = lineMap,
                //    ItemsSource = track.ObservedPeaks,
                //    Color = OxyColors.Purple
                //});
            }

            return model;
        }
예제 #14
0
파일: Old.cs 프로젝트: benketriel/sknn
        //Solutions
        private void LinearRegression()
        {
            var data = Matrix.Build.DenseOfRows(
                File.ReadAllLines(@"C:\SK\Programming\VSProjects\Stuff\Files\stanford_dl_ex-master\ex1\housing.data")
                .Select(l => l.Split(' ').Where(x => x.Any()).Select(double.Parse)));

            PermuteRows(data);
            InsertOnesColumn(ref data);

            int trainNum = (int)(data.RowCount * 0.80);
            int featNum = data.Row(0).Count - 1;

            var train = data.SubMatrix(0, trainNum, 0, data.ColumnCount);
            var test = data.SubMatrix(trainNum, data.RowCount - trainNum, 0, data.ColumnCount);

            train = DenseMatrix.OfRows(train.EnumerateRows().OrderBy(row => row.Last()));
            test = DenseMatrix.OfRows(test.EnumerateRows().OrderBy(row => row.Last()));

            var X = train.SubMatrix(0, train.RowCount, 0, featNum);
            var y = train.Column(featNum);
            var theta = Vector.Build.Dense(featNum);
            theta = (X.Transpose() * X).Inverse() * X.Transpose() * y;

            {
                var s1 = new ScatterSeries() { Title = "Test Solution", MarkerSize = 1, };
                s1.Points.AddRange(Enumerable.Range(0, test.RowCount).Select(i => new ScatterPoint(i, test.Row(i).Last())));

                var s2 = new ScatterSeries() { Title = "Test Guess", MarkerSize = 1, };
                s2.Points.AddRange(Enumerable.Range(0, test.RowCount).Select(i => new ScatterPoint(i, test.Row(i).SubVector(0, featNum) * theta)));

                var s3 = new ScatterSeries() { Title = "Test Error", MarkerSize = 1, };
                s3.Points.AddRange(Enumerable.Range(0, test.RowCount).Select(i => new ScatterPoint(i, Math.Abs(s1.Points[i].Y - s2.Points[i].Y))));

                Console.WriteLine("Test error: " + s3.Points.Select(p => p.Y).Sum() / s3.Points.Count());

                new Plotter("Test", s1, s2, s3);
            }

            {
                var s1 = new ScatterSeries() { Title = "Train Solution", MarkerSize = 1, };
                s1.Points.AddRange(Enumerable.Range(0, train.RowCount).Select(i => new ScatterPoint(i, train.Row(i).Last())));

                var s2 = new ScatterSeries() { Title = "Train Guess", MarkerSize = 1, };
                s2.Points.AddRange(Enumerable.Range(0, train.RowCount).Select(i => new ScatterPoint(i, train.Row(i).SubVector(0, featNum) * theta)));

                var s3 = new ScatterSeries() { Title = "Train Error", MarkerSize = 1, };
                s3.Points.AddRange(Enumerable.Range(0, train.RowCount).Select(i => new ScatterPoint(i, Math.Abs(s1.Points[i].Y - s2.Points[i].Y))));

                Console.WriteLine("Train error: " + s3.Points.Select(p => p.Y).Sum() / s3.Points.Count());

                new Plotter("Train", s1, s2, s3);
            }

            Func<Vector<double>, double> error = row => theta * row.SubVector(0, featNum) - row[featNum];

            Func<double> J = () => train.EnumerateRows().Select(error).Sum(err => 0.5 * err * err);

            Func<Vector<double>> Grad = () => Vector.Build.DenseOfEnumerable(Enumerable.Range(0, featNum)
                .Select(_ => train.EnumerateRows().Sum(row => row[_] * error(row))));

            var j = J();
            var g = Grad();
        }
예제 #15
0
파일: Old.cs 프로젝트: benketriel/sknn
        private void LogicRegression()
        {
            Console.WriteLine("Loading files");
            var trainX = Matrix.Build.DenseOfRows(MNIST.LoadImages(@"C:\SK\Programming\VSProjects\Stuff\Files\data\common\train-images-idx3-ubyte"));
            var trainY = Vector.Build.Dense(MNIST.LoadLabels(@"C:\SK\Programming\VSProjects\Stuff\Files\data\common\train-labels-idx1-ubyte"));
            var testX = Matrix.Build.DenseOfRows(MNIST.LoadImages(@"C:\SK\Programming\VSProjects\Stuff\Files\data\common\t10k-images-idx3-ubyte"));
            var testY = Vector.Build.Dense(MNIST.LoadLabels(@"C:\SK\Programming\VSProjects\Stuff\Files\data\common\t10k-labels-idx1-ubyte"));
            Console.WriteLine("Learning");

            var EPSILON = 0.00000000001;

            var train = trainX.InsertColumn(trainX.ColumnCount, trainY);
            train = DenseMatrix.OfRows(train.EnumerateRows().Where(row => row.Last() <= 1.0).ToList());
            InsertOnesColumn(ref train);

            var test = testX.InsertColumn(testX.ColumnCount, testY);
            test = DenseMatrix.OfRows(test.EnumerateRows().Where(row => row.Last() <= 1.0).ToList());
            InsertOnesColumn(ref test);

            int featNum = train.Row(0).Count - 1;
            var theta = Vector.Build.Dense(featNum);

            Func<Vector<double>, Vector<double>, double> h = (th, x) => 1 / (1 + Math.Exp(-th * x));

            Func<Vector<double>, double> J = th => -train.EnumerateRows().Sum(row =>
            {
                var hval = h(th, row.SubVector(0, featNum));
                var res = 0.0;

                if (row[featNum] == 1.0)
                {
                    if (hval == 0.0)
                    {
                        res += 1.0 / EPSILON;
                    }
                    else
                    {
                        res += -Math.Log(hval);
                    }
                }

                if (row[featNum] == 0.0)
                {
                    if (1 - hval == 0.0)
                    {
                        res += 1.0 / EPSILON;
                    }
                    else
                    {
                        res += -Math.Log(1 - hval);
                    }
                }
                return res;
            }
            );

            Func<Vector<double>, Vector<double>> Grad = th =>
            {
                var sum = Vector.Build.Dense(featNum);
                foreach (var row in train.EnumerateRows())
                {
                    var xi = row.SubVector(0, featNum);
                    var yi = row[featNum];
                    sum += xi * (h(th, xi) - yi);
                }
                return sum;
            };

            theta = FindMin(J, theta, Grad);

            {
                var s1 = new ScatterSeries() { Title = "Test Solution", MarkerSize = 1, };
                s1.Points.AddRange(Enumerable.Range(0, test.RowCount).Select(i => new ScatterPoint(i, test.Row(i).Last())));

                var s2 = new ScatterSeries() { Title = "Test Guess", MarkerSize = 1, };
                s2.Points.AddRange(Enumerable.Range(0, test.RowCount).Select(i => new ScatterPoint(i, h(theta, test.Row(i).SubVector(0, featNum)) > 0.5 ? 1.0 : 0.0)));

                var s3 = new ScatterSeries() { Title = "Test Error", MarkerSize = 1, };
                s3.Points.AddRange(Enumerable.Range(0, test.RowCount).Select(i => new ScatterPoint(i, Math.Abs(s1.Points[i].Y - s2.Points[i].Y))));

                Console.WriteLine("Test error: " + s3.Points.Select(p => p.Y).Sum() / s3.Points.Count());

                new Plotter("Test", s1, s2, s3);
            }

            {
                var s1 = new ScatterSeries() { Title = "Train Solution", MarkerSize = 1, };
                s1.Points.AddRange(Enumerable.Range(0, train.RowCount).Select(i => new ScatterPoint(i, train.Row(i).Last())));

                var s2 = new ScatterSeries() { Title = "Train Guess", MarkerSize = 1, };
                s2.Points.AddRange(Enumerable.Range(0, train.RowCount).Select(i => new ScatterPoint(i, h(theta, train.Row(i).SubVector(0, featNum)) > 0.5 ? 1.0 : 0.0)));

                var s3 = new ScatterSeries() { Title = "Train Error", MarkerSize = 1, };
                s3.Points.AddRange(Enumerable.Range(0, train.RowCount).Select(i => new ScatterPoint(i, Math.Abs(s1.Points[i].Y - s2.Points[i].Y))));

                Console.WriteLine("Train error: " + s3.Points.Select(p => p.Y).Sum() / s3.Points.Count());

                new Plotter("Train", s1, s2, s3);
            }
        }
예제 #16
0
        private void CreateMdsChartModel()
        {
            var model = new PlotModel();

            var xAxis = new OxyPlot.Axes.LinearAxis
            {
                Position = OxyPlot.Axes.AxisPosition.Bottom,
                MajorGridlineStyle = LineStyle.None
            };
            model.Axes.Add(xAxis);

            var yAxis = new OxyPlot.Axes.LinearAxis
            {
                Position = OxyPlot.Axes.AxisPosition.Left,
                MajorGridlineStyle = LineStyle.None
            };
            model.Axes.Add(yAxis);

            var series = new OxyPlot.Series.ScatterSeries
            {
                ItemsSource = (Data.MdsCoords.Rows.Cast<filterReportDS.MdsCoordsRow>()
                    .Select(dr => new DataPoint(dr.X, dr.Y))),
                DataFieldX = "X",
                DataFieldY = "Y",
                MarkerType = MarkerType.Circle,
                MarkerSize = 2,
                MarkerFill = OxyColor.FromRgb(79, 129, 189)
            };

            model.Series.Add(series);

            foreach(filterReportDS.MdsCoordsRow dr in Data.MdsCoords.Rows)
            {
                var annotation = new OxyPlot.Annotations.TextAnnotation
                {
                    Text = dr.StrategyName,
                    TextPosition = new DataPoint(dr.X, dr.Y),
                    TextHorizontalAlignment = OxyPlot.HorizontalAlignment.Center,
                    TextVerticalAlignment = OxyPlot.VerticalAlignment.Top,
                    Font = "Segoe UI",
                    TextColor = OxyColor.FromRgb(0, 0, 0),
                    StrokeThickness = 0
                };

                model.Annotations.Add(annotation);
            }

            MdsChartModel = model;
        }
예제 #17
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Inclination_Calc       sine_fit = new Inclination_Calc();
            LineFitting            line_fit = new LineFitting();
            Tuple <double, double> points;

            //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(@"C:\Users\Test3\source\repos\PrintedImageBooth\python\precession measurement new baumer location\1.bmp");
            //points = line_fit.fit_Baumer_Image(bmp);

            for (int i = 0; i < 16; i++)
            {
                //System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(@"C:/Users/Test3/source/repos/PrintedImageBooth/python/precession_image_" + (i + 1) + ".bmp");
                //points = line_fit.fit_metrology_booth(bmp);

                System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(@"C:\Users\Test3\source\repos\PrintedImageBooth\python\precession measurement new baumer location\" + (i + 1) + ".bmp");
                points = line_fit.fit_Baumer_Image(bmp);

                Console.WriteLine(points.Item1);
                Console.WriteLine(points.Item2);

                Ypoint1_list.Add(points.Item1);
                Ypoint2_list.Add(points.Item2);
            }

            //double[] Angle = { 0, 22.5, 45, 67.5, 90, 112.5, 135, 157.5, 180, 202.5, 225, 247.5, 270, 292.5, 315, 337.5 };
            //double[] Angle_Rad = { 0, 0.3926991, 0.785398, 1.178097, 1.5708, 1.9634954, 2.35619, 2.7488936, 3.14159, 3.5342917, 3.92699, 4.3196899, 4.71239, 5.1050881, 5.49779, 5.8904862 };
            //double[] Ypoint1 = { 1853.81529, 1847.660185, 1844.26392, 1844.565391, 1850.022335, 1853.779641, 1861.10121, 1869.905686, 1876.988192, 1882.889382, 1886.051181, 1886.038851, 1885.149105, 1876.565114, 1868.736134, 1860.421681 };
            //double[] Ypoint2 = { 1853.248, 1846.372287, 1843.176348, 1843.989568, 1850.517779, 1857.074984, 1867.463348, 1878.007069, 1887.979784, 1895.239886, 1898.598238, 1897.837502, 1894.264412, 1883.825911, 1873.735975, 1862.378465 };



            double inclination_angle;
            Func <double, double> sinewave;
            Func <double, double> sinewave_2;

            Ypoint1 = Ypoint1_list.ToArray();
            Ypoint2 = Ypoint2_list.ToArray();

            Tuple <double, Func <double, double>, Func <double, double>, Func <double, double> > tuple_return = sine_fit.fit_sinewave(Angle_Rad, Ypoint1, Ypoint2);

            //Inclination_angle = tuple_return.Item1;

            var line1 = new OxyPlot.Series.ScatterSeries();
            var line2 = new OxyPlot.Series.ScatterSeries();

            for (int i = 0; i < Angle_Rad.Length; i++)
            {
                line1.Points.Add(new ScatterPoint(Angle_Rad[i], Ypoint1[i]));
                line2.Points.Add(new ScatterPoint(Angle_Rad[i], Ypoint2[i]));
            }

            var myModel = new PlotModel {
                Title = "Inclination"
            };

            myModel.Series.Add(line1);
            myModel.Series.Add(line2);

            //myModel.Series.Add(new FunctionSeries(Math.Cos, 0, 10, 0.1, "cos(x)"));
            myModel.Series.Add(new FunctionSeries(tuple_return.Item2, 0, 2 * Math.PI, 0.1, "lower"));
            myModel.Series.Add(new FunctionSeries(tuple_return.Item3, 0, 2 * Math.PI, 0.1, "upper"));
            // myModel.Series.Add(new FunctionSeries(batFn2, 0, 360, 0.1, "linear"));

            var textAnnotation = new TextAnnotation
            {
                Text         = "Angle: " + Math.Round(tuple_return.Item1, 6).ToString(),
                TextPosition = new DataPoint(1, 1890),
                FontSize     = 20
            };

            myModel.Annotations.Add(textAnnotation);

            this.plotView1.Model = myModel;
        }
        private void InitializeGraph()
        {
            PlotModel plot = new PlotModel();

            OxyPlot.Axes.LinearAxis costAxis = new OxyPlot.Axes.LinearAxis(AxisPosition.Left);
            costAxis.Key = "cost";
            OxyPlot.Axes.LinearAxis progressionAxis = new OxyPlot.Axes.LinearAxis(AxisPosition.Right);
            progressionAxis.Key = "progression";

            plot.Axes.Add(costAxis); 
            plot.Axes.Add(progressionAxis);
            plot.Axes.Add(new OxyPlot.Axes.LinearAxis(AxisPosition.Bottom));

            OxyPlot.Series.ScatterSeries costSeries = new OxyPlot.Series.ScatterSeries();
            costSeries.YAxisKey = "cost";
            OxyPlot.Series.StairStepSeries progressionSeries = new OxyPlot.Series.StairStepSeries(OxyColor.FromRgb(0, 255, 0), LINES_THICKNESS, "Poprawa");
            progressionSeries.YAxisKey = "progression";
            OxyPlot.Series.StairStepSeries regressionSeries = new OxyPlot.Series.StairStepSeries(OxyColor.FromRgb(255, 0, 0), LINES_THICKNESS, "Pogorszenie");
            regressionSeries.YAxisKey = "progression";

            plot.Series.Add(costSeries);
            plot.Series.Add(progressionSeries);
            plot.Series.Add(regressionSeries);

            VM.GraphPlotModel = plot;
        }
        public void UpdateChart()
        {
            if (Thread.CurrentThread != Dispatcher.Thread)
            {
                Dispatcher.BeginInvoke(new Action(UpdateChart));
                return;
            }

            //--- remove all series
            PlotViewModel.Series.Clear();
            while (Drawer.Candles.MoveNext())
            {
                this.Candles.Items.Add(new ChartBar(Drawer.Candles.Current));
                this.Volumes.Items.Add(new ChartBarVol(Drawer.Candles.Current)
                {
                });
            }

            //create exes
            CreateAxes();

            //---
            if (Candles.Items.Count > 0)
            {
                PlotViewModel.Series.Add(Candles);
                PlotViewModel.Series.Add(Volumes);
                //draw volumes
                //PlotViewModel.Series.Add(Volumes);
            }

            //-----------------  HORIZONTAL LINES --------------
            var levels = new List <double>(Drawer.HorizontalLines);

            levels.Sort();
            for (int l = 1; l < levels.Count; l++)
            {
                if (levels[l] - levels[l - 1] < 0.00001)
                {
                    levels[l] = levels[l - 1] + 0.00001;
                }
            }

            foreach (var level in levels)
            {
                //if (level < range.High + range.Length && level > range.Low - range.Length)
                {
                    LineSeriesEx line = new LineSeriesEx(false)
                    {
                        MarkerStrokeThickness = 1,
                        LineStyle             = LineStyle.Solid,
                        Color           = OxyColor.FromArgb(200, 1, 1, 200),
                        StrokeThickness = 0.5f,
                    };

                    line.Points.Add(new DataPoint(0, level));
                    line.Points.Add(new DataPoint(PlotViewModel.Axes[0].Maximum - 1, level));
                    PlotViewModel.Series.Add(line);
                }
            }

            //----------------- lines ----------------------
            this.Lines.Clear();
            foreach (var line in Drawer.Lines.Concat(Drawer.VerticalLines))
            {
                var          ingnoreZoom = Drawer.VerticalLines.Contains(line);
                LineSeriesEx lineserie   = new LineSeriesEx(ingnoreZoom)
                {
                    MarkerStrokeThickness = 2,
                    LineStyle             = LineStyle.Solid,
                    Color           = OxyColor.FromArgb(line.Color.A, line.Color.R, line.Color.G, line.Color.B),
                    StrokeThickness = 3f,
                    YAxisKey        = line.AxisId ?? this.Candles_Yaxis.Key
                };

                lineserie.Points.AddRange(
                    line.Points.Select(dot => new DataPoint(dot.X.ToAxisDouble(), dot.Y)));
                PlotViewModel.Series.Add(lineserie);
                this.Lines.Add(lineserie);
            }

            //-------plot points ---------------
            var pointsSerie = new OxyPlot.Series.ScatterSeries()
            {
                MarkerSize = 15, MarkerType = MarkerType.Circle
            };

            for (int p = 0; p < Drawer.Points.Count; p++)
            {
                pointsSerie.Points.Add(
                    new ScatterPoint(Drawer.Points[p].Time.ToAxisDouble(), Drawer.Points[p].Value, 5));
            }
            PlotViewModel.Series.Add(pointsSerie);

            //---------- ADJUST X to show 100 candles

            PlotViewModel.Axes[0].Minimum = Drawer.InitialView.start.ToAxisDouble();
            PlotViewModel.Axes[0].Maximum = Drawer.InitialView.end.ToAxisDouble();
            PlotViewModel.Axes[0].Reset();


            //--------- ADJUST Y
            AdjustYAxisZoom();
            PlotViewModel.InvalidatePlot(true);
            return;
        }
예제 #20
0
파일: Old.cs 프로젝트: benketriel/sknn
        private void SoftMax()
        {
            Console.WriteLine("Loading files");
            var trainX = Matrix.Build.DenseOfRows(MNIST.LoadImages(@"C:\SK\Programming\VSProjects\Stuff\Files\data\common\train-images-idx3-ubyte"));
            var trainY = Vector.Build.Dense(MNIST.LoadLabels(@"C:\SK\Programming\VSProjects\Stuff\Files\data\common\train-labels-idx1-ubyte"));
            var testX = Matrix.Build.DenseOfRows(MNIST.LoadImages(@"C:\SK\Programming\VSProjects\Stuff\Files\data\common\t10k-images-idx3-ubyte"));
            var testY = Vector.Build.Dense(MNIST.LoadLabels(@"C:\SK\Programming\VSProjects\Stuff\Files\data\common\t10k-labels-idx1-ubyte"));
            Console.WriteLine("Learning");

            var EPSILON = 0.00001;

            var train = trainX.InsertColumn(trainX.ColumnCount, trainY);
            train = train.SubMatrix(0, train.RowCount, 0, train.ColumnCount);
            //train = DenseMatrix.OfRows(train.EnumerateRows().Where(row => row.Last() <= 1.0).ToList());
            //InsertOnesColumn(ref train);

            var test = testX.InsertColumn(testX.ColumnCount, testY);
            //test = DenseMatrix.OfRows(test.EnumerateRows().Where(row => row.Last() <= 1.0).ToList());
            //InsertOnesColumn(ref test);

            int featNum = train.Row(0).Count - 1;
            int choiceNum = 10;
            var theta = Matrix.Build.Dense(featNum, choiceNum);
            var r = new Random(1234);
            theta = theta.Map(x => r.NextDouble() * EPSILON);

            Func<Matrix<double>, Vector<double>, Vector<double>> h = (th, x) => (th.Transpose() * x).Map(Math.Exp).Normalize(1.0);

            Func<Matrix<double>, double> J = th =>
            {
                double sum = 0;
                object l = new { };
                Parallel.ForEach(train.EnumerateRows(), row =>
                {
                    var hmul = h(th, row.SubVector(0, featNum));
                    int yi = (int)row[featNum]; //Assumes the y values are exactly from 0 to choiceNum-1
                    double hval = hmul[yi];

                    lock (l)
                    {
                        sum += -(hval == 0.0 ? -1 / EPSILON : Math.Log(hval));
                    }
                });
                return sum;
            };

            Func<Matrix<double>, Matrix<double>> Grad = th =>
            {
                var mat = new Vector<double>[choiceNum];
                for (int i = 0; i < mat.Length; ++i)
                {
                    mat[i] = Vector.Build.Dense(featNum);
                }

                Parallel.ForEach(train.EnumerateRows(), row =>
                {
                    var xi = row.SubVector(0, featNum);
                    var hmul = h(th, xi);
                    int yi = (int)row[featNum];

                    for (int k = 0; k < choiceNum; ++k)
                    {
                        lock (mat)
                        {
                            mat[k] += xi * (hmul[k] - (yi == k ? 1.0 : 0.0));
                        }
                    }
                });

                return Matrix.Build.DenseOfColumns(mat);
            };

            theta = FindMin(J, theta, Grad, 100);
            Func<Vector<double>, int, double> guess = (row, i) =>
            {
                var xi = row.SubVector(0, featNum);
                var hmul = h(theta, xi);
                return (double)hmul.MaximumIndex();
            };

            {
                var s1 = new ScatterSeries() { Title = "Test Solution", MarkerSize = 10, };
                s1.Points.AddRange(Enumerable.Range(0, test.RowCount).Select(i => new ScatterPoint(i, test.Row(i).Last())));

                var s2 = new ScatterSeries() { Title = "Test Guess", MarkerSize = 10, };

                s2.Points.AddRange(Enumerable.Range(0, test.RowCount).Select(i => new ScatterPoint(i, guess(test.Row(i), i))));

                var s3 = new ScatterSeries() { Title = "Test Error", MarkerSize = 10, };
                s3.Points.AddRange(Enumerable.Range(0, test.RowCount).Select(i => new ScatterPoint(i, s1.Points[i].Y == s2.Points[i].Y ? 0.0 : 1.0)));

                Console.WriteLine("Test error: " + s3.Points.Select(p => p.Y).Sum() / s3.Points.Count());

                new Plotter("Test", s1, s2, s3);
            }

            {
                var s1 = new ScatterSeries() { Title = "Train Solution", MarkerSize = 10, };
                s1.Points.AddRange(Enumerable.Range(0, train.RowCount).Select(i => new ScatterPoint(i, train.Row(i).Last())));

                var s2 = new ScatterSeries() { Title = "Train Guess", MarkerSize = 10, };
                s2.Points.AddRange(Enumerable.Range(0, train.RowCount).Select(i => new ScatterPoint(i, guess(train.Row(i), i))));

                var s3 = new ScatterSeries() { Title = "Train Error", MarkerSize = 10, };
                s3.Points.AddRange(Enumerable.Range(0, train.RowCount).Select(i => new ScatterPoint(i, s1.Points[i].Y == s2.Points[i].Y ? 0.0 : 1.0)));

                Console.WriteLine("Train error: " + s3.Points.Select(p => p.Y).Sum() / s3.Points.Count());

                new Plotter("Train", s1, s2, s3);
            }
        }
        private PlotModel AnnotateRemovedPeaks(PlotModel associationHypothsisPlot, IDictionary<string, IList<ObservedPeak>> preFilteredPeaks)
        {
            Func<ObservedPeak, ScatterPoint> fitPointMap = obj =>
            {
                ObservedPeak observation = obj;
                ContinuousXYPoint xyPoint = observation.ToContinuousXyPoint(false, 0);
                double size = MapToPointSize(observation);
                ScatterPoint sp = new ScatterPoint(xyPoint.X, xyPoint.Y, size);
                return sp;
            };

            foreach (KeyValuePair<string, IList<ObservedPeak>> pair in preFilteredPeaks)
            {
                string rejectionReason = pair.Key;
                IEnumerable<ObservedPeak> peaks = pair.Value;

                ScatterSeries series = new ScatterSeries
                {
                    Title = rejectionReason,
                    MarkerType = MarkerType.Circle
                };

                associationHypothsisPlot.Series.Add(series);
                series.Points.AddRange(peaks.Select(x => fitPointMap(x)));
            }

            return associationHypothsisPlot;
        }
예제 #22
0
 /// <summary>
 /// Initializes a new instance of the <see cref = "ScatterSeries{T}" /> class.
 /// </summary>
 protected ScatterSeries()
 {
     InternalSeries = new OxyPlot.Series.ScatterSeries();
 }