Ejemplo n.º 1
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.º 2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="data"></param>
 /// <returns></returns>
 public NumericVector RNumeric(double data)
 {
     try
     {
         NumericVector vector = engine.CreateNumericVector(new[] { data });
         vector.Protect();
         return(vector);
     }
     catch (SEHException e)
     {
         throw new ApplicationException("R Engine has thrown an Exception - memory possibly corrupted; Vector could not be created in R.", e);
     }
     finally
     {
         ClearMemory();
     }
 }
Ejemplo n.º 3
0
        public static void CreateNumericVector(REngine engine, int n, Stopwatch s)
        {
            double[] d = createDoubleArray(n);
            s.Start();
            var nvec = engine.CreateNumericVector(d);

            s.Stop();
        }
Ejemplo n.º 4
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.º 5
0
        internal static SymbolicExpression ToVector(REngine engine, IEnumerable values)
        {
            if (values == null)
            {
                throw new ArgumentNullException("values", "values to transform to an R vector must not be null");
            }
            var ints     = values as IEnumerable <int>;
            var chars    = values as IEnumerable <string>;
            var cplxs    = values as IEnumerable <Complex>;
            var logicals = values as IEnumerable <bool>;
            var nums     = values as IEnumerable <double>;
            var raws     = values as IEnumerable <byte>;
            var sexpVec  = values as SymbolicExpression;

            if (sexpVec != null && sexpVec.IsVector())
            {
                return(sexpVec);
            }
            if (ints != null)
            {
                return(engine.CreateIntegerVector(ints));
            }
            if (chars != null)
            {
                return(engine.CreateCharacterVector(chars));
            }
            if (cplxs != null)
            {
                return(engine.CreateComplexVector(cplxs));
            }
            if (logicals != null)
            {
                return(engine.CreateLogicalVector(logicals));
            }
            if (nums != null)
            {
                return(engine.CreateNumericVector(nums));
            }
            if (raws != null)
            {
                return(engine.CreateRawVector(raws));
            }
            throw new NotSupportedException(string.Format("Cannot convert type {0} to an R vector", values.GetType()));
        }
Ejemplo n.º 6
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;
        }
Ejemplo n.º 7
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;
      }
 }
Ejemplo n.º 8
0
 public static void CreateNumericVector(REngine engine, int n, Stopwatch s)
 {
     double[] d = createDoubleArray(n);
     s.Start();
     var nvec = engine.CreateNumericVector(d);
     s.Stop();
 }
Ejemplo n.º 9
0
        internal static SymbolicExpression ToVector(REngine engine, IEnumerable values)
        {
            if (values == null) throw new ArgumentNullException("values", "values to transform to an R vector must not be null");
            var ints = values as IEnumerable<int>;
            var chars = values as IEnumerable<string>;
            var cplxs = values as IEnumerable<Complex>;
            var logicals = values as IEnumerable<bool>;
            var nums = values as IEnumerable<double>;
            var raws = values as IEnumerable<byte>;
            var sexpVec = values as SymbolicExpression;

            if (sexpVec != null && sexpVec.IsVector())
                return sexpVec;
            if (ints != null)
                return engine.CreateIntegerVector(ints);
            if (chars != null)
                return engine.CreateCharacterVector(chars);
            if (cplxs != null)
                return engine.CreateComplexVector(cplxs);
            if (logicals != null)
                return engine.CreateLogicalVector(logicals);
            if (nums != null)
                return engine.CreateNumericVector(nums);
            if (raws != null)
                return engine.CreateRawVector(raws);
            throw new NotSupportedException(string.Format("Cannot convert type {0} to an R vector", values.GetType()));
        }
Ejemplo n.º 10
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();
        }