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="symbolname"></param>
 /// <param name="expression"></param>
 internal void SetSymbol(string symbolname, SymbolicExpression expression)
 {
     /* if (!expression.IsProtected)
      *   expression.Protect();
      */
     engine.SetSymbol(symbolname, expression);
 }
        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.º 4
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.º 5
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.º 6
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.º 7
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.º 8
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();
        }