Ejemplo n.º 1
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.º 2
0
        public static void CreateCharacterVector(REngine engine, int n, Stopwatch s)
        {
            string[] d = createStringArray(n);
            s.Start();
            var nvec = engine.CreateCharacterVector(d);

            s.Stop();
        }
Ejemplo n.º 3
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="text"></param>
 /// <returns></returns>
 public CharacterVector RVector(string[] text)
 {
     try
     {
         CharacterVector vector = engine.CreateCharacterVector(text);
         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();
     }
 }
        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.º 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
        /// <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);
        }
Ejemplo n.º 7
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];
        }
Ejemplo n.º 8
0
 public static void CreateCharacterVector(REngine engine, int n, Stopwatch s)
 {
     string[] d = createStringArray(n);
     s.Start();
     var nvec = engine.CreateCharacterVector(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();
        }