public void SetText(String text, Fit fit)
        {
            this.name = text;

            switch (fit)
            {
                case Fit.AlignLeft:
                    AlignLeft();
                    break;
                case Fit.AlignCenter:
                    CenterLabel();
                    break;
                case Fit.AlignRight:
                    AlignRight();
                    break;
                case Fit.Stretch:
                    StretchLabel();
                    break;
            }
        }
Example #2
0
        public FitData CalcFit(List <DataPoint> points)
        {
            FitData result           = new FitData("Power function");
            var     xdata            = points.Select(x => x.X).ToArray();
            var     ydata            = points.Select(x => x.Y).ToArray();
            Tuple <double, double> p = Fit.Power(xdata, ydata);

            result.A = p.Item1;
            result.B = p.Item2;

            result.Points = DataPoints(points).ToList();

            return(result);

            //local function for return list of regresion Points[need to C# 8]
            IEnumerable <DataPoint> DataPoints(List <DataPoint> points)
            {
                foreach (var point in points)
                {
                    yield return(new DataPoint(point.X, result.A * Math.Exp(result.B * point.X)));
                }
            }
        }
Example #3
0
        public void FitsToBestLineThroughOrigin()
        {
            // Mathematica: Fit[{{1,4.986},{2,2.347},{3,2.061},{4,-2.995},{5,-2.352},{6,-5.782}}, {x}, x]
            // -> -0.467791 x

            var x = Enumerable.Range(1, 6).Select(Convert.ToDouble).ToArray();
            var y = new[] { 4.986, 2.347, 2.061, -2.995, -2.352, -5.782 };

            var resp = Fit.LineThroughOrigin(x, y);

            Assert.AreEqual(-0.467791, resp, 1e-4);

            var resf = Fit.LineThroughOriginFunc(x, y);

            foreach (var z in Enumerable.Range(-3, 10))
            {
                Assert.AreEqual(-0.467791 * z, resf(z), 1e-4);
            }

            var respSeq = SimpleRegression.FitThroughOrigin(Generate.Map2(x, y, Tuple.Create));

            Assert.AreEqual(-0.467791, respSeq, 1e-4);
        }
Example #4
0
        public void SetText(String text, Fit fit)
        {
            this.name = text;

            switch (fit)
            {
            case Fit.AlignLeft:
                AlignLeft();
                break;

            case Fit.AlignCenter:
                CenterLabel();
                break;

            case Fit.AlignRight:
                AlignRight();
                break;

            case Fit.Stretch:
                StretchLabel();
                break;
            }
        }
Example #5
0
            protected void doFit(Measurements hi, Measurements med, Measurements low)
            {
                // Voltages need to be shifted for calibration constants to be correct.
                double[] voltageX = { Vhi.setting + 4.096, Vmed.setting + 4.096, Vlow.setting + 4.096 };
                double[] voltageY = { Vhi.average + 4.096, Vmed.average + 4.096, Vlow.average + 4.096 };
                Tuple <double, double> fitParams = Fit.Line(voltageX, voltageY);

                gain    = fitParams.Item2;
                offset  = fitParams.Item1;
                gainInt = (UInt16)(fitParams.Item2 * 32768);
                // offsetInt is a 12-bit 2's compliment integer.
                // The sign needs to be reversed for it to be applied correctly.
                if (offset < 0)
                {
                    offsetInt = (UInt16)(-fitParams.Item1 * 500);
                }
                else
                {
                    offsetInt = (UInt16)(4096 - fitParams.Item1 * 500);
                }
                string slope     = gainInt.ToString("X");
                string intercept = offsetInt.ToString("X");
            }
        /// https://numerics.mathdotnet.com/Regression.html#Linearizing-non-linear-models-by-transformation
        /// https://github.com/mathnet/mathnet-numerics/blob/master/src/Numerics/Fit.cs
        /// https://discuss.mathdotnet.com/t/exponential-fit/131/2
        /// https://discuss.mathdotnet.com/t/curve-fitting-power/605
        /// Power function: y = a * (x ^ b)
        private void ApplyPowerFunctionFitting()
        {
            double[] x = Points.Select(p => p.X).ToArray();
            double[] y = Points.Select(p => p.Y).ToArray();
            Tuple <double, double> p = Fit.Power(x, y); // a=1.017, r=0.687

            A = p.Item1;
            B = p.Item2;

            Func <double, double> f = Fit.LinearCombinationFunc(
                Points.Select(p => p.X).ToArray(),
                Points.Select(p => p.Y).ToArray(),
                x => p.Item1 * Math.Pow(x, p.Item2));

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

            foreach (var item in Points)
            {
                fittedPoints.Add(new DataPoint(item.X, f(item.X)));
            }

            FittedPoints = fittedPoints;
        }
        public Tuple <double[], double[]> CalculateMovingLinearFit(double[] data, int period)
        {
            double[] a = new double[data.Length];
            double[] b = new double[data.Length];

            for (int i = data.Length - 1; i >= 0; i--)
            {
                var numTake = i - period >= 0 ? period : i;
                var subset  = data.Skip(i + 1 - numTake).Take(numTake).ToArray();

                Tuple <double, double> fit = Tuple.Create(0d, 0d);

                if (subset.Length >= 2)
                {
                    fit = Fit.Line(Enumerable.Range(0, subset.Length).Select(_ => (double)_).ToArray(), subset);
                }

                a[i] = fit.Item1;
                b[i] = fit.Item2;
            }

            return(Tuple.Create(a, b));
        }
    Vector3 getDirectionVector(List <Vector3> points)
    {
        int len = points.Count;

        double[] xdata = new double[len];
        double[] zdata = new double[len];
        for (int i = 0; i < len; i++)
        {
            xdata[i] = points[i].x;
            zdata[i] = points[i].z;
        }

        Tuple <double, double> p = Fit.Line(xdata, zdata);
        float   b = (float)p.Item1;
        float   a = (float)p.Item2;
        Vector2 dirVector;

        if (float.IsNaN(b))
        {
            if (zdata[0] < zdata[1])
            {
                dirVector = new Vector2(0, 1);
            }
            else
            {
                dirVector = new Vector2(0, -1);
            }
        }
        else
        {
            Vector2 A = new Vector2(points[0].x, a * points[0].x + b);
            Vector2 B = new Vector2(points[len - 1].x, a * points[len - 1].x + b);
            dirVector = (B - A).normalized;
        }

        return(new Vector3(dirVector.x, 0, dirVector.y));
    }
Example #9
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("MathNetNumericsSample <data file>");
                return;
            }
            var order = 1;
            var xs    = new List <double>();
            var ys    = new List <double>();

            using (var reader = new StreamReader(args[0], Encoding.UTF8)) {
                order = reader.ReadLine()
                        .TryParse <int>();
                if (order < 1)
                {
                    Console.WriteLine("Invalid order");
                    return;
                }
                while (!reader.EndOfStream)
                {
                    var pair = reader.ReadLine()
                               .Split(new[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
                    if (pair.Length < 2)
                    {
                        Console.WriteLine("Invalid pair");
                        return;
                    }
                    xs.Add(pair[0].TryParse <double>());
                    ys.Add(pair[1].TryParse <double>());
                }
            }
            // [Curve Fitting: Linear Regression](http://numerics.mathdotnet.com/Regression.html)
            var coefficients = Fit.Polynomial(xs.ToArray(), ys.ToArray(), order);

            Console.WriteLine(String.Join("\n", coefficients.Select((p, i) => i + "\t" + p.ToString("0.0000"))));
        }
Example #10
0
        /// <summary>
        /// Enlarge each element in the group to match the largest one.
        /// </summary>
        public static void MakeSameSize(this List <LayoutElement> elements, Fit axis)
        {
            if (axis == Fit.Width)
            {
                float newWidth = 0;

                foreach (var le in elements)
                {
                    if (le.SizeF.Width > newWidth)
                    {
                        newWidth = le.SizeF.Width;
                    }
                }

                foreach (var le in elements)
                {
                    le.SizeF = new SizeF(newWidth, le.SizeF.Height);
                }
            }
            else
            {
                float newHeight = 0;

                foreach (var le in elements)
                {
                    if (le.SizeF.Height > newHeight)
                    {
                        newHeight = le.SizeF.Height;
                    }
                }

                foreach (var le in elements)
                {
                    le.SizeF = new SizeF(le.SizeF.Width, newHeight);
                }
            }
        }
Example #11
0
    void OnDrawGizmos()
    {
        List <Vector3> points = new List <Vector3>(parentTransform.childCount);

        foreach (Transform child in parentTransform)
        {
            if (child.gameObject.activeInHierarchy)
            {
                points.Add(child.position);
            }
        }

        if (fitType == FitType.Line)
        {
            Fit.Line(points, out origin, ref direction, 1, true);
        }
        else if (fitType == FitType.LineFast)
        {
            Fit.LineFast(points, out origin, ref direction, 1, true);
        }
        else if (fitType == FitType.Plane)
        {
            Fit.Plane(points, out origin, out direction, 100, true);
        }
        else if (fitType == FitType.OrdinaryLine)
        {
            Fit.Polynomial(points, 1, true);
        }
        else if (fitType == FitType.OrdinaryParabola)
        {
            Fit.Polynomial(points, 2, true);
        }
        else if (fitType == FitType.OrdinaryCubic)
        {
            Fit.Polynomial(points, 3, true);
        }
    }
Example #12
0
        private double[][] CalcP(List <DataRaw> data)
        {
            var x  = new List <double>();
            var yc = new List <double>();
            var ys = new List <double>();
            var yh = new List <double>();
            var yd = new List <double>();

            data.ForEach(i =>
            {
                var da = (i.日期 - DateTime.Parse("2020-1-12")).TotalDays;
                x.Add(da);
                yc.Add(i.确诊人数);
                ys.Add(i.疑似人数);
                yh.Add(i.治愈人数);
                yd.Add(i.死亡人数);
            });
            var Pc = Fit.Polynomial(x.ToArray(), yc.ToArray(), 3);
            var Ps = Fit.Polynomial(x.ToArray(), ys.ToArray(), 3);
            var Ph = Fit.Polynomial(x.ToArray(), yh.ToArray(), 3);
            var Pd = Fit.Polynomial(x.ToArray(), yd.ToArray(), 3);

            return(new double[][] { Pc, Ps, Ph, Pd });
        }
Example #13
0
        public static double CalcPolynomialRegression(string buysField, int seconds, int degrees = 1)
        {
            /// get frames in the last n seconds
            var ratioFrames = lstRatioFrames.DistinctBy(frame => frame.dateTime).Where(frame => frame.seconds == seconds && TDAChart.svcDateTime.Subtract(frame.dateTime).TotalSeconds <= seconds).ToList();
            var n           = ratioFrames.Count;

            var lstBuysD = ratioFrames.Select(item => (double)Convert.ToDouble(item[buysField])).ToList();

            var xData = ratioFrames.Select(item => (double)ratioFrames.IndexOf(item)).ToArray();
            /// Fitting a fifth degree polynomial to the data can have up to 4 curves
            ///
            var cb = Fit.Polynomial(xData, lstBuysD.ToArray(), degrees).Select(t => (float?)t).ToList();

            var x        = (double)xData.Last();
            var buysPoly = 0d;

            for (int i = 0; i < degrees; i++)
            {
                var xx = Math.Pow(x, i);
                buysPoly += (double)(cb[i] * xx);
            }

            return((double)buysPoly);
        }
Example #14
0
        public double[] CreateWavelenghtToPixelLocationsUsingReferenceSpectra(int bluePeakLocation, int redPeakLocation, int RefLengthanyChannel)
        {
            double[] wavelengthArray = new double[RefLengthanyChannel];

            //r = a x + b;

            double[] xdata = { redPeakLocation, bluePeakLocation };
            double[] ydata = { 610.65, 449.1 };

            Tuple <double, double> p = Fit.Line(xdata, ydata);
            double b = p.Item1; //  intercept
            double a = p.Item2; //  slope

            Console.WriteLine("wavelengthslope: " + a + " ,  intercept: " + b);

            for (int i = 0; i < RefLengthanyChannel; i++)
            {
                wavelengthArray[i] = i * a + b;
                //Console.WriteLine("i "+i+" wavearray: " + wavelengthArray[i]);
            }


            return(wavelengthArray);
        }
        public void Analyze(List <ReceivedMeasurement> measurements, AnalysisVM viewmodel)
        {
            var measurementDates = measurements.Select(x => x.RecordCreateTime.ToOADate()).ToArray();

            DirectRegressionMethod regressionMethod = (DirectRegressionMethod)Enum.Parse(typeof(DirectRegressionMethod), viewmodel.regressionMethod);

            var polynomialCoefficients = Fit.Polynomial(measurementDates,
                                                        measurements.Select(y => y.Value).ToArray(), viewmodel.polynomialDegree, regressionMethod).ToList();

            var functionFormula = GetPolynomialFormula(polynomialCoefficients);

            var newDates = GenerateNewDates(measurementDates);

            var approximationResults = GetApproximationResults(newDates.ToArray(), polynomialCoefficients);

            _result = new ComputationResultVM()
            {
                X_values  = measurementDates.Select(x => DateTime.FromOADate(x).ToString("yyyy-MM-dd HH:mm:ss")).ToList(),
                X2_values = newDates.Select(x => DateTime.FromOADate(x).ToString("yyyy-MM-dd HH:mm:ss")).ToList(),
                Y_values  = measurements.Select(x => x.Value).ToList(),
                Y2_values = approximationResults,
                Formula   = functionFormula
            };
        }
Example #16
0
        public void Analyze(List <ReceivedMeasurement> measurements, AnalysisVM viewmodel)
        {
            var dates = measurements.Select(x => x.RecordCreateTime.ToOADate()).ToArray();

            DirectRegressionMethod regressionMethod = (DirectRegressionMethod)Enum.Parse(typeof(DirectRegressionMethod), viewmodel.regressionMethod);

            var polynomialCoefficients = Fit.Polynomial(dates,
                                                        measurements.Select(y => y.Value).ToArray(), viewmodel.polynomialDegree, regressionMethod).ToList();

            var predictionDate    = DateTime.Parse(viewmodel.predictionDate);
            var predictionResults = GetPredictionResults(predictionDate.ToOADate(), polynomialCoefficients);

            List <string> predictionDates = new List <string>()
            {
                viewmodel.predictionDate
            };

            _result = new ComputationResultVM()
            {
                X_values = predictionDates,
                Y_values = predictionResults,
                Formula  = ""
            };
        }
Example #17
0
        public void FitsToLineSameAsExcelTrendLine()
        {
            // X	Y
            // 1   0.2
            // 2   0.3
            // 4   1.3
            // 6   4.2
            // -> y = -1.078 + 0.7932*x

            var x = new[] { 1.0, 2.0, 4.0, 6.0 };
            var y = new[] { 0.2, 0.3, 1.3, 4.2 };

            var resp = Fit.Line(x, y);

            Assert.AreEqual(-1.078, resp.Item1, 1e-3);
            Assert.AreEqual(0.7932, resp.Item2, 1e-3);

            var resf = Fit.LineFunc(x, y);

            foreach (var z in Enumerable.Range(-3, 10))
            {
                Assert.AreEqual(-1.078 + 0.7932 * z, resf(z), 1e-2);
            }
        }
Example #18
0
        public void FitsToExponentialSameAsExcelTrendLine()
        {
            // X	Y
            // 1   0.2
            // 2   0.3
            // 4   1.3
            // 6   4.2
            // -> y = 0.0981*exp(0.6284*x)

            var x = new[] { 1.0, 2.0, 4.0, 6.0 };
            var y = new[] { 0.2, 0.3, 1.3, 4.2 };

            var resp = Fit.Exponential(x, y);

            Assert.AreEqual(0.0981, resp.Item1, 1e-3);
            Assert.AreEqual(0.6284, resp.Item2, 1e-3);

            var resf = Fit.ExponentialFunc(x, y);

            foreach (var z in Enumerable.Range(-3, 10))
            {
                Assert.AreEqual(0.0981 * Math.Exp(0.6284 * z), resf(z), 1e-2);
            }
        }
        public static double[] PolynomialRegression(double[] xVals,
            double[] yVals,int year)
        {
            double x1, x2;
            double[] p = Fit.Polynomial(xVals, yVals, 2);
            if (xVals.Length != yVals.Length)
            {
                throw new Exception("Input values should be with the same length.");
            }

            // p2X^2 + p1X + p0 = year 
            // X => score

            double p0 = p[0] - year;
            double p1 = p[1];
            double p2 = p[2];
            double denta = p1 * p1 - 4 * p2 * p0;

            if (denta < 0)
            {
                return new double[]{ };
            }

            if(denta == 0)
            {
                x1 = -p1 / (2*p2);
                return new double[] { x1 };
            }

            double sqrtDenta = System.Math.Sqrt(denta);
            double denominator = 2 * p2;
            x1 = (-p1 + sqrtDenta) / denominator;
            x2 = (-p1 - sqrtDenta) / denominator;
            
            return new double[]{ x1, x2 };
        }
Example #20
0
        /**
         * Method to Calculate points from file and R02
         * @param IList<double> - data of Y values
         * @param IList<double> - data of X values
         * @return IList<ObservablePoint> - list of observable potins
         */
        private IList <ObservablePoint> GetNewPoints(IList <double> yPoints, IList <double> xPoints)
        {
            int    maxNumber = (int)(0.2 * xPoints.Count);
            var    item      = Fit.Line(xPoints.Take(maxNumber).ToArray(), yPoints.Take(maxNumber).ToArray());
            double a         = item.Item2;
            double b         = item.Item1;
            IList <ObservablePoint> points     = new List <ObservablePoint>();
            IList <ObservablePoint> pointsData = (IList <ObservablePoint>)mainLineSeries.Values;
            double moveRight     = xPoints[0] * 1.002;
            double moveLeft      = xPoints[0] * 0.998;
            bool   rightOverLeft = moveRight > moveLeft;

            f02 = null;
            for (int i = 0; i < xPoints.Count; i++)
            {
                double x = xPoints[i] * 1.002;
                if (!rightOverLeft)
                {
                    x = xPoints[i] * 0.998;
                }
                var y = (xPoints[i] * a) + (b);

                var data  = pointsData[i];
                var yLow  = data.Y * 0.95;
                var yHigh = data.Y * 1.05;

                if (yLow > y && y < yHigh)
                {
                    f02 = data;
                }

                points.Add(new ObservablePoint(x, y));
            }

            return(points);
        }
Example #21
0
        public static double[] CalculateCenterOfCircle(TouchPoint[][] touchPoints)
        {
            List <double[]> X = new List <double[]>();
            List <double>   Y = new List <double>();

            foreach (var pointsInSameRow in touchPoints)
            {
                var point0 = pointsInSameRow[0];
                var point1 = pointsInSameRow[1];
                var point2 = pointsInSameRow[2];

                var x0 = point0.X;
                var y0 = point0.Y;
                var x1 = point1.X;
                var y1 = point1.Y;
                var x2 = point2.X;
                var y2 = point2.Y;

                var Y0 = x1 * x1 + y1 * y1 - x0 * x0 - y0 * y0;
                var Y1 = x2 * x2 + y2 * y2 - x1 * x1 - y1 * y1;
                Y.Add(Y0);
                Y.Add(Y1);

                var X11 = (x1 - x0) * 2;
                var X12 = (y1 - y0) * 2;
                X.Add(new[] { X11, X12 });

                var X21 = (x2 - x1) * 2;
                var X22 = (y2 - y1) * 2;
                X.Add(new[] { X21, X22 });
            }

            double[] result = Fit.MultiDim(X.ToArray(), Y.ToArray(), false, DirectRegressionMethod.NormalEquations);

            return(result);
        }
        /// https://numerics.mathdotnet.com/Regression.html#Evaluating-the-model-at-specific-data-points
        /// https://numerics.mathdotnet.com/Regression.html#Linearizing-non-linear-models-by-transformation
        /// https://discuss.mathdotnet.com/t/exponential-fit/131/2
        /// Exponential: y = a * exp(b * x)
        private void ApplyExponentialFitting()
        {
            double[] x = Points.Select(p => p.X).ToArray();
            double[] y = Points.Select(p => p.Y).ToArray();
            double[] p = Exponential(x, y); // a=1.017, r=0.687

            A = p[0];
            B = p[1];

            Func <double, double> f = Fit.LinearCombinationFunc(
                Points.Select(p => p.X).ToArray(),
                Points.Select(p => p.Y).ToArray(),
                x => p[0] * Math.Exp(p[1] * x));


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

            foreach (var item in Points)
            {
                fittedPoints.Add(new DataPoint(item.X, f(item.X)));
            }

            FittedPoints = fittedPoints;
        }
        public void UpdateFromTarget()
        {
            Guid = TargetDesktop.Guid;

            var background = TargetDesktop.Background;

            var updatedBackgroundPath = background.Path;

            if (!Equals(_backgroundPath, updatedBackgroundPath))
            {
                _backgroundPath = updatedBackgroundPath;

                OnPropertyChanged(nameof(BackgroundPath));
            }

            var updatedFit = background.Fit;

            if (!Equals(_fit, updatedFit))
            {
                _fit = updatedFit;

                OnPropertyChanged(nameof(Fit));
            }
        }
Example #24
0
        public void FitsToLogarithmSameAsExcelTrendLine()
        {
            // X	Y
            // 1   0.2
            // 2   0.3
            // 4   1.3
            // 6   4.2
            // -> y = -0.4338 + 1.9981*ln(x)

            var x = new[] { 1.0, 2.0, 4.0, 6.0 };
            var y = new[] { 0.2, 0.3, 1.3, 4.2 };

            var resp = Fit.Logarithm(x, y);

            Assert.AreEqual(-0.4338, resp.Item1, 1e-3);
            Assert.AreEqual(1.9981, resp.Item2, 1e-3);

            var resf = Fit.LogarithmFunc(x, y);

            foreach (var z in Enumerable.Range(-3, 10))
            {
                Assert.AreEqual(-0.4338 + 1.9981 * Math.Log(z), resf(z), 1e-2);
            }
        }
Example #25
0
        public void FitsToPowerSameAsExcelTrendLine()
        {
            // X	Y
            // 1   0.2
            // 2   0.3
            // 4   1.3
            // 6   4.2
            // -> y = 0.1454*x^1.7044

            var x = new[] { 1.0, 2.0, 4.0, 6.0 };
            var y = new[] { 0.2, 0.3, 1.3, 4.2 };

            var resp = Fit.Power(x, y);

            Assert.AreEqual(0.1454, resp.Item1, 1e-3);
            Assert.AreEqual(1.7044, resp.Item2, 1e-3);

            var resf = Fit.PowerFunc(x, y);

            foreach (var z in Enumerable.Range(-3, 10))
            {
                Assert.AreEqual(0.1454 * Math.Pow(z, 1.7044), resf(z), 1e-2);
            }
        }
Example #26
0
        public static AnalysisResults AnalyzeSurroundingHouses(List <House> houses, BovetaSearch search)
        {
            var results = new AnalysisResults();

            // Should always be the case. Extra check just to make sure.
            houses = houses.Where(house => house.livingArea > 0).ToList();

            // Should we use listing price or sold price? Better if possible.
            bool useSoldPrice = false;

            if (houses.Where(house => house.soldPrice > 0).Count() >=
                houses.Where(house => house.listPrice > 0).Count())
            {
                useSoldPrice = true;
                houses       = houses.Where(house => house.soldPrice > 0).ToList();
            }
            else
            {
                houses = houses.Where(house => house.listPrice > 0).ToList();
            }

            // For convenience
            int numHouses = houses.Count();

            // At least MIN_RESULTS houses in big initial radius
            if (numHouses < MIN_RESULTS)
            {
                return(results);
            }

            // Optimize the number of houses/search radius
            houses = houses.OrderBy(w => w.distanceToReferencePoint).ToList();

            double bestRadius = 0;
            double bestScore  = Double.MinValue;

            for (double radius = 100; radius < 10000; radius = radius * 2)
            {
                int    s     = houses.Where(w => w.distanceToReferencePoint <= radius).Count();
                double order = Math.Log(s, LOG_BASE);
                double score = order - radius / RADIUS_W;
                Console.WriteLine(" Radius: " + radius + "Score: " + score);
                if (score > bestScore & s > MIN_RESULTS)
                {
                    bestRadius = radius;
                    bestScore  = score;
                }
            }
            results.SearchRadius = bestRadius;

            houses = houses.Where(w => w.distanceToReferencePoint < bestRadius).ToList();

            if (houses.Count < MIN_RESULTS)
            {
                return(results);
            }

            List <double> xdata   = new List <double>();
            List <double> ydata   = new List <double>();
            List <double> weights = new List <double>();

            foreach (var house in houses)
            {
                int housePrice = house.listPrice;
                if (useSoldPrice)
                {
                    housePrice = house.soldPrice;
                }

                weights.Add(1 + POL_WEIGHT_NUM / (POL_WEIGHT_DENOM + house.distanceToReferencePoint));
                xdata.Add(house.livingArea);
                ydata.Add(housePrice);
            }

            var    p          = Fit.PolynomialWeighted(xdata.ToArray(), ydata.ToArray(), weights.ToArray(), 1);
            double estimation = p[0] + p[1] * search.Size;

            if (search.Condition != HouseCondition.Average)
            {
                // Adjust weights to accomodate for condition

                List <double> modelerr = new List <double>();

                // 1. Find error in current model. Use this as measure for over/under valuation
                for (int i = 0; i < ydata.Count; ++i)
                {
                    double modelError = ydata[i] - (p[0] + p[1] * xdata[i]);
                    modelerr.Add(modelError);
                }

                // 2. Adjust weights so that overvalued houses are worth more.
                for (int i = 0; i < modelerr.Count; i++)
                {
                    if (modelerr[i] < 0) // Model price > real price. Probably bad condition
                    {
                        if (search.Condition == HouseCondition.AboveAverage)
                        {
                            weights[i] = weights[i] * 0.5; // Less representive of true house price
                        }
                        else if (search.Condition == HouseCondition.BelowAverage)
                        {
                            weights[i] = weights[i] * 2; // More representive of true house price
                        }
                    }
                    else  // Model price < real price. Probably good condition
                    {
                        if (search.Condition == HouseCondition.AboveAverage)
                        {
                            weights[i] = weights[i] * 2; // More representive of true house price
                        }
                        else if (search.Condition == HouseCondition.BelowAverage)
                        {
                            weights[i] = weights[i] * 0.5; // Less representive of true house price
                        }
                    }
                }

                // Recalculate polynomial
                p = Fit.PolynomialWeighted(xdata.ToArray(), ydata.ToArray(), weights.ToArray(), 1);
            }



            results.Intercept = p[0];
            results.BetaSize  = p[1];

            results.NumDatapointsUsed = houses.Count();
            results.EstimatedValue    = (int)(results.Intercept + results.BetaSize * search.Size);

            if (search.Condition == HouseCondition.BelowAverage & results.EstimatedValue > estimation)
            {
                // Oops. Our advanced searched failed. Reduce cost by 10% for now.....
                results.EstimatedValue = results.EstimatedValue * 0.9;
            }

            if (search.Condition == HouseCondition.AboveAverage & results.EstimatedValue < estimation)
            {
                // Oops. Our advanced searched failed. Increase cost by 10% for now.....
                results.EstimatedValue = results.EstimatedValue * 1.1;
            }

            results.ConfidenceScore = 0.6;

            return(results);
        }
        public void CreateControllerElements(IMyTerminalBlock block)
        {
            try
            {
                if (DsControl)
                {
                    return;
                }
                var comp = block?.GameLogic?.GetAs <DefenseShields>();
                TerminalHelpers.Separator(comp?.Shield, "DS-C_sep0");
                ToggleShield = TerminalHelpers.AddOnOff(comp?.Shield, "DS-C_ToggleShield", Localization.GetText("TerminalToggleShieldTitle"), Localization.GetText("TerminalToggleShieldTooltip"), Localization.GetText("TerminalSwitchUp"), Localization.GetText("TerminalSwitchDown"), DsUi.GetRaiseShield, DsUi.SetRaiseShield);
                TerminalHelpers.Separator(comp?.Shield, "DS-C_sep1");
                //ChargeSlider = TerminalHelpers.AddSlider(comp?.Shield, "DS-C_ChargeRate", "Shield Charge Rate", "Percentage Of Power The Shield May Consume", DsUi.GetRate, DsUi.SetRate);
                //ChargeSlider.SetLimits(20, 95);
                PowerScaleSelect = TerminalHelpers.AddCombobox(comp?.Shield, "DS-C_PowerScale", Localization.GetText("TerminalPowerScaleSelectTitle"), Localization.GetText("TerminalPowerScaleSelectTooltip"), DsUi.GetPowerScale, DsUi.SetPowerScale, DsUi.ListPowerScale);

                PowerWatts = TerminalHelpers.AddSlider(comp?.Shield, "DS-C_PowerWatts", Localization.GetText("TerminalPowerWattsTitle"), Localization.GetText("TerminalPowerWattsTooltip"), DsUi.GetPowerWatts, DsUi.SetPowerWatts, DsUi.EnablePowerWatts);
                PowerWatts.SetLimits(1, 999);
                if (comp != null && comp.GridIsMobile)
                {
                    TerminalHelpers.Separator(comp.Shield, "DS-C_sep2");
                }

                Fit = TerminalHelpers.AddSlider(comp?.Shield, "DS-CFit", Localization.GetText("TerminalFitTitle"), Localization.GetText("TerminalFitTooltip"), DsUi.GetFit, DsUi.SetFit);
                Fit.SetLimits(0, 22);

                SphereFit     = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_SphereFit", Localization.GetText("TerminalSphereFitTitle"), Localization.GetText("TerminalSphereFitTooltip"), DsUi.GetSphereFit, DsUi.SetSphereFit);
                FortifyShield = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_ShieldFortify", Localization.GetText("TerminalFortifyShieldTitle"), Localization.GetText("TerminalFortifyShieldTooltip"), DsUi.GetFortify, DsUi.SetFortify);

                TerminalHelpers.Separator(comp?.Shield, "DS-C_sep3");

                WidthSlider = TerminalHelpers.AddSlider(comp?.Shield, "DS-C_WidthSlider", Localization.GetText("TerminalWidthSliderTitle"), Localization.GetText("TerminalWidthSliderTooltip"), DsUi.GetWidth, DsUi.SetWidth);
                WidthSlider.SetLimits(30, 1000);

                HeightSlider = TerminalHelpers.AddSlider(comp?.Shield, "DS-C_HeightSlider", Localization.GetText("TerminalHeightSliderTitle"), Localization.GetText("TerminalHeightSliderTooltip"), DsUi.GetHeight, DsUi.SetHeight);
                HeightSlider.SetLimits(30, 1000);

                DepthSlider = TerminalHelpers.AddSlider(comp?.Shield, "DS-C_DepthSlider", Localization.GetText("TerminalDepthSliderTitle"), Localization.GetText("TerminalDepthSliderTooltip"), DsUi.GetDepth, DsUi.SetDepth);
                DepthSlider.SetLimits(30, 1000);

                OffsetWidthSlider = TerminalHelpers.AddSlider(comp?.Shield, "DS-C_OffsetWidthSlider", Localization.GetText("TerminalOffsetWidthSliderTitle"), Localization.GetText("TerminalOffsetWidthSliderTooltip"), DsUi.GetOffsetWidth, DsUi.SetOffsetWidth);
                OffsetWidthSlider.SetLimits(-69, 69);

                OffsetHeightSlider = TerminalHelpers.AddSlider(comp?.Shield, "DS-C_OffsetHeightSlider", Localization.GetText("TerminalOffsetHeightSliderTitle"), Localization.GetText("TerminalOffsetHeightSliderTooltip"), DsUi.GetOffsetHeight, DsUi.SetOffsetHeight);
                OffsetHeightSlider.SetLimits(-69, 69);

                OffsetDepthSlider = TerminalHelpers.AddSlider(comp?.Shield, "DS-C_OffsetDepthSlider", Localization.GetText("TerminalOffsetDepthSliderTitle"), Localization.GetText("TerminalOffsetDepthSliderTooltip"), DsUi.GetOffsetDepth, DsUi.SetOffsetDepth);
                OffsetDepthSlider.SetLimits(-69, 69);

                TerminalHelpers.Separator(comp?.Shield, "DS-C_sep4");

                BatteryBoostCheckBox = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_UseBatteries", Localization.GetText("TerminalBatteryBoostCheckBoxTitle"), Localization.GetText("TerminalBatteryBoostCheckBoxTooltip"), DsUi.GetBatteries, DsUi.SetBatteries);
                SendToHudCheckBox    = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_HideIcon", Localization.GetText("TerminalSendToHudCheckBoxTitle"), Localization.GetText("TerminalSendToHudCheckBoxTooltip"), DsUi.GetSendToHud, DsUi.SetSendToHud);
                TerminalHelpers.Separator(comp?.Shield, "DS-C_sep5");
                ShellSelect = TerminalHelpers.AddCombobox(comp?.Shield, "DS-C_ShellSelect", Localization.GetText("TerminalShellSelectTitle"), Localization.GetText("TerminalShellSelectTooltip"), DsUi.GetShell, DsUi.SetShell, DsUi.ListShell);

                ShellVisibility = TerminalHelpers.AddCombobox(comp?.Shield, "DS-C_ShellSelect", Localization.GetText("TerminalShellVisibilityTitle"), Localization.GetText("TerminalShellVisibilityTooltip"), DsUi.GetVisible, DsUi.SetVisible, DsUi.ListVisible);

                HideActiveCheckBox = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_HideActive", Localization.GetText("TerminalHideActiveCheckBoxTitle"), Localization.GetText("TerminalHideActiveCheckBoxTooltip"), DsUi.GetHideActive, DsUi.SetHideActive);

                //RefreshAnimationCheckBox = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_RefreshAnimation", "Show Refresh Animation  ", "Show Random Refresh Animation", DsUi.GetRefreshAnimation, DsUi.SetRefreshAnimation);
                //HitWaveAnimationCheckBox = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_HitWaveAnimation", "Show Hit Wave Animation", "Show Wave Effect On Shield Damage", DsUi.GetHitWaveAnimation, DsUi.SetHitWaveAnimation);
                NoWarningSoundsCheckBox = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_NoWarningSounds", Localization.GetText("TerminalNoWarningSoundsCheckBoxTitle"), Localization.GetText("TerminalNoWarningSoundsCheckBoxTooltip"), DsUi.GetNoWarningSounds, DsUi.SetNoWarningSounds);
                DimShieldHitsCheckBox   = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_DimShieldHits", Localization.GetText("TerminalDimShieldHitsCheckBoxTitle"), Localization.GetText("TerminalDimShieldHitsCheckBoxTooltip"), DsUi.GetDimShieldHits, DsUi.SetDimShieldHits);

                TerminalHelpers.Separator(comp?.Shield, "DS-C_sep6");
                SideShunting = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_SideRedirect", Localization.GetText("TerminalSideShuntingTitle"), Localization.GetText("TerminalSideShuntingTooltip"), DsUi.GetSideShunting, DsUi.SetSideShunting);
                ShowShunting = TerminalHelpers.AddCheckbox(comp?.Shield, "DS-C_ShowRedirect", Localization.GetText("TerminalShowShuntingTitle"), Localization.GetText("TerminalShowShuntingTooltip"), DsUi.GetShowShunting, DsUi.SetShowShunting);

                TopShield    = TerminalHelpers.AddOnOff(comp?.Shield, "DS-C_TopShield", Localization.GetText("TerminalTopShieldTitle"), Localization.GetText("TerminalTopShieldTooltip"), Localization.GetText("TerminalSwitchPush"), Localization.GetText("TerminalSwitchPull"), DsUi.GeTopShield, DsUi.SetTopShield, DsUi.RedirectEnabled);
                BottomShield = TerminalHelpers.AddOnOff(comp?.Shield, "DS-C_BottomShield", Localization.GetText("TerminalBottomShieldTitle"), Localization.GetText("TerminalBottomShieldTooltip"), Localization.GetText("TerminalSwitchPush"), Localization.GetText("TerminalSwitchPull"), DsUi.GetBottomShield, DsUi.SetBottomShield, DsUi.RedirectEnabled);
                LeftShield   = TerminalHelpers.AddOnOff(comp?.Shield, "DS-C_LeftShield", Localization.GetText("TerminalLeftShieldTitle"), Localization.GetText("TerminalLeftShieldTooltip"), Localization.GetText("TerminalSwitchPush"), Localization.GetText("TerminalSwitchPull"), DsUi.GetLeftShield, DsUi.SetLeftShield, DsUi.RedirectEnabled);
                RightShield  = TerminalHelpers.AddOnOff(comp?.Shield, "DS-C_RightShield", Localization.GetText("TerminalRightShieldTitle"), Localization.GetText("TerminalRightShieldTooltip"), Localization.GetText("TerminalSwitchPush"), Localization.GetText("TerminalSwitchPull"), DsUi.GetRightShield, DsUi.SetRightShield, DsUi.RedirectEnabled);
                FrontShield  = TerminalHelpers.AddOnOff(comp?.Shield, "DS-C_FrontShield", Localization.GetText("TerminalFrontShieldTitle"), Localization.GetText("TerminalFrontShieldTooltip"), Localization.GetText("TerminalSwitchPush"), Localization.GetText("TerminalSwitchPull"), DsUi.GetFrontShield, DsUi.SetFrontShield, DsUi.RedirectEnabled);
                BackShield   = TerminalHelpers.AddOnOff(comp?.Shield, "DS-C_BackShield", Localization.GetText("TerminalBackShieldTitle"), Localization.GetText("TerminalBackShieldTooltip"), Localization.GetText("TerminalSwitchPush"), Localization.GetText("TerminalSwitchPull"), DsUi.GetBackShield, DsUi.SetBackShield, DsUi.RedirectEnabled);


                CreateAction <IMyUpgradeModule>(ToggleShield);

                CreateAction <IMyUpgradeModule>(SphereFit);
                CreateFitAction <IMyUpgradeModule>(Fit);
                CreateAction <IMyUpgradeModule>(FortifyShield);


                CreateAction <IMyUpgradeModule>(HideActiveCheckBox);
                //CreateAction<IMyUpgradeModule>(RefreshAnimationCheckBox);
                //CreateAction<IMyUpgradeModule>(HitWaveAnimationCheckBox);
                CreateAction <IMyUpgradeModule>(SendToHudCheckBox);
                CreateAction <IMyUpgradeModule>(BatteryBoostCheckBox);
                CreateDepthAction <IMyUpgradeModule>(DepthSlider);
                CreateWidthAction <IMyUpgradeModule>(WidthSlider);
                CreateHeightAction <IMyUpgradeModule>(HeightSlider);

                CreateShuntAction <IMyUpgradeModule>(TopShield);
                CreateShuntAction <IMyUpgradeModule>(BottomShield);
                CreateShuntAction <IMyUpgradeModule>(LeftShield);
                CreateShuntAction <IMyUpgradeModule>(RightShield);
                CreateShuntAction <IMyUpgradeModule>(FrontShield);
                CreateShuntAction <IMyUpgradeModule>(BackShield);

                CreateAction <IMyUpgradeModule>(SideShunting);

                DsControl = true;
            }
            catch (Exception ex) { Log.Line($"Exception in CreateControlerUi: {ex}"); }
        }
Example #28
0
 //Private method to perform some operation that will NOT be exposed in Decisions
 private double[] PerformPolynomialRegression(double[] xData, double[] yData)
 {
     //Use External Math.Net library to perform operations
     return(Fit.Polynomial(xData, yData, 3));
 }
Example #29
0
 /// <summary>
 /// Makes all of the input layout elements have the same width or height
 /// </summary>
 /// <param name="elements">A list of elements to resize to the max size of all elements or the margins</param>
 /// <param name="axis">Fit the width or the height</param>
 /// <param name="margin">True if use margin size false to use arges element in input list</param>
 public void MatchElementsSize(List<LayoutElement> elements, Fit axis, bool margin)
 {
     if (axis == Fit.Width)
     {
         if (margin)
         {
             float newWidth = PaperWidth - _printerSettings.DefaultPageSettings.Margins.Left - _printerSettings.DefaultPageSettings.Margins.Right;
             foreach (LayoutElement le in elements)
                 le.Size = new SizeF(newWidth, le.Size.Height);
         }
         else
         {
             float newWidth = 0;
             foreach (LayoutElement le in elements)
                 if (le.Size.Width > newWidth) newWidth = le.Size.Width;
             foreach (LayoutElement le in elements)
                 le.Size = new SizeF(newWidth, le.Size.Height);
         }
     }
     else
     {
         if (margin)
         {
             float newHeight = PaperHeight - _printerSettings.DefaultPageSettings.Margins.Top - _printerSettings.DefaultPageSettings.Margins.Bottom;
             foreach (LayoutElement le in elements)
                 le.Size = new SizeF(le.Size.Width, newHeight);
         }
         else
         {
             float newHeight = 0;
             foreach (LayoutElement le in elements)
                 if (le.Size.Height > newHeight) newHeight = le.Size.Height;
             foreach (LayoutElement le in elements)
                 le.Size = new SizeF(le.Size.Width, newHeight);
         }
     }
 }
Example #30
0
        static void Main(string[] args)
        {
            //首先生成 x 点的向量,在区间 [0,2.5] 内等间距分布;然后计算这些点处的 erf(x)。
            //double[] x = Generate.LinearRange(start: 0, step: 0.1, stop: 2.5);
            double[]      x = Generate.LinearRange(start: 1, step: 1, stop: 10);
            List <double> y = new List <double>();

            foreach (double x0 in x)
            {
                y.Add(SpecialFunctions.Erf(x0));
            }
            //确定 6 阶逼近多项式的系数。
            double[] p = Fit.Polynomial(x, y.ToArray(), order: 6);
            Write("p = ");
            foreach (double coefficient in p)
            {
                Write($"{coefficient:F2} ");
            }
            WriteLine();
            //为了查看拟合情况如何,在各数据点处计算多项式,并生成说明数据、拟合和误差的一个表。
            WriteLine();
            var funcP = Fit.PolynomialFunc(x, y.ToArray(), 6);

            WriteLine($"{"x",10}|{"y",10}|{"Fit",10}|{"FitError",10}");
            WriteLine($"{new string('-', 10)}|{new string('-', 10)}|{new string('-', 10)}|{new string('-', 10)}");
            foreach (double x0 in Generate.LinearRange(1, 1, 10))
            {
                double y0       = SpecialFunctions.Erf(x0);
                double fit      = funcP(x0);
                double fitError = fit - y0;
                WriteLine($"{x0,10:F2}|{y0,10:F2}|{fit,10:F2}|{fitError,10:F2}");
            }
            ReadKey();



            /*
             *
             * using MathNet.Numerics;
             * using System.Collections.Generic;
             * using static System.Console;
             *
             * namespace ConsoleApp1
             * {
             * class Program
             * {
             * static void Main()
             * {
             * //首先生成 x 点的向量,在区间 [0,2.5] 内等间距分布;然后计算这些点处的 erf(x)。
             * double[] x = Generate.LinearRange(start: 0, step: 0.1, stop: 2.5);
             * List<double> y = new List<double>();
             * foreach (double x0 in x)
             * {
             *  y.Add(SpecialFunctions.Erf(x0));
             * }
             * //确定 6 阶逼近多项式的系数。
             * double[] p = Fit.Polynomial(x, y.ToArray(), order: 6);
             * Write("p = ");
             * foreach (double coefficient in p)
             * {
             *  Write($"{coefficient:F5} ");
             * }
             * WriteLine();
             * //为了查看拟合情况如何,在各数据点处计算多项式,并生成说明数据、拟合和误差的一个表。
             * WriteLine();
             * var funcP = Fit.PolynomialFunc(x, y.ToArray(), 6);
             * WriteLine($"{"x",10}|{"y",10}|{"Fit",10}|{"FitError",10}");
             * WriteLine($"{new string('-', 10)}|{new string('-', 10)}|{new string('-', 10)}|{new string('-', 10)}");
             * foreach (double x0 in Generate.LinearRange(0, 0.1, 1.5))
             * {
             *  double y0 = SpecialFunctions.Erf(x0);
             *  double fit = funcP(x0);
             *  double fitError = fit - y0;
             *  WriteLine($"{x0,10:F4}|{y0,10:F4}|{fit,10:F4}|{fitError,10:F4}");
             * }
             * }
             * }
             * }
             */
        }
        private void button4_Click_2(object sender, EventArgs e)
        {
            chart2.Series.Clear();

            List <double> xdataList = new List <double>();
            List <double> ydataList = new List <double>();

            /*xdataList.Add(0);
            *  ydataList.Add(0);*/
            DataGridViewRowCollection drc = dataGridViewInterpolation.Rows;

            settings.CollectionH.Clear();
            settings.CollectionV.Clear();
            foreach (DataGridViewRow item in drc)
            {
                try
                {
                    //save to settings

                    /*
                     * settings.CollectionH.Add(item.Cells[0].Value.ToString());
                     * settings.CollectionV.Add(item.Cells[1].Value.ToString());
                     * settings.Save();*/

                    //add to ArrayList
                    xdataList.Add(Convert.ToDouble(item.Cells[1].Value));
                    ydataList.Add(Convert.ToDouble(item.Cells[0].Value));
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Please introduce only numbers. " + ex.Message);
                }
            }
            xdataList.Add(0);
            ydataList.Add(0);
            double[] xdata = xdataList.ToArray();
            double[] ydata = ydataList.ToArray();

            double[] p = Fit.Polynomial(xdata, ydata, 2);

            chart2.Series.Add("Data");
            chart2.Series.Add("Interpolation");
            //set chart type
            chart2.Series["Data"].ChartType   = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
            chart2.Series["Data"].BorderWidth = myBorderWidth;
            //chart2.Series["Data"].LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dot;
            chart2.Series["Data"].MarkerStyle = MarkerStyle.Circle;
            chart2.Series["Data"].MarkerSize  = 10;
            chart2.Series["Data"].Color       = System.Drawing.Color.Green;

            //set chart type
            chart2.Series["Interpolation"].ChartType       = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            chart2.Series["Interpolation"].BorderWidth     = myBorderWidth;
            chart2.Series["Interpolation"].BorderDashStyle = ChartDashStyle.Dot;
            chart2.Series["Interpolation"].Color           = System.Drawing.Color.Blue;

            for (int i = 0; i < xdata.Length; i++)
            {
                chart2.Series["Data"].Points.AddXY(Convert.ToDouble(xdata[i]), Convert.ToDouble(ydata[i]));
            }
            for (int i = 0; i < 50; i++)
            {
                double newx = ((xdata[xdata.Length - 1] - xdata[0]) / 50) * i + xdata[0];
                double newy = p[0] + p[1] * newx + p[2] * Math.Pow(newx, 2);
                chart2.Series["Interpolation"].Points.AddXY(newx, newy);
            }

            //calculate v at head of 50mm (solve quadratic equation at 50mm):
            double sqrtpart = p[1] * p[1] - 4 * p[2] * (p[0] - 50);

            textBoxAnswer.Text = ((-p[1] + Math.Sqrt(sqrtpart)) / (2 * p[2])).ToString("#0.000");
            textBox3.Text      = ((-p[1] - Math.Sqrt(sqrtpart)) / (2 * p[2])).ToString("#0.000");

            double answer = (-p[1] + Math.Sqrt(sqrtpart)) / (2 * (p[2]));

            textBox4.Text = (p[0] + p[1] * answer + p[2] * Math.Pow(answer, 2)).ToString("#0.000");
        }
Example #32
0
 private void poAutoruToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try
     {
         OdbcConnection connection = new OdbcConnection();
         connection.ConnectionString = "DSN=PostgreSQL35W;UID=masterwordcounter;PWD=masterwordcounter";
         connection.Open();
         string         q           = "SELECT * FROM (SELECT sum(s.num_of_repeats) prosjek, avg(s.pct_of_occurence), s.word_text, t.author FROM stats s, texts t WHERE s.text_id = t.id AND t.author = 'Agatha Christie' AND type_of_stats = 2 GROUP BY s.word_text,t.author ORDER BY prosjek DESC) top_sve OFFSET 0 LIMIT 200";
         OdbcCommand    getAllTexts = new OdbcCommand(q, connection);
         OdbcDataReader odr         = getAllTexts.ExecuteReader();
         int            a           = 0;
         lista_stats_text.Clear();
         double ukupno = 0;
         while (odr.Read())
         {
             a++;
             Statistika s = new Statistika();
             s.Broj_ponavljanja = odr.GetInt32(0);
             s.Procenat_pojave_unutar_teksta = odr.GetDecimal(1) * 100;
             s.Id          = a;
             s.Rijec_tekst = odr.GetString(2);
             lista_stats_text.Add(s);
             ukupno += s.Broj_ponavljanja;
         }
         odr.Close();
         List <koordinate> pravi_rez    = new List <koordinate>();
         List <koordinate> ideal_rez    = new List <koordinate>();
         double            suma_razlike = 0;
         for (int i = 0; i < lista_stats_text.Count; i++)
         {
             if (double.IsNegativeInfinity(Math.Log10(lista_stats_text[i].Broj_ponavljanja)))
             {
                 break;
             }
             if (double.IsNegativeInfinity(Math.Log10(lista_stats_text[0].Broj_ponavljanja / (i + 1))))
             {
                 break;
             }
             koordinate k = new koordinate();
             k.X = Math.Log10(i + 1);
             k.Y = Math.Log10(lista_stats_text[i].Broj_ponavljanja);
             pravi_rez.Add(k);
             koordinate k1 = new koordinate();
             k1.X = Math.Log10(i + 1);
             k1.Y = Math.Log10(lista_stats_text[0].Broj_ponavljanja / (i + 1));
             ideal_rez.Add(k1);
         }
         try
         {
             for (int i = 0; i < pravi_rez.Count; i++)
             {
                 double a1 = Math.Round(Math.Pow((pravi_rez[i].X - ideal_rez[i].X), 2) + Math.Pow((pravi_rez[i].Y - ideal_rez[i].Y), 2), 4);
                 suma_razlike += a1;
                 suma_razlike  = Math.Round(suma_razlike, 4);
             }
         }
         catch (ArithmeticException ae)
         {
             MessageBox.Show(ae.Message);
         }
         double   MSE     = suma_razlike / pravi_rez.Count;
         double[] lista_x = new double[ideal_rez.Count];
         double[] lista_y = new double[ideal_rez.Count];
         int      j       = 0;
         foreach (koordinate k in pravi_rez)
         {
             lista_x[j] = k.X;
             lista_y[j] = k.Y;
             j++;
         }
         double[] f       = Fit.Polynomial(lista_x, lista_y, 2, MathNet.Numerics.LinearRegression.DirectRegressionMethod.NormalEquations);
         var      bestfit = Tuple.Create(0.0, 0.0);
         bestfit           = Fit.Line(lista_x, lista_y);
         l_text_stats.Text = "Date riječi u tabeli predstavljaju " + Math.Round((double)(podsuma / ukupno) * 100, 2) + "% od cijelog teksta. Ukupno posebnih riječi ima " + lista_stats_text.Count + " a cijeli tekst ima " + ukupno + " riječi.";
         l_nastavak.Text   = "Suma odstupanja od idealnog Zipfovog zakona je " + suma_razlike + ", MSE je " + Math.Round(MSE, 5) + ", RMSE je " + Math.Round(Math.Sqrt(MSE), 5) + ". Best-fit polinom za rezultate je y(x) = " + Math.Round(f[1], 2) + "X + " + Math.Round(f[2], 2) + "X ^ 2 + " + Math.Round(f[0], 2);
         if (c_analiza.SelectedIndex == 0)
         {
             MSENDPF = Math.Round(MSE, 5);
         }
         else
         {
             MSEGPDF = Math.Round(MSE, 5);
         }
         if (MSENDPF != 0.0 && MSEGPDF != 0.0)
         {
             StatistikaTekst st = new StatistikaTekst();
             st.Ime_teksta = c_tekst.SelectedItem.ToString();
             st.RMSE_G1    = MSEGPDF;
             st.RMSE_N1    = MSENDPF;
             double h = Math.Round(st.RMSE_N1 - st.RMSE_G1, 5);
             st.Pct_diff = Math.Round(h / st.RMSE_N1, 5);
             if (st.Pct_diff > 1)
             {
                 st.Pct_diff = st.Pct_diff - 1;
             }
             lista_PDF.Add(st);
             MSEGPDF = 0.0;
             MSENDPF = 0.0;
         }
     }
     catch (Exception es)
     {
         MessageBox.Show(es.Message);
     }
 }
 /// <summary>
 /// Creates a text label to fit within a specified area
 /// </summary>
 public Label(String name, Rectangle area, Fit fit)
     : base(name, area)
 {
     SetText(name, fit);
     bgTransparency = bgColor.A / 255.0f;
 }