Beispiel #1
0
        //private  DataTable ReadCVS(string filepath, string filename)
        //{
        //    //string cvsDir = filepath;//要读取的CVS路径
        //    DataTable dt = new DataTable();
        //    if (filename.Trim().ToUpper().EndsWith("CSV"))//判断所要读取的扩展名
        //    {
        //        string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='text;HDR=NO;FMT=Delimited'";//有列的读取
        //        string commandText = "select * from [" + filename + "]";//SQL语句

        //        OleDbConnection olconn = new OleDbConnection(connStr);
        //        olconn.Open();
        //        OleDbDataAdapter odp = new OleDbDataAdapter(commandText, olconn);
        //        odp.Fill(dt);
        //        olconn.Close();
        //        odp.Dispose();
        //        olconn.Dispose();
        //    }
        //    return dt;
        //}

        private void openCSV(string filepach)
        {
            REngine engine = REngine.GetInstanceFromID("RDotNet") ?? REngine.CreateInstance("RDotNet");
            //bool isok = engine.IsRunning;
            string cmd = string.Format("dataset=read.csv('{0}')", filepach).Replace("\\", "\\\\");//不加Replace错误
            //string cmd = @"dataset=read.csv('C:\\Users\\wm\\Desktop\\煤与瓦斯2.csv')";//不加@错误
            string cmd2 = @"levels(dataset$突出规模)";

            engine.Evaluate(cmd);
            RDotNet.CharacterVector levels = engine.Evaluate(cmd2).AsCharacter();
            dataset = engine.Evaluate("dataset").AsDataFrame();

            for (int i = 0; i < dataset.ColumnCount; ++i)
            {
                dataGridView1.ColumnCount++;
                dataGridView1.Columns[i].Name = dataset.ColumnNames[i];
            }

            for (int i = 0; i < dataset.RowCount; ++i)
            {
                dataGridView1.RowCount++;
                dataGridView1.Rows[i].HeaderCell.Value = dataset.RowNames[i];

                for (int k = 0; k < dataset.ColumnCount; ++k)
                {
                    dataGridView1[k, i].Value = dataset[i, k];
                }
            }
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            string rhome = System.Environment.GetEnvironmentVariable("R_HOME");

            if (string.IsNullOrEmpty(rhome))
            {
                rhome = @"C:\Program Files\R\R-3.3.1";
            }
            System.Environment.SetEnvironmentVariable("R_HOME", rhome);
            System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" + rhome + @"binx64");
            // Set the folder in which R.dll locates.
            //REngine.SetDllDirectory(@"C:Program FilesRR-2.12.0bini386″);
            REngine.SetDllDirectory(@"C:\Program Files\R\R-3.3.1\bin\x64");
            // REngine e = REngine.CreateInstance("test", new[] { "" });
            using (REngine engine = REngine.CreateInstance("RDotNet", "-q"))        // quiet mode
            {
                foreach (string path in engine.Evaluate(".libPaths()").AsCharacter())
                {
                    Console.WriteLine(path);
                }
                engine.Evaluate(".libPaths(C:\\Program Files\\R\\R-3.3.1\\library)");
                engine.Evaluate("source(D:\\R\\Script\\load_forecast_grid.r)");
                Console.ReadLine();
            }
        }
    static void Main(string[] args)
    {
        // Set the folder in which R.dll locates.
        var envPath  = Environment.GetEnvironmentVariable("PATH");
        var rBinPath = @"C:\Program Files (x86)\R\R-2.11.1\bin";

        //var rBinPath = @"C:\Program Files\R\R-2.11.1-x64\bin"; // Doesn't work ("DLL was not found.")
        Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);
        using (REngine engine = REngine.CreateInstance("RDotNet"))
        {
            // Initializes settings.
            engine.Initialize();

            // .NET Framework array to R vector.
            NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });
            engine.SetSymbol("group1", group1);
            // Direct parsing from R script.
            NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();

            // Test difference of mean and get the P-value.
            GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
            double        p          = testResult["p.value"].AsNumeric().First();

            Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
            Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
            Console.WriteLine("P-value = {0:0.000}", p);
        }
    }
Beispiel #4
0
        public void SetUpEngine()
        {
            Helper.SetEnvironmentVariables();
            var engine = REngine.CreateInstance(EngineName);

            engine.Initialize();
            engine.Evaluate("setClass('testclass', representation(foo='character', bar='integer'))");
        }
        public static void StartEngine()
        {
            SetupPath();

            _engine = REngine.CreateInstance("RDotNet");
            _engine.Initialize();
            _engine.Evaluate("library(bindata)");
            _engine.Evaluate("library(Matrix)");
        }
        public RInterface()
        {
            //check for environmental variable to DLL file, note I custom recompiled this
            if (RInterface.pEngine == null)
            {
                lock (lockObject)
                {
                    //check for value once lock obtained, as may have been set already
                    if (RInterface.pEngine == null)
                    {
                        string dll = System.Environment.GetEnvironmentVariable(R_LIB_ENV_DIR);
                        if (String.IsNullOrEmpty(dll))
                        {
                            throw new Exception("R - library file was not set by environmental variable: " + R_LIB_ENV_DIR + ".\n Please set this variable to point to the directory with the library (libR.so, R.dylib or R.dll as needed).");
                        }
                        string r_home = System.Environment.GetEnvironmentVariable(R_HOME_ENV_DIR);
                        if (String.IsNullOrEmpty(r_home))
                        {
                            throw new Exception(R_HOME_ENV_DIR + " environmental variable is not set.  Please point this to your R Directory");
                        }
                        //change path
                        System.Diagnostics.Debug.WriteLine(R_HOME_ENV_DIR + ": " + r_home);
                        System.Diagnostics.Debug.WriteLine(R_LIB_ENV_DIR + ":" + dll);


                        if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                        {
                            var envPath = Environment.GetEnvironmentVariable("PATH");
                            Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + dll);
                            RInterface.pEngine = REngine.CreateInstance("RDotNet", "R");
                        }
                        else
                        {
                            RInterface.pEngine = REngine.CreateInstance("RDotNet", dll);
                        }

                        StartupParameter sp = new StartupParameter();
                        sp.Interactive = false;
                        sp.Slave       = true;
                        sp.Verbose     = false;
                        sp.Quiet       = true;
                        sp.SaveAction  = StartupSaveAction.NoSave;
                        //THIS IS CRITICAL: See https://rdotnet.codeplex.com/workitem/70
                        var platform = Environment.OSVersion.Platform;
                        if (platform == PlatformID.Unix || platform == PlatformID.MacOSX)
                        {
                            System.Diagnostics.Debug.WriteLine("Removing R signal handlers");
                            IntPtr callBackPointer = RInterface.pEngine.DangerousGetHandle("R_SignalHandlers");
                            Marshal.WriteInt32(callBackPointer, 0);
                        }
                        RInterface.pEngine.Initialize(sp);
                    }
                }
            }
        }
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            string RDllDir = Properties.Settings.Default.RDLLDir;

            //REngine.SetDllDirectory(@"C:\Program Files\R\R-2.15.0\bin\i386");
            REngine.SetDllDirectory(RDllDir);
            REngine.CreateInstance("RDotNet");

            Application.Run(new frmMain());
        }
Beispiel #8
0
        private void InicializeRNet()
        {
            //Create R.NET instance
            string rhome = System.Environment.GetEnvironmentVariable("R_HOME");

            engine = REngine.CreateInstance("RDotNet");
            engine.Initialize();

            //Copy the Function.R file from the source code package to the folder C:\Program Files\R\R-2.15.3\library\
            string rfilepath = @"C:\\Program Files\\R\\R-2.15.3\\library\\Functions.R";

            engine.Evaluate("source(\"" + rfilepath + "\")");
        }
        private void frmMain_Load(object sender, EventArgs e)
        {
            REngine engine = REngine.GetInstanceFromID("RDotNet") ?? REngine.CreateInstance("RDotNet");

            engine.Initialize();
            //this.txtOutput.Text = engine.IsRunning.ToString();
            string RFDir = System.IO.Directory.GetCurrentDirectory().ToString() + "\\model\\RF.Model.RData";
            // string cmd = @"load(file='C:\\Users\\wm\\Desktop\\RF.Model.RData',envir = parent.frame())";
            string cmd  = string.Format("load(file='{0}',envir = parent.frame())", RFDir.Replace("\\", "\\\\"));
            string cmd2 = @"library(randomForest)";

            engine.Evaluate(cmd2);
            engine.Evaluate(cmd);
            // MessageBox.Show(System.IO.Directory.GetCurrentDirectory().ToString());
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            //Create R.NET instance
            REngine engine = REngine.CreateInstance("RDotNet");

            engine.Initialize();

            Console.WriteLine("Is engine running? " + engine.IsRunning);
            Console.WriteLine("Engine ID: " + engine.ID);
            ExportingRDotNetObjs.Start(engine);
            ImportingRDotNetObjs.Start(engine);


            //Close R.NET connection
            //engine.Close();

            Console.WriteLine("\nFinished");
            Console.ReadKey();
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            var    rHome = "/usr/lib/R";
            string path  = Environment.GetEnvironmentVariable("PATH") ?? String.Empty;

            // Note that using /usr/lib where a libR.so symlink exists is not good enough
            path = string.Concat(path, ":", "/usr/lib/R/lib");
            Environment.SetEnvironmentVariable("R_HOME", rHome);
            Environment.SetEnvironmentVariable("PATH", path);

            Console.WriteLine("R init: creating R engine");
            REngine rEngine = REngine.CreateInstance("RDotNet");

            rEngine.Initialize();
            Console.WriteLine("Created rEngine: " + rEngine.ToString());

            // simple arithmetic test
            const string arithmeticExpression = "2 + 14 * 7";
            var          result = rEngine.Evaluate(arithmeticExpression).AsNumeric().ToArray();

            Console.WriteLine(arithmeticExpression + " = " + result[0]);

            // test the problematic CreateNumericVector method
            // Missing method RDotNet.REngineExtension::CreateNumericVector(REngine,IEnumerable`1<double>) in assembly /data/col52j/calibration-files/bin/Release/R.NET.dll
            // values <- 0:99
            double[] values = new double[100];
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = i;
            }
            rEngine.SetSymbol("values", rEngine.CreateNumericVector(values));
            // calculate the sum
            // sum(values) # 4950
            string sum = "sum(values)";

#if RDN15
            result = rEngine.Evaluate(sum).AsNumeric().ToArray();
#else
            result = rEngine.EagerEvaluate(sum).AsNumeric().ToArray();
#endif
            Console.WriteLine("Sum of integer range 0:99 = " + result[0]);
        }
        static void Main(string[] args)
        {
            SetupPath();     // current process, soon to be deprecated
            using (REngine engine = REngine.CreateInstance("RDotNet"))
            {
                engine.Initialize();     // required since v1.5

                REngine.SetDllDirectory(rPath);

                foreach (string path in engine.Evaluate(".libPaths()").AsCharacter())
                {
                    Console.WriteLine(path);
                }
                engine.Evaluate(".libPaths(C:\\Program Files\\R\\R-3.3.1\\library)");
                //engine.Evaluate("source('c:/Program Files/R/R-3.3.1/bin/load_forecast_grid.r')");
                engine.Evaluate("source('c:/Program Files/R/R-3.3.1/bin/testcmd.r')");
                Console.ReadLine();
                Console.ReadKey();
            }
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
            Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-US");
            //R Должен быть добавлен в переменную окружения PATH
            InitializeR();
            var engine = REngine.CreateInstance("RDotNet");

            engine.Initialize();
            engine.Evaluate("source('../../../createForecastFunctionSample.R')");
            var x = engine.CreateNumericVector(new[] { 2.0 });
            var y = engine.CreateNumericVector(new[] { 3.0 });

            engine.SetSymbol("x", x);
            engine.SetSymbol("y", y);
            var s = engine.Evaluate("forecast(x, y)").AsNumeric()[0];

            Console.WriteLine($"Получен результат: {s}. Нажмите любую кнопку для продолжения.");
            Console.ReadKey();
        }
        public BacktestReportForm()
        {
            InitializeComponent();

            // initialise R engine
            var envPath  = Environment.GetEnvironmentVariable("PATH");
            var rBinPath = @"C:\Program Files\R\R-3.0.1\bin\x64";

            //            var rBinPath = @"C:\Program Files\R\R-3.0.1\bin\i386";
            Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);
            engine = REngine.CreateInstance("RDotNet");
            engine.Initialize();

            // do some initial R setup
            engine.Evaluate("Sys.setenv(TZ='Europe/London')");
            engine.Evaluate("library(quantmod)");
            engine.Evaluate("library(PerformanceAnalytics)");
            engine.Evaluate("print(getwd())");
            engine.Evaluate(r_set_working_directory);
            engine.Evaluate("print(getwd())");
        }
Beispiel #15
0
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //Get Start up path to set a sample data path and path of temporary folder
                strPath = System.Windows.Forms.Application.StartupPath;
                //R environment setting
                //Current version of R is 3.4.4 (05/23/18 HK)
                var envPath  = Environment.GetEnvironmentVariable("PATH");
                var rBinPath = strPath + @"\R-3.4.4\bin\i386"; // R is copited into startup path
                Environment.SetEnvironmentVariable("PATH", envPath + System.IO.Path.PathSeparator + rBinPath);
                Environment.SetEnvironmentVariable("R_HOME", strPath + @"\R-3.4.4");

                //Loading REngine
                pEngine = REngine.CreateInstance(strREngineName);
                pEngine.Initialize();

                //Set Library home and remove local home!
                LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                string strLibPath = strPath.Replace(@"\", @"/") + "/R-3.4.4/library"; //path for R packages
                pEngine.Evaluate(".Library.site <- file.path('" + strLibPath + "')");
                pEngine.Evaluate("Sys.setenv(R_LIBS_USER='******')");
                pEngine.Evaluate(".libPaths(c('" + strLibPath + "', .Library.site, .Library))");

                //Checked installed packages and R
                LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                pEngine.Evaluate("ip <- installed.packages()").AsCharacter();
                string[] installedPackages = pEngine.Evaluate("ip[,1]").AsCharacter().ToArray(); //To Check Installed Packages in R

                //The funtion below will be added to check installed packages in R (HK 05/23/18)
                //clsRPackageNames pPckNames = new clsRPackageNames();
                //blnsInstalledPcks = pPckNames.CheckedRequiredPackages(installedPackages);
            }
            catch (Exception ex)
            {
                frmErrorLog pfrmErrorLog = new frmErrorLog(); pfrmErrorLog.ex = ex; pfrmErrorLog.ShowDialog();
                return;
            }
        }
Beispiel #16
0
        public PortfolioReportForm()
        {
            InitializeComponent();

            // initialise R engine
            var envPath = Environment.GetEnvironmentVariable("PATH");
            //var rBinPath = @"C:\Program Files\R\R-2.15.2\bin\i386";
            var rBinPath = @"C:\Program Files\R\R-3.0.1\bin\x64";

            Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);
            engine = REngine.CreateInstance("RDotNet");
            engine.Initialize();

            // do some initial R setup
            engine.Evaluate("Sys.setenv(TZ='Europe/London')");
            engine.Evaluate("library(quantmod)");
            engine.Evaluate("library(PerformanceAnalytics)");
            engine.Evaluate("print(getwd())");
//            engine.Evaluate("setwd('C:/Users/Keiran/Documents/Backtest_Source/R')");
            engine.Evaluate("setwd('C:/Users/User/Desktop/KT_src/Backtest_Source/R')");
            engine.Evaluate("print(getwd())");
        }
        private void btnSumbit_Click(object sender, EventArgs e)
        {
            // REngine.SetDllDirectory(@"C:\Program Files\R\R-2.15.0\bin\i386");
            if (!string.IsNullOrEmpty(this.txtPram1.Text) && !string.IsNullOrEmpty(this.txtPram2.Text) && !string.IsNullOrEmpty(this.txtPram3.Text) && !string.IsNullOrEmpty(this.txtPram4.Text) && !string.IsNullOrEmpty(this.txtPram5.Text))
            {
                REngine engine = REngine.GetInstanceFromID("RDotNet") ?? REngine.CreateInstance("RDotNet");
                //engine.Initialize();//只能初始化一次

                string strCreateTest = string.Format("test2=data.frame(X1={0},X2={1},X3={2},X4={3},X5={4},Y=0)", double.Parse(this.txtPram1.Text), double.Parse(this.txtPram2.Text), double.Parse(this.txtPram3.Text), double.Parse(this.txtPram4.Text), double.Parse(this.txtPram5.Text));
                string cmd8          = @"predict(RF.Model,test2[,-6],type='response')";

                engine.Evaluate(strCreateTest);

                IntegerVector index = engine.Evaluate(cmd8).AsInteger();


                this.txtOutput.Text = getResult(index[0]);
            }
            else
            {
                MessageBox.Show("参数不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            var envPath  = Environment.GetEnvironmentVariable("PATH");
            var rBinPath = System.Environment.Is64BitProcess ? @"C:\Program Files\R\R-3.1.2\bin\x64" : @"C:\Program Files\R\R-3.1.2\bin\i386";

            Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);
            StringWriter builder = new StringWriter();
            var          temp    = Console.Out;

            Console.SetOut(builder);
            using (var engine = REngine.CreateInstance("RDotNet"))
            {
                engine.Initialize();

                String content = File.ReadAllText(@"C:/Users/Nithin/Desktop/aprioriStub.R");
                content = content.Replace("filePathStub", "C:/Users/Nithin/Desktop/test.csv");
                content = content.Replace("headerStub", "FALSE");
                content = content.Replace("supportStub", "0.1");
                content = content.Replace("confStub", "0.1");
                content = content.Replace("sideStub", "rhs");
                content = content.Replace("valueStub", "V3=High");
                content = content.Replace("sortStub", "confidence");
                content = content.Replace("nStub", "3");
                File.WriteAllText(@"C:/Users/Nithin/Desktop/apriori.R", content);

                //using (var fs = File.OpenRead(@"C:\R-scripts\r-test.R"))
                //{
                //    engine.Evaluate(fs);
                //}
                engine.Evaluate(@"source('C:/Users/Nithin/Desktop/apriori.R')");
                Console.SetOut(temp);
                string output = builder.ToString();
                output = output.Substring(output.IndexOf("lhs"));
                Console.WriteLine(output);
            }
            Console.Read();
        }
Beispiel #19
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            //Get Start up path to set a sample data path and path of temporary folder
            strPath = System.Windows.Forms.Application.StartupPath;
            axMapControl1.ActiveView.FocusMap.Name = "Layers";
            //get the MapControl
            m_mapControl = (IMapControl3)axMapControl1.Object;

            //disable the Save menu (since there is no document yet)
            menuSaveDoc.Enabled = false;

            lstRenderedLayers = new List <clsRenderedLayers>();
            m_pSnippet        = new clsSnippet();
            try
            {
                //Load sample mxd
                //string filePath = strPath + @"\Sample.mxd";
                //string filePath = strPath + @"\SampleData\Sample_plano.mxd";//For Plano
                //string filePath = strPath + @"\SampleData\Classification\Iowa_cnties.mxd";//For Iowa

                //if (axMapControl1.CheckMxFile(filePath))
                //    axMapControl1.LoadMxFile(filePath, Type.Missing, Type.Missing);
                //else
                //    MessageBox.Show("Wrong direction");

                ////Get Envelope of mxd
                //IActiveView pActiveView1 = axMapControl1.ActiveView.FocusMap as IActiveView;
                ////ILayer pLayer1 = pActiveView1.FocusMap.get_Layer(2);
                //ILayer pLayer1 = pActiveView1.FocusMap.get_Layer(0);

                ////adjust extent to fit a screen resolution
                //IFeatureLayer pFLayer1 = pLayer1 as IFeatureLayer;
                //IEnvelope envelope1 = new EnvelopeClass();
                //envelope1.PutCoords(pFLayer1.AreaOfInterest.Envelope.XMin - (pFLayer1.AreaOfInterest.Envelope.XMin * 0.0005), pFLayer1.AreaOfInterest.Envelope.YMin - (pFLayer1.AreaOfInterest.Envelope.YMin * 0.0005), pFLayer1.AreaOfInterest.Envelope.XMax * 1.0005, pFLayer1.AreaOfInterest.Envelope.YMax * 1.0005);
                //axMapControl1.ActiveView.Extent = envelope1;
                //axMapControl1.ActiveView.Refresh();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error 101: " + ex.Message);
            }

            try
            {
                //R environment setting

                #region Previous Methods
                //var envPath = Environment.GetEnvironmentVariable("PATH");
                //var rBinPath = strPath + @"\R-3.1.2\bin\i386"; // R is copited into startup path
                //Environment.SetEnvironmentVariable("PATH", envPath + System.IO.Path.PathSeparator + rBinPath);
                ////Environment.SetEnvironmentVariable("PATH", rBinPath); //Not working
                //Environment.SetEnvironmentVariable("R_HOME", strPath + @"\R-3.1.2");

                ////Loading REngine
                //pEngine = REngine.CreateInstance(strREngineName);
                //pEngine.Initialize();

                ////string[] strRHOME = pEngine.Evaluate("R.home(component = 'home')").AsCharacter().ToArray(); //For Deburgging
                //LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();

                //string strLibPath = strPath.Replace(@"\", @"/") + "/R-3.1.2/library";
                ////pEngine.Evaluate(".libPaths(" + strLibPath + ")");
                ////pEngine.Evaluate(".libPaths(c(" + strLibPath + ", .Library.site, .Library))");//Same results with the above
                ////pEngine.Evaluate(".libPaths(c(" + strLibPath + "))");//Same results with the above
                //pEngine.Evaluate(".Library.site <- file.path('"+strLibPath+"')"); //Same results with the above
                //pEngine.Evaluate("Sys.setenv(R_LIBS_USER='******')");
                ////string[] tempstring1 = pEngine.Evaluate("Sys.getenv('R_LIBS_USER')").AsCharacter().ToArray();
                ////string[] tempstring = pEngine.Evaluate(".Library.site").AsCharacter().ToArray();
                //pEngine.Evaluate(".libPaths(c('" + strLibPath + "', .Library.site, .Library))");

                //LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                //pEngine.Evaluate("ip <- installed.packages()").AsCharacter();
                //string[] installedPackages = pEngine.Evaluate("ip[,1]").AsCharacter().ToArray(); //To Check Installed Packages in R
                //clsRPackageNames pPckNames = new clsRPackageNames();
                //blnsInstalledPcks = pPckNames.CheckedRequiredPackages(installedPackages);

                #endregion

                //Current version of R is 3.4.4 (03/19/18 HK)
                var envPath  = Environment.GetEnvironmentVariable("PATH");
                var rBinPath = strPath + @"\R-3.4.4\bin\i386"; // R is copited into startup path
                Environment.SetEnvironmentVariable("PATH", envPath + System.IO.Path.PathSeparator + rBinPath);
                Environment.SetEnvironmentVariable("R_HOME", strPath + @"\R-3.4.4");

                //Loading REngine
                pEngine = REngine.CreateInstance(strREngineName);
                pEngine.Initialize();

                //Set Library home and remove local home!
                LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                string strLibPath = strPath.Replace(@"\", @"/") + "/R-3.4.4/library"; //path for R packages
                pEngine.Evaluate(".Library.site <- file.path('" + strLibPath + "')");
                pEngine.Evaluate("Sys.setenv(R_LIBS_USER='******')");
                pEngine.Evaluate(".libPaths(c('" + strLibPath + "', .Library.site, .Library))");

                //Checked installed packages and R
                LibHome = pEngine.Evaluate(".libPaths()").AsCharacter().ToArray();
                pEngine.Evaluate("ip <- installed.packages()").AsCharacter();
                string[]         installedPackages = pEngine.Evaluate("ip[,1]").AsCharacter().ToArray(); //To Check Installed Packages in R
                clsRPackageNames pPckNames         = new clsRPackageNames();
                blnsInstalledPcks = pPckNames.CheckedRequiredPackages(installedPackages);



                ////Installing Additional Package
                //Currently required pacakges:: MASS, geoR, car, spdep, maptools, deldir, rgeos, e1071
                //package required for Testing: fpc
                //pEngine.Evaluate("install.packages('fpc')");
                //pEngine.Evaluate("install.packages('e1071')");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error 102:" + ex.Message);
            }

            try
            {
                //Toolbar Control, insert new tools here!!
                m_ToolbarControl = (IToolbarControl2)axToolbarControl1.Object;

                int intItemCounts = m_ToolbarControl.Count;
                m_ToolbarControl.AddItem(new toolDenPlot(), -1, intItemCounts, true, 0, esriCommandStyles.esriCommandStyleIconOnly);        //Probability density plot tool
                //m_ToolbarControl.AddItem(new toolUncernFeature(), -1, intItemCounts+1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); // Remove now 07/31/15
                m_ToolbarControl.AddItem(new ToolCumsum(), -1, intItemCounts + 1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);    // Empirical cumulative density function
                m_ToolbarControl.AddItem(new toolHistogram(), -1, intItemCounts + 2, false, 0, esriCommandStyles.esriCommandStyleIconOnly); // Histogram tool
                m_ToolbarControl.AddItem(new LinkingTool(), -1, intItemCounts + 3, true, 0, esriCommandStyles.esriCommandStyleIconOnly);    // Histogram tool
                m_ToolbarControl.AddItem(new AddFeatureClass(), -1, 1, false, 0, esriCommandStyles.esriCommandStyleIconOnly);               // Histogram tool
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error 103: " + ex.Message);
            }

            try
            {
                //Loading Context menu at TOC
                m_tocControl = axTOCControl1.Object as ITOCControl2;
                m_tocControl.SetBuddyControl(m_mapControl);
                m_menuLayer = new ToolbarMenuClass();
                m_menuLayer.AddItem(new RemoveLayer(), -1, 0, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new OpenAttriTable(), -1, 1, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new ZoomToLayer(), -1, 2, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new ZoomToSelectedFeatures(), -1, 3, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new SaveLayerFile(), -1, 4, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new LayerSymbology(), -1, 5, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.AddItem(new LayerProperty(), -1, 6, false, esriCommandStyles.esriCommandStyleTextOnly);
                //m_menuLayer.AddItem(new Symbology(), -1, 3, false, esriCommandStyles.esriCommandStyleTextOnly);
                //m_menuLayer.AddItem(new SimpleSymbology(), -1, 3, false, esriCommandStyles.esriCommandStyleTextOnly);
                m_menuLayer.SetHook(m_mapControl);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error 104:" + ex.Message);
            }
        }
 static CSLib()
 {
     // Set the folder in which R.dll locates.
     REngine.SetDllDirectory(@"C:\Program Files\R\R-2.13.0\bin\i386");
     rengine = REngine.CreateInstance("RDotNet", new[] { "-q" });
 }
Beispiel #21
0
 //Set REngine
 public REngine setEngine()
 {
     engine = REngine.CreateInstance("RDotNet");
     engine.Initialize();
     return(engine);
 }
Beispiel #22
0
        static void Main(string[] args)
        {
            //require R 2.15, package forecast on R
            var envPath  = Environment.GetEnvironmentVariable("PATH");
            var rBinPath = GetRPath(); //C:\Program Files\R\R-2.15.1\bin\i386

            Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);
            REngine engine = REngine.CreateInstance("RDotNet");

            engine.Initialize();

            string currentPath     = Directory.GetCurrentDirectory();
            string dataPath        = currentPath + @"\data\paper.dat";
            string readDataCommand = string.Format("predata <- read.table(\"{0}\", header=FALSE)", dataPath).Replace('\\', '/');


            engine.Evaluate("library(forecast)");
            engine.Evaluate(readDataCommand);
            engine.Evaluate("data <- predata[,1]");
            var model = engine.Evaluate("fit <- auto.arima(data)").AsList();
            var coef  = model["coef"].AsList();

            int lengthData = engine.Evaluate("data").AsNumeric().Length;

            double[] dataSeries  = new double[lengthData];
            double[] errorSeries = new double[lengthData];

            engine.Evaluate("data").AsNumeric().CopyTo(dataSeries, lengthData);
            model["residuals"].AsNumeric().CopyTo(errorSeries, lengthData);
            //residuals

            int arOrder         = model["arma"].AsInteger().ElementAt(0);
            int maOrder         = model["arma"].AsInteger().ElementAt(1);
            int arSeasonOrder   = model["arma"].AsInteger().ElementAt(2);
            int maSeasonOrder   = model["arma"].AsInteger().ElementAt(3);
            int seasonOrder     = model["arma"].AsInteger().ElementAt(4);
            int diffOrder       = model["arma"].AsInteger().ElementAt(5);
            int diffSeasonOrder = model["arma"].AsInteger().ElementAt(6);

            double[] arCoef       = new double[arOrder];
            double[] maCoef       = new double[maOrder];
            double[] arSeasonCoef = new double[arSeasonOrder];
            double[] maSeasonCoef = new double[maSeasonOrder];
            double   intercept    = 0;

            int n     = model["coef"].AsNumeric().Length;
            int start = 0;

            model["coef"].AsNumeric().CopyTo(arCoef, arOrder, start, 0);
            start += arOrder;
            model["coef"].AsNumeric().CopyTo(maCoef, maOrder, start, 0);
            start += maOrder;
            model["coef"].AsNumeric().CopyTo(arSeasonCoef, arSeasonOrder, start, 0);
            start += arSeasonOrder;
            model["coef"].AsNumeric().CopyTo(maSeasonCoef, maSeasonOrder, start, 0);
            start += maSeasonOrder;
            if (n > start)
            {
                intercept = model["coef"].AsNumeric().ElementAt(start);
            }

            ArimaModel arimaModel     = new ArimaModel(arCoef, maCoef, arSeasonCoef, maSeasonCoef, intercept, (uint)seasonOrder, (uint)diffOrder, (uint)diffSeasonOrder);
            Polynomial arModel        = arimaModel.ComputeARModel();
            Polynomial maModel        = arimaModel.ComputeMAModel();
            double     interceptModel = arimaModel.ComputeIntercept();

            double test = arimaModel.ComputeValue(dataSeries, errorSeries, dataSeries.Length);

            Console.WriteLine("Forecast");
            Console.WriteLine(test);
            Console.WriteLine("Model");
            Console.WriteLine(interceptModel);
            Console.WriteLine("Ar");
            Console.WriteLine(arModel.ToString());
            Console.WriteLine("Ma");
            Console.WriteLine(maModel.ToString());
            Console.ReadLine();
        }