Ejemplo n.º 1
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="MultiCatchmentCompositeObjectiveEvaluator" /> class.
        /// </summary>
        /// <param name="objDefn"> The objective definition. </param>
        private RCompositeObjectiveEvaluator(RexpObjectiveDefinition objDefn)
        {
            objectiveDefinition = objDefn;
            string pathToRDynLib = objDefn.DirectoryForRLibrary;
            string rhome         = Environment.GetEnvironmentVariable("R_HOME");

            if (!Directory.Exists(pathToRDynLib))
            {
                REngine.SetEnvironmentVariables();
            }
            else
            {
                if (string.IsNullOrEmpty(rhome))
                {
                    var plat = NativeUtility.GetPlatform();
                    switch (plat)
                    {
                    case PlatformID.Win32NT:
                        if (string.IsNullOrEmpty(rhome))
                        {
                            rhome = Path.Combine(pathToRDynLib, @"..\..");     // Assume R more recent than 2.12 : binaries under bin\x64 for instance; folder containing 'bin' is R_HOME
                            Log.WarnFormat("R_HOME environment variable not set. Setting R_HOME = {0}", rhome);
                        }
                        break;

                    case PlatformID.Unix:
                        Log.Debug("R init: detected Unix platform");
                        if (String.IsNullOrEmpty(rhome))
                        {
                            throw new Exception("R_HOME environment variable is not set");
                        }
                        break;

                    default:
                        throw new NotSupportedException(string.Format("Platform not supported: {0}", plat));
                    }
                }
                Log.Debug("R init: R_HOME = " + rhome);
                REngine.SetEnvironmentVariables(pathToRDynLib, rhome);
            }

            Log.Debug("R init: creating R engine");
            rEngine = REngine.GetInstance(dll: null, initialize: false, parameter: null, device: null);
            Log.Debug("R init: initialising R engine");
            StartupParameter rStartParams = new StartupParameter
            {
                Quiet         = true,
                SaveAction    = StartupSaveAction.NoSave,
                Slave         = false,
                Interactive   = true,
                Verbose       = false,
                LoadInitFile  = true,
                LoadSiteFile  = true,
                RestoreAction = StartupRestoreAction.NoRestore,
                NoRenviron    = false
            };

            rEngine.Initialize(rStartParams);
            Log.Debug("Created rEngine: " + rEngine.ToString());
        }
Ejemplo n.º 2
0
        private Q1R()
        {
            RDotNet.StartupParameter sp = new StartupParameter();
            sp.Interactive = false;
            sp.Quiet       = false;

            //RDotNet.Devices.ICharacterDevice ic = new RConsola();
            RConsola ic = new RConsola();

            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance("", true, sp, ic);

            if (engine.IsRunning == false)
            {
                engine.Initialize(sp, ic, true);
            }

            //engine.Evaluate code...

            string rConsoleMessages = ic.sb.ToString();

            REngine.SetEnvironmentVariables();
            engine = REngine.GetInstance();
            engine.Initialize();
            //engine.Evaluate("source('P:/Q1/R/Q1Linear.R')");
        }
Ejemplo n.º 3
0
        public static void initializeREngine(string R_HOME, string R_DLL, string R_packages)
        {
            if (string.IsNullOrEmpty(R_HOME) || string.IsNullOrWhiteSpace(R_HOME))
            {
                REngine.SetEnvironmentVariables();
            }
            else
            {
                REngine.SetEnvironmentVariables(rHome: R_HOME);
            }

            StartupParameter myparameter = new StartupParameter()
            {
                Interactive = false,
                Quiet       = true,
                Verbose     = false
            };

            if (string.IsNullOrEmpty(R_DLL) || string.IsNullOrWhiteSpace(R_DLL))
            {
                engine = REngine.GetInstance(null, true, myparameter, null);
            }
            else
            {
                engine = REngine.GetInstance(R_DLL, true, myparameter, null);
            }

            // REngine requires explicit initialization.
            // You can set some parameters.
            prepareREngine(R_packages);
        }
Ejemplo n.º 4
0
        public Model()
        {
            StartupParameter rinit = new StartupParameter();

            rinit.Quiet       = true;
            rinit.RHome       = "C:\\Program Files\\R\\R-3.4.2\\";
            rinit.Interactive = true;
            REngine.SetEnvironmentVariables();
            en = REngine.GetInstance(null, true, rinit);
        }
Ejemplo n.º 5
0
        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);
                    }
                }
            }
        }
Ejemplo n.º 6
0
        private static void Main(string[] args)
        {
            REngine.SetEnvironmentVariables();
            StartupParameter parameter = args.Length > 0 ?
                                         new StartupParameter()
            {
                MaxMemorySize = ulong.Parse(args[0]) * (1024 * 1024)
            } :
            new StartupParameter()
            {
            };
            uint   maxPowTwo  = args.Length > 1 ? uint.Parse(args[1]) : 24;
            string outputfile = args.Length > 2 ? args[2] :
                                (RDotNet.NativeLibrary.NativeUtility.IsUnix ? "~/tmp/rdotnetruntimes.csv" : "c:/tmp/runtimes.csv");

            using (var engine = REngine.GetInstance(device: device, parameter: parameter))
            {
                printMemLimit(engine);
                var measures = new List <Measurement>();

                //engine.Evaluate("cases <- expand.grid(c(2,5,10), 10^(0:6))");
                var sizes = engine.Evaluate(string.Format("as.integer(2^(0:{0}))", maxPowTwo)).AsInteger().ToArray();

                RuntimeDiagnostics r = new RuntimeDiagnostics(engine)
                {
                    Types = new[] { "numeric", "integer", "logical" }, // characters are much slower / cannot include here
                    Sizes = sizes
                };

                var funMap = RuntimeDiagnostics.GetMatrixCreationFunctions();
                measures.AddRange(r.DoMeasures(funMap, what: "matrix", operation: ".NET->R", tag: ""));

                funMap = RuntimeDiagnostics.GetVectorCreationFunctions();
                measures.AddRange(r.DoMeasures(funMap, what: "vector", operation: ".NET->R", tag: ""));

                funMap = RuntimeDiagnostics.GetMatrixRetrievalFunctions();
                measures.AddRange(r.DoMeasures(funMap, what: "matrix", operation: "R->.NET", tag: ""));

                funMap = RuntimeDiagnostics.GetVectorRetrievalFunctions();
                measures.AddRange(r.DoMeasures(funMap, what: "vector", operation: "R->.NET", tag: ""));

                Console.WriteLine("Writing results to {0}", outputfile);
                engine.SetSymbol("runtimes", r.CollateResults(measures));
                engine.Evaluate(string.Format("write.table(runtimes, '{0}', row.names=FALSE, col.names=TRUE, quote=FALSE, sep = ',')", outputfile));

                // rt <- read.csv('c:/tmp/runtimes.csv')
                // d <- ggplot(rt, aes_string(x='Size', y="Duration", color='Type', shape='What'))
                // d <- d + geom_point() + facet_wrap( ~ Operation )
                // d <- d + scale_y_log10() + scale_x_log10() + annotation_logticks(sides='bl')
                // d + ggtitle('Data conversion') + xlab("data size") + ylab('duration (ms)')

                engine.Dispose();
            }
        }
Ejemplo n.º 7
0
        private void Form1_Load(object sender, EventArgs e)
        {
            REngine.SetEnvironmentVariables();
            StartupParameter rinit = new StartupParameter();

            rinit.Quiet       = true;
            rinit.RHome       = @"C:\Program Files\R\R-3.4.0";
            rinit.Interactive = true;
            engine            = REngine.GetInstance(null, true, rinit);
            engine.Initialize();
            var rScript = File.ReadAllText(@"..\..\Data\Concretes.r");

            engine.Evaluate(rScript);
        }
Ejemplo n.º 8
0
        private REngine StartEngine()
        {
            StartupParameter Rinit = new StartupParameter
            {
                Quiet       = true,
                RHome       = R_HOME,
                Interactive = true
            };

            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance(null, true, Rinit);

            return(engine);
        }
Ejemplo n.º 9
0
        internal void Install(REngine engine, StartupParameter parameter)
        {
            this.engine = engine;
            switch (NativeUtility.GetPlatform())
            {
            case PlatformID.Win32NT:
                SetupWindowsDevice(parameter);
                break;

            case PlatformID.MacOSX:
            case PlatformID.Unix:
                SetupUnixDevice();
                break;
            }
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var first = 1;

            foreach (var item in Professions)
            {
                if (item.Value == ComboBoxProfession.Text)
                {
                    first = item.Id;
                }
            }
            var second = 3;

            if (ComboBoxSex.Text == "мужчины")
            {
                second = 2;
            }
            else if (ComboBoxSex.Text == "All")
            {
                second = 1;
            }
            var third = 1;

            foreach (var item in Region)
            {
                if (item.Value == ComboBoxRegion.Text)
                {
                    third = item.Id;
                }
            }
            StartupParameter rinit         = new StartupParameter();
            RdotNetCaller    rdotNetCaller = new RdotNetCaller("Salary.R");

            if (!CheckTextBoxes())
            {
                MessageBox.Show("Введены не все значения параметров!!!");
            }
            else
            {
                var result          = rdotNetCaller.CallMyModel(first.ToString(), second.ToString(), third.ToString()).Replace('.', ',');
                var convertedResult = Convert.ToDouble(result);
                var roundedResult   = Math.Round(convertedResult, 2);
                result = roundedResult.ToString();
                labelResult.Content = string.Format("Ваша прогнозируемая зарплата: {0} рублей", result);
            }
        }
Ejemplo n.º 11
0
 private void SetupWindowsDevice(StartupParameter parameter)
 {
     if (parameter.RHome == null)
     {
         parameter.start.rhome = ToNativeUnixPath(NativeUtility.GetRHomeEnvironmentVariable());
     }
     if (parameter.Home == null)
     {
         string home = Marshal.PtrToStringAnsi(Engine.GetFunction <getValue>("getRUser")());
         parameter.start.home = ToNativeUnixPath(home);
     }
     parameter.start.ReadConsole    = ReadConsole;
     parameter.start.WriteConsole   = WriteConsole;
     parameter.start.WriteConsoleEx = WriteConsoleEx;
     parameter.start.CallBack       = Callback;
     parameter.start.ShowMessage    = ShowMessage;
     parameter.start.YesNoCancel    = Ask;
     parameter.start.Busy           = Busy;
 }
Ejemplo n.º 12
0
        //Execute a previson on esempio on the 8 future values based on stagionality = 4.
        private void esempioForecast()
        {
            string           esempioPath = (dataDirectory + "\\esempio.csv").Replace("\\", "/");
            StartupParameter rinit       = new StartupParameter();

            rinit.Quiet       = true;
            rinit.RHome       = "C:\\Program Files\\R\\R-3.4.4";
            rinit.Interactive = true;
            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance(null, true, rinit);

            engine.Evaluate("");
            engine.Evaluate("library(tseries)");
            engine.Evaluate("library(forecast)");
            engine.Evaluate("data <- read.csv(\"" + esempioPath + "\")");
            engine.Evaluate("myts <- ts(data[,2], frequency = 4)");
            engine.Evaluate("ARIMAfit1 <- auto.arima(myts, stepwise = FALSE, approximation = FALSE)");
            engine.Evaluate("myfc <- forecast(ARIMAfit1, h = 8)");
            engine.Evaluate("intMean <- as.integer(myfc$mean)");
            IntegerVector a1 = engine.GetSymbol("intMean").AsInteger();

            results = a1.ToArray();
        }
Ejemplo n.º 13
0
        //Execute a previson on gioiellerie time series on the 24 future values based on stagionality = 12.
        private void gioiellerieForecast()
        {
            string           gioielleriePath = (dataDirectory + "\\gioiellerie.csv").Replace("\\", "/");
            StartupParameter rinit           = new StartupParameter();

            rinit.Quiet       = true;
            rinit.RHome       = "C:\\Program Files\\R\\R-3.4.4";
            rinit.Interactive = true;
            REngine.SetEnvironmentVariables();
            REngine engine = REngine.GetInstance(null, true, rinit);

            engine.Evaluate("");
            engine.Evaluate("library(tseries)");
            engine.Evaluate("library(forecast)");
            engine.Evaluate("data <- read.csv(\"" + gioielleriePath + "\")");
            //THIS 3 must be converted back into two when the data are readed.
            engine.Evaluate("myts <- ts(data[,3], frequency = 12)");
            engine.Evaluate("ARIMAfit1 <- auto.arima(myts, stepwise = FALSE, approximation = FALSE)");
            engine.Evaluate("myfc <- forecast(ARIMAfit1, h = 24)");
            engine.Evaluate("intMean <- as.integer(myfc$mean)");
            IntegerVector a1 = engine.GetSymbol("intMean").AsInteger();

            results = a1.ToArray();
        }
Ejemplo n.º 14
0
        public static void Main(string[] args)
        {
            /*
             * REngine engine = REngine.GetInstance();
             * string fileName;
             *
             * //init the R engine
             * REngine.SetEnvironmentVariables();
             * engine = REngine.GetInstance();
             * engine.Initialize();
             *
             * //prepare data
             * List<int> size = new List<int>() { 29, 33, 51, 110, 357, 45, 338, 543, 132, 70, 103, 301, 146, 10, 56, 243, 238 };
             * List<int> population = new List<int>() { 3162, 11142, 3834, 7305, 81890, 1339, 5414, 65697, 11280, 4589, 320, 60918, 480, 1806, 4267, 63228, 21327 };
             *
             * fileName = "C:\\Users\\ofunke\\Desktop\\myplot.png";
             *
             * //calculate
             * IntegerVector sizeVector = engine.CreateIntegerVector(size);
             * engine.SetSymbol("size", sizeVector);
             *
             * IntegerVector populationVector = engine.CreateIntegerVector(population);
             * engine.SetSymbol("population", populationVector);
             *
             * CharacterVector fileNameVector = engine.CreateCharacterVector(new[] { fileName });
             * engine.SetSymbol("fileName", fileNameVector);
             *
             * engine.Evaluate("reg <- lm(population~size)");
             * engine.Evaluate("png(filename=fileName, width=6, height=6, units='in', res=100)");
             * engine.Evaluate("plot(population~size)");
             * engine.Evaluate("abline(reg)");
             * engine.Evaluate("dev.off()");
             *
             * //clean up
             * engine.Dispose();
             *
             * //output
             * Console.WriteLine("");
             * Console.WriteLine("Press any key to exit");
             * Console.ReadKey();
             */
            StartupParameter rinit = new StartupParameter();

            rinit.Quiet       = true;
            rinit.RHome       = "C:/Program Files/R/R-3.4.3";
            rinit.Interactive = true;

            REngine.SetEnvironmentVariables();
            // There are several options to initialize the engine, but by default the following suffice:
            REngine engine = REngine.GetInstance();

            // .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);

            // you should always dispose of the REngine properly.
            // After disposing of the engine, you cannot reinitialize nor reuse it
            engine.Dispose();
        }