Пример #1
0
        static void Main(string[] args)
        {
            var leastSquares = new LeastSquares(@"C:\Users\Ilya\Desktop\LinearRegression\LinearRegression\LinearRegression\test.txt");

            leastSquares.TrainModel();
            leastSquares.TestModel();
            Console.ReadLine();
        }
Пример #2
0
        public void LeastSquaresSingleElementSourceReturnsNaN()
        {
            var data = new List <Tuple <double, double> >()
            {
                new Tuple <double, double>(1, 10)
            };

            var ls = data.LeastSquaresNaN();

            Assert.IsTrue(LeastSquares.IsNaN(ls));
            Assert.IsTrue(double.IsNaN(ls.M));
            Assert.IsTrue(double.IsNaN(ls.B));
        }
Пример #3
0
        private void GetData()
        {
            ReadData();

            _leastSquares = new LeastSquares(YValues);

            XRange = new List <double>();
            XRange = _leastSquares.XRange;

            DeltaX = 2 * Math.PI / XRange.Count;

            Polynom = _leastSquares.ToString();

            _furierTransform = new DiscreteFurierTransform(XRange, YValues);
        }
        public ForecastingModel calculateTrend()
        {
            this.Trend = new List <double>();
            List <Tuple <double, double> > LeastSquaresSerie = new List <Tuple <double, double> >();

            for (int i = 0; i < this.SeasonallyAdjustedData.Count; i++)
            {
                LeastSquaresSerie.Add(new Tuple <double, double>(i + 1, this.SeasonallyAdjustedData.ElementAt(i)));
            }
            //y = mx + b
            LeastSquaresParameters = StatisticsModel.LeastSquares(LeastSquaresSerie);
            for (int i = 0; i < this.Serie.Count; i++)
            {
                this.Trend.Add((i + 1) * LeastSquaresParameters.M + LeastSquaresParameters.B);
            }
            return(this);
        }
Пример #5
0
        public async Task SetDate(Date date, CrdsGeographical geoLocation)
        {
            await Task.Run(() =>
            {
                double jd0  = date.ToJulianEphemerisDay();
                daysInMonth = Date.DaysInMonth(date.Year, date.Month);

                var eL = new PointF[5];
                var eB = new PointF[5];
                var eR = new PointF[5];
                var jL = new PointF[5];
                var jB = new PointF[5];
                var jR = new PointF[5];

                var earth   = new CrdsHeliocentrical[5];
                var jupiter = new CrdsHeliocentrical[5];

                // calculate heliocentrical positions of Earth and Jupiter for 5 instants
                // and find least squares approximation model of planets position
                // to quick calculation of Galilean moons postions.
                for (int i = 0; i < 5; i++)
                {
                    double jd  = jd0 + (i / 4.0) * daysInMonth;
                    earth[i]   = PlanetPositions.GetPlanetCoordinates(3, jd);
                    jupiter[i] = PlanetPositions.GetPlanetCoordinates(5, jd);
                }

                double[] earthL = earth.Select(x => x.L).ToArray();
                double[] earthB = earth.Select(x => x.B).ToArray();
                double[] earthR = earth.Select(x => x.R).ToArray();

                double[] jupiterL = jupiter.Select(x => x.L).ToArray();
                double[] jupiterB = jupiter.Select(x => x.B).ToArray();
                double[] jupiterR = jupiter.Select(x => x.R).ToArray();

                // it's important to align longitudes (avoid 0 degrees crossing)
                // before applying least squares method
                earthL   = Angle.Align(earthL);
                jupiterL = Angle.Align(jupiterL);

                for (int i = 0; i < 5; i++)
                {
                    eL[i] = new PointF(i, (float)earthL[i]);
                    eB[i] = new PointF(i, (float)earthB[i]);
                    eR[i] = new PointF(i, (float)earthR[i]);
                    jL[i] = new PointF(i, (float)jupiterL[i]);
                    jB[i] = new PointF(i, (float)jupiterB[i]);
                    jR[i] = new PointF(i, (float)jupiterR[i]);
                }

                Begin       = jd0;
                End         = jd0 + daysInMonth;
                GeoLocation = geoLocation;
                this.eL     = LeastSquares.FindCoeffs(eL, 3);
                this.eB     = LeastSquares.FindCoeffs(eB, 3);
                this.eR     = LeastSquares.FindCoeffs(eR, 3);
                this.jL     = LeastSquares.FindCoeffs(jL, 3);
                this.jB     = LeastSquares.FindCoeffs(jB, 3);
                this.jR     = LeastSquares.FindCoeffs(jR, 3);
            });
        }
Пример #6
0
    public ChronoJumpWindow(string progVersion, string progName, string runningFileName)
    {
        this.progVersion = progVersion;
        this.progName = progName;
        this.runningFileName = runningFileName;

        Glade.XML gxml;
        gxml = Glade.XML.FromAssembly (Util.GetGladePath() + "app1.glade", "app1", "chronojump");
        gxml.Autoconnect(this);

        //put an icon to window
        UtilGtk.IconWindow(app1);

        //show chronojump logo on down-left area
        changeTestImage("", "", "LOGO");

        //white bg
        eventbox_image_test.ModifyBg(StateType.Normal, UtilGtk.WHITE);

        //start with the Mode selector
        notebook_start.CurrentPage = 0;

        //new DialogMessage(Constants.MessageTypes.INFO, UtilGtk.ScreenHeightFitted(false).ToString() );
        //UtilGtk.ResizeIfNeeded(stats_window);

        //app1.Maximize(); //this was for starting at fullscreen

        report = new Report(-1); //when a session is loaded or created, it will change the report.SessionID value
        //TODO: check what happens if a session it's deleted
        //i think report it's deactivated until a new session is created or loaded,
        //but check what happens if report window is opened

        //put videoOn as false before loading preferences to start always without the camera
        //this is good if camera produces crash
        SqlitePreferences.Update("videoOn", "False", false);

        //preferencesLoaded is a fix to a gtk#-net-windows-bug where radiobuttons raise signals
        //at initialization of chronojump and gives problems if this signals are raised while preferences are loading
        loadPreferences ();

        createTreeView_persons (treeview_persons);

        createTreeView_jumps (treeview_jumps);
        createTreeView_jumps_rj (treeview_jumps_rj);
        createTreeView_runs (treeview_runs);
        createTreeView_runs_interval (treeview_runs_interval);
        createTreeView_reaction_times (treeview_reaction_times);
        createTreeView_pulses (treeview_pulses);
        createTreeView_multi_chronopic (false, treeview_multi_chronopic);

        createComboSelectJumps(true);
        createComboSelectJumpsRj(true);
        createComboSelectRuns(true);
        createComboSelectRunsInterval(true);

        createComboResultJumps();
        createComboResultJumpsRj();
        createComboResultRuns();
        createComboResultRunsInterval();

        //reaction_times has no combo
        createComboPulses();
        //createComboMultiChronopic();
        createdStatsWin = false;

        repetitiveConditionsWin = RepetitiveConditionsWindow.Create();
        repetitiveConditionsWin.FakeButtonClose.Clicked += new EventHandler(on_repetitive_conditions_closed);

        //createChronopicWindow(false, "");
        //wizardPortContacts = "";
        //wizardPortEncoder = "";

        on_extra_window_multichronopic_test_changed(new object(), new EventArgs());
        on_extra_window_pulses_test_changed(new object(), new EventArgs());
        on_extra_window_reaction_times_test_changed(new object(), new EventArgs());
        on_extra_window_runs_interval_test_changed(new object(), new EventArgs());
        on_extra_window_runs_test_changed(new object(), new EventArgs());
        on_extra_window_jumps_rj_test_changed(new object(), new EventArgs());
        on_extra_window_jumps_test_changed(new object(), new EventArgs());
        //changeTestImage("", "", "LOGO");

        //We have no session, mark some widgets as ".Sensitive = false"
        sensitiveGuiNoSession();
        definedSession = false;

        rand = new Random(40);

        formatModeMenu();
        putNonStandardIcons();
        eventExecutePutNonStandardIcons();
        //eventExecuteCreateComboGraphResultsSize();

        /*

        if(chronopicPort != Constants.ChronopicDefaultPortWindows &&
                (chronopicPort != Constants.ChronopicDefaultPortLinux && File.Exists(chronopicPort))
          ) {
            ConfirmWindow confirmWin = ConfirmWindow.Show(Catalog.GetString("Do you want to connect to Chronopic now?"), "", "");
            confirmWin.Button_accept.Clicked += new EventHandler(chronopicAtStart);
        }
        */

        stats_win_create();
        createdStatsWin = true;
        //stats_win_initializeSession();

        encoderInitializeStuff();

        //presentationInit();

        videoCaptureInitialize();

        //leave empty on new releases
        //string buildDate = " (2016-07-27)";
        string buildVersion = UtilAll.ReadVersionFromBuildInfo();
        label_version.Text = buildVersion;
        LogB.Information("Build version:" + buildVersion);

        LeastSquares ls = new LeastSquares();
        ls.Test();
        LogB.Information(string.Format("coef = {0} {1} {2}", ls.Coef[0], ls.Coef[1], ls.Coef[2]));

        //these are constructed only one time
        threshold = new Threshold();
        cp2016 = new Chronopic2016();

        restTime = new RestTime();
        updatingRestTimes = true;
        //GLib.Timeout.Add(5000, new GLib.TimeoutHandler(updateRestTimes)); //each 5s
        GLib.Timeout.Add(1000, new GLib.TimeoutHandler(updateRestTimes)); //each s, better for don't have problems sorting data on treeview

        /*
         * start a ping in other thread
         * http://www.mono-project.com/docs/gui/gtksharp/responsive-applications/
         * Gtk.Application.Invoke
         */
        pingThread = new Thread (new ThreadStart (pingAtStart));
        pingThread.Start();

        //moveStartTestInitial();
    }
Пример #7
0
        public void Evalute()
        {
            var rawMatrix = new Matrix <double>(ArrayHelper.FromVectors(Points.Select(v => new[] { v.X, v.Y }).ToArray())).Transpose();
            int basis     = PolynomeDegree + 1;
            var matrix    = LeastSquares.MakeSystem(rawMatrix.Value, basis);

            Console.WriteLine("---\nСоставляем систему уравнений:\n");
            for (int i = 0; i < basis; i++)
            {
                for (int j = 0; j < basis; j++)
                {
                    Console.Write((matrix[i, j] > 0 ? "+" : "") +
                                  Math.Round(matrix[i, j], 3) + "*c" + j.ToString() + " ");
                }
                Console.WriteLine(" = " + matrix[i, basis]);
            }

            var result = LeastSquares.Gauss(matrix, basis, basis + 1);

            if (result == null)
            {
                Console.WriteLine("Невозможно найти частное решение составленной системы уравнений\n");
                return;
            }
            Console.WriteLine("Решение системы уравнений:\n");
            for (int i = 0; i < basis; i++)
            {
                Console.WriteLine("C" + i + " = " + Math.Round(result[i], 3));
            }
            Console.WriteLine("Таким образом, среднеквадратичное приближение:");
            var func = new StringBuilder();

            for (int i = 0; i < basis; i++)
            {
                if (Math.Round(result[i], 3) != 0)
                {
                    func.Append(((result[i] > 0) ? "+" : "") +
                                Math.Round(result[i], 3) + ((i > 0) ? "*x^" + i : "") + " ");
                }
            }
            Console.WriteLine($"y = {func.ToString()}");
            Console.WriteLine();

            // Строим график
            var min  = Points.Select(p => p.X).Min();
            var max  = Points.Select(p => p.X).Max();
            var step = (max - min) / 20;

            var newPlot = new ChartValues <ObservablePoint>();
            var xi      = min;

            do
            {
                double y = 0;
                for (int i = 0; i < basis; i++)
                {
                    y += result[i] * Math.Pow(xi, i);
                }
                newPlot.Add(new ObservablePoint()
                {
                    X = xi, Y = y
                });
                xi += step;
            } while (xi <= max);

            // Применяем график
            var gr = new LineSeries
            {
                Title             = "F(x)",
                Values            = newPlot,
                LineSmoothness    = 0,
                PointGeometry     = DefaultGeometries.Cross,
                PointGeometrySize = 5.0
            };

            SeriesCollection.Add(gr);
        }