public TSAnalyze () { InitializeComponent (); // There are several options to initialize thengine, but by default the following suffice: REngine engine = REngine.GetInstance(); //init the R engine REngine.SetEnvironmentVariables (); engine = REngine.GetInstance (); engine.Initialize (); //prepare data List<int> size = new List<int>() { 29, 33, 51, 110, 357, 45, 338, 543, 132, 70, 103, 301, 146, 10, 56, 243, 238 }; List<int> population = new List<int>() { 3162, 11142, 3834, 7305, 81890, 1339, 5414, 65697, 11280, 4589, 320, 60918, 480, 1806, 4267, 63228, 21327 }; var docPath = Directory.GetCurrentDirectory(); //var myDir = $@"{docPath}\output"; var myDir = bingPathToAppDir ("output"); Directory.CreateDirectory (myDir); Console.WriteLine (Directory.Exists (myDir)); Console.WriteLine (myDir); Console.WriteLine (bingPathToAppDir ("output")); Console.WriteLine ("my image location {0}", myDir); fileName = myDir + "\\myplot.png"; //calculate IntegerVector sizeVector = engine.CreateIntegerVector(size); engine.SetSymbol ("size", sizeVector); IntegerVector populationVector = engine.CreateIntegerVector(population); engine.SetSymbol ("population", populationVector); CharacterVector fileNameVector = engine.CreateCharacterVector(new[] { fileName }); engine.SetSymbol ("fileName", fileNameVector); engine.Evaluate ("reg <- lm(population~size)"); engine.Evaluate ("png(filename=fileName, width=6, height=6, units='in', res=100)"); engine.Evaluate ("plot(population~size)"); engine.Evaluate ("abline(reg)"); engine.Evaluate ("dev.off()"); //clean up engine.Dispose (); //output Console.WriteLine (""); Console.WriteLine ("Press any key to exit"); Console.ReadKey (); }
public void DrawCharRTest() { var x = engine.CreateIntegerVector(new[] { 1, 2, 3 }); var y = engine.CreateIntegerVector(new[] { 1, 2, 3 }); engine.SetSymbol("x", x); engine.SetSymbol("y", y); engine.Evaluate("plot(x,y)"); }
private void SetupDotNetToRConverters() { SetupDotNetToRConverter(typeof(void), p => null); SetupDotNetToRConverter(typeof(string), p => engine.CreateCharacter((string)p)); SetupDotNetToRConverter(typeof(string[]), p => engine.CreateCharacterVector((string[])p)); SetupDotNetToRConverter(typeof(List <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(IList <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(ICollection <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(IEnumerable <string>), p => engine.CreateCharacterVector((IEnumerable <string>)p)); SetupDotNetToRConverter(typeof(string[, ]), p => engine.CreateCharacterMatrix((string[, ])p)); SetupDotNetToRConverter(typeof(int), p => engine.CreateInteger((int)p)); SetupDotNetToRConverter(typeof(int[]), p => engine.CreateIntegerVector((int[])p)); SetupDotNetToRConverter(typeof(List <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(IList <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(ICollection <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(IEnumerable <int>), p => engine.CreateIntegerVector((IEnumerable <int>)p)); SetupDotNetToRConverter(typeof(int[, ]), p => engine.CreateIntegerMatrix((int[, ])p)); SetupDotNetToRConverter(typeof(bool), p => engine.CreateLogical((bool)p)); SetupDotNetToRConverter(typeof(bool[]), p => engine.CreateLogicalVector((bool[])p)); SetupDotNetToRConverter(typeof(List <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(IList <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(ICollection <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(IEnumerable <bool>), p => engine.CreateLogicalVector((IEnumerable <bool>)p)); SetupDotNetToRConverter(typeof(bool[, ]), p => engine.CreateLogicalMatrix((bool[, ])p)); SetupDotNetToRConverter(typeof(double), p => engine.CreateNumeric((double)p)); SetupDotNetToRConverter(typeof(double[]), p => engine.CreateNumericVector((double[])p)); SetupDotNetToRConverter(typeof(List <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(IList <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(ICollection <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(IEnumerable <double>), p => engine.CreateNumericVector((IEnumerable <double>)p)); SetupDotNetToRConverter(typeof(double[, ]), p => engine.CreateNumericMatrix((double[, ])p)); SetupDotNetToRConverter(typeof(DateTime), p => engine.CreatePosixct((DateTime)p)); SetupDotNetToRConverter(typeof(DateTime[]), p => engine.CreatePosixctVector((DateTime[])p)); SetupDotNetToRConverter(typeof(List <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(IList <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(ICollection <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(IEnumerable <DateTime>), p => engine.CreatePosixctVector((IEnumerable <DateTime>)p)); SetupDotNetToRConverter(typeof(DateTime[, ]), p => engine.CreatePosixctMatrix((DateTime[, ])p)); SetupDotNetToRConverter(typeof(TimeSpan), p => engine.CreateDiffTime((TimeSpan)p)); SetupDotNetToRConverter(typeof(TimeSpan[]), p => engine.CreateDiffTimeVector((TimeSpan[])p)); SetupDotNetToRConverter(typeof(List <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(IList <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(ICollection <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(IEnumerable <TimeSpan>), p => engine.CreateDiffTimeVector((IEnumerable <TimeSpan>)p)); SetupDotNetToRConverter(typeof(TimeSpan[, ]), p => engine.CreateDiffTimeMatrix((TimeSpan[, ])p)); }
/// <summary> /// (Private) Applies the inputs of an RScript object. /// </summary> private void ApplyInputs(RScript script, object[] inputs) { UiControls.Assert(inputs.Length == script.InputNames.Length, "Number of inputs requested by script must match number of inputs provided."); for (int i = 0; i < inputs.Length; i++) { string name = script.InputNames[i]; if (name != null) { var obj = inputs[i]; SymbolicExpression sym; if (obj is double[, ]) { sym = _r.CreateNumericMatrix((double[, ])obj); } else if (obj is IReadOnlyList <double> ) { sym = _r.CreateNumericVector((IReadOnlyList <double>)obj); } else if (obj is IEnumerable <double> ) { sym = _r.CreateNumericVector((IEnumerable <double>)obj); } else if (obj is int[]) { sym = _r.CreateIntegerVector((int[])obj); } else if (obj is int[, ]) { sym = _r.CreateIntegerMatrix((int[, ])obj); } else if (obj is IEnumerable <int> ) { sym = _r.CreateIntegerVector((IEnumerable <int>)obj); } else { throw new InvalidOperationException("Cannot create R object for obj: " + obj); } _r.SetSymbol(name, sym); } } }
static void Main(string[] args) { // Sample code used for updating the documentation at the codeplex web site. using (REngine engine = REngine.GetInstance()) { var e = engine.Evaluate("x <- 3"); // You can now access x defined in the R environment. NumericVector x = engine.GetSymbol("x").AsNumeric(); engine.Evaluate("y <- 1:10"); NumericVector y = engine.GetSymbol("y").AsNumeric(); // Invoking functions; Previously you may have needed custom function definitions var myFunc = engine.Evaluate("function(x, y) { expand.grid(x=x, y=y) }").AsFunction(); var v1 = engine.CreateIntegerVector(new[] { 1, 2, 3 }); var v2 = engine.CreateCharacterVector(new[] { "a", "b", "c" }); var df = myFunc.Invoke(new SymbolicExpression[] { v1, v2 }).AsDataFrame(); // As of R.NET 1.6, more function call syntaxes are supported. var expandGrid = engine.Evaluate("expand.grid").AsFunction(); var d = new Dictionary <string, SymbolicExpression>(); d["x"] = v1; d["y"] = v2; df = expandGrid.Invoke(d).AsDataFrame(); // querying data frames engine.SetSymbol("cases", df); // As of R.NET 1.6, factor to character expressions work consistently with R var letterCases = engine.Evaluate("cases[,'y']").AsCharacter().ToArray(); // "a","a","a","b","b","b", etc. Same as as.character(cases[,'y']) in R // This used to return "1", "1", "1", "2", "2", etc. with R.NET 1.5.5 // Equivalent: letterCases = df[1].AsCharacter().ToArray(); letterCases = df["y"].AsCharacter().ToArray(); // Accessing items by two dimensional indexing string s = (string)df[1, 1]; // "a" s = (string)df[3, 1]; // "a" s = (string)df[3, "y"]; // "b" // s = (string)df["4", "y"]; // fails because there are no row names df[3, "y"] = "a"; s = (string)df[3, "y"]; // "a" df[3, "y"] = "d"; s = (string)df[3, "y"]; // null, because we have an <NA> string in R // invoking a whole script // engine.Evaluate("source('c:/src/path/to/myscript.r')"); // TODO // Date-time objects } }
public static void Start(REngine engine) { Console.WriteLine("\n\nExporting Objects\n\n"); string RCodeString = string.Empty; //R character vector -- R.NET RDotNet.RDotNet.CharacterVector Console.WriteLine("\nR character vector\n"); string[] myStringArray = new string[] { "PIDataLink", "PIProcessBook", "PIWebParts" }; CharacterVector myCharacterVector = engine.CreateCharacterVector(myStringArray.AsEnumerable()); engine.SetSymbol("mycharvector", myCharacterVector); engine.Evaluate("print(mycharvector)"); //R integer vector -- R.NET RDotNet.NumericVector Console.WriteLine("\nR int vector\n"); int[] myIntegerArray = new int[] { 4, 6, 10, 140, 54, 25 }; IntegerVector myIntegerVector = engine.CreateIntegerVector(myIntegerArray); engine.SetSymbol("myintvector", myIntegerVector); engine.Evaluate("print(myintvector)"); //R real vector -- R.NET RDotNet.NumericVector Console.WriteLine("\nR real vector\n"); NumericVector myNumericVector = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); engine.SetSymbol("mynumvector", myNumericVector); engine.Evaluate("print(mynumvector)"); //R complex vector -- R.NET RDotNet.ComplexVector Console.WriteLine("\nR complex vector\n"); Complex[] myComplexArray = new Complex[] { Complex.FromPolarCoordinates(10, 0.524), new Complex(12, 6), new Complex(14, 3), (Complex)12.3m, Complex.One + Complex.One }; ComplexVector myComplexVector = engine.CreateComplexVector(myComplexArray); engine.SetSymbol("mycomplexvector", myComplexVector); engine.Evaluate("print(mycomplexvector)"); //R raw vector -- R.NET RDotNet.RawVector Console.WriteLine("\nR raw vector\n"); byte[] myByteArray = System.Text.Encoding.ASCII.GetBytes("u03a0"); RawVector myRawVector = engine.CreateRawVector(myByteArray); engine.SetSymbol("myrawvector", myRawVector); engine.Evaluate("print(myrawvector)"); //R logical vector -- R.NET RDotNet.LogicalVector Console.WriteLine("\nR logical vector\n"); LogicalVector myLogicalVector = engine.CreateLogicalVector(new Boolean[] { true, false, false, false, true }); engine.SetSymbol("mylogicalvector", myLogicalVector); engine.Evaluate("print(mylogicalvector)"); }
private void cboVariable1_SelectedIndexChanged(object sender, EventArgs e) { string strTargetLayerName = cboTargetLayer.Text; m_strVar1Name = cboVariable1.Text; int intTargetIndex = m_pSnippet.GetIndexNumberFromLayerName(m_pActiveView, strTargetLayerName); m_intNFeatureCount = 0; ILayer pTargetLayer = m_pForm.axMapControl1.get_Layer(intTargetIndex); m_pTargetFLayer = (IFeatureLayer)pTargetLayer; //Extract geometry from selected feature IFeatureCursor pFCursor = null; pFCursor = m_pTargetFLayer.Search(null, true); m_intNFeatureCount = m_pTargetFLayer.FeatureClass.FeatureCount(null); IFeature pFeature = pFCursor.NextFeature(); //Source and Group Field Index int intVar1Idx = m_pTargetFLayer.FeatureClass.Fields.FindField(m_strVar1Name); int intFIDIdx = m_pTargetFLayer.FeatureClass.FindField(m_pTargetFLayer.FeatureClass.OIDFieldName); m_adblVar1 = new double[m_intNFeatureCount]; m_arrFID = new int[m_intNFeatureCount]; //Feature Value to Array int i = 0; while (pFeature != null) { m_adblVar1[i] = Convert.ToDouble(pFeature.get_Value(intVar1Idx)); m_arrFID[i] = Convert.ToInt32(pFeature.get_Value(intFIDIdx)); i++; pFeature = pFCursor.NextFeature(); } //Draw Boxplot at the Form //Array to R vector. NumericVector vecVar1 = m_pEngine.CreateNumericVector(m_adblVar1); m_pEngine.SetSymbol(m_strVar1Name, vecVar1); IntegerVector vecFID = m_pEngine.CreateIntegerVector(m_arrFID); m_pEngine.SetSymbol("FID", vecFID); }
private static void github_issue_90() { string rHome = @"c:\Program Files\R\R-3.4.4\"; string rPath = @"C:\Program Files\R\R-3.4.4\bin\x64"; REngine.SetEnvironmentVariables(rPath: rPath, rHome: rHome); //p.RHome = @"c:\Program Files\Microsoft\R Open\R-3.4.3\"; REngine engine = REngine.GetInstance(); engine.Evaluate("library(dplyr)"); engine.Evaluate("library(keras)"); engine.Evaluate("model <- keras_model_sequential() %>% layer_dense(units = 1000, input_shape = c(1000)) %>% compile(loss = 'mse',optimizer = 'adam')"); int counter = 0; while (true) { Console.WriteLine(counter++); IntegerVector vec = engine.CreateIntegerVector(1000); vec.SetVector(new int[1000]); engine.SetSymbol("vec1000", vec); var execution = "predict(model, t(vec1000))"; using (var output = engine.Evaluate(execution)) { using (var a = output.AsList()) { for (int i = 0; i < 1000; i++) { using (var b = a[i].AsNumeric()) { } } } }; } }
private void button3_Click(object sender, EventArgs e) { int FeatureNum = app.FeaName.GetLength(0); int SampleNum = app.SamName.GetLength(0); REngine.SetEnvironmentVariables(); REngine PCA = REngine.GetInstance(); PCA.Initialize(); NumericMatrix Freq = PCA.CreateNumericMatrix(app.CountMatrix); PCA.SetSymbol("Freq", Freq); CharacterVector SampleName = PCA.CreateCharacterVector(app.SamName); CharacterVector FeatureName = PCA.CreateCharacterVector(app.FeaName); PCA.SetSymbol("FeatureName", FeatureName); PCA.SetSymbol("SampleName", SampleName); PCA.Evaluate("library(stats)"); PCA.Evaluate("pr <- prcomp(t(Freq),cor = TRUE)"); PCA.Evaluate("score <- predict(pr)"); double[,] Count = PCA.GetSymbol("score").AsNumericMatrix().ToArray(); app.Score = new double[SampleNum, 2]; for (int i = 0; i < SampleNum; i++) { app.Score[i, 0] = Count[i, 0]; app.Score[i, 1] = Count[i, 1]; } if (this.radioButton1.Checked) { PCA.Evaluate("windows()"); PCA.Evaluate("plot(score[,1:2],main=\"PCA\", type=\"p\")"); } else { if ((app.cluster == null) || (app.cluster.Length != SampleNum)) { MessageBox.Show("Sample number in input data is not equal to that in cluster information!!", "Warning!!!", MessageBoxButtons.OK); } else { IntegerVector cluster = PCA.CreateIntegerVector(app.cluster); PCA.SetSymbol("cluster", cluster); PCA.Evaluate("clusterNum <- max(cluster)"); PCA.Evaluate("clustermin <- min(cluster)"); app.clusterNum = (int)PCA.GetSymbol("clusterNum").AsNumeric().First(); int clustermin = (int)PCA.GetSymbol("clustermin").AsNumeric().First(); if (app.clusterNum > 10) { MessageBox.Show("Too many clusters!!", "WARNING!"); } else if (clustermin < 0) { MessageBox.Show("Illegal cluster number!!!", "WARNING!"); } else { PCA_whole_Output plot = new PCA_whole_Output(); plot.MdiParent = this.MdiParent; plot.Show(); } } } this.Close(); }
static void Main(string[] args) { REngine.SetEnvironmentVariables(); REngine RBlock = REngine.GetInstance(); DirectoryInfo di = new DirectoryInfo("C:\\Users\\" + Environment.UserName + "\\Documents\\File Attachments\\"); string searchPattern = "*"; // Set some bases. These need to be tested for each sample. int avgRowCount = 100; int avgColCount = 20; int fileCount = 0; // Get our files, Create a library to hold everything Library.ListofFiles = Library.makeList(di, searchPattern); // Look Through Each File foreach (var a in Library.ListofFiles) { Console.WriteLine(a.FileName); string fileLocation = di + a.FileName; // Open The File, Set the Page EL.singleExcel thisExcel = new EL.singleExcel().createExcel(fileLocation); EL.singleExcel.ExcelWorkSheetChange(thisExcel, 1); // Get Basic Vars new EDA.excelBasics().basicVars(a, thisExcel); // Run Series of Operations to Get More Exact Bounds EDA.lookTriggers LT = new EDA.lookTriggers(); LT.runTriggers(fileCount, a, avgRowCount, avgColCount, out avgRowCount, out avgColCount); Library.colCounts.Add(a.colCount); Library.rowCounts.Add(a.rowCount); // In the event that no rows are found, the file is not counted if (a.rowCount != 0) { fileCount++; } EL.singleExcel.CloseSheet(thisExcel); //Console.ReadLine(); Console.WriteLine("\n"); } // Run some R analysis IntegerVector rowR = RBlock.CreateIntegerVector(Library.rowCounts); IntegerVector colR = RBlock.CreateIntegerVector(Library.colCounts); RBlock.SetSymbol("rowR", rowR); RBlock.SetSymbol("colR", colR); int[] thisTemp; RBlock.Evaluate("temp <- table(as.vector(rowR))"); thisTemp = RBlock.Evaluate("names(temp)[temp == max(temp)]").AsInteger().ToArray(); Library.groupStats.modeRow = thisTemp[0]; RBlock.Evaluate("temp <- table(as.vector(colR))"); thisTemp = RBlock.Evaluate("names(temp)[temp == max(temp)]").AsInteger().ToArray(); Library.groupStats.modeCol = thisTemp[0]; thisTemp = RBlock.Evaluate("mean(rowR)").AsInteger().ToArray(); Library.groupStats.meanRow = thisTemp[0]; thisTemp = RBlock.Evaluate("mean(colR)").AsInteger().ToArray(); Library.groupStats.meanCol = thisTemp[0]; thisTemp = RBlock.Evaluate("median(rowR)").AsInteger().ToArray(); Library.groupStats.medianRow = thisTemp[0]; thisTemp = RBlock.Evaluate("median(colR)").AsInteger().ToArray(); Library.groupStats.medianCol = thisTemp[0]; thisTemp = RBlock.Evaluate("min(rowR)").AsInteger().ToArray(); Library.groupStats.minRow = thisTemp[0]; thisTemp = RBlock.Evaluate("min(colR)").AsInteger().ToArray(); Library.groupStats.minCol = thisTemp[0]; thisTemp = RBlock.Evaluate("max(rowR)").AsInteger().ToArray(); Library.groupStats.maxRow = thisTemp[0]; thisTemp = RBlock.Evaluate("max(colR)").AsInteger().ToArray(); Library.groupStats.maxCol = thisTemp[0]; thisTemp = RBlock.Evaluate("IQR(rowR)").AsInteger().ToArray(); Library.groupStats.iqrRow = thisTemp[0]; thisTemp = RBlock.Evaluate("IQR(colR)").AsInteger().ToArray(); Library.groupStats.iqrCol = thisTemp[0]; thisTemp = RBlock.Evaluate("quantile(rowR)").AsInteger().ToArray(); Library.groupStats.quantileRow = thisTemp[0]; thisTemp = RBlock.Evaluate("quantile(colR)").AsInteger().ToArray(); Library.groupStats.quantileCol = thisTemp[0]; RBlock.Dispose(); EL.singleExcel.outputObjectToExcel(Library.groupStats); // Build some training data from previous information, assumptions object[,] theWords = TSR.trainMethods.getTrainData(di, "\\testdata\\trainlist.xlsx"); List <string> words = new List <string>(); TSR.trainMethods.makeTrainList(theWords, words); theWords = TSR.trainMethods.getTrainData(di, "\\testdata\\looselist.xlsx"); List <string> looseWords = new List <string>(); TSR.trainMethods.makeTrainList(theWords, looseWords); Dictionary <string, int> discreteTermsDict = new Dictionary <string, int>(); Dictionary <string, int> betterTermsDict = new Dictionary <string, int>(); Dictionary <string, int> secondaryTermsDict = new Dictionary <string, int>(); // Run training scenarios TSR.trainMethods.runTrainScan(words, looseWords, avgColCount, Library.ListofFiles, out discreteTermsDict, out betterTermsDict, out secondaryTermsDict); TSR.trainMethods.buildTrainList(discreteTermsDict, words); TSR.trainMethods.runTrainScan(words, looseWords, avgColCount, Library.ListofFiles, out discreteTermsDict, out betterTermsDict, out secondaryTermsDict); TSR.trainMethods.buildTrainList(betterTermsDict, looseWords); TSR.trainMethods.buildTrainList(secondaryTermsDict, looseWords); // In tests, three cycles make for extremely high confidence TSR.trainMethods.runTrainScan(words, looseWords, avgColCount, Library.ListofFiles, out discreteTermsDict, out betterTermsDict, out secondaryTermsDict); // Terms for classifcation EL.singleExcel.outputListToExcel(words, "strongTrainList"); EL.singleExcel.outputListToExcel(looseWords, "learnedTrainList"); }