示例#1
0
        private static async Task <(double R2, double Beta)> RollingRegression(string fundCode, string index, DateTime end)
        {
            var fundExcessReturn = await GetFundExcessReturn(fundCode, end.AddDays(-13 * 7), end);

            if (!fundExcessReturn.Any())
            {
                return(double.NaN, 1);
            }

            var styleExcessReturn = GetStyleExcessReturn(index, end.AddDays(-13 * 7), end);
            var y = new List <double>();
            var x = new List <double>();

            foreach (var item in styleExcessReturn)
            {
                var fundItem = fundExcessReturn.FirstOrDefault(it => it.Begin == item.Begin);
                if (fundItem == null)
                {
                    continue;
                }

                y.Add((double)fundItem.ExcessReturn);
                x.Add((double)item.ExcessReturn);
            }
            if (x.Count < 2)
            {
                return(double.NaN, 1);
            }

            var fitResult = Fit.Line(x.ToArray(), y.ToArray());
            var y2        = x.Select(item => fitResult.Item1 + fitResult.Item2 * item).ToArray();

            return(GoodnessOfFit.RSquared(y2, y), fitResult.Item2);
        }
        public void DrawRegressionLine()
        {
            var theta = Fit.Line(Data.OrderBy(d => d.Item1).Select(d => d.Item1).ToArray(), Data.OrderBy(d => d.Item1).Select(d => d.Item2).ToArray());

            var x = Expr.Variable("x");
            var a = Expr.Variable("a");
            var b = Expr.Variable("b");

            a = System.Math.Round(theta.Item2, 2);
            b = System.Math.Round(theta.Item1, 2);

            Func <double, double> fx = (a * x + b).Compile("x");

            if (_regressionPlot != null)
            {
                Series.plt.Remove(_regressionPlot);
            }

            var x1 = Data.OrderBy(d => d.Item1).First().Item1;
            var y1 = fx(Data.OrderBy(d => d.Item1).First().Item1);
            var x2 = Data.OrderBy(d => d.Item1).Last().Item1;
            var y2 = fx(Data.OrderBy(d => d.Item1).Last().Item1);

            _regressionPlot = Series.plt.PlotLine(x1, y1, x2, y2, color: System.Drawing.Color.Red);

            Series.plt.PlotText($"{System.Math.Round(fx(25), 2)}", 17, fx(25), System.Drawing.Color.Red, fontSize: 16);
            Series.Render();

            ;
        }
 public async Task <Tuple <double, double> > AlphaFromRawData(List <RawLJVDatum> data)
 {
     return(await Task.Run(() =>
     {
         Tuple <double, double> alphaAndR2 = new Tuple <double, double>(-1, 0.001);
         List <double> pdBCData = new List <double>();
         List <double> camData = new List <double>();
         foreach (RawLJVDatum raw in data)
         {
             if (raw.CameraLuminance != null)
             {
                 //interpolate readings to account for device instability
                 pdBCData.Add(Convert.ToDouble((raw.PhotoCurrentB + raw.PhotoCurrentC)) / 2.0f);
                 camData.Add(Convert.ToDouble(raw.CameraLuminance));
             }
         }
         if (camData.Count > 2)
         {
             double[] xdata = pdBCData.ToArray();
             double[] ydata = camData.ToArray();
             Tuple <double, double> p = Fit.Line(xdata, ydata);
             Debug.WriteLine("Measured Alpha = " + p.Item2);
             double rsquared = GoodnessOfFit.RSquared(xdata.Select(x => p.Item1 + p.Item2 *x), ydata);
             alphaAndR2 = new Tuple <double, double>(p.Item2, rsquared);
             Debug.WriteLine("R^2 was: " + rsquared);
         }
         //take the ratio from a single measurement if not enough data for linear regression
         else if (camData.Count <= 2 && camData.Count >= 1)
         {
             double ratioAlpha = camData.Last() / pdBCData.Last();
             alphaAndR2 = new Tuple <double, double>(ratioAlpha, 0);
         }
         return alphaAndR2;
     }).ConfigureAwait(false));
 }
示例#4
0
    private void calcMeanPlane(List <propagationStep> path, out Vector2 start, out Vector2 end)
    {
        List <double> xdata = new List <double>();
        List <double> ydata = new List <double>();

        foreach (propagationStep step in path)
        {
            xdata.Add(step.distance);
            ydata.Add(step.groundLevel);
        }
        //Check if there is only one point, then set the mean plane to a straight line
        if (xdata.Count < 2 || ydata.Count < 2)
        {
            start = new Vector2((float)xdata[0], (float)ydata[0]);
            end   = start + Vector2.right;
            return;
        }
        //If there are more then two, we need to use numerics
        System.Tuple <double, double> p = Fit.Line(xdata.ToArray(), ydata.ToArray());
        //In this tuple we have the coefficients of the line equation a and b
        //Translate into start and end vectors
        float a = (float)p.Item1;
        float b = (float)p.Item2;

        start.x = path.First().distance;
        start.y = a + path.First().distance *b;
        end.x   = path.Last().distance;
        end.y   = a + path.Last().distance *b;
        return;
    }
示例#5
0
        /// <inheritdoc />
        async Task <BloatCoefficients> IBloatAnalysis.ExecuteAsync()
        {
            var averageBloatHistory = await LoadHistory().ToArrayAsync();

            // At least two values are required to build approximated linear function.
            if (averageBloatHistory.Length < 2)
            {
                throw Error.NoBloatHistory();
            }

            var leftTimeBound = averageBloatHistory
                                .First()
                                .LogTimestamp;

            // abscissa values are shift to left, so selection values starts from zero.
            var abscissaValues = averageBloatHistory
                                 .Select(entry => (double)entry.LogTimestamp.Ticks)
                                 .Select(ticks => ticks - leftTimeBound.Ticks)
                                 .ToArray();

            var ordinateValues = averageBloatHistory
                                 .Select(entry => (double)(decimal)entry.AverageBloatFraction)
                                 .ToArray();

            // approximate bloat fraction selection to linear function.
            var(intercept, slope) = Fit.Line(abscissaValues, ordinateValues);
            return(new BloatCoefficients(intercept, slope));
        }
    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);
        }
    }
示例#7
0
        public bool Test(double start_wl, double end_wl, double max_slope, double min_slope, double max_error,
                         out bool noisyFit, out double slope)
        {
            noisyFit = false;

            //normalize
            var curve = _spectrum.SpectrumData;
            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();

            var roi = curve.Where(p => p.X >= start_wl && p.X <= end_wl).ToList();

            x = roi.Select(p => p.X).ToArray();
            y = roi.Select(p => p.Y).ToArray();

            var    linear        = Fit.Line(x, y);
            double intercept     = linear.Item1;
            double s             = linear.Item2;
            var    standardError = GoodnessOfFit.PopulationStandardError(x.Select(d => s * d + intercept), y);

            if (Math.Round(standardError, 3) > max_error)
            {
                noisyFit = true;
            }

            slope = s;
            bool res = (!noisyFit) && (slope >= min_slope) && (slope <= max_slope);

            return(res);
        }
示例#8
0
        public LinearViewModel(double[] xdata, double[] ydata, Tuple <double, double> xlimit, Tuple <double, double> ylimit)
        {
            Tuple <double, double> p = Fit.Line(xdata, ydata);
            double a = p.Item1;
            double b = p.Item2;

            if (!Double.IsNaN(a) && !Double.IsNaN(b))
            {
                this.FunctionModel = new PlotModel {
                    Title = "Linear regresion [ f(x) = " + b + " x + " + a + " ]"
                };
                Func <double, double> linearFunction = (x) => (b * x) + a;
                FunctionModel.Series.Add(new FunctionSeries(linearFunction, xlimit.Item1, xlimit.Item2, 0.0001));
                // view limits
                FunctionModel.Axes.Add(new LinearAxis {
                    Position = AxisPosition.Bottom, Minimum = xlimit.Item1, Maximum = xlimit.Item2
                });
                FunctionModel.Axes.Add(new LinearAxis {
                    Position = AxisPosition.Left, Minimum = ylimit.Item1, Maximum = ylimit.Item2
                });
            }
            else
            {
                displayed = false;
            }
        }
        /// https://numerics.mathdotnet.com/Regression.html#Evaluating-the-model-at-specific-data-points
        /// Linear: y = (a * x) + b
        private void ApplyLinearFitting()
        {
            double[] xdata = Points.Select(p => p.X).ToArray();
            double[] ydata = Points.Select(p => p.Y).ToArray();

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

            A = a;
            B = b;

            //Func<double, double> f = Fit.LineFunc(xdata, ydata);

            Func <double, double> f = Fit.LinearCombinationFunc(
                xdata,
                ydata,
                x => a * x,
                x => b);

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

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

            FittedPoints = fittedPoints;
        }
示例#10
0
        /*左边补偿,拟合出的斜率给最右边的点*/
        static List <double> QCDSDataFit2(List <double> listX, List <double> listY, int factor)
        {
            //k为拟合的斜率曲线Y轴数组,factor 为拟合的点数,listX为轮廓横坐标数组,listY为轮廓纵坐标数组
            double[] x = new double[factor];
            double[] y = new double[factor];
            Tuple <double, double> s = new Tuple <double, double>(0, 0);
            List <double>          k = new List <double>();
            int count = listX.Count;

            if (count != listY.Count)//数组大小不一致,抛出异常?
            {
                return(k);
            }

            for (int pos = 0; pos < count - factor; pos++)//count - factor为迭代的右边界
            {
                for (int j = 0; j < factor; j++)
                {
                    x[j] = listX.ElementAt(pos + j);

                    y[j] = listY.ElementAt(pos + j);
                }
                s = Fit.Line(x, y);
                k.Add(s.Item2);
            }
            double first = k.First <double>();//填充边界空出的点数

            for (int j = 0; j < factor; j++)
            {
                k.Insert(0, first);
            }

            return(k);
        }
示例#11
0
        public ComputedResultSetFitLine ComputeLinearData(List <DeviceValue> dataPoints)
        {
            var resultSet = new ComputedResultSetFitLine();

            double[] xdata = CreateXDataFromDateTimeToTotalSeconds(dataPoints);
            double[] ydata = CreateYDataFromDoubleValues(dataPoints);

            Tuple <double, double> p = Fit.Line(xdata, ydata);
            double intercept         = p.Item1; // == 10; intercept -- No clue what this is
            double slope             = p.Item2; // == 0.5; slope

            resultSet.Slope     = slope;
            resultSet.Intercept = intercept;
            if (slope > 0)
            {
                resultSet.IsAscending = true;
            }

            if (slope < 0)
            {
                resultSet.IsDescending = true;
            }

            return(resultSet);
        }
示例#12
0
        private int QtyByAnalysis(string itemId, int reqQtyLastM)
        {
            int        predict = 0;
            List <int> reqList;
            List <int> orderList;

            //2 arrarys: (1) request qty; (2) order qty
            GetReqAndOrderHistory(itemId, out reqList, out orderList);
            //early exit since there is no meaning for analysis if there are no requsitions or order data
            if (reqList.Sum() == 0 || orderList.Sum() == 0)
            {
                return(predict);
            }
            double[] reqArray   = new double[reqList.Count];
            double[] orderArray = new double[orderList.Count];
            for (int i = 0; i < reqList.Count; i++)
            {
                reqArray[i]   = Convert.ToDouble(reqList[i]);
                orderArray[i] = Convert.ToDouble(orderList[i]);
            }
            Tuple <double, double> p = Fit.Line(reqArray, orderArray);
            double a = p.Item1;
            double b = p.Item2;

            predict = (int)Math.Ceiling(b * reqQtyLastM + a);
            return(predict);
        }
示例#13
0
        public Double getAnalogPH()
        {
            double result = 0.0;

            PHAnalogItem setting = (PHAnalogItem)settings.CurrentSettings.GetComponent(ID);

            if (setting.ph4Voltage > 0 & setting.ph7Voltage > 0)
            {
                double[] x = { setting.ph4Voltage, setting.ph7Voltage };
                double[] y = { 4, 7 };

                try
                {
                    Tuple <double, double> p = Fit.Line(x, y);
                    double c = p.Item1;
                    double m = p.Item2;

                    //y = mx + c;
                    result = m * aDConverter.GetADVoltage(sensorId) + c;
                }
                catch (Exception e)
                {
                }
            }

            return(result);
        }
示例#14
0
        private static async Task FillAsync()
        {
            using (var db = new SqlLocalDB())
            {
                var es = new SqlEventStore(db.ConnectionString);

                await es.Database.InitializeAsync();

                var marks = new List <double>();

                for (int i = 0; i < 100; i++)
                {
                    var sw = Stopwatch.StartNew();

                    await es.WithBulkCopyAppend().AppendAsync(GetUncommittedSource(1000, 100000));

                    var mark = 100000 / sw.Elapsed.TotalSeconds;
                    var size = new FileInfo(db.FileName).Length / (1024d * 1024d);

                    marks.Add(mark);

                    if (marks.Count > 1)
                    {
                        var fit = Fit.Line(Enumerable.Range(1, marks.Count).Select(x => (double)x).ToArray(), marks.ToArray());

                        Console.WriteLine($"{mark,9:N1} op/s {size,10:N0} MiB {fit.Item2,9:N1} op/s");
                    }
                    else
                    {
                        Console.WriteLine($"{mark,9:N1} op/s {size,10:N0} MiB");
                    }
                }
            }
        }
示例#15
0
        public double regression(List <Sensor> list, DateTime predictTime)
        {
            if (list == null)
            {
                throw new ArgumentException();
            }

            double[] x = new double[list.Count];
            double[] y = new double[list.Count];

            int i = 0;

            foreach (Sensor s in list)
            {
                x[i] = s.TimeStamp.Ticks;
                y[i] = s.CurrentVoltage;

                ++i;
            }

            Tuple <double, double> linear = Fit.Line(x, y);
            double p = predictTime.Ticks;

            double predict = linear.Item1 + (p * linear.Item2);

            return(predict);
        }
示例#16
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;
        }
示例#17
0
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                // NumberSeries =0 ;

                for (int i = 0; i < MyAllSensors.Count; i++)
                {
                    if (comboBox1.Text == MyAllSensors[i].KKS_Name)
                    {
                        IndexAFP = i;
                        break;
                    }
                }
                //  if (textBox1.Text == null || textBox1.Text == "")
                //    {
                //    textBox1.Text = MyAllSensors[IndexAFP].MyListRecordsForOneKKS.Count.ToString();
                // }
                int MyAverage = int.Parse(textBox1.Text.Trim());

                MyBeginIndex = MyAllSensors[IndexAFP].MyListRecordsForOneKKS.Count - MyAverage;

                //вообще здесь j должен равняться MyBeginIndex
                for (int j = MyBeginIndex; j < MyAllSensors[IndexAFP].MyListRecordsForOneKKS.Count; j++)
                {
                    double MyVal = MyAllSensors[IndexAFP].MyListRecordsForOneKKS[MyBeginIndex].Value / MyAllSensors[IndexAFP].MyListRecordsForOneKKS[j].Value;
                    //  MessageBox.Show(MyAllSensors[i].MyListRecordsForOneKKS[MyBeginIndex].Value.ToString() + " " + MyAllSensors[i].MyListRecordsForOneKKS[j].Value.ToString());

                    Y.Add(MyVal);
                    X.Add(MyAllSensors[IndexAFP].MyListRecordsForOneKKS[j].DateTime.ToOADate() - MyAllSensors[IndexAFP].MyListRecordsForOneKKS[MyBeginIndex].DateTime.ToOADate());
                    chart1.Series[NumberSeries].Points.AddXY(MyAllSensors[IndexAFP].MyListRecordsForOneKKS[j].DateTime, MyVal);
                }

                //chart1.Series[0].XValueType = ChartValueType.Time;
                NumberSeries++;

                Tuple <double, double> myLine1 = Fit.Line(X.ToArray(), Y.ToArray());

                double MyCritika = 0;
                for (int j = 0; j < X.Count; j++)
                {
                    chart1.Series[NumberSeries].Points.AddXY(MyAllSensors[IndexAFP].MyListRecordsForOneKKS[MyBeginIndex].DateTime.ToOADate() + X[j], X[j] * myLine1.Item2 + myLine1.Item1);
                }

                chart1.Series[NumberSeries].Points.AddXY(MyAllSensors[IndexAFP].MyListRecordsForOneKKS[MyBeginIndex].DateTime.ToOADate() + -myLine1.Item1 / myLine1.Item2, 0);

                MyCritika = MyAllSensors[IndexAFP].MyListRecordsForOneKKS[MyBeginIndex].DateTime.ToOADate() + -myLine1.Item1 / myLine1.Item2;

                chart1.Series[0].XValueType = ChartValueType.Time;
                chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
                label1.Text = "Критическое состояние в " + DateTime.FromOADate(MyCritika);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            button3.Enabled = true;
            button5.Enabled = false;
        }
        private static Chart GetPurchasesByCategoryChart(ICollection <Purchase> purchases)
        {
            var chart = new Chart {
                Layout = { Title = "Purchases by Category" }
            };

            // Create total purchase line
            var totalPurchaseRegressionTraceData = new TraceData {
                Name = "Total purchase regression",
                Type = "scatter",
                Mode = "lines",
                Line = { Dash = "dot", Width = 4 }
            };
            var uniqueOrderDates   = purchases.Select(x => x.OrderDate.Date).Distinct().ToList();
            var xdata              = new List <double>();
            var ydata              = new List <double>();
            var oldestPurchaseDate = purchases.OrderBy(x => x.OrderDate).First().OrderDate;

            foreach (var uniqueOrderDate in uniqueOrderDates)
            {
                var purchaseTotal =
                    purchases.Where(x => x.OrderDate.Date == uniqueOrderDate)
                    .Select(x => x.UnitPrice * x.Quantity).Sum();
                var timespan = uniqueOrderDate - oldestPurchaseDate;
                xdata.Add(timespan.TotalHours);
                ydata.Add((double)purchaseTotal);
            }
            var p         = Fit.Line(xdata.ToArray(), ydata.ToArray());
            var intercept = p.Item1;
            var slope     = p.Item2;

            foreach (var point in xdata)
            {
                var regression = slope * point + intercept;
                var timespan   = TimeSpan.FromHours(point);
                totalPurchaseRegressionTraceData.X.Add(oldestPurchaseDate + timespan);
                totalPurchaseRegressionTraceData.Y.Add(regression);
            }
            chart.Data.Add(totalPurchaseRegressionTraceData);

            // TODO: Capture purchases with null category
            var categories = purchases.Where(x => x.CategoryId != null).Select(x => x.Category).Distinct().ToList();

            foreach (var category in categories)
            {
                var categoryTraceData = new TraceData {
                    Name = category.Name, Type = "scatter", Mode = "markers"
                };
                var purchasesInCategory = purchases.Where(x => x.CategoryId == category.Id).ToList();
                foreach (var purchaseInCategory in purchasesInCategory)
                {
                    categoryTraceData.X.Add(purchaseInCategory.OrderDate.Date);
                    categoryTraceData.Y.Add(purchaseInCategory.UnitPrice * purchaseInCategory.Quantity);
                }
                chart.Data.Add(categoryTraceData);
            }
            return(chart);
        }
        /// <summary>
        /// Calculates the depth from surface that a PDD will drop below the percent provided. percent=50 would yield the depth at which the profile falls to below 0.5*Peak
        /// </summary>
        /// <param name="doseValues">PDD Profile data</param>
        /// <param name="percent">Integer representing percent of depth of interest </param>
        /// <returns>The index of the furthest voxel from the surface that has a dose value above the percent of interest</returns>
        ///<exception cref="ArgumentOutOfRangeException">Thrown when the profile does not drop below the sought percent</exception>
        public static DoseValue DepthToPercentOfPeak(List <DoseValue> doseValues, int percent)
        {
            if (doseValues == null)
            {
                throw new ArgumentNullException(nameof(doseValues));
            }
            // finding value and location of maximum
            double max      = 0;
            int    indexMax = 0;

            for (int i = 0; i < doseValues.Count; i++)
            {
                if (doseValues[i].Dose > max)
                {
                    max      = doseValues[i].Dose;
                    indexMax = i;
                }
            }
            // I have the location and value of max
            double threshold = max * (double)percent / 100.0;

            for (int i = indexMax; i < doseValues.Count - 5; i++)
            {
                if (doseValues[i].Dose < threshold)
                {
                    double[] x = new double[5], y = new double[5], z = new double[5], dose = new double[5];
                    int      k = 0;
                    for (int j = i - 2; j <= i + 2; j++)
                    {
                        x[k]    = doseValues[j].X;
                        y[k]    = doseValues[j].Y;
                        z[k]    = doseValues[j].Z;
                        dose[k] = doseValues[j].Dose;
                        k++;
                    }
                    if (x[0] != x[1])
                    {
                        var retTuple = Fit.Line(x, dose);
                        var retX     = (threshold - retTuple.Item1) / retTuple.Item2;
                        return(new DoseValue(retX, y[0], z[0], threshold));
                    }
                    else if (y[0] != y[1])
                    {
                        var retTuple = Fit.Line(y, dose);
                        var retY     = (threshold - retTuple.Item1) / retTuple.Item2;
                        return(new DoseValue(x[0], retY, z[0], threshold));
                    }
                    else
                    {
                        var retTuple = Fit.Line(z, dose);
                        var retZ     = (threshold - retTuple.Item1) / retTuple.Item2;
                        return(new DoseValue(x[0], y[0], retZ, threshold));
                    }
                }
            }
            return(new DoseValue(-1, -1, -1, 0));
        }
示例#20
0
        //Private method to perform some operation that will NOT be exposed in Decisions
        private double[] PerformSimpleRegression(double[] xData, double[] yData)
        {
            //Use External Math.Net library to perform operations
            Tuple <double, double> p = Fit.Line(xData, yData);

            double a = p.Item1; // intercept
            double b = p.Item2; // slope

            return(new double[] { a, b });
        }
示例#21
0
        /// <summary>
        /// Least-Squares fitting the points (x, y) to a line
        /// y : x -> a + b * x.
        /// </summary>
        public static IModelledFunction LineFunc(double[] xArray, double[] yArray)
        {
            Tuple <double, double> parameters = Fit.Line(xArray, yArray);
            double intercept = parameters.Item1;
            double slope     = parameters.Item2;

            Func <double, double> function = t => intercept + slope * t;

            return(new LineFunction(function, parameters));
        }
示例#22
0
        internal static (double b0, double b1, double r2) LinealRegression(int[] xdata, int[] ydata)
        {
            var x = xdata.Select(c => (double)c).ToArray();
            var y = ydata.Select(c => (double)c).ToArray();
            Tuple <double, double> p = Fit.Line(x, y);
            double a  = Math.Round(p.Item1, 5);
            double b  = Math.Round(p.Item2, 5);
            var    r2 = GoodnessOfFit.RSquared(xdata.Select(x => a + b * x), y);

            return(a, b, Math.Round(r2, 4));
        }
    // Start is called before the first frame update
    void Start()
    {
        double[] xdata = new double[] { 0, 1, 3 };
        double[] ydata = new double[] { 0, 1, 1 };

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

        ;
    }
示例#24
0
        public void FitData()
        {
            Tuple <double, double> fitParams = Fit.Line(voltageDataFEB, voltageDataScope);

            slopeDouble     = fitParams.Item2;
            interceptDouble = fitParams.Item1;
            Int16 slopeInt     = (Int16)(fitParams.Item2 * 32768);
            Int16 interceptInt = (Int16)(fitParams.Item1 * 32768);

            slope     = slopeInt.ToString("X");
            intercept = interceptInt.ToString("X");
        }
示例#25
0
        /// <inheritdoc/>
        public double PredictValueAt(long x)
        {
            if (this.data.Count < 3)
            {
                return 0;
            }

            Tuple<double, double> linearparams = Fit.Line(this.data.Keys.ToArray(), this.data.Values.ToArray());
            double a = linearparams.Item1;
            double b = linearparams.Item2;
            return a + (b * x);
        }
        private static Chart GetPurchasesByNecessityValueChart(ICollection <Purchase> purchases)
        {
            var chart = new Chart {
                Layout = { Title = "Purchases by Necessity" }
            };

            // TODO: Capture purchases with null category
            var necessityValues = purchases.Select(x => x.GetNecessityValue()).Distinct();

            foreach (var necessityValue in necessityValues)
            {
                var necessityValueTraceData =
                    new TraceData {
                    Name = necessityValue.ToDescription(), Type = "scatter", Mode = "markers"
                };
                var xdata = new List <double>();
                var ydata = new List <double>();
                var purchasesWithNecessityValue = purchases
                                                  .Where(x => x.GetNecessityValue() == necessityValue).ToList();
                var oldestPurchaseDate = purchasesWithNecessityValue.OrderBy(x => x.OrderDate).First().OrderDate;
                foreach (var purchaseWithNecessityValue in purchasesWithNecessityValue)
                {
                    var purchaseTotal = purchaseWithNecessityValue.UnitPrice * purchaseWithNecessityValue.Quantity;
                    var timespan      = purchaseWithNecessityValue.OrderDate - oldestPurchaseDate;
                    xdata.Add(timespan.TotalHours);
                    ydata.Add((double)purchaseTotal);
                    necessityValueTraceData.X.Add(purchaseWithNecessityValue.OrderDate.Date);
                    necessityValueTraceData.Y.Add(purchaseTotal);
                }
                chart.Data.Add(necessityValueTraceData);

                var necessityRegresstionTraceData = new TraceData
                {
                    Name = $"{necessityValue.ToDescription()} regression",
                    Type = "scatter",
                    Mode = "lines",
                    Line = { Dash = "dot", Width = 4 }
                };
                var p         = Fit.Line(xdata.ToArray(), ydata.ToArray());
                var intercept = p.Item1;
                var slope     = p.Item2;
                foreach (var point in xdata)
                {
                    var regression = slope * point + intercept;
                    var timespan   = TimeSpan.FromHours(point);
                    necessityRegresstionTraceData.X.Add(oldestPurchaseDate + timespan);
                    necessityRegresstionTraceData.Y.Add(regression);
                }
                chart.Data.Add(necessityRegresstionTraceData);
            }
            return(chart);
        }
示例#27
0
        private void krit_prognoz_concentration()
        {
            for (int i = 0; i < MyAllSensors.Count; i++)
            {
                if (comboBox1.Text == MyAllSensors[i].KKS_Name)
                {
                    IndexBor = i;
                    break;
                }
            }
            //  double sum = 0;
            double C0 = (MyAllSensors[IndexBor].MyListRecordsForOneKKS[0].Value + MyAllSensors[IndexBor].MyListRecordsForOneKKS[1].Value) / 2;

            //double t0 = MyAllSensors[IndexBor].MyListRecordsForOneKKS[0].DateTime.ToOADate();

            for (int j = 0; j < MyAllSensors[IndexBor].MyListRecordsForOneKKS.Count; j++)
            {
                Y.Add(Math.Log(MyAllSensors[IndexBor].MyListRecordsForOneKKS[j].Value / C0));
                X.Add(MyAllSensors[IndexBor].MyListRecordsForOneKKS[j].DateTime.ToOADate());
                chart1.Series[NumberSeries].Points.AddXY(X[X.Count - 1], Y[Y.Count - 1]);
            }
            // chart1.Series[NumberSeries].Points.AddXY(X[X.Count - 1], Y[Y.Count - 1]);
            //     MessageBox.Show(MyVal.ToString());
            NumberSeries++;

            Tuple <double, double> myLine1 = Fit.Line(X.ToArray(), Y.ToArray());

            //  double MyCritika = 0;
            //for (int j = 0; j < X.Count; j++)
            //{
            //    chart1.Series[NumberSeries].Points.AddXY(X[j], X[j] * myLine1.Item2 + myLine1.Item1);
            //}
            chart1.Series[NumberSeries].Points.AddXY(X[0], (X[0]) * myLine1.Item2 + myLine1.Item1);

            chart1.Series[NumberSeries].Points.AddXY(X[X.Count - 1], (X[X.Count - 1]) * myLine1.Item2 + myLine1.Item1);

            //  chart1.Series[NumberSeries-1].Points.AddXY(X[X.Count - 1], Y[Y.Count - 1]);
            double t = (Math.Log(double.Parse(textBox2.Text) / C0) - myLine1.Item1) / myLine1.Item2;


            chart1.Series[NumberSeries].Points.AddXY(t, Math.Log(double.Parse(textBox2.Text) / C0));
            //   MessageBox.Show(t.ToString());


            double MyCritika = t;

            //  MessageBox.Show(myLine1.Item2.ToString());
            // MessageBox.Show(MyCritika.ToString());
            chart1.Series[0].XValueType = ChartValueType.Time;
            chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
            label1.Text = " в " + DateTime.FromOADate(MyCritika);
        }
        public void ComputesStandardErrorOfTheRegression()
        {
            // Definition as described at: http://onlinestatbook.com/lms/regression/accuracy.html
            var xes           = new[] { 1.0, 2, 3, 4, 5 };
            var ys            = new[] { 1, 2, 1.3, 3.75, 2.25 };
            var fit           = Fit.Line(xes, ys);
            var a             = fit.Item1;
            var b             = fit.Item2;
            var predictedYs   = xes.Select(x => a + b * x);
            var standardError = Numerics.GoodnessOfFit.StandardError(predictedYs, ys, degreesOfFreedom: 2);

            Assert.AreEqual(0.964, standardError, 1e-3);
        }
        private void ComputeMomentum(HistoricPrice historicPrice, out double momentum, out double volatility)
        {
            var closingPrices       = historicPrice.Candles.Select(r => Math.Log((double)r.Close)).ToArray();
            var seqNumbers          = Enumerable.Range(0, closingPrices.Count()).Select <int, double>(i => i).ToArray();
            var leastSquaresFitting = Fit.Line(seqNumbers, closingPrices);
            var correlationCoff     = GoodnessOfFit.R(seqNumbers, closingPrices);
            var annualizedSlope     = (Math.Pow(Math.Exp(leastSquaresFitting.Item2), 252) - 1) * 100;
            var score = annualizedSlope * correlationCoff * correlationCoff;

            momentum = score;
            var r = Math.Exp(leastSquaresFitting.Item2) * correlationCoff * correlationCoff * 100;

            volatility = r;
        }
示例#30
0
        /// <summary>
        /// Returns the bR-squared value
        /// </summary>
        /// <param name="Other"></param>
        /// <returns></returns>
        public static double?bR2(this FixedTimeStepSeries Me, FixedTimeStepSeries Other)
        {
            double[] val1;
            double[] val2;
            Me.AlignRemoveDeletevalues(Other, out val1, out val2);
            int c = val1.Count();

            if (val1.Count() > 1 & Me.Count > 1)
            {
                var coeff = Fit.Line(val1, val2);
                return(Math.Abs(coeff[1]) * TSTools.R2(val1, val2));
            }
            return(null);
        }