Esempio 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);
             }
        }
Esempio n. 2
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();
 }
Esempio n. 3
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()");

        }
Esempio n. 4
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];
 }
Esempio n. 5
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];
		}
Esempio n. 6
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]);
      }
        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
        }
Esempio n. 8
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?");
 }
Esempio n. 9
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]);
			}
		}
Esempio n. 10
0
        private static void ReproInMemoryDataFrameCreation(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" }));
             f.Invoke(e.CreateCharacterVector(new[] { "blah", "blah" }));

             // IEnumerable[] columns, string[] columnNames = null, string[] rowNames = null, bool checkRows = false, bool checkNames = true, bool stringsAsFactors = true);
             var columns = new[] {
            new[]{1,2,3,4,5},
            new[]{1,2,3,4,5},
            new[]{1,2,3,4,5}
             };
             var df = e.CreateDataFrame(columns, new[] { "a", "b", "c" });
             columns[1] = new[] { 1, 2, 3 };
             object blah;
             try
             {
            df = e.CreateDataFrame(columns, new[] { "a", "b", "c" });
            blah = df[1, 1];
             }
             catch
             {
             }
             df = e.CreateDataFrame(columns, new[] { "a", "b", "c" });
             blah = df[1, 1];
        }
Esempio n. 11
0
 private static void GetDataFrame(string sexpression, REngine engine)
 {
     var dataFrame = engine.Evaluate(sexpression).AsDataFrame();
      SimpleHyperCube s = convert(dataFrame);
 }
Esempio n. 12
0
 private static void TestPlot(REngine e)
 {
     e.Evaluate("library(DAAG)");
     for (int i = 0; i < 100; i++)
     {
         e.Evaluate("p <- plot(northing ~ easting, data=frogs, pch=c(1,16)[frogs$pres.abs+1], xlab='Meters east of reference point', ylab='Meters north')");
         e.Evaluate(string.Format("print(paste('plot iteration number', {0}))", i));
     }
 }
Esempio n. 13
0
 private static void ReproWorkitem43(REngine engine)
 {
     Random r = new Random(0);
      int N = 500;
      int n1 = 207;
      int n2 = 623;
      var arGroup1Intensities = new double[N][];
      var arGroup2Intensities = new double[N][];
      for (int i = 0; i < N; i++)
      {
     arGroup1Intensities[i] = new double[n1];
     arGroup2Intensities[i] = new double[n2];
     for (int j = 0; j < n1; j++)
        arGroup1Intensities[i][j] = r.NextDouble();
     for (int j = 0; j < n2; j++)
        arGroup2Intensities[i][j] = r.NextDouble();
      }
      var res = new GenericVector[N];
      NumericVector vGroup1, vGroup2;
      for (int i = 0; i < N; i++)
      {
     vGroup1 = engine.CreateNumericVector(arGroup1Intensities[i]);
     Console.WriteLine(vGroup1.Length);
     if (i % 10 == 4)
     {
        engine.ForceGarbageCollection();
        engine.ForceGarbageCollection();
     }
     vGroup2 = engine.CreateNumericVector(arGroup2Intensities[i]);
     Console.WriteLine(vGroup2.Length);
     engine.SetSymbol("group1", vGroup1);
     engine.SetSymbol("group2", vGroup2);
     GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
     res[i] = testResult;
      }
 }
Esempio n. 14
0
        private static DataFrame UserReported(REngine engine)
        {
            // Incomplete data and repro info.
             // See https://rdotnet.codeplex.com/discussions/569196
             NumericVector PreprocessedValue = null;
             DataFrame PredictedData = null;

             // Some info was missing. Make up.
             string StartDate = "2001-01-01";
             double[] PreProcessedList = new[] { 1.1, 7.3, 4.5, 7.4, 11.23, 985.44 };
             string days = "2"; string interval = "3";

             PreprocessedValue = engine.CreateNumericVector(PreProcessedList);
             // Assign the Utilization value to R variable UtilValue
             engine.SetSymbol("PreprocessedValue", PreprocessedValue);
             engine.Evaluate("library(forecast)");
             engine.Evaluate("StartDate <- as.Date('" + StartDate + "') + " + days);
             engine.Evaluate("size = length(seq(from=as.Date('" + StartDate + "'), by='" + "day" + "', to=as.Date(StartDate)))");
             engine.Evaluate("startDate <- as.POSIXct('" + StartDate + "')");
             engine.Evaluate("endDate <- StartDate + as.difftime(size, units='" + "days" + "')");
             engine.Evaluate("PredictDate = seq(from=StartDate, by=" + interval + "*60, to=endDate)");
             engine.Evaluate("freq <- ts(PreprocessedValue, frequency = 20)");
             engine.Evaluate("forecastnavie <-snaive(freq, Datapoints)");
             engine.Evaluate("PredictValue = (forecastnavie$mean)");
             engine.Evaluate("PredictedData = cbind(PredictValue, data.frame(PredictDate))");
             PredictedData = engine.Evaluate("PredictedData").AsDataFrame();
             return PredictedData;
        }
Esempio n. 15
0
        private static void ReproDiscussion30824095(REngine e)
        {
            e.Evaluate("library(cluster)");
              e.Evaluate("library(rrcov)");

              // plot from R
              //to show outlier with method : classic & robust Mve

              e.Evaluate("n <- 100 ; spread <- (n/2 - abs(1:n - n/2))/n * 4");
              e.Evaluate("X <- data.frame(1:n + spread * rnorm(n), 2 * 1:n + spread * rnorm(n))");

              int xAxis = 1;
              int yAxis = 2;
              e.Evaluate("x<-X[," + xAxis + "] ");
              e.Evaluate("y<-X[," + yAxis + "] ");
              e.Evaluate("shape <- cov(X)");
              e.Evaluate("center<- colMeans(X)");
              e.Evaluate("d2.95 <- qchisq(0.95, df = 2)");
              //e.Evaluate("gr<- grid(lty=3,col='lightgray', equilogs = 'TRUE')");
              //dataform.rconn.Evaluate("mtext('with classical (red) and robust (blue)')");
              e.Evaluate("plot(x,y, main='Draw Ellipse ', pch=19,col='black', type='p')");
              e.Evaluate("elp<- unname(ellipsoidPoints(shape, d2.95,center))");
              e.Evaluate(" lines(elp, col='red' , lty=7 , lwd=2)");
              //e.Evaluate("lines(e)");
              //e.Evaluate("lines(ellipsoidPoints(mve@cov, d2 = d2.95, loc=mve@center), col='blue', lty='7' , lwd='2') ");
              // axGraphicsDevice2.RemoveFromConnector();
              e.Evaluate("dev.off()");
        }
Esempio n. 16
0
        private static void ReproWorkitem22(REngine engine)
        {
            var statements = @"
            parameters <- data.frame(name=paste('x', 1:4, sep=''),
              min = c(1, -10, 1, 0.5),
              value= c(700, 0, 100, 2),
              max = c(1500, 5, 500, 4),
              stringsAsFactors=FALSE)

            f <- function(i, p) {
              runif(1, p[i,'min'], p[i,'max'])
            }

            ";
             var df = engine.Evaluate(statements);
             var rndParams = "parameters$value <- as.numeric(lapply(1:nrow(parameters), FUN=f, parameters))";
             engine.Evaluate("set.seed(0)");
             for (int i = 0; i < 1000; i++)
             {
            engine.Evaluate(rndParams);
            //engine.Evaluate("print(parameters)");
            GetDataFrame("parameters", engine);
             }
        }
Esempio n. 17
0
 private static DataFrame getBiopsyDataFrame(REngine engine)
 {
     engine.Evaluate("data(biopsy, package='MASS')");
     var biopsy = engine.Evaluate("biopsy").AsDataFrame();
     return biopsy;
 }
Esempio n. 18
0
 private static void readNumericList(long i, double[][] res, REngine engine)
 {
     res[i] = engine.Evaluate("x[["+(i+1).ToString()+"]]").AsNumeric().ToArray();
 }
Esempio n. 19
0
        //public ForecastResult Fcast1()
        //{
        //    ForecastResult fcastResult = new ForecastResult();
        //    int productId = 1;
        //    Methods method = Methods.rwf; //meanf(YYMMDD,MMDD,MMWWDD,DD), rtw, rtw(with Drift), Moving AVG,ets, Arima, HoltWinters, msts
        //    DataPeriod dataType = DataPeriod.Daily;
        //    int periods = 50;
        //    var values = GetCorrespondingData(dataType, productId);
        //    //FFCEntities db = new FFCEntities();
        //    //var list = db.sp_Forecast_GetProductCountYearDayByProductId(productId).ToList();
        //    //List<double> values = list.Select(r => Double.Parse(r.Count.ToString())).ToList();
        //    //REngine.SetEnvironmentVariables(@"C:\Program Files\R\R-2.13.1\bin\i386");
        //    //SetupPath();
        //    //Log();
        //    REngine.SetEnvironmentVariables();
        //    // There are several options to initialize the engine, but by default the following suffice:
        //    REngine engine = REngine.GetInstance();
        //    //engine.Initialize();
        //    // .NET Framework array to R vector.
        //    //NumericVector testTs = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99, 1000 });
        //    NumericVector testTs = engine.CreateNumericVector(new double[] { 6, 5, 6, 5, 6, 5 });
        //    //NumericVector testTs = engine.CreateNumericVector(values);
        //    engine.SetSymbol("testTs", testTs);
        //    engine.Evaluate("n <- c(1,2,3)");
        //    //auto arima for monthly
        //    engine.Evaluate("tsValue <- ts(testTs, frequency=1, start=c(2010, 1, 1))");
        //    engine.Evaluate("library(forecast)");
        //    //engine.Evaluate(String.Format("Fit <- {0}(tsValue)", method)); // Fit <- Arima(tsValue)
        //    MethodManipulation(engine, method);
        //    engine.Evaluate(String.Format("fcast <- forecast(Fit, h={0})", periods));
        //    Plot(engine);
        //    //var a = engine.Evaluate("fcast <- forecast(tsValue, h=5)").AsCharacter();
        //    NumericVector forecasts = engine.Evaluate("fcast$mean").AsNumeric();
        //    fcastResult.Values = forecasts.ToList();
        //    //foreach (var item in forecasts)
        //    //{
        //    //    Console.WriteLine(item);
        //    //}
        //    //engine.Dispose();
        //    return fcastResult;
        //}
        //public static ForecastResult fcast2()
        //{
        //    ForecastResult forecastResult = new ForecastResult() { Method = Methods.Arima, results = new List<double>() { 1.0 } };
        //   // model.ForecastResult = forecastResult;
        //    return forecastResult;
        //}
        //public static void SetupPath(string Rversion = "R-3.2.2")
        //{
        //    var oldPath = System.Environment.GetEnvironmentVariable("PATH");
        //    var rPath = System.Environment.Is64BitProcess ?
        //                           string.Format(@"C:\Program Files\R\{0}\bin\x64", Rversion) :
        //                           string.Format(@"C:\Program Files\R\{0}\bin\i386", Rversion);
        //    if (!Directory.Exists(rPath))
        //        throw new DirectoryNotFoundException(
        //          string.Format(" R.dll not found in : {0}", rPath));
        //    var newPath = string.Format("{0}{1}{2}", rPath,
        //                                 System.IO.Path.PathSeparator, oldPath);
        //    System.Environment.SetEnvironmentVariable("PATH", newPath);
        //}
        public string PlotForecast(REngine engine, string method)
        {
            //string imagePath = @"C:\\Users\\ashfernando\\Desktop\\Test\\";
            string imagePath = @"D:\\Ashen\\Development\\GitHub\\FFCF\\FFC.Framework\\FFC.Framework.ClientSubscription.Web\\Content\\Images";
            //string imagePath = @"~\\Content\\Images";

            string fileName = String.Format("{0}_image.png", method);

            //engine.Evaluate(@"png(filename='~\\Content\Images\\Test2.png')");
            engine.Evaluate(String.Format(@"png(filename='{0}\\{1}')", imagePath, fileName));
            //engine.Evaluate(@"png(filename='C:\\Users\\ashfernando\\Desktop\\Test\\Test2.png')");
            //engine.Evaluate(@"png(filename='C:\\Users\\ashen\\Desktop\\Images\\Test2.png')");
            engine.Evaluate("plot(fcast)");
            engine.Evaluate("dev.off()");
            return fileName;
        }
Esempio n. 20
0
 public string GetWorkingDirectory()
 {
     if (IsRunning & _dirChanged)
     {
         if (engine != null)
         {
             _wd         = engine.Evaluate("getwd()").AsCharacter().First();
             _dirChanged = false;
             return(_wd);
         }
         else
         {
             throw new Exception("Engine is null..");
         }
     }
     else if (!_dirChanged)
     {
         return(_wd);
     }
     else
     {
         return(string.Empty);
     }
 }
Esempio n. 21
0
        protected static double GetRMemorySize(REngine engine)
        {
            var memoryAfterAlloc = engine.Evaluate("memory.size()").AsNumeric().First();

            return(memoryAfterAlloc);
        }
Esempio n. 22
0
 private static void ReproIssue77(REngine engine)
 {
     object expr = engine.Evaluate("function(k) substitute(bar(x) = k)");
      Console.WriteLine(expr ?? "null");
 }
Esempio n. 23
0
 private static void ReproDiscussion528955(REngine engine)
 {
     engine.Evaluate("a <- 1");
      engine.Evaluate("a <- a+1");
      NumericVector v1 = engine.GetSymbol("a").AsNumeric();
      bool eq = 2.0 == v1[0];
      engine.Evaluate("a <- a+1");
      NumericVector v2 = engine.GetSymbol("a").AsNumeric();
      eq = 3.0 == v2[0];
 }
Esempio n. 24
0
 private static void ReproTreeEnquiry(REngine e)
 {
     e.Evaluate("library(tree)");
      var irtr = e.Evaluate("ir.tr <- tree(Species ~., iris)");
      // the following will print a human readable tree to the console output
      e.Evaluate("print(ir.tr)");
      var aList = irtr.AsList(); // May work only with the latest dev code
      // for R.NET 1.5.5 you may need to do instead:
      aList = e.Evaluate("as.list(tree(Species ~., iris))").AsList();
      var theDataFrame = aList[0].AsDataFrame();
      // Further processing of theDataFrame, etc.
 }
Esempio n. 25
0
 protected virtual void SetUpTest()
 {
     engine.Evaluate("rm(list=ls())");
     this.Device.Initialize();
 }
Esempio n. 26
0
        /*
        1.5.5
                 //var blah = x.RowNames;
        memoryInitial	50.16	double
        netMemBefore	87860	long
        blah	null	string[]
        memoryAfterAlloc	62.08	double
        netMemAfter	0	long

         var blah = engine.Evaluate("rownames(x)").AsCharacter().ToArray();
        memoryInitial	50.15	double
        netMemBefore	87948	long
        blah	null	string[]
        memoryAfterAlloc	65.95	double
        netMemAfter	0	long

        1.5.6, not waiting for final total memory (otherwise hangs, as with above)

        memoryInitial	50.16	double
        netMemBefore	88608	long
        blah	null	string[]
        memoryAfterAlloc	65.95	double
        netMemAfter	98738480	long

        memoryInitial	50.16	double
        netMemBefore	88572	long
        blah	null	string[]
        memoryAfterAlloc	62.08	double
        netMemAfter	99319384	long

               */
        private static void ReproWorkitem41(REngine engine)
        {
            var fname = "c:/tmp/rgraph.png";
             engine.Evaluate("library(ggplot2)");
             engine.Evaluate("library(scales)");
             engine.Evaluate("library(plyr)");
             engine.Evaluate("d <- data.frame( x = rnorm(1000), y = rnorm(1000), z = rnorm(1000))");
             engine.Evaluate("p <- ggplot(d, aes(x = x, y = y, color = z)) + geom_point(size=4.5, shape=19)");
             // Use:
             engine.Evaluate("png('" + fname + "')");
             engine.Evaluate("print(p)");
             // but not:
             // engine.Evaluate("p");
             // engine.Evaluate("dev.copy(png, '" + fname + "')");
             // the statement engine.Evaluate("p") does not behave the same as p (or print(p)) directly in the R console.
             engine.Evaluate("dev.off()");
        }
Esempio n. 27
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);
 }
Esempio n. 28
0
        private static void TestMultiThreads(REngine engine)
        {
            engine.Evaluate("x <- rnorm(10000)");
             var blah = engine.GetSymbol("x").AsNumeric().ToArray();

             double[][] res = new double[2][];
             // Can two threads access in parallel the same
             Parallel.For(0, 2, i => readNumericX(i, res, engine));

             engine.Evaluate("x <- list()");
             engine.Evaluate("x[[1]] <- rnorm(10000)");
             engine.Evaluate("x[[2]] <- rnorm(10000)");

             // Can two threads access in parallel the same list
             // Usually bombs, though passes sometimes.
             // The console output would report the following:
             //Error: unprotect_ptr: pointer not found
             //Error: R_Reprotect: only 3 protected items, can't reprotect index 9
             //Error: unprotect_ptr: pointer not found
             //Parallel.For(0, 2, i => readNumericList(i, res, engine));

             // And in seqence, but from other threads - seems to work consistently
             Parallel.For(0, 1, i => readNumericList(i, res, engine));
             Parallel.For(1, 2, i => readNumericList(i, res, engine));

             Console.WriteLine(res[1][1]);
        }
Esempio n. 29
0
 private static void ReproDiscussion539094(REngine e)
 {
     e.Evaluate("library(Rcpp)");
      e.Evaluate("setwd('c:/tmp')");
      e.Evaluate("sourceCpp('fibonacci.cpp')");
      var x = e.Evaluate("fibonacci(7)").AsNumeric();
 }
Esempio n. 30
0
        private void runPrint(SymbolicExpression obj)
        {
            var func = Engine.Evaluate("print").AsFunction();

            func.Invoke(new SymbolicExpression[] { obj });
        }
Esempio n. 31
0
 private static void ReproDiscussion540017(REngine e)
 {
     e.Evaluate("library(sn)");
       e.Evaluate("data(wines, package='sn')");
       e.Evaluate("X <- model.matrix(~ phenols + wine, data=wines)");
       e.Evaluate("fit <- msn.mle(x=X, y=cbind(wines$acidity, wines$alcohol), opt.method='BFGS')");
       var beta = e.Evaluate("fit$dp$beta").AsNumericMatrix();
       var value = beta[0,1];
       var betaNames = e.Evaluate("rownames(fit$dp$beta)").AsCharacter().ToArray();
 }
Esempio n. 32
0
 public bool SetWorkingDirectory(string directory)
 {
     if (directory != this.WorkingDirectory)
     {
         try
         {
             engine.Evaluate("setwd(\"" + directory + "\")");
             dirChanged = true;
             return(true);
         }
         catch (Exception e)
         {
             throw new ApplicationException(e.Message, e);
         }
     }
     else
     {
         dirChanged = false;
         return(true);
     }
 }
Esempio n. 33
0
 // https://rdotnet.codeplex.com/discussions/569196
 private static void ReproDiscussion569196(REngine engine)
 {
     // UserReported(engine);
      engine.Evaluate("library(forecast)");
      engine.Evaluate("snaiveRes <- snaive(wineind)");
      engine.Evaluate("str(snaiveRes)");
 }
Esempio n. 34
0
        private static void ReproDiscussion532760(REngine engine)
        {
            // https://rdotnet.codeplex.com/discussions/532760
             //> x <- data.frame(1:1e6, row.names=format(1:1e6))
             //> object.size(x)
             //60000672 bytes
             //> object.size(rownames(x))
             //56000040 bytes

             engine.Evaluate("x <- data.frame(1:1e6, row.names=format(1:1e6))");
             var x = engine.GetSymbol("x").AsDataFrame();
             engine.ForceGarbageCollection();
             engine.ForceGarbageCollection();
             var memoryInitial = engine.Evaluate("memory.size()").AsNumeric().First();

             var netMemBefore = GC.GetTotalMemory(true);

             var blah = x.RowNames;
             //var blah = engine.Evaluate("rownames(x)").AsCharacter().ToArray();
             blah = null;

             GC.Collect();
             engine.ForceGarbageCollection();
             engine.ForceGarbageCollection();
             var memoryAfterAlloc = engine.Evaluate("memory.size()").AsNumeric().First();

             var netMemAfter = GC.GetTotalMemory(false);
        }
Esempio n. 35
0
        static void Main(string[] args)
        {
            SetupPath(); // current process, soon to be deprecated

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

            engine.Initialize(); // required since v1.5

            // some random weight samples
            double[] weight = new double[] { 3.2, 3.6, 3.2, 1.7, 0.8, 2.9, 2, 1.4, 1.2, 2.1, 2.5, 3.9, 3.7, 2.4, 1.5, 0.9, 2.5, 1.7, 2.8, 2.1, 1.2 };
            double[] lenght = new double[] { 2, 3, 3.2, 4.7, 5.8, 3.9, 2, 8.4, 5.2, 4.1, 2.5, 3.9, 5, 2.4, 3.5, 0.9, 2.5, 2.7, 2.8, 2.1, 1.2 };

            // introduce the samples into R
            engine.SetSymbol("weight", engine.CreateNumericVector(weight));
            engine.SetSymbol("lenght", engine.CreateNumericVector(lenght));

            // set the weights and lenghts as a data frame (regular R syntax in string)
            engine.Evaluate("df <- data.frame(id=c(1:length(weight)), weight = weight,lenght = lenght )");


            // evaluate and retrieve mean
            double avg = engine.Evaluate("mean(df$weight)").AsNumeric().ToArray()[0];
            // same for standard deviation
            double std = engine.Evaluate("sd(df$weight)").AsNumeric().ToArray()[0];

            // NumericVector coeff = engine.Evaluate("coefficients(lm(df$weight ~ df$lenght ))").AsNumeric();
            // print output in console
            System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-gb");

            //Show in console the weight and lenght data
            Console.WriteLine(string.Format("Weights: ({0})", string.Join(",",
                                                                          weight.Select(f => f.ToString(ci)) // LINQ expression
                                                                          )));
            Console.WriteLine(string.Format("Length: ({0})", string.Join(",",
                                                                         lenght.Select(f => f.ToString(ci)) // LINQ expression
                                                                         )));
            Console.WriteLine(string.Format("Sample size: {0}", weight.Length));
            Console.WriteLine(string.Format(ci, "Average: {0:0.00}", avg));
            Console.WriteLine(string.Format(ci, "Standard deviation: {0:0.00}", std));

            var result = engine.Evaluate("lm(df$weight ~ df$lenght)");

            engine.SetSymbol("result", result);
            var    coefficients = result.AsList()["coefficients"].AsNumeric().ToList();
            double r2           = engine.Evaluate("summary(result)").AsList()["r.squared"].AsNumeric().ToList()[0];
            double intercept    = coefficients[0];
            double slope        = coefficients[1];

            Console.WriteLine("Intercept:" + intercept.ToString());
            Console.WriteLine("slope:" + slope);
            Console.WriteLine("r2:" + r2);

            string fileName = "myplot.png";

            CharacterVector fileNameVector = engine.CreateCharacterVector(new[] { fileName });

            engine.SetSymbol("fileName", fileNameVector);

            engine.Evaluate("png(filename=fileName, width=6, height=6, units='in', res=100)");
            engine.Evaluate("reg <- lm(df$weight ~ df$lenght)");
            engine.Evaluate("plot(df$weight ~ df$lenght)");
            engine.Evaluate("abline(reg)");
            engine.Evaluate("dev.off()");
            //The file will save in debug directory

            Application.Run(new Form1());
            // After disposing of the engine, you cannot reinitialize nor reuse it
            engine.Dispose();
        }
 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)");
 }
Esempio n. 37
0
 private static void ReproDiscussion537259(REngine e)
 {
     e.Evaluate("library(rJava)");
      e.Evaluate(".jinit()");
      e.Evaluate("f <- .jnew('java/awt/Frame','Hello')");
      e.Evaluate(".jcall(f,,'setVisible',TRUE)");
 }