示例#1
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];
 }
示例#2
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]);
			}
		}
示例#3
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]);
      }
示例#4
0
        /// <summary>
        /// Create an R data frame from managed arrays and objects.
        /// </summary>
        /// <param name="engine">R engine</param>
        /// <param name="columns">The columns with the values for the data frame. These must be array of supported types (double, string, bool, integer, byte)</param>
        /// <param name="columnNames">Column names. default: null.</param>
        /// <param name="rowNames">Row names. Default null.</param>
        /// <param name="checkRows">Check rows. See data.frame R documentation</param>
        /// <param name="checkNames">See data.frame R documentation</param>
        /// <param name="stringsAsFactors">Should columns of strings be considered as factors (categories). See data.frame R documentation</param>
        /// <returns></returns>
        public static DataFrame CreateDataFrame(this REngine engine, IEnumerable[] columns, string[] columnNames = null,
                                                string[] rowNames = null, bool checkRows = false, bool checkNames = true, bool stringsAsFactors = true)
        {
            var df = engine.GetSymbol("data.frame").AsFunction();

            SymbolicExpression[] colVectors = ToVectors(engine, columns);
            Tuple <string, SymbolicExpression>[] namedColArgs = CreateNamedArgs(colVectors, columnNames);
            var args = new List <Tuple <string, SymbolicExpression> >(namedColArgs);

            if (rowNames != null)
            {
                args.Add(Tuple.Create("row.names", (SymbolicExpression)engine.CreateCharacterVector(rowNames)));
            }
            args.Add(Tuple.Create("check.rows", (SymbolicExpression)engine.CreateLogical(checkRows)));
            args.Add(Tuple.Create("check.names", (SymbolicExpression)engine.CreateLogical(checkNames)));
            args.Add(Tuple.Create("stringsAsFactors", (SymbolicExpression)engine.CreateLogical(stringsAsFactors)));
            var result = df.InvokeNamed(args.ToArray()).AsDataFrame();

            return(result);
        }
示例#5
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="symbolname"></param>
 /// <returns></returns>
 public SymbolicExpression GetSymbol(string symbolname)
 {
     // Exception handling ?
     return((engine == null) ?  null : engine.GetSymbol(symbolname));
 }
示例#6
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]);
        }
示例#7
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);
        }
示例#8
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];
 }
示例#9
0
 private static void readNumericX(long i, double[][] res, REngine engine)
 {
     res[i] = engine.GetSymbol("x").AsNumeric().ToArray();
 }
示例#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();
        }