Ejemplo n.º 1
1
        private static void DoTest(REngine engine)
        {
            var setupStr = @"library(deldir)
            set.seed(421)
            x <- runif(20)
            y <- runif(20)
            z <- deldir(x,y)
            w <- tile.list(z)

            z <- deldir(x,y,rw=c(0,1,0,1))
            w <- tile.list(z)

            z <- deldir(x,y,rw=c(0,1,0,1),dpl=list(ndx=2,ndy=2))
            w <- tile.list(z)
            ";

             engine.Evaluate(setupStr);
             var res = new List<List<Tuple<double, double>>>();
             var n = engine.Evaluate("length(w)").AsInteger()[0];
             for (int i = 1; i <= n; i++)
             {
            var x = engine.Evaluate("w[[" + i + "]]$x").AsNumeric().ToArray();
            var y = engine.Evaluate("w[[" + i + "]]$y").AsNumeric().ToArray();
            var t = x.Zip(y, (first, second) => Tuple.Create(first, second)).ToList();
            res.Add(t);
             }
        }
Ejemplo n.º 2
1
        public Form1()
        {
            InitializeComponent();
            this.FormClosed += new FormClosedEventHandler(OnFormClosed);

            REngine.SetEnvironmentVariables();
            engine = REngine.GetInstance();
            // REngine requires explicit initialization.
            // You can set some parameters.
            engine.Initialize();
        }
Ejemplo n.º 3
1
 private static void TestPendingFinalizersThreadingIssues(REngine e)
 {
     e.Evaluate("f <- function(a) {if (length(a)!= 1) stop('What goes on?')}");
     var f = e.Evaluate("f").AsFunction();
     try
     {
         e.Evaluate("f(letters[1:3])");
     }
     catch (EvaluationException)
     {
     }
     f.Invoke(e.CreateCharacterVector(new[] { "blah" }));
     try
     {
         f.Invoke(e.CreateCharacterVector(new[] { "blah", "blah" }));
     }
     catch (EvaluationException)
     {
         Console.WriteLine("Caught the expected exception");
     }
     f = null;
     GC.Collect();
     GC.WaitForPendingFinalizers();
     e.Dispose();
     Console.WriteLine("Just waiting for crash...");
     GC.Collect();
     GC.WaitForPendingFinalizers();
 }
Ejemplo n.º 4
0
        public void Start(params REngineOptions[] list)
        {
            try
            {
                // Only one instance per process
                if (!IsRunning)
                {
                    SetupEnvironment();

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

                    // Load compiler package on startup - may speed up code if long running
                    LoadPackage("compiler");
                }
                else
                {
                    engine = RDotNet.REngine.GetInstanceFromID(InstanceID);
                }
            }
            catch (SEHException e)
            {
                throw new  ApplicationException(e.Message, e);
            }
            if (engine == null)
            {
                throw new ApplicationException("Could not start R");
            }
        }
Ejemplo n.º 5
0
        static void rdotnet_discussions_646729(REngine engine)
        {
            var setup = @"library(rdotnetsamples)
rdotnetsamples::register_default_progress_handler()
";
            engine.Evaluate(setup);
            var myRFunction = @"
my_r_calculation <- function()
{
  for (i in seq(0, 100, by=20)) {
    rdotnetsamples::broadcast_progress_update(paste0('Some Update Message for ', i), i);
  }
}
";
            engine.Evaluate(myRFunction);
            engine.Evaluate("my_r_calculation()");

            var unixDllPath = engine.Evaluate("getLoadedDLLs()$rdotnetsamples[['path']]").AsCharacter()[0];
            var dllPath = unixDllPath.Replace("/", "\\");
            var dll = new DynamicInterop.UnmanagedDll(dllPath);
            TestCallback cback = new TestCallback();
            CallBackHandlers cbh = new CallBackHandlers();
            cback.MyHandler = cbh.ProcessProgress;

            string cFunctionRegisterCallback = "register_progress_handler";
            register_default_progress_handler registerHandlerFun = dll.GetFunction<register_default_progress_handler>(cFunctionRegisterCallback);
            registerHandlerFun(cback.MyHandler);

            Console.WriteLine();
            Console.WriteLine("After registering the callback with a function pointer to a C# function:");
            Console.WriteLine();
            engine.Evaluate("my_r_calculation()");

        }
        public RService()
            : base()
        {
            string RLogFilename = DirectoryHelper.GetLogFileName();
            this._log = new RDotNetConsoleLogDevice();
            this._log.LogDevice = new Journal() { FileName = RLogFilename };
            logService.WriteToLogLevel("R DotNet Server (deepest function call) initialization started.", LogLevelEnum.Info); 
            try
            {

                StartupParameter sp = new StartupParameter(); 
                REngine.SetEnvironmentVariables(null, null );//can set R Path and R Home by passing params
                this._RServer = REngine.GetInstance();//null, true, null, _log);
                this._RServer.Initialize();
                logService.WriteToLogLevel("R DotNet Server initialized.", LogLevelEnum.Info); //writes to ApplicationLog
                _log.WriteConsole("R.Net Initialized!!!", 1024, RDotNet.Internals.ConsoleOutputType.None); //writes to RLog
            }
            catch (Exception ex)
            {
                _log.WriteConsole("Unable to initialize R Server.(note: 64bit R must already be present)", 5, RDotNet.Internals.ConsoleOutputType.None);//Added by Anil
                logService.WriteToLogLevel("Unable to initialize R Server.", LogLevelEnum.Error, ex);
                
                throw new Exception();
            }
            logService.WriteToLogLevel("R  DotNet Server (deepest function call) initialization ended.", LogLevelEnum.Info); 
        }
Ejemplo n.º 7
0
		static double calcSDev (REngine engine, double[] arr)
		{
			// Note: only one quick and slightly dirty way to do it
			NumericVector rVector = engine.CreateNumericVector(arr);
			engine.SetSymbol ("x", rVector);
			return engine.Evaluate ("sd(x)").AsNumeric () [0];
		}
Ejemplo n.º 8
0
        public Form1()
        {
            InitializeComponent();
            string strFileName = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            saveFileDialog1.InitialDirectory = "c:\\";
            saveFileDialog1.FileName = "dimer_result.xlsx";
            saveFileDialog1.Filter = "Excel文件(*.xlsx)|*.xlsx|所有文件(*.*)|*.*";
            configDoc.Load(strFileName);
            progressBar1.Visible = false;

            string installHome = Environment.GetEnvironmentVariable("PRIMERDIMERTOOL_HOME");
            if (installHome != null)
            {
                installPath = installHome;
            }
            else
            {
                installPath = getConfigSetting("installpath");
            }

            Environment.SetEnvironmentVariable("PATH", installPath + "/Primer3/");
            Environment.SetEnvironmentVariable("JAVA_HOME", installPath + "/Java");
            REngine.SetEnvironmentVariables(installPath + "/R/bin/x64", installPath + "/R");
            engine=REngine.GetInstance();
        }
Ejemplo n.º 9
0
 public frmData()
 {
     InitializeComponent();
     // There are several options to initialize thengine, but by default the following suffice:
     engine = REngine.GetInstance();
     engine.Initialize();
 }
Ejemplo n.º 10
0
        private static void ReproStackOverflow_34355201(REngine engine)
        {
            engine.AutoPrint = true;
            //samples taken from ?fscores man page in package mirt
            engine.Evaluate("library(mirt)");
            // 'Science' is a prepackage sample data in mirt; you can use 'engine.CreateDataFrame' in C# to create your own if need be.
            engine.Evaluate("mod <- mirt(Science, 1)");
            engine.Evaluate("class(mod)");
            S4Object modcs = engine.GetSymbol("mod").AsS4();

            // TODO - noticed 2015-12 that R.NET 1.6.5, HasSlot causes a stack imbalance warning. To unit test.
            // Normally should do:
            // if (modcs.HasSlot("Fit"))

            IDictionary<string, string> slotTypes = modcs.GetSlotTypes();
            if (slotTypes.Keys.Contains("Fit"))
            {
                GenericVector fit = modcs["Fit"].AsList();
                // should check logLik in fit.Names;
                double logLik = fit["logLik"].AsNumeric()[0];
            }
            engine.Evaluate("tabscores <- fscores(mod, full.scores = FALSE)");
            engine.Evaluate("head(tabscores)");
            engine.Evaluate("class(tabscores)");
            NumericMatrix tabscorescs = engine.GetSymbol("tabscores").AsNumericMatrix();
        }
Ejemplo n.º 11
0
 public RGraphForm()
 {
     InitializeComponent();
       REngine.SetDllDirectory(GetRPath());
       REngine.CreateInstance("RDotNet");
       engine = REngine.GetInstanceFromID("RDotNet");
       cbt = new RGraphAppHook {GraphControl = RPanel1};
 }
Ejemplo n.º 12
0
        public CodeController()
        {
            if (_engine != null) return;

            _engine = REngine.GetInstance(null, true, null, CharacterDevice);
            _engine.Initialize();
            _engine. .Install(GraphicsDevice);
        }
Ejemplo n.º 13
0
 public RuntimeDiagnostics(REngine engine)
 {
     this.engine = engine;
     Types = new string[0];
     Sizes = new int[0];
     What = "";
     Operation = "";
     Tag = "";
 }
Ejemplo n.º 14
0
 private static void ReproIssue169(REngine engine)
 {
     engine.Evaluate("library(mirt)");
     engine.Evaluate("x=mirt(Science,1)");
     S4Object obj111 = engine.GetSymbol("x").AsS4();
     engine.Evaluate("ff=fscores(x, response.pattern=c(1,0,0,0))");
     GenericVector dataset111 = engine.GetSymbol("ff").AsList();
     NumericVector v = dataset111[0].AsNumeric();
     double firstval = v[0];
 }
Ejemplo n.º 15
0
 public static bool ReproWorkitem45(REngine engine, int numThreads = 1)
 {
     for (int i = 0; i < numThreads; i++)
      {
     Graphics = new Thread(Repro45Thread);
     Graphics.Start(engine);
      }
      //Started = true;
      return true;
 }
Ejemplo n.º 16
0
		/// <summary>
		/// http://stackoverflow.com/q/27689786/2752565
		/// </summary>
		static void stackoverflow_27689786_2752565 (REngine engine)
		{
			var rand = new System.Random (0);
			double[] randValues;

			for (int i = 0; i < 10; i++) {
				randValues = mkValues (rand, 100);
				Console.WriteLine ("std dev iteration {0} = {1}", i + 1, calcSDev (engine, randValues));
			}
		}
Ejemplo n.º 17
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);
                    }
                }
            }
        }
 private static GenericVector asList(SymbolicExpression expression)
 {
     if (!object.ReferenceEquals(engine, expression.Engine) || engine == null)
     {
         engine = expression.Engine;
         asListFunction = null;
     }
     if (asListFunction == null)
         asListFunction = engine.Evaluate("invisible(as.list)").AsFunction();
     var newExpression = asListFunction.Invoke(expression);
     return new GenericVector(newExpression.Engine, newExpression.DangerousGetHandle());
 }
Ejemplo n.º 19
0
 internal static void InitializeRDotNet()
 {
     try
     {
         REngine.SetEnvironmentVariables();
         _engine = REngine.GetInstance();
         _engine.Initialize();
     }
     catch (Exception ex)
     {
         LogDisplay.WriteLine("Error initializing RDotNet: " + ex.Message);
     }
 }
        static void GenetateLatencyVsMessageLengthPlot_RScript(REngine engine, string latencyCsvFilename)
        {
            //For formatting purposes, make sure the filename is acceptable for R function read.csv
            string fileToReadFromCommand = latencyCsvFilename.Replace(@"\", @"/");

            //Convert to R character vector
            CharacterVector cvFilename = engine.CreateCharacterVector(new[] { fileToReadFromCommand });
            // and assign it to variable (in R engine) called fileToReadFrom
            engine.SetSymbol("fileToReadFrom", cvFilename);

            //And then evaluate the script - this uses the 'fileToReadFrom' in a read.csv call
            engine.Evaluate(MyRDotNetApplication.Properties.Resources.latencyVsMessageLengthScatterPlot); //R-Script to generate plot
        }
Ejemplo n.º 21
0
 private static void TestCallStop(REngine engine)
 {
     try
     {
         engine.Evaluate("stop('Just stop')");
     }
     catch (Exception ex)
     {
         counter++;
         Console.WriteLine(string.Format("Caught an exception ({0})", counter));
         Console.WriteLine(ex.ToString());
     }
     Console.WriteLine("Recovered from evaluation exception?");
 }
Ejemplo n.º 22
0
 public static REngine getREngineInstance()
 {
     if (engine == null)
     {
         string primer3Home = System.Web.Configuration.WebConfigurationManager.AppSettings["primer3Home"];
         string RHome = System.Web.Configuration.WebConfigurationManager.AppSettings["RHome"];
         string javaHome = System.Web.Configuration.WebConfigurationManager.AppSettings["javaHome"];
         Environment.SetEnvironmentVariable("PATH", primer3Home);
         Environment.SetEnvironmentVariable("JAVA_HOME", javaHome);
         REngine.SetEnvironmentVariables(RHome + "/bin/x64", RHome);
         engine = REngine.GetInstance(null, true, null, null);
     }
     return engine;
 }
Ejemplo n.º 23
0
 public frmData(int id)
 {
     InitializeComponent();
     // There are several options to initialize thengine, but by default the following suffice:
     engine = REngine.GetInstance();
     engine.Initialize();
     intID = id;
     setFilters(id);
     setGrid(id);
     setButtons(bAdd, bEdit);
     cTitle = Color.Black;
     cAxis = Color.Black;
     cLegend = Color.Black;
     cTick = Color.Black;
 }
Ejemplo n.º 24
0
        public Form1()
        {
            InitializeComponent();

            string R_HOME = System.Environment.GetEnvironmentVariable("R_HOME");

            if (!R_HOME.EndsWith("\\"))
            {
                R_HOME += "\\";
            }

            REngine.SetEnvironmentVariables(R_HOME + "bin\\x64", R_HOME);
            Engine = REngine.GetInstance();

            Console.WriteLine("REngine is initialized.");
        }
Ejemplo n.º 25
0
		/// <summary>
		/// http://stackoverflow.com/q/27597542/2752565
		/// </summary>
		static void stackoverflow_27597542_2752565 (REngine engine)
		{
			var createModel = @"
			set.seed(0)
			x <- ts(rnorm(100))
			library(forecast)
			blah <- ets(x)
			# str(blah)
			";
			engine.Evaluate (createModel);
			var m = engine.GetSymbol ("blah").AsList ();
			var components = m ["components"].AsCharacter ().ToArray ();
			for (int i = 0; i < components.Length; i++) {
				Console.WriteLine ("m$components[{0}] = {1}", i + 1, components [i]);
			}
		}
        /// <summary>
        /// Creates an untrained learner, that uses the given number of frames to learn.
        /// <param name="numberFrames">Number of frames after which this learner switches 
        /// to 'learned' state and predicts instead of further fitting the model.</param>
        /// </summary>
        public SupervisedLearner(int numberFrames)
        {
            // Initialize R engine for the untrained (or to-be-trained) learner
            if (_engine == null)
            {
                #region Find R DLL
            #if UNIX
                // Hope, the RDotNet.NativeLibrary project finds it...
            #else
                // Try to find the path from the Windows registry and add it to a special environment variable,
                // as well as the subfolders containing the dlls to the PATH variable.
                string rhome = System.Environment.GetEnvironmentVariable("R_HOME");
                if (string.IsNullOrEmpty(rhome)){
                    rhome = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\Software\R-core\R", "InstallPath", "C:");

                    System.Environment.SetEnvironmentVariable("R_HOME", rhome);
                    System.Environment.SetEnvironmentVariable("PATH", System.Environment.GetEnvironmentVariable("PATH") + ";" +
                                                                        rhome + @"\bin\i386;" +
                                                                        rhome + @"\bin\x64;");
                }

                // Obsolete: set directory explicitly
                //REngine.SetDllDirectory(rhome + @"\bin\i386");
            #endif
                #endregion

                _engine = REngine.CreateInstance("R");
                _engine.InitializeConsoleOutput();
            }

            // Only keep one single instance of the R engine (R.Net restriction: one engine per process).
            // Therefore, make use of different virtual engines via an incrementing number, that is
            // prepended to each used variable.
            // Also, keep track of all SupervisedLearner instances: if the last one is disposed, no
            // virtual engine is needed anymore: therefore dispose the R engine.
            this._engineNum = _engines;
            _engines++;
            _disposedLearners.Add(false);
            if (_disposedLearners.Count != _engines)
            {
                throw new Exception("Something has gone wrong: the list that keeps track of the virtual engines " +
                    "is different to the number of virtual engines.");
            }

            this.numberLearningSamples = numberFrames;
            this.learned = false;
        }
Ejemplo n.º 27
0
      static void TestOptimCsharp(REngine engine)
      {
         var rand = new Random(0);
         int n = 10000;
         double x, y, r, xb, yb, rb;
         rb = double.MaxValue; xb = yb = double.MaxValue;
         engine.Evaluate("rosen <- function(x, y) { (1-x)**2 + 100*(y-x*x)**2 }");
         Console.WriteLine("*** Try a basic way to call the function in R ***");
         for (int i = 0; i < n; i++)
         {
            x = -1 + rand.NextDouble() * (3 - (-1));
            y = -1 + rand.NextDouble() * (3 - (-1));
            r = engine.Evaluate(string.Format("rosen({0}, {1})", x, y)).AsNumeric().ToArray()[0];
            if (r < rb)
            {
               rb = r;
               xb = x;
               yb = y;
            }
         }
         Console.WriteLine("The best score r={0} is for x={1}, y={2}", rb, xb, yb);
         Console.WriteLine("*** Try an R function 'pointer' with a vectorized function call. Faster, if you can do it this way***");

         var f = engine.GetSymbol("rosen").AsFunction();
         double[] xa = new double[n], ya = new double[n];
         rand = new Random(0);
         for (int i = 0; i < n; i++)
         {
            xa[i] = -1 + rand.NextDouble() * (3 - (-1));
            ya[i] = -1 + rand.NextDouble() * (3 - (-1));
         }
         double[] ra = f.Invoke(new[] { engine.CreateNumericVector(xa), engine.CreateNumericVector(ya) })
             .AsNumeric().ToArray();
         rb = ra.Min();
         int indBest = -1;
         for (int i = 0; i < ra.Length; i++)
         { // no which.min in C#. Should call R here too...
            if (ra[i] <= rb)
               indBest = i;
         }
         Console.WriteLine("The best score r={0} is for x={1}, y={2}", rb, xa[indBest], ya[indBest]);
      }
Ejemplo n.º 28
0
 private static void TestDataFrameInMemoryCreation(REngine engine)
 {
     IEnumerable[] columns;
     string[] columnNames;
     DataFrame df;
     createTestDataFrame(engine, out columns, out columnNames, out df);
     df = engine.CreateDataFrame(columns, columnNames: null);
     columns[1] = new int[] { 1, 2, 3, 4, 5, 6, 7 };
     try
     {
         df = engine.CreateDataFrame(columns, columnNames: null);
     }
     catch (Exception ex)
     {
         counter++;
         Console.WriteLine(string.Format("Caught an exception ({0})", counter));
         Console.WriteLine(ex.ToString());
     }
     Console.WriteLine("Recovered from evaluation exception?");
 }
Ejemplo n.º 29
0
        // Investigate use of the Defer method. Deprecated?
        private static string DeferedStatementRepro(REngine engine)
        {
            // Looking at the issues reported in https://rdotnet.codeplex.com/discussions/458547
            // indeed the R.NET documentation page as of 22 Sept 2013 is off as to what Defer method there is.
            // The following memory stream is a workaround out of curiosity: not something intended for ongoing use.
            // With the memory stream workaround, it bombs. 
            // Not sure whether this is because of the conversion to byte, but unlikely to be a false positive.
            string deferedStatement = "x <- 3";

            var byteArr = Array.ConvertAll(deferedStatement.ToArray(), c => Convert.ToByte(c));
            using (var stream = new MemoryStream(byteArr))
            {
                // Defer method delays an effect on the R environment.
                var e = engine.Defer(stream);
                // Error: GetSymbol method returns null at the moment.
                // NumericVector x = engine.GetSymbol("x").AsNumeric();

                // Evaluates the statement.
                e.ToArray();
            }
            return deferedStatement;
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="s">The string</param>
 public InternalString(REngine engine, string s)
     : base(engine, engine.GetFunction <Rf_mkChar>()(s))
 {
 }
Ejemplo n.º 31
0
 /// <summary>
 /// Creates a built-in function proxy.
 /// </summary>
 /// <param name="engine">The engine.</param>
 /// <param name="pointer">The pointer.</param>
 protected internal BuiltinFunction(REngine engine, IntPtr pointer)
     : base(engine, pointer)
 {
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Creates a symbol.
 /// </summary>
 /// <param name="engine">The engine.</param>
 /// <param name="pointer">The pointer.</param>
 protected internal Symbol(REngine engine, IntPtr pointer)
     : base(engine, pointer)
 {
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="pointer">The pointer to a string.</param>
 public InternalString(REngine engine, IntPtr pointer)
     : base(engine, pointer)
 {
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Creates a new empty ComplexVector with the specified length.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="length">The length.</param>
 /// <seealso cref="REngineExtension.CreateComplexVector(REngine, int)"/>
 public ComplexVector(REngine engine, int length)
     : base(engine, SymbolicExpressionType.ComplexVector, length)
 {
 }
Ejemplo n.º 35
0
 /// <summary>
 /// Creates a new instance for a complex number vector.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="coerced">The pointer to a complex number vector.</param>
 protected internal ComplexVector(REngine engine, IntPtr coerced)
     : base(engine, coerced)
 {
 }
Ejemplo n.º 36
0
 /// <summary>
 /// Creates a new environment object.
 /// </summary>
 /// <param name="engine">The engine.</param>
 /// <param name="parent">The parent environment.</param>
 public REnvironment(REngine engine, REnvironment parent)
     : base(engine, engine.GetFunction <Rf_NewEnvironment>()(engine.NilValue.DangerousGetHandle(), engine.NilValue.DangerousGetHandle(), parent.handle))
 {
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Creates a function object.
 /// </summary>
 /// <param name="engine">The engine.</param>
 /// <param name="pointer">The pointer.</param>
 protected Function(REngine engine, IntPtr pointer)
     : base(engine, pointer)
 {
 }
Ejemplo n.º 38
0
 public void SetUp()
 {
     REngine.SetEnvironmentVariables();
 }
Ejemplo n.º 39
0
 /// <summary>
 /// Creates an environment object.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="pointer">The pointer to an environment.</param>
 protected internal REnvironment(REngine engine, IntPtr pointer)
     : base(engine, pointer)
 {
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Creates a new instance for a string vector.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="coerced">The pointer to a string vector.</param>
 protected internal CharacterVector(REngine engine, IntPtr coerced)
     : base(engine, coerced)
 {
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Creates a new CharacterVector with the specified values.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="vector">The values.</param>
 /// <seealso cref="REngineExtension.CreateCharacterVector(REngine, IEnumerable{string})"/>
 public CharacterVector(REngine engine, IEnumerable <string> vector)
     : base(engine, SymbolicExpressionType.CharacterVector, vector)
 {
 }
Ejemplo n.º 42
0
 /// <summary>
 /// Creates a new empty CharacterVector with the specified length.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="length">The length.</param>
 /// <seealso cref="REngineExtension.CreateCharacterVector(REngine, int)"/>
 public CharacterVector(REngine engine, int length)
     : base(engine, SymbolicExpressionType.CharacterVector, length)
 {
 }
Ejemplo n.º 43
0
 /// <summary>
 /// Creates a language object.
 /// </summary>
 /// <param name="engine">The engine</param>
 /// <param name="pointer">The pointer.</param>
 protected internal Language(REngine engine, IntPtr pointer)
     : base(engine, pointer)
 {
 }
Ejemplo n.º 44
0
 /// <summary>
 /// Creates a new vector with the specified values.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="type">The element type.</param>
 /// <param name="vector">The elements of vector.</param>
 protected Vector(REngine engine, SymbolicExpressionType type, IEnumerable <T> vector)
     : base(engine, engine.GetFunction <Rf_allocVector>()(type, vector.Count()))
 {
     SetVector(vector.ToArray());
 }
Ejemplo n.º 45
0
        protected static double GetRMemorySize(REngine engine)
        {
            var memoryAfterAlloc = engine.Evaluate("memory.size()").AsNumeric().First();

            return(memoryAfterAlloc);
        }
Ejemplo n.º 46
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="coerced">The pointer to a data frame.</param>
 protected internal DataFrame(REngine engine, IntPtr coerced)
     : base(engine, coerced)
 {
 }
Ejemplo n.º 47
0
 /// <summary>
 /// Creates a new instance for an expression vector.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="coerced">The pointer to an expression vector.</param>
 internal ExpressionVector(REngine engine, IntPtr coerced)
     : base(engine, coerced)
 {
 }
Ejemplo n.º 48
0
 /// <summary>
 /// Creates a new empty NumericMatrix with the specified size.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="rowCount">The row size.</param>
 /// <param name="columnCount">The column size.</param>
 /// <seealso cref="REngineExtension.CreateNumericMatrix(REngine, int, int)"/>
 public NumericMatrix(REngine engine, int rowCount, int columnCount)
     : base(engine, SymbolicExpressionType.NumericVector, rowCount, columnCount)
 {
 }
Ejemplo n.º 49
0
 /// <summary>
 /// Creates a new ComplexVector with the specified values.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="vector">The values.</param>
 /// <seealso cref="REngineExtension.CreateComplexVector(REngine, System.Collections.Generic.IEnumerable{System.Numerics.Complex})"/>
 public ComplexVector(REngine engine, IEnumerable <Complex> vector)
     : base(engine, SymbolicExpressionType.ComplexVector, vector)
 {
 }
Ejemplo n.º 50
0
 /// <summary>
 /// Creates a new instance for a numeric matrix.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="coerced">The pointer to a numeric matrix.</param>
 protected internal NumericMatrix(REngine engine, IntPtr coerced)
     : base(engine, coerced)
 {
 }
 private void InitializeRDotNet()
 {
     REngine.SetEnvironmentVariables();
     engine = REngine.GetInstance();
     // REngine requires explicit initialization.
     // You can set some parameters.
     engine.Initialize();
     //load BSky and R packages
     engine.Evaluate("library(uadatapackage)");
     engine.Evaluate("library(foreign)");
     engine.Evaluate("library(data.table)");
     engine.Evaluate("library(RODBC)");
     engine.Evaluate("library(car)");
     engine.Evaluate("library(aplpack)");
     engine.Evaluate("library(mgcv)");
     engine.Evaluate("library(rgl)");
     engine.Evaluate("library(gmodels)");
 }
Ejemplo n.º 52
0
 private static void createTestDataFrame(REngine engine, out IEnumerable[] columns, out string[] columnNames, out DataFrame df)
 {
     columns     = createTestDfColumns();
     columnNames = new[] { "Category", "No.", "Measure" };
     df          = engine.CreateDataFrame(columns, columnNames: columnNames);
 }
Ejemplo n.º 53
0
        public static void RtoDotNetLogicalMatrix(REngine engine, int n, Stopwatch s, Func <REngine, Array> fun, string symbolName)
        {
            var mode = "logical";

            measureRtoDotnetMatrix(engine, n, s, fun, mode, symbolName);
        }
Ejemplo n.º 54
0
 private static void setValueAndMeasure(REngine engine, Stopwatch s, Func <REngine, Array> fun, string symbolName, string vStatement)
 {
     engine.SetSymbol(symbolName, engine.Evaluate(vStatement));
     //engine.Evaluate("cat(ls())");
     measure(engine, s, fun);
 }
Ejemplo n.º 55
0
 /// <summary>
 /// Creates a new instance for a vector.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="coerced">The pointer to a vector.</param>
 protected Vector(REngine engine, IntPtr coerced)
     : base(engine, coerced)
 {
 }
Ejemplo n.º 56
0
 /// <summary>
 /// Creates a new NumericMatrix with the specified values.
 /// </summary>
 /// <param name="engine">The <see cref="REngine"/> handling this instance.</param>
 /// <param name="matrix">The values.</param>
 /// <seealso cref="REngineExtension.CreateNumericMatrix(REngine, double[,])"/>
 public NumericMatrix(REngine engine, double[,] matrix)
     : base(engine, SymbolicExpressionType.NumericVector, matrix)
 {
 }
Ejemplo n.º 57
0
 /// <summary>
 /// Creates a new instance that handles R.DLL.
 /// </summary>
 /// <param name="id">ID.</param>
 /// <param name="dll">The file name of the library to load, e.g. "R.dll" for Windows. You should usually not provide this optional parameter</param>
 /// <returns>The engine.</returns>
 private static REngine CreateInstance(string id, string dll = null)
 {
     if (id == null)
     {
         throw new ArgumentNullException("id", "Empty ID is not allowed.");
     }
     if (id == string.Empty)
     {
         throw new ArgumentException("Empty ID is not allowed.", "id");
     }
     dll = ProcessRDllFileName(dll);
     var engine = new REngine(id, dll);
     return engine;
 }
Ejemplo n.º 58
0
 /// <summary>
 /// Gets a reference to the R engine, creating and initializing it if necessary. In most cases users need not provide any parameter to this method.
 /// </summary>
 /// <param name="dll">The file name of the library to load, e.g. "R.dll" for Windows. You usually do not need need to provide this optional parameter</param>
 /// <param name="initialize">Initialize the R engine after its creation. Default is true</param>
 /// <param name="parameter">If 'initialize' is 'true', you can optionally specify the specific startup parameters for the R native engine</param>
 /// <param name="device">If 'initialize' is 'true', you can optionally specify a character device for the R engine to use</param>
 /// <returns>The engine.</returns>
 /// <example>
 /// <p>A minimalist approach is to just call GetInstance</p>
 /// <code>
 /// REngine.SetEnvironmentVariables();
 /// var engine = REngine.GetInstance();
 /// engine.Evaluate("letters[1:26]");
 /// </code>
 /// <p>In unusual circumstances you may need to elaborate on the initialization in a separate method call</p>
 /// <code>
 /// REngine.SetEnvironmentVariables(rPath=@"c:\my\peculiar\path\to\R\bin\x64");
 /// var engine = REngine.GetInstance(initialize=false);
 /// StartupParameter sParams=new StartupParameter(){NoRenviron=true;};
 /// ICharacterDevice device = new YourCustomDevice();
 /// engine.Initialize(parameter: sParams, device: device);
 /// engine.Evaluate("letters[1:26]");
 /// </code>
 /// </example>
 public static REngine GetInstance(string dll = null, bool initialize = true, StartupParameter parameter = null, ICharacterDevice device = null)
 {
     if (!environmentIsSet) // should there be a warning? and how?
         SetEnvironmentVariables();
     if (engine == null)
     {
         engine = CreateInstance(EngineName, dll);
         if (initialize)
             engine.Initialize(parameter, device);
     }
     if (engine.Disposed)
         throw new InvalidOperationException("The single REngine instance has already been disposed of (i.e. shut down). Multiple engine restart is not possible.");
     return engine;
 }
Ejemplo n.º 59
0
        private static void measureRtoDotnetVector(REngine engine, int n, Stopwatch s, Func <REngine, Array> fun, string mode, string symbolName)
        {
            var vStatement = string.Format("as.{1}(1:{0})", n.ToString(CultureInfo.InvariantCulture), mode);

            setValueAndMeasure(engine, s, fun, symbolName, vStatement);
        }
Ejemplo n.º 60
-1
        private void InitializeR()
        {
            engine = REngine.GetInstance();
            engine.Initialize();
            var currentDir = System.Environment.CurrentDirectory.Replace('\\', '/');
            if (!m_JADE_Loaded)
            {
               
                engine.Evaluate("install.packages('JADE', repos='http://cran.us.r-project.org')");

                //repos ='https://cran.rstudio.com/bin/windows/contrib/3.2/JADE_1.9-93.zip')");

                engine.Evaluate("library('JADE')");
                m_JADE_Loaded = true;
            }
            
        }