Пример #1
0
        public static double poly3degree(List <double> points)  // n day polynomial fit  must have degrees +1 nodes  degree 3 is x^2+x+k
        {
            int           nodes = points.Count;
            List <double> vals  = new List <double>();

            //  Tuple<double, double> p;
            double[] p;
            double[] ydata = new double[nodes];
            double[] xdata = new double[nodes];
            double   m;
            double   b;
            double   s;
            double   val = 0F;

            for (int i = 0; i < nodes; ++i)
            {
                xdata[i] = i;
            }
            ydata = points.ToArray();
            p     = Fit.Polynomial(xdata, ydata, 2);
            b     = p[0];
            m     = p[1];
            s     = p[2];
            val   = s * nodes * nodes + m * nodes + b;
            return(val);
        }
Пример #2
0
        /*
         * For tyre life estimates we want to know how long the tyres will last, so we're asking for a time prediction
         * given a wear amount (100% wear). So y_data is the y-axis which may be time points (session running time) or
         * number of sectors since session start incrementing +1 for each sector. When we change tyres we clear these
         * data sets but the y-axis time / sector counts will start at however long into the session (time or total
         * sectors) we are.
         * x_data is the tyre wear at that y point (a percentage).
         * the x_point is the point you want to predict the life - wear amount. So we pass 100% in here to give us
         * a time / sector count estimate.
         * order is the polynomial fit order - 1 for linear, 2 for quadratic etc. > 3 does not give a suitable
         * curve and will produce nonsense. Use 2 for tyre wear.
         */
        public static double getYEstimate(double[] x_data, double[] y_data, double x_point, int order)
        {
            // get the polynomial from the Numerics library:
            double[] curveParams = Fit.Polynomial(x_data, y_data, order);

            // solve for x_point:
            double y_point = 0;

            for (int power = 0; power < curveParams.Length; power++)
            {
                if (power == 0)
                {
                    y_point = y_point + curveParams[power];
                }
                else if (power == 1)
                {
                    y_point = y_point + curveParams[power] * x_point;
                }
                else
                {
                    y_point = y_point + curveParams[power] * Math.Pow(x_point, power);
                }
            }
            return(y_point);
        }
Пример #3
0
        public DlcpPoint(double bias, double[] dVseries, double[] Cseries, double eps)
        {
            Bias = bias;
            dVs  = dVseries;
            Cs   = Cseries;

            var    lineFitRes = Fit.Line(dVs, Cs);
            double c0guess    = lineFitRes.Item1;
            double c1guess    = lineFitRes.Item2;

            var    quadFitRes = Fit.Polynomial(dVs, Cs, 2);
            double C0         = quadFitRes[0];
            double C1         = quadFitRes[1];
            double C2         = quadFitRes[2];

            Density  = -(C0 * C0 * C0) / (2 * eps * Consts.ElementaryCharge * C1);
            Position = 2 * eps / C0;

            //var f = new Func<double, double, double, double>((x, a, b) => a * (Math.Sqrt(1 + b * x) - 1) / x);
            //double aGuess = -c0guess * c0guess / c1guess;
            //double bGuess = c0guess / aGuess;
            //Tuple<double, double> res = Fit.Curve(dVs, Cs, f, aGuess, bGuess);
            //double alpha = res.Item1;
            //double beta = res.Item2;
            //Density = alpha * alpha * beta / (2 * eps * area * area * Consts.ElementaryCharge);
            //Position = 2 * eps * area / (alpha * beta);

            //var f = new Func<double, double, double, double>((x, c0, c1) => c0 + c1 * x + 2 * (c1 * c1 / c0) * x * x);
            //Tuple<double, double> res = Fit.Curve(dVs, Cs, f, c0guess, c1guess);
            //double C0 = res.Item1;
            //double C1 = res.Item2;
            //Density = -C0 * C0 * C0 / (2 * eps * area * area * Consts.ElementaryCharge * C1);
            //Position = 2 * eps * area / C1;
        }
Пример #4
0
        private static void MathNetTest()
        {
            var datas       = new Datas();
            var sourceDatas = datas.LoadSourceDatas();

            foreach (var data in sourceDatas)
            {
                var values = data.Skip(32).Take(6);

                double[] X = Enumerable.Range(1, 6).Select(r => (double)r).ToArray();
                double[] Y = values.ToArray();

                double[] parameters = Fit.Polynomial(X, Y, 2);


                List <double> result = new List <double>();
                for (int i = 1; i < 15; i++)
                {
                    result.Add(parameters[0] + parameters[1] * i + parameters[2] * i * i);
                }

                for (int i = 0; i < 8; i++)
                {
                    data[data.Count - 1 - i] = result[result.Count - 1 - i];
                }

                SetUnitary(data);
            }

            datas.SaveResultDatas(sourceDatas, "MathNetData.txt");
        }
        private static void GetPoly(List <float> listfTemp, List <short> ilstOutIR, List <float> flstTotalAcc, out List <double> poly2EstFACC, out List <double> poly2EstIR)
        {
            var ilstTemp = listfTemp.Select(o => (short)o * 10).ToList();
            int i        = 0;

            //object objMini = wsfMini.LinEst(ilstOutIR.ToArray(), ilstTemp.ToArray(), true, true);
            double[] xdata = new double[ilstTemp.Count];
            double[] ydata = new double[ilstOutIR.Count];
            double[] zdata = new double[flstTotalAcc.Count];
            for (i = 0; i < ilstTemp.Count; i++)
            {
                xdata[i] = Convert.ToDouble(ilstTemp[i]);
            }
            for (i = 0; i < ilstOutIR.Count; i++)
            {
                ydata[i] = Convert.ToDouble(ilstOutIR[i]);
            }
            for (i = 0; i < flstTotalAcc.Count; i++)
            {
                zdata[i] = Convert.ToDouble(flstTotalAcc[i]);
            }
            //Tuple<double, double> lineEst = Fit.Line(xdata, ydata);
            poly2EstIR   = Fit.Polynomial(xdata, ydata, 2).ToList();      //2-order polynomial
            poly2EstFACC = Fit.Polynomial(xdata, zdata, 2).ToList();      //2-order polynomial
        }
        private void fitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List <List <double> > fitOD = new List <List <double> >();

            // data points
            for (int i = 0; i < numChan; i++)
            {
                fitOD.Add(new List <double>());
                var xdata = new double[Volt[i].Count];
                var ydata = new double[OD[i].Count];
                for (int j = 0; j < Volt[i].Count; j++)
                {
                    xdata[j] = Math.Log(Volt[i][j]);
                    ydata[j] = (OD[i][j]);
                }

                double[] p = Fit.Polynomial(xdata, ydata, 1);
                p0[i] = p[0]; p1[i] = p[1];

                for (int j = 0; j < Volt[i].Count; j++)
                {
                    fitOD[i].Add((Math.Log(Volt[i][j]) * p1[i]) + p0[i]);
                }
                charts[i].Series["fit"].Points.DataBindXY(Volt[i], fitOD[i]);
            }
        }
Пример #7
0
        private List <DateTimeValues> DoPolynomialRegression(List <DateTimeValues> values)
        {
            myPolyFilteredData = new List <DateTimeValues>();
            myPolyFilteredData = CopyList(values);

            double[] _values = new double[myPolyFilteredData.Count];
            double[] _time   = new double[myPolyFilteredData.Count];


            for (int i = 0; i < myPolyFilteredData.Count; i++)
            {
                _time[i]   = i;
                _values[i] = myPolyFilteredData[i].values;
            }

            double[] p = Fit.Polynomial(_time, _values, (int)numRank.Value);

            for (int i = 0; i < myPolyFilteredData.Count; i++)
            {
                myPolyFilteredData[i].values = p[0];

                for (int z = 1; z < p.Length; z++)
                {
                    double t1 = p[z] * Math.Pow(_time[i], z);
                    myPolyFilteredData[i].values += p[z] * Math.Pow(_time[i], z);
                }
            }

            return(myPolyFilteredData);
        }
Пример #8
0
        private void processData()
        {
            var x = measurements.Select(item => Convert.ToDouble(item)).ToArray();
            var y = measureValues;

            var constants = Fit.Polynomial(x, y, 2);

            //foreach(int constant in constants) {
            //    Console.Write(constant + " ");
            //}
            //Console.WriteLine();

            displayPolynomial(constants);

            try
            {
                calibrationConstants[selectedFingerIndex][0] = (decimal)Math.Round(constants[2], 4);
                calibrationConstants[selectedFingerIndex][1] = (decimal)Math.Round(constants[1], 4);
                calibrationConstants[selectedFingerIndex][2] = (decimal)Math.Round(constants[0], 4);

                saveCalibrationData();

                string message = english ? "Calibration succesful!" : "Kalibratie succesvol!";
                MessageBox.Show(message, "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch
            {
                MessageBox.Show("Kalibratie is niet gelukt :(\n Misschien is er iets mis gegaan met de verbinding, u kunt proberen dit te resetten.", "Mislukt", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            exportDataBtn.Enabled = true;
        }
    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.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);
        }
    }
Пример #10
0
        public static double FitToPolynomial(double[] xdata, double[] ydata, out double[] coeff)
        {
            double minTime = double.MaxValue;
            double maxTime = double.MinValue;

            foreach (double val in xdata)
            {
                if (val > maxTime)
                {
                    maxTime = val;
                }
                if (val < minTime)
                {
                    minTime = val;
                }
            }
            var omega = 1.0 / (maxTime - minTime);

            double[] xNormed = new double[xdata.Length];
            for (int i = 0; i < xdata.Length; i++)
            {
                xNormed[i] = xdata[i] * omega;
            }

            coeff = Fit.Polynomial(xdata, ydata, 2);

            return(AreaUnderTheCurve(minTime, maxTime, coeff));
        }
Пример #11
0
        public void FitsToOrder2PolynomialSameAsExcelTrendLine()
        {
            // X	Y
            // 1   0.2
            // 2   0.3
            // 4   1.3
            // 6   4.2
            // -> y = 0.7101 - 0.6675*x + 0.2077*x^2

            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.Polynomial(x, y, 2);

            Assert.AreEqual(0.7101, resp[0], 1e-3);
            Assert.AreEqual(-0.6675, resp[1], 1e-3);
            Assert.AreEqual(0.2077, resp[2], 1e-3);

            var resf = Fit.PolynomialFunc(x, y, 2);

            foreach (var z in Enumerable.Range(-3, 10))
            {
                Assert.AreEqual(0.7101 - 0.6675 * z + 0.2077 * z * z, resf(z), 1e-2);
            }
        }
Пример #12
0
 /// <summary>
 /// 根据 公式ID,拟合数据,返回公式系数
 /// </summary>
 /// <param name="EQID"></param>
 /// <param name="x_arr"></param>
 /// <param name="y_arr"></param>
 /// <returns></returns>
 public static double[] CurveFitting(int EQID, double[] x_arr, double[] y_arr)
 {
     double[] Coefs_arr;
     if (EQID == PPMConsts.PerformanceMD_power_ID)
     {
         double[] y_hat = Generate.Map(y_arr, Math.Log);
         Coefs_arr = Fit.LinearCombination(x_arr, y_hat, DirectRegressionMethod.QR, t => 1.0, t => t);
         return(new[] { Math.Exp(Coefs_arr[0]), Coefs_arr[1], 0 });
     }
     else if (EQID == PPMConsts.PerformanceMD_poly2nd_ID)
     {
         //var design = Matrix<double>.Build.Dense(x_arr.Length, 3, (i, j) => Math.Pow(x_arr[i], j));
         //return MultipleRegression.QR(design, Vector<double>.Build.Dense(y_arr)).ToArray();
         Coefs_arr = Fit.Polynomial(x_arr, y_arr, 2, DirectRegressionMethod.QR);
         return(Coefs_arr);
     }
     else if (EQID == PPMConsts.PerformanceMD_mihanshu_ID)
     {
         Power_Paras   Param      = Power_ISM(x_arr, y_arr);
         List <double> Coefs_list = new List <double>();
         Coefs_list.Add(Param.C);
         Coefs_list.Add(Param.m);
         Coefs_list.Add(Param.P);
         Coefs_arr = Coefs_list.ToArray();
         return(Coefs_arr);
     }
     else
     {
         throw new Exception("Unknown Equation ID: 30id ");
     }
 }
Пример #13
0
        /// <summary>
        /// Least-Squares fitting the points (x, y) to a k-order polynomial
        /// y : x -> p0 + p1 * x + p2 * x^2 + ... + pk * x^k.
        /// </summary>
        public static IModelledFunction PolynomialFunc(double[] xArray, double[] yArray, int order)
        {
            double[] parameters = Fit.Polynomial(xArray, yArray, order);

            Func <double, double> function = t => Polynomial.Evaluate(t, parameters);

            return(new PolynomialFunction(function, parameters));
        }
Пример #14
0
        public bool Exists2()
        {
            try
            {
                var curve = _spectrum.SpectrumData.Where(p => p.X >= 700 && p.X <= 900).ToList();
                var x     = curve.Select(p => p.X).ToArray();
                var y     = curve.Select(p => p.Y).ToArray();
                var minY  = y.Min();
                var maxY  = y.Max();
                y = y.Select(p => (p - minY) / (maxY - minY)).ToArray();

                //fit cubic function
                var p3 = Fit.Polynomial(x, y, 3);
                //y = p3[3]x^3 + p3[2]x^2 + p3[1]x + p3[0]
                var pointOfInflectionX     = (-1 * p3[2]) / (3 * p3[3]);
                var pointOfInflectionY     = Polynomial.Evaluate(pointOfInflectionX, p3);
                var slopeAtInflectionPoint = 3 * p3[3] * pointOfInflectionX * pointOfInflectionX
                                             + 2 + p3[2] * pointOfInflectionX + p3[1];

                /*
                 * Debug.WriteLine("p3");
                 * foreach (var d in p3)
                 *  Debug.WriteLine(d);
                 * Debug.WriteLine(pointOfInflection + "," + Polynomial.Evaluate(pointOfInflection, p3));
                 * Debug.WriteLine(slopeAtInflectionPoint);
                 * for (int i = 0; i < x.Length; i++)
                 * {
                 *  String s = String.Format("{0},{1},{2}", x[i], y[i],
                 *      Polynomial.Evaluate(x[i], p3));
                 *  Debug.WriteLine(s);
                 * }
                 */

                bool rule1 = p3[3] > 0 && p3[2] < 0 && p3[1] > 0 && p3[0] < 0;
                if (!rule1)
                {
                    return(false);//wrong shape
                }
                bool rule2 = pointOfInflectionX > 800 && pointOfInflectionX <850 && pointOfInflectionY> 0.5;
                if (!rule2)
                {
                    return(false);//wrong position
                }
                bool rule3 = slopeAtInflectionPoint > 2 && slopeAtInflectionPoint < 4;
                if (!rule3)
                {
                    return(false);//wrong curve
                }
                return(true);
            }
            catch
            {
            }

            return(true);
        }
Пример #15
0
        public bool CheckDiamondCurve()
        {
            try
            {
                //normalize
                var curve = _spectrum.SpectrumData.Where(p => p.X >= 415 && p.X <= 500).ToList();
                var x     = curve.Select(p => p.X).ToArray();
                var y     = curve.Select(p => p.Y).ToArray();
                var minY  = y.Min();
                var maxY  = y.Max();
                y     = y.Select(p => (p - minY) / (maxY - minY)).ToArray();
                curve = x.Zip(y, (xp, yp) => new System.Windows.Point(xp, yp)).ToList();

                //fit quadratic function
                var xq = curve.Select(p => p.X).ToArray();
                var yq = curve.Select(p => p.Y).ToArray();
                var p2 = Fit.Polynomial(xq, yq, 2);
                //y = p2[2]x^2 + p2[1]x + p2[0]

                if ((p2[2] >= -0.00055) && (p2[2] <= -0.0003) &&
                    (p2[1] >= 0.25) && (p2[1] <= 0.5) &&
                    (p2[0] >= -110) && (p2[0] <= -60))
                {
                    return(true);
                }

                //normalize
                var curve1 = _spectrum.SpectrumData.Where(p => p.X >= 423 && p.X <= 447).ToList();
                var y2     = curve1.Select(p => p.Y).ToList();
                var minY2  = y2.Min();
                var maxY2  = y2.Max();
                y2 = y2.Select(p => (p - minY2) / (maxY2 - minY2)).ToList();
                List <double> Y2_sum = new List <double>();
                Y2_sum.Add(y2.First());
                for (int i = 1; i < y2.Count; i++)
                {
                    Y2_sum.Add(Y2_sum[i - 1] + y2[i]);
                }
                var Y2_diff       = Y1_sum.Zip(Y2_sum, (y_1, y_2) => Math.Abs(y_1 - y_2)).ToList();
                var dissimilarity = Y2_diff.Max();
                if (dissimilarity < 10)
                {
                    return(true);
                }


                return(false);
            }
            catch
            {
            }

            return(true);
        }
Пример #16
0
 /// <summary>
 /// Performs a polynomial regression.
 /// </summary>
 /// <param name="x">x data</param>
 /// <param name="y">y data</param>
 /// <param name="n">Degree of polynomial.</param>
 /// <returns></returns>
 public static double[] PolyFit(double[] x, double[] y, int n)
 {
     double[] coeffs = Fit.Polynomial(x, y, n);
     return(Generate.Map(x, xi =>
     {
         double term = 0.0;
         for (int i = 0; i < coeffs.Length; i++)
         {
             term += coeffs[i] * Math.Pow(xi, i);
         }
         return term;
     }));
 }
Пример #17
0
        public static void CalibrateWavelengthForPosition(Vector <double> z, Vector <double> w)
        {
            double[] fit   = Fit.Polynomial(z.ToArray(), w.ToArray(), 2);
            var      model = z.PointwiseMultiply(z) * fit[2] + z * fit[1] + fit[0];
            var      dif   = model - w;
            double   rms   = Math.Sqrt(dif.DotProduct(dif) / (calibration_points + 1));

            WebApiApplication.calibration.K0       = fit[0];
            WebApiApplication.calibration.K1       = fit[1];
            WebApiApplication.calibration.K2       = fit[2];
            WebApiApplication.calibration.State    = MbrCalibration.Calibrated;
            WebApiApplication.calibration.RmsError = rms;
        }
Пример #18
0
        /// <summary>
        /// Takes the position and intensity average arrays and fits a polynomial
        /// </summary>
        /// <param name="z">z position / height</param>
        /// <param name="Data">average intensity</param>
        /// <returns>returns maximum point</returns>
        internal double FitPolynomial(double[] z, double[] Data)
        {
            //runs Math numerics fit polynomial finction
            double[] p = Fit.Polynomial(z, Data, 2);
            //performs operations to find maxima
            double a = p[1];
            double b = p[2];

            b = b * 2;
            double max = -a / b;

            return(max);
        }
Пример #19
0
    // Implmenentation of the Savitsky Golay Filter.  I am not sure that this implementation follows the exact defitinition.
    // Basically we fit a line to the previous points (I found that a line worked the best) and adjust the point
    // based on the point where it existed on the line.
    private double SavGolay(double[] x, double[] y, int polyOrder = 1)
    {
        double[] fit    = Fit.Polynomial(x, y, polyOrder);
        double   retVal = 0.0;


        for (int i = 0; i <= polyOrder; i++)
        {
            retVal += fit[i] * Math.Pow(x[x.Length / 2], i);
        }

        return(retVal);
    }
Пример #20
0
        public void FitsToMeanOnOrder0Polynomial()
        {
            // Mathematica: Fit[{{1,4.986},{2,2.347},{3,2.061},{4,-2.995},{5,-2.352},{6,-5.782}}, {1}, x]
            // -> -0.289167

            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.Polynomial(x, y, 0);

            Assert.AreEqual(1, resp.Length);
            Assert.AreEqual(-0.289167, resp[0], 1e-4);
            Assert.AreEqual(y.Mean(), resp[0], 1e-4);
        }
Пример #21
0
        public InterpolatedUnit _Fitter(double[] values, double[] places, int order)
        {
            int arrayLength = values.Length;

            double[] fit          = Fit.Polynomial(places, values, order);
            double[] fittedValues = new double[arrayLength];
            for (int i = 0; i < arrayLength; i++)
            {
                fittedValues[i] = Polynomial.Evaluate(i, fit);
            }
            double error = _ErrorOfFit(values, fittedValues);

            return(new InterpolatedUnit {
                value = (int)Polynomial.Evaluate(arrayLength >> 1, fit), goodnessOfFit = error
            });
        }
Пример #22
0
        private Func <double, double> CreateFitMethod(double[] xData, double[] yData)
        {
            var p = Fit.Polynomial(xData, yData, PolynomialOrder);

            var func = new Func <double, double>(x =>
            {
                var endResult = p[0];
                for (var i = 1; i <= PolynomialOrder; i++)
                {
                    endResult += (p[i] * Math.Pow(x, i));
                }
                return(endResult);
            });

            return(func);
        }
        public PolynomialInjectWithdrawConstraint([NotNull] IEnumerable <InjectWithdrawRangeByInventory> injectWithdrawRanges,
                                                  double newtonRaphsonAccuracy = 1E-10, int newtonRaphsonMaxNumIterations = 100, int newtonRaphsonSubdivision = 20)
        {
            if (injectWithdrawRanges == null)
            {
                throw new ArgumentNullException(nameof(injectWithdrawRanges));
            }

            // TODO check in MATH.NET that this preconditions are consistent with their implementation
            if (newtonRaphsonAccuracy < 0)
            {
                throw new ArgumentException("Newton Raphson Accuracy must be positive number.", nameof(newtonRaphsonAccuracy));
            }
            if (newtonRaphsonMaxNumIterations < 2)
            {
                throw new ArgumentException("Newton Raphson max number of iteration must be at least 2.", nameof(newtonRaphsonMaxNumIterations));
            }
            if (newtonRaphsonSubdivision < 1)
            {
                throw new ArgumentException("Newton Raphson subdivision must be at least 1.", nameof(newtonRaphsonSubdivision));
            }

            List <InjectWithdrawRangeByInventory> injectWithdrawRangesList = injectWithdrawRanges.ToList();

            if (injectWithdrawRangesList.Count < 2)
            {
                throw new ArgumentException("At least 2 inject/withdraw constraints must be specified", nameof(injectWithdrawRanges));
            }

            double[] inventories            = injectWithdrawRangesList.Select(iwi => iwi.Inventory).ToArray();
            double[] maxInjectWithdrawRates = injectWithdrawRangesList.Select(iwi => iwi.InjectWithdrawRange.MaxInjectWithdrawRate).ToArray();
            double[] minInjectWithdrawRates = injectWithdrawRangesList.Select(iwi => iwi.InjectWithdrawRange.MinInjectWithdrawRate).ToArray();

            // Polynomial of order n can be fitted exactly to n + 1 data points
            int polyOrder = injectWithdrawRangesList.Count - 1;

            _maxInjectWithdrawPolynomial         = new Polynomial(Fit.Polynomial(inventories, maxInjectWithdrawRates, polyOrder));
            _maxInjectWithdrawPolynomial1StDeriv = _maxInjectWithdrawPolynomial.Differentiate();

            _minInjectWithdrawPolynomial         = new Polynomial(Fit.Polynomial(inventories, minInjectWithdrawRates, polyOrder));
            _minInjectWithdrawPolynomial1StDeriv = _minInjectWithdrawPolynomial.Differentiate();

            _newtonRaphsonAccuracy         = newtonRaphsonAccuracy;
            _newtonRaphsonMaxNumIterations = newtonRaphsonMaxNumIterations;
            _newtonRaphsonSubdivision      = newtonRaphsonSubdivision;
        }
Пример #24
0
        public static void FitGaussian(int[] data, int[] peakData, int index, int window, string fileName)
        {
            var logData = data.Where((x, i) => i > peakData[index] - window && i < peakData[index] + window).Select(x => x != 0 ? Math.Log(x) : 0).ToArray();
            var xData   = Enumerable.Range(peakData[index] - window, logData.Length).Select(x => (double)x).ToArray();

            double[] p        = Fit.Polynomial(xData, logData, 2);
            var      sigma    = Math.Sqrt(-(1 / (p[2])));
            var      centroid = -(p[1] / (2 * p[2]));
            var      area     = Math.Pow(Math.E, (p[0] + (p[1] * p[1]) / 2.0));

            // Write them to a file
            using (StreamWriter writetext = new StreamWriter(String.Format("{0}_{1}_fitData.txt", fileName, index)))
            {
                writetext.WriteLine("{0}:{1}:{2}", area, centroid, sigma);
            }
            return;
        }
Пример #25
0
        /// <summary>
        /// Polynominal 커브피팅
        /// </summary>
        /// <param name="x">x축 값 배열</param>
        /// <param name="y">y축 값 배열</param>
        /// <param name="order">커브피팅하고자 하는 다항식 차수</param>
        /// <returns></returns>
        //다항 커브피팅 6차 다항식까지 지원
        public static double[] polynominalRegression(double[] x, double[] y, int order) // x: x 배열, y: y: 배열, order :차수
        {
            double[] p  = Fit.Polynomial(x, y, order);                                  //curve fitting 하여 반환
            double   R2 = 0;

            switch (order)
            {
            case 2:
                R2 = GoodnessOfFit.RSquared(x.Select(d => p[0] + p[1] * d + p[2] * Math.Pow(d, 2)), y);
                break;

            case 3:
                R2 = GoodnessOfFit.RSquared(x.Select(d => p[0] + p[1] * d + p[2] * Math.Pow(d, 2) + p[3] * Math.Pow(d, 3)), y);
                break;

            case 4:
                R2 = GoodnessOfFit.RSquared(x.Select(d => p[0] + p[1] * d + p[2] * Math.Pow(d, 2) + p[3] * Math.Pow(d, 3) + p[4] * Math.Pow(d, 4)), y);
                break;

            case 5:
                R2 = GoodnessOfFit.RSquared(x.Select(d => p[0] + p[1] * d + p[2] * Math.Pow(d, 2) + p[3] * Math.Pow(d, 3) + p[4] * Math.Pow(d, 4) + p[5] * Math.Pow(d, 5)), y);
                break;

            case 6:
                R2 = GoodnessOfFit.RSquared(x.Select(d => p[0] + p[1] * d + p[2] * Math.Pow(d, 2) + p[3] * Math.Pow(d, 3) + p[4] * Math.Pow(d, 4) + p[5] * Math.Pow(d, 5) + p[6] * Math.Pow(d, 6)), y);
                break;

            case 7:
                R2 = GoodnessOfFit.RSquared(x.Select(d => p[0] + p[1] * d + p[2] * Math.Pow(d, 2) + p[3] * Math.Pow(d, 3) + p[4] * Math.Pow(d, 4) + p[5] * Math.Pow(d, 5) + p[6] * Math.Pow(d, 6)), y);
                break;

            case 8:
                R2 = GoodnessOfFit.RSquared(x.Select(d => p[0] + p[1] * d + p[2] * Math.Pow(d, 2) + p[3] * Math.Pow(d, 3) + p[4] * Math.Pow(d, 4) + p[5] * Math.Pow(d, 5) + p[6] * Math.Pow(d, 6)), y);
                break;
            }

            double[] result = new double[order + 2];
            result[0] = R2;

            for (var i = 0; i <= order; i++)
            {
                result[i + 1] = p[i];
            }

            return(result);
        }
Пример #26
0
        public void testRegression()
        {
            Console.WriteLine("---------------------------");
            var ans = Fit.Line(X, Y);
            var a   = ans.Item1;
            var b   = ans.Item2;

            Console.WriteLine("intercept:{0}, slope:{1}", ans.Item1, ans.Item2);
            Console.WriteLine("r^2:" + GoodnessOfFit.RSquared(X.Select(x => a + b * x), Y));

            Console.WriteLine("-------------------------");
            var p = Fit.Polynomial(X, Y, 3);

            Console.WriteLine("p:" + string.Join(",", p));
            Console.WriteLine("r^2:" + GoodnessOfFit.RSquared(X.Select(x => p[0] + p[1] * x + p[2] * x * x + p[3] * x * x * x), Y));
            Assert.True(true);
        }
        private void button4_Click_1(object sender, EventArgs e)
        {
            //requires MathNet
            double[] xdata = new double[] { 10, 20, 30, 40 };
            double[] ydata = new double[] { 18, 20, 25, 45 };

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

            //xdataList.Insert(0,0);
            //ydataList.Insert(0,0);

            xdata = xdataList.ToArray();
            ydata = ydataList.ToArray();


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


            chart2.Series.Add("j");
            //set chart type
            chart2.Series["j"].ChartType   = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            chart2.Series["j"].BorderWidth = myBorderWidth;
            chart2.Series["j"].Color       = System.Drawing.Color.Green;

            chart2.Series.Add("k");
            //set chart type
            chart2.Series["k"].ChartType   = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            chart2.Series["k"].BorderWidth = myBorderWidth;
            chart2.Series["k"].Color       = System.Drawing.Color.Blue;

            for (int i = 0; i < xdata.Length; i++)
            {
                chart2.Series["j"].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["k"].Points.AddXY(newx, newy);
            }
        }
Пример #28
0
        List <double> UpdateLinRegEquation(double[] KG, double[] MV)
        {
            List <double> linregTemp = new List <double>();

            if (KG.Count() > 2)
            {
                double[] p    = Fit.Polynomial(MV, KG, 1);
                double   rSqr = GoodnessOfFit.RSquared(MV.Select(x => p[1] * x + p[0]), KG);
                linregTemp.Add(p[1]);
                linregTemp.Add(p[0]);
                linregTemp.Add(rSqr);
                this.BeginInvoke(new Action(() =>
                {
                    if (tipoSelected == "1D - 500x500")
                    {
                        EquationBox.Text = "Fy: " + Math.Round(linregTemp[0], 5) + "x + (" + Math.Round(linregTemp[1], 5) + ") [Kg] --> " + "R2: " + Math.Round(linregTemp[2], 5);
                    }
                    //EquationBox.Text = "Fy: " + Math.Round(SLOPE, 5) + "x + (" + Math.Round(INTERCEPT, 5) + ") [Kg] --> " + "R2: " + Math.Round(RSQR, 5);
                    else if (tipoSelected == "3D - 500x500")
                    {
                        if (FyCheckBox.Checked)
                        {
                            EquationBox.Text = "Fy: " + Math.Round(linregTemp[0], 5) + "x + (" + Math.Round(linregTemp[1], 5) + ") [Kg] --> " + "R2: " + Math.Round(linregTemp[2], 5);
                        }
                        if (MxCheckBox.Checked)
                        {
                            EquationBox.Text = "Mx: " + Math.Round(linregTemp[0], 5) + "x + (" + Math.Round(linregTemp[1], 5) + ") [Kg] --> " + "R2: " + Math.Round(linregTemp[2], 5);
                        }
                        if (MzCheckBox.Checked)
                        {
                            EquationBox.Text = "Mz: " + Math.Round(linregTemp[0], 5) + "x + (" + Math.Round(linregTemp[1], 5) + ") [Kg] --> " + "R2: " + Math.Round(linregTemp[2], 5);
                        }
                    }
                }));
            }
            else
            {
                this.BeginInvoke(new Action(() =>
                {
                    EquationBox.Text = "São necessários pelo menos 3 medidas.";
                }));
            }
            return(linregTemp);
        }
        private void RegressionMC()
        {
            LeastSquareMatrix[(int)(EnvironmentSettings.Instance.GridForTime - 1)] = MC_PayOff[(int)(EnvironmentSettings.Instance.GridForTime - 1)];
            for (var i = (int)(EnvironmentSettings.Instance.GridForTime - 1); i > 0; i--)
            {
                var regression = Fit.Polynomial(MC_PriceMatrix[i - 1].Item2,
                                                LeastSquareMatrix[i].Select(x => x * this.Discount).ToArray(), EnvironmentSettings.Instance.PolynomialDegree);
                var continuation_value = MC_PriceMatrix[i - 1].Item2.Select(x => Polynomial.Evaluate(x, regression)).ToArray();

                var newVal = new double[this.Simulations];
                if (EnvironmentSettings.Instance.IsParallel)
                {
                    Parallel.For(0, this.Simulations, (i1) =>
                    {
                        if (MC_PayOff[i - 1][i1] > continuation_value[i1])
                        {
                            newVal[i1] = MC_PayOff[i - 1][i1];
                        }
                        else
                        {
                            newVal[i1] = LeastSquareMatrix[i][i1] * this.Discount;
                        }
                    });
                }
                else
                {
                    for (var i1 = 0; i1 < this.Simulations; i1++)
                    {
                        if (MC_PayOff[i - 1][i1] > continuation_value[i1])
                        {
                            newVal[i1] = MC_PayOff[i - 1][i1];
                        }
                        else
                        {
                            newVal[i1] = LeastSquareMatrix[i][i1] * this.Discount;
                        }
                    }
                }

                LeastSquareMatrix[i - 1] = newVal;
            }
        }
Пример #30
0
        void LinRegRaw()
        {
            try
            {
                LinRegChart.Series.Clear();
                LinRegChart.ChartAreas[0].CursorX.IsUserEnabled          = false;
                LinRegChart.ChartAreas[0].CursorY.IsUserEnabled          = false;
                LinRegChart.ChartAreas[0].AxisX.ScaleView.Zoomable       = false;
                LinRegChart.ChartAreas[0].AxisY.ScaleView.Zoomable       = false;
                LinRegChart.ChartAreas[0].CursorX.AutoScroll             = false;
                LinRegChart.ChartAreas[0].CursorY.AutoScroll             = false;
                LinRegChart.ChartAreas[0].CursorX.IsUserSelectionEnabled = false;
                LinRegChart.ChartAreas[0].CursorY.IsUserSelectionEnabled = false;

                double[] KGinit = { 0, 10, 20, 30, 40, 50, 60 };
                double[] MVinit = { 0, 5, 10, 15, 20, 25, 30 };
                double[] p      = Fit.Polynomial(MVinit, KGinit, 2);
                double   rSqr   = GoodnessOfFit.RSquared(MVinit.Select(x => p[1] * x + p[2]), KGinit);
                EquationBox.Text = "Fy: " + Math.Round(p[1], 5) + "x + (" + Math.Round(p[2], 5) + ") [Kg] --> " + "R2: " + Math.Round(rSqr, 5);

                Series s = new Series();
                for (int i = 0; i < KGinit.Count(); i++)
                {
                    s.Points.AddXY(KGinit[i], MVinit[i]);
                }
                LinRegChart.Series.Add(s);
                LinRegChart.Series[0].ChartType       = SeriesChartType.Point;
                LinRegChart.Series[0].Color           = Color.Blue;
                LinRegChart.Series[0].BorderWidth     = 3;
                LinRegChart.ChartAreas[0].AxisX.Title = "Carga Vertical (KG)";
                LinRegChart.ChartAreas[0].AxisY.Title = "Tensão (mV)";

                LinRegChart.ChartAreas[0].AxisX.Maximum  = 60;
                LinRegChart.ChartAreas[0].AxisX.Minimum  = 0;
                LinRegChart.ChartAreas[0].AxisX.Interval = 10;
                LinRegChart.ChartAreas[0].AxisY.Maximum  = 30;
                LinRegChart.ChartAreas[0].AxisY.Minimum  = 0;
                LinRegChart.ChartAreas[0].AxisY.Interval = 5;
            }
            catch (Exception ex) { MessageBox.Show("Erro: " + ex.Message); }
        }