// C:\Program Files\R\R-3.2.4revised public double[] ForeCast(double[] serie, int numberOfPredictions) { // source: http://stackoverflow.com/questions/14879697/retrieve-results-from-r-evaluation-using-r-net engine.Initialize(); // code below to run the first time, choose yes to install in personal directory // engine.Evaluate("install.packages(\"forecast\")"); NumericVector testGroup = engine.CreateNumericVector(serie); engine.SetSymbol("testGroup", testGroup); engine.Evaluate("testTs <- c(testGroup)"); NumericVector ts = engine.GetSymbol("testTs").AsNumeric(); engine.Evaluate("tsValue <- ts(testTs, frequency=1, start=c(2016, 4, 9))"); engine.Evaluate("library(forecast)"); engine.Evaluate("arimaFit <- auto.arima(tsValue)"); engine.Evaluate("fcast <- forecast(tsValue, h=" + numberOfPredictions + ")"); engine.Evaluate("results <- fcast$mean"); //engine.Evaluate("plot(fcast)"); var fcast = engine.GetSymbol("results").AsNumeric().Select(d => Math.Round(d, 2)).ToArray(); //var nv = ts.AsNumeric().ToArray().Select(a => ""+ a).Aggregate((a,b) => a + "," + b); //var rstring = fcast.Select(a => "" + a).Aggregate((a, b) => a + "," + b); ////var result = nv.ToArray<double>(); return(fcast); }
private void ProcessData() { var currentDir = System.Environment.CurrentDirectory.Replace('\\', '/'); bool errorOccured = false; try { #if DEBUG_TEST engine.Evaluate(string.Format("heartRateData <- read.csv('{0}/NormHeartRate_r61.csv')", currentDir.Replace('\\', '/'))); #else engine.Evaluate(string.Format("heartRateData <- read.csv('{0}')", m_filePath.Replace('\\', '/'))); #endif engine.Evaluate(string.Format("source('{0}/RScripts/KinectHeartRate_JADE.r')", currentDir)); } catch (Exception e) { errorOccured = true; } if (errorOccured) { lblRate.Text = "DR: An error occured, please try again."; } else { //HR1 and HR4 are band filtered to match frequency of normal heart rate range //HR2 and HR3 are not and included incase your environment has closer matches to these frequencies which were seperated NumericVector hrVect1 = engine.GetSymbol("hr1").AsNumeric(); NumericVector hrVect4 = engine.GetSymbol("hr4").AsNumeric(); //In case your environment matches closer NumericVector hrVect2 = engine.GetSymbol("hr2").AsNumeric(); NumericVector hrVect3 = engine.GetSymbol("hr3").AsNumeric(); double hr1 = hrVect1.First(); double hr4 = hrVect4.First(); //incase you need these seperated frequencies double hr2 = hrVect2.First(); double hr3 = hrVect3.First(); double hr = (hr1 > hr4) ? hr1 : hr4; lblRate.Text = ((int)hr).ToString(); lblColorFeeds.Text = "Signal processed."; } bool?isChecked = keepResults.IsChecked; if (!isChecked.HasValue) { System.IO.File.Delete(m_filePath); } else { if (!isChecked.Value) { System.IO.File.Delete(m_filePath); } } }
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 void OnData(TradeBars data) { if (IsWarmingUp) { return; } var logData = _window.Select(closingPrice => Math.Log10(closingPrice)); var diff = logData.Zip(logData.Skip(1), (x, y) => y - x); var returns = _engine.CreateNumericVector(diff); _engine.SetSymbol("roll.returns", returns); _engine.Evaluate(@"source('C:\Users\M\Documents\Visual Studio 2015\Projects\Trading\Trading\arima_garch.r')"); var direction = _engine.GetSymbol("directions").AsInteger()[0]; var holdings = Portfolio[Symbol].Quantity; if (holdings <= 0 && direction == 1) { Log("BUY >> " + Securities[Symbol].Price); SetHoldings(Symbol, 1.0); } else if (holdings >= 0 && direction == -1) { Log("SELL >> " + Securities[Symbol].Price); SetHoldings(Symbol, -1.0); } }
private static double GetRecomendedQuntity(List <double> countList) { List <double> data = new List <double>(); for (int i = 0; i < countList.Count; i++) { data.Add(countList[i]); } REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); engine.Initialize(); NumericVector dataVector = engine.CreateNumericVector(data.ToArray()); engine.SetSymbol("dataVector", dataVector); engine.Evaluate("graphObj <- ts(dataVector, frequency=1, start=c(1, 1, 1))"); engine.Evaluate("library(\"forecast\")"); engine.Evaluate("arimaFit <- arima(graphObj,order=c(2,2,2))"); engine.Evaluate("fcast <- forecast(arimaFit, h=1)"); engine.Evaluate("result <- as.numeric(fcast$mean)"); NumericVector forecastResult = engine.GetSymbol("result").AsNumeric(); double result = forecastResult.First(); engine.Dispose(); return(result); }
private void runButton_Click(object sender, EventArgs e) { REngine.SetEnvironmentVariables(); // There are several options to initialize the engine, but by default the following suffice: REngine engine = REngine.GetInstance(); string textoCifrado = Encrypting.Hashmd5.Encript("3+5"); string texto = Encrypting.Hashmd5.Decrypt(textoCifrado); var group1 = engine.Evaluate(texto); var group = engine.Evaluate("source('C:/Desarrollo/AlamoConsulting/PFRunner/R_Example_Test/test.r')"); var a = engine.GetSymbol("a").AsNumeric(); var b = engine.GetSymbol("b").AsNumeric(); messagesBox.Text = string.Format("Secuencia de Entrada: [{0}]", string.Join(", ", a)); messagesBox.Text += Environment.NewLine + string.Format("Raíz cuadrada: [{0}]", string.Join(", ", b)); }
static void RService() { REngine.SetEnvironmentVariables(); // <-- May be omitted; the next line would call it. REngine engine = REngine.GetInstance(); // A somewhat contrived but customary Hello World: var e = engine.Evaluate("x <- 3"); NumericVector x = engine.GetSymbol("x").AsNumeric(); engine.Evaluate("y <- 1:10"); NumericVector y = engine.GetSymbol("y").AsNumeric(); CharacterVector charVec = engine.CreateCharacterVector(new[] { "Hello, R world!, .NET speaking" }); engine.SetSymbol("greetings", charVec); engine.Evaluate("str(greetings)"); // print out in the console string[] a = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray(); Console.WriteLine("R answered: '{0}'", a[0]); Console.WriteLine("Press any key to exit the program"); Console.ReadKey(); }
/// <summary> /// Read output data from the .Rdata file generated by CroptimizR. /// </summary> /// <param name="path">Path to the .Rdata file on disk.</param> public DataTable ReadRData(string path) { REngine engine = REngine.GetInstance(); engine.Evaluate($"load('{path.Replace(@"\", @"\\")}')"); GenericVector nlo = engine.GetSymbol("nlo").AsList(); DataTable table = new DataTable(Name); table.Columns.Add("Repetition", typeof(int)); table.Columns.Add("Objective Function Value", typeof(double)); table.Columns.Add("Number of Iterations"); foreach (Parameter param in Parameters) { table.Columns.Add($"{param.Name} Initial", typeof(double)); } foreach (Parameter param in Parameters) { table.Columns.Add($"{param.Name} Final", typeof(double)); } table.Columns.Add("Message", typeof(string)); for (int i = 0; i < nlo.Count(); i++) { double[] initial = engine.Evaluate($"nlo[[{i + 1}]]$x0").AsNumeric().ToArray(); double[] solution = engine.Evaluate($"nlo[[{i + 1}]]$solution").AsNumeric().ToArray(); string message = engine.Evaluate($"nlo[[{i + 1}]]$message").AsCharacter().ToArray().FirstOrDefault(); double objective = engine.Evaluate($"nlo[[{i + 1}]]$objective").AsNumeric().ToArray().FirstOrDefault(); int iterations = engine.Evaluate($"nlo[[{i + 1}]]$iterations").AsInteger().ToArray().FirstOrDefault(); DataRow row = table.NewRow(); List <object> data = new List <object>(); data.Add(i); data.Add(objective); data.Add(iterations); foreach (double initialValue in initial) { data.Add(initialValue); } foreach (double solutionValue in solution) { data.Add(solutionValue); } data.Add(message); row.ItemArray = data.ToArray(); table.Rows.Add(row); } return(table); }
private SymbolicExpression GetSym(string name) { SymbolicExpression sym; try { sym = _engine.GetSymbol(name); clsRCmdLog.LogRComment(string.Format("RdnConnectorClass.GetSym:{0} -> {1}", name, sym.Type.ToString())); } catch (Exception ex) { clsRCmdLog.LogRComment(string.Format("GetSym:{0} -> error:{1}", name, ex.Message)); throw; } return(sym); }
private void ComputeNNForecast() { string filePath = (dataDirectory + "\\" + fileName).Replace("\\", "/"); REngine engine = StartEngine(); engine.Evaluate(libraries); engine.Evaluate("data <- read.csv(\"" + filePath + "\")"); engine.Evaluate("myts <- ts(data[,1], frequency = " + frequency + ")"); engine.Evaluate("NNfit <- nnetar(myts)"); engine.Evaluate("NNpred <- forecast(NNfit, h = " + periods + ")"); engine.Evaluate("mean <- as.integer(NNpred$mean)"); IntegerVector v = engine.GetSymbol("mean").AsInteger(); results = v.ToArray(); }
private void ComputeArimaForecast() { string filePath = (dataDirectory + "\\" + fileName).Replace("\\", "/"); REngine engine = StartEngine(); engine.Evaluate(libraries); engine.Evaluate("data <- read.csv(\"" + filePath + "\")"); engine.Evaluate("myts <- ts(data[,1], frequency = " + frequency + ")"); engine.Evaluate("ARIMAfit1 <- auto.arima(myts, stepwise = FALSE, approximation = FALSE)"); engine.Evaluate("myfc <- forecast(ARIMAfit1, h = " + periods + ")"); engine.Evaluate("mean <- as.integer(myfc$mean)"); IntegerVector v = engine.GetSymbol("mean").AsInteger(); results = v.ToArray(); }
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]); }
public NumericVector computerRScript(string file, string seasonality, string startingYear) { string ddr = dataDirectory.Replace("\\", "/"); //en.Evaluate("install.packages('tseries')"); //en.Evaluate("install.packages('forecast')"); en.Evaluate("library(tseries)"); en.Evaluate("library(forecast)"); en.Evaluate("data <- read.csv(\"" + ddr + "/" + file + ".csv" + "\")"); en.Evaluate("myts <- ts(data[,3], frequency = " + seasonality + ")"); en.Evaluate("ARIMAfit1 <- auto.arima(myts)"); en.Evaluate("myfc <- forecast(ARIMAfit1, h = " + startingYear + ")"); en.Evaluate("forecast <- myfc$mean"); NumericVector forcastedValues = en.GetSymbol("forecast").AsNumeric(); return(forcastedValues); }
private Dictionary <string, DataFrame> GetDataFrames() { // Look at all the symbols. var symbolNames = engine.GlobalEnvironment.GetSymbolNames(); var dataFrames = new Dictionary <string, DataFrame>(); foreach (var symbolName in symbolNames) { var expr = engine.GetSymbol(symbolName); if (expr.IsDataFrame()) { dataFrames.Add(symbolName, expr.AsDataFrame()); } } return(dataFrames); }
static void codeplex_discussion_647874(REngine engine) { var npkscript = @" op <- options(contrasts = c('contr.helmert', 'contr.poly')) npk.aov <- aov(yield ~ block + N*P*K, npk) npk.sum <- summary(npk.aov) " ; engine.Evaluate(npkscript); var m = engine.GetSymbol("npk.sum").AsList(); var df = m [0].AsDataFrame(); var names = df.Names; var colnames = df.ColumnNames; // should do some checkes on names double[] meanSqr = df["Mean Sq"].AsNumeric().ToArray(); }
/// <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]); } }
static void Main(string[] args) { List <double> data = new List <double>(); for (int i = 0; i < 6; i++) { data.Add(2.0); data.Add(0.0); data.Add(0.0); data.Add(2.0); data.Add(0.0); data.Add(1.0); data.Add(0.0); } REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); NumericVector dataVector = engine.CreateNumericVector(data.ToArray()); engine.SetSymbol("dataVector", dataVector); engine.Evaluate("graphObj <- ts(dataVector, frequency=1, start=c(1, 1, 1))"); engine.Evaluate("library(\"forecast\")"); engine.Evaluate("arimaFit <- arima(graphObj,order=c(2,2,2))"); engine.Evaluate("fcast <- forecast(arimaFit, h=1)"); engine.Evaluate("result <- as.numeric(fcast$mean)"); NumericVector forecastResult = engine.GetSymbol("result").AsNumeric(); double result = forecastResult.First(); if (result >= 1) { Console.WriteLine("Go buy milk today"); } else { Console.WriteLine("Dont buy milk today"); } Console.WriteLine("Result = " + result); Console.ReadKey(); engine.Dispose(); }
private static void ReproGH97(REngine engine) { // https://github.com/jmp75/rdotnet/issues/97 SymbolicExpression expression; var log = NativeUtility.SetEnvironmentVariablesLog; engine.Initialize(); engine.Evaluate("x <- data.frame(c1 = c('a', 'b'), stringsAsFactors = FALSE)"); engine.Evaluate("y <- data.frame(x = c('a', 'b'), stringsAsFactors = TRUE)"); engine.Evaluate("c1 <- x$c1"); expression = engine.GetSymbol("x"); Console.WriteLine("Values as characters:"); Console.WriteLine(expression.AsDataFrame()[0][0]); Console.WriteLine(expression.AsDataFrame()[0][1]); Console.WriteLine("*********************"); expression = engine.GetSymbol("y"); Console.WriteLine("Values as factor:"); Console.WriteLine(expression.AsDataFrame()[0][0]); Console.WriteLine(expression.AsDataFrame()[0][1]); Console.WriteLine("*********************"); expression = engine.GetSymbol("c1"); Console.WriteLine("Values direct from column:"); Console.WriteLine(expression.AsCharacter()[0]); Console.WriteLine(expression.AsCharacter()[1]); Console.WriteLine("*********************"); Console.WriteLine(""); Console.WriteLine("*********************"); Console.WriteLine("Now going for a second round"); Console.WriteLine("*********************"); expression = engine.GetSymbol("x"); Console.WriteLine("Values as characters:"); Console.WriteLine(expression.AsDataFrame()[0][0]); Console.WriteLine(expression.AsDataFrame()[0][1]); Console.WriteLine("*********************"); expression = engine.GetSymbol("y"); Console.WriteLine("Values as factor:"); Console.WriteLine(expression.AsDataFrame()[0][0]); Console.WriteLine(expression.AsDataFrame()[0][1]); Console.WriteLine("*********************"); expression = engine.GetSymbol("c1"); Console.WriteLine("Values direct from column:"); Console.WriteLine(expression.AsCharacter()[0]); Console.WriteLine(expression.AsCharacter()[1]); Console.WriteLine("*********************"); Console.WriteLine(log); }
/// <summary> /// Odpala skrypt o podanej nazwie /// </summary> /// <param name="scriptName">Nazwa pliku (z rozszerszeniem .R lub bez)</param> /// <param name="hasArguments">Czy dołączamy jakieś argumenty wywołania</param> /// <param name="arg">Argumenty wywołania</param> /// <returns>-1 dla danych z pliku; dla własnoręcznych 0 jak złe zdjęcie, 1 jak dobre</returns> public int launchScript(string scriptName, bool hasArguments, params string[] arg) { try { if (engine != null) { // Dodawanie argumentów (symulacja linii poleceń if (hasArguments) { string arguments = arg[0].ToString(); for (int i = 1; i < arg.Length; i++) { arguments += ("," + arg[i].ToString()); } engine.Evaluate("commandArgs <- function() c(" + arguments + ")"); } if (scriptName.Contains(".R")) { engine.Evaluate("source('" + scriptName + "')"); } else { engine.Evaluate("source('" + scriptName + ".R')"); } } if (scriptName.Contains("User")) { IntegerVector result = engine.GetSymbol("userResult").AsInteger(); return(result[0]); } } catch (EvaluationException) { throw new EvaluationException("Brak pliku"); } return(-1); }
//Execute a previson on esempio on the 8 future values based on stagionality = 4. private void esempioForecast() { string esempioPath = (dataDirectory + "\\esempio.csv").Replace("\\", "/"); StartupParameter rinit = new StartupParameter(); rinit.Quiet = true; rinit.RHome = "C:\\Program Files\\R\\R-3.4.4"; rinit.Interactive = true; REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(null, true, rinit); engine.Evaluate(""); engine.Evaluate("library(tseries)"); engine.Evaluate("library(forecast)"); engine.Evaluate("data <- read.csv(\"" + esempioPath + "\")"); engine.Evaluate("myts <- ts(data[,2], frequency = 4)"); engine.Evaluate("ARIMAfit1 <- auto.arima(myts, stepwise = FALSE, approximation = FALSE)"); engine.Evaluate("myfc <- forecast(ARIMAfit1, h = 8)"); engine.Evaluate("intMean <- as.integer(myfc$mean)"); IntegerVector a1 = engine.GetSymbol("intMean").AsInteger(); results = a1.ToArray(); }
private void button1_Click(object sender, EventArgs e) { REngine.SetEnvironmentVariables(); REngine cluster = REngine.GetInstance(); cluster.Initialize(); //try //{ cluster.Evaluate("cluster = read.table(file.choose())"); cluster.Evaluate("cluster <- as.matrix(cluster)"); IntegerMatrix clusterinfo = cluster.GetSymbol("cluster").AsIntegerMatrix(); app.cluster = new int[clusterinfo.AsNumericMatrix().ToArray().GetLength(1)]; for (int i = 0; i < app.cluster.Length; i++) { app.cluster[i] = clusterinfo[0, i]; } //foreach (var item in Enumerable.Range(0, clusterinfo.AsNumericMatrix().ToArray().GetLength(0) * clusterinfo.AsNumericMatrix().ToArray().GetLength(1)).Select(i => new { x = i / clusterinfo.AsNumericMatrix().ToArray().GetLength(1), y = i % clusterinfo.AsNumericMatrix().ToArray().GetLength(1) })) //{ // app.cluster[item.x, item.y] = (int)clusterinfo.AsNumericMatrix().ToArray()[item.x, item.y]; //} //} //try //{ // StatConnector factor = new STATCONNECTORSRVLib.StatConnectorClass(); // factor.Init("R"); // factor.EvaluateNoReturn("cluster = read.table(file.choose())"); // factor.Evaluate("cluster <- as.matrix(cluster)"); // object temp = factor.GetSymbol("cluster"); // app.cluster = (int[,])temp; //} //catch { } }
//Execute a previson on gioiellerie time series on the 24 future values based on stagionality = 12. private void gioiellerieForecast() { string gioielleriePath = (dataDirectory + "\\gioiellerie.csv").Replace("\\", "/"); StartupParameter rinit = new StartupParameter(); rinit.Quiet = true; rinit.RHome = "C:\\Program Files\\R\\R-3.4.4"; rinit.Interactive = true; REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(null, true, rinit); engine.Evaluate(""); engine.Evaluate("library(tseries)"); engine.Evaluate("library(forecast)"); engine.Evaluate("data <- read.csv(\"" + gioielleriePath + "\")"); //THIS 3 must be converted back into two when the data are readed. engine.Evaluate("myts <- ts(data[,3], frequency = 12)"); engine.Evaluate("ARIMAfit1 <- auto.arima(myts, stepwise = FALSE, approximation = FALSE)"); engine.Evaluate("myfc <- forecast(ARIMAfit1, h = 24)"); engine.Evaluate("intMean <- as.integer(myfc$mean)"); IntegerVector a1 = engine.GetSymbol("intMean").AsInteger(); results = a1.ToArray(); }
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(); }
private void button4_Click(object sender, EventArgs e) { if (this.textBox3.Text == "") { MessageBox.Show("Please enter the sample number of Group I!", "WARNIMG"); Two_Groups_Ana TwoGroupsTest = new Two_Groups_Ana(); TwoGroupsTest.MdiParent = this.MdiParent; TwoGroupsTest.Show(); this.Close(); } else { int FeatureNum = app.FeaName.GetLength(0); int SampleNum = app.SamName.GetLength(0); List <double> prob = new List <double>(); List <double> stat = new List <double>(); List <double> pvalue = new List <double>(); double[] bonferroni = new double[FeatureNum]; double[] fdr = new double[FeatureNum]; int NAnum = 0; REngine.SetEnvironmentVariables(); REngine TGS = REngine.GetInstance(); TGS.Initialize(); NumericMatrix Freq = TGS.CreateNumericMatrix(app.FreqMatrix); TGS.SetSymbol("Freq", Freq); NumericMatrix Count = TGS.CreateNumericMatrix(app.CountMatrix); TGS.SetSymbol("Count", Count); NumericVector RFeatureNum = TGS.CreateNumeric(FeatureNum); NumericVector RSampleNum = TGS.CreateNumeric(SampleNum); TGS.SetSymbol("FeatureNum", RFeatureNum); TGS.SetSymbol("SampleNum", RSampleNum); CharacterVector SampleName = TGS.CreateCharacterVector(app.SamName); CharacterVector FeatureName = TGS.CreateCharacterVector(app.FeaName); TGS.SetSymbol("FeatureName", FeatureName); TGS.SetSymbol("SampleName", SampleName); List <string> SampleNameFreq = new List <string>(); List <double?> OddRatio = new List <double?>(); List <double?> absOddRatio = new List <double?>(); List <List <double> > Freqtemp = new List <List <double> >(); List <double> FreqSum = new List <double>(); int Correct1 = 0; int Correct2 = 0; int method = 0; int GroupNum = int.Parse(this.textBox3.Text.ToString()); NumericVector RGroupNum = TGS.CreateNumeric(GroupNum); TGS.SetSymbol("Groupsep", RGroupNum); for (int i = 0; i < SampleNum; i++) { SampleNameFreq.Add(SampleName[i] + "Freq"); } if (this.comboBox1.SelectedIndex == 0) { int effNum1, effNum2; TGS.Evaluate("FeatureSums1 <- rowSums(Count[,1:Groupsep])"); TGS.Evaluate("FeatureSums2 <- rowSums(Count[,Groupsep:SampleNum])"); TGS.Evaluate("effnum1 <- length(FeatureSums1[FeatureSums1 > Groupsep])"); TGS.Evaluate("effnum2 <- length(FeatureSums2[FeatureSums2 > (SampleNum - Groupsep)])"); effNum1 = Convert.ToInt32(TGS.GetSymbol("effnum1").AsNumeric().First()); effNum2 = Convert.ToInt32(TGS.GetSymbol("effnum2").AsNumeric().First()); for (int i = 0; i < FeatureNum; i++) { double rowsums1 = 0; double rowsums2 = 0; double[] rowsCount1 = new double[GroupNum]; for (int j = 0; j < GroupNum; j++) { rowsums1 = rowsums1 + app.CountMatrix[i, j]; rowsCount1[j] = app.CountMatrix[i, j]; } if (rowsums1 > GroupNum) { NumericVector rowscount1 = TGS.CreateNumericVector(rowsCount1); TGS.SetSymbol("rowcount1", rowscount1); TGS.Evaluate("result1 <- ks.test(rowcount1,\"pnorm\",mean(rowcount1),sd(rowcount1))"); TGS.Evaluate("factor1 <- result1$p"); double prows1 = TGS.GetSymbol("factor1").AsNumeric().First(); if (prows1 < 0.05) { Correct1 = Correct1 + 1; } } double[] rowsCount2 = new double[SampleNum - GroupNum]; for (int j = GroupNum; j < SampleNum; j++) { rowsums2 = rowsums2 + app.CountMatrix[i, j]; rowsCount2[j - GroupNum] = app.CountMatrix[i, j]; } if (rowsums2 > (SampleNum - GroupNum)) { NumericVector rowscount2 = TGS.CreateNumericVector(rowsCount2); TGS.SetSymbol("rowcount2", rowscount2); TGS.Evaluate("result2 <- ks.test(rowcount2,\"pnorm\",mean(rowcount2),sd(rowcount2))"); TGS.Evaluate("factor2 <- result2$p"); double prows2 = TGS.GetSymbol("factor2").AsNumeric().First(); if (prows2 < 0.05) { Correct2 = Correct2 + 1; } } } bool condition1 = (Correct1 >= effNum1 * 0.5) && (Correct2 >= effNum2 * 0.5); bool condition2 = GroupNum == SampleNum - GroupNum; if (condition1) { if (condition2) { method = 2; } else { method = 1; } } else { if (condition2) { method = 4; } else { method = 3; } } switch (method) { case 1: MessageBox.Show("Statistical Method : t-test"); break; case 2: MessageBox.Show("Statistical Method : Pair t-test"); break; case 3: MessageBox.Show("Statistical Method : Mann-Whitney U test"); break; case 4: MessageBox.Show("Statistical Method : Wilcoxon sign-rank test"); break; default: break; } } TGS.Evaluate("FreqMatrix <- as.data.frame(Freq)"); TGS.Evaluate("names(FreqMatrix) <- SampleName"); TGS.Evaluate("samp1_mean <- apply(FreqMatrix[,1:Groupsep],1,mean)"); TGS.Evaluate("samp2_mean <- apply(FreqMatrix[,(Groupsep+1):SampleNum],1,mean)"); TGS.Evaluate("samp1_sd <- apply(FreqMatrix[,1:Groupsep],1,sd)"); TGS.Evaluate("samp2_sd <- apply(FreqMatrix[,(Groupsep+1):SampleNum],1,sd)"); TGS.Evaluate("samp1_stat <- paste(samp1_mean,samp1_sd,sep=\"±\")"); TGS.Evaluate("samp2_stat <- paste(samp2_mean,samp2_sd,sep=\"±\")"); string[] s1_stat = (string[])TGS.GetSymbol("samp1_stat").AsCharacter().ToArray(); string[] s2_stat = (string[])TGS.GetSymbol("samp2_stat").AsCharacter().ToArray(); if (this.comboBox1.SelectedIndex != 6) { switch (this.comboBox1.SelectedIndex + method) { case 1: for (int i = 1; i <= FeatureNum; i++) { TGS.SetSymbol("i", TGS.CreateNumeric(i)); TGS.Evaluate("group1_freq <- as.numeric(FreqMatrix[i,1:Groupsep])"); TGS.Evaluate("group2_freq <- as.numeric(FreqMatrix[i,(Groupsep+1):SampleNum])"); TGS.Evaluate("p.value <- t.test(group1_freq,group2_freq, paired=FALSE)$p.value"); pvalue.Add(TGS.GetSymbol("p.value").AsNumeric().First()); } break; case 2: if (GroupNum != SampleNum - GroupNum) { MessageBox.Show("This statistical test must have same number samples in each category!", "WARNIMG"); break; } else { for (int i = 1; i <= FeatureNum; i++) { TGS.SetSymbol("i", TGS.CreateNumeric(i)); TGS.Evaluate("group1_freq <- as.numeric(FreqMatrix[i,1:Groupsep])"); TGS.Evaluate("group2_freq <- as.numeric(FreqMatrix[i,(Groupsep+1):SampleNum])"); TGS.Evaluate("p.value <- t.test(group1_freq,group2_freq, paired=TRUE)$p.value"); pvalue.Add(TGS.GetSymbol("p.value").AsNumeric().First()); } break; } case 3: for (int i = 1; i <= FeatureNum; i++) { TGS.SetSymbol("i", TGS.CreateNumeric(i)); TGS.Evaluate("group1_freq <- as.numeric(FreqMatrix[i,1:Groupsep])"); TGS.Evaluate("group2_freq <- as.numeric(FreqMatrix[i,(Groupsep+1):SampleNum])"); TGS.Evaluate("p.value <- wilcox.test(group1_freq,group2_freq,exact = FALSE)$p.value"); pvalue.Add(TGS.GetSymbol("p.value").AsNumeric().First()); } break; case 4: if (GroupNum != SampleNum - GroupNum) { MessageBox.Show("This statistical test must have same number samples in each category!", "WARNIMG"); break; } else { for (int i = 1; i <= FeatureNum; i++) { TGS.SetSymbol("i", TGS.CreateNumeric(i)); TGS.Evaluate("group1_freq <- as.numeric(FreqMatrix[i,1:Groupsep])"); TGS.Evaluate("group2_freq <- as.numeric(FreqMatrix[i,(Groupsep+1):SampleNum])"); TGS.Evaluate("p.value <- wilcox.test(group1_freq,group2_freq,paired=TRUE,exact = FALSE)$p.value"); pvalue.Add(TGS.GetSymbol("p.value").AsNumeric().First()); } break; } case 5: double Sum1 = 0; double Sum2 = 0; for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < GroupNum; j++) { Sum1 = Sum1 + app.CountMatrix[i, j]; } for (int j = GroupNum; j < SampleNum; j++) { Sum2 = Sum2 + app.CountMatrix[i, j]; } } for (int i = 0; i < FeatureNum; i++) { double n11 = 0; double n12 = 0; double n21 = 0; double n22 = 0; for (int j = 0; j < GroupNum; j++) { n11 = n11 + app.CountMatrix[i, j]; } for (int j = GroupNum; j < SampleNum; j++) { n21 = n21 + app.CountMatrix[i, j]; } n12 = Sum1 - n11; n22 = Sum2 - n21; NumericVector Rn11 = TGS.CreateNumeric(n11); NumericVector Rn21 = TGS.CreateNumeric(n21); NumericVector Rn12 = TGS.CreateNumeric(n12); NumericVector Rn22 = TGS.CreateNumeric(n22); TGS.SetSymbol("n11", Rn11); TGS.SetSymbol("n12", Rn12); TGS.SetSymbol("n21", Rn21); TGS.SetSymbol("n22", Rn22); TGS.Evaluate("compare <- matrix(c(n11,n12,n21,n22),nr=2)"); TGS.Evaluate("p.value <- fisher.test(compare)$p.value"); pvalue.Add(TGS.GetSymbol("p.value").AsNumeric().First()); } break; default: break; } NumericVector Rpvalue = TGS.CreateNumericVector(pvalue); TGS.SetSymbol("p.value", Rpvalue); TGS.Evaluate("NAnum = length(p.value[is.nan(p.value)])"); NAnum = Convert.ToInt32(TGS.GetSymbol("NAnum").AsNumeric().First()); TGS.Evaluate("bonferroni.p <- p.adjust(p.value,\"bonferroni\")"); TGS.Evaluate("fdr.p <- p.adjust(p.value,\"fdr\")"); for (int i = 0; i < FeatureNum; i++) { bonferroni[i] = TGS.GetSymbol("bonferroni.p").AsNumeric()[i]; fdr[i] = TGS.GetSymbol("fdr.p").AsNumeric()[i]; } List <string> Annotation = new List <string>(); if (this.checkBox1.Checked) { if (this.radioButton1.Checked) { string strConnCOG; strConnCOG = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + System.Windows.Forms.Application.StartupPath + "/COG.xlsx" + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection OleConnCOG = new OleDbConnection(strConnCOG); OleConnCOG.Open(); String sqlCOG = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter OleDaExcelCOG = new OleDbDataAdapter(sqlCOG, OleConnCOG); app.OleDsExcleCOG = new DataSet(); OleDaExcelCOG.Fill(app.OleDsExcleCOG, "Sheet1"); OleConnCOG.Close(); for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < app.OleDsExcleCOG.Tables[0].Rows.Count; j++) { if (string.Equals(FeatureName[i], app.OleDsExcleCOG.Tables[0].Rows[j][0].ToString())) { Annotation.Add(app.OleDsExcleCOG.Tables[0].Rows[j][1].ToString()); } } if (Annotation.Count < i + 1) { Annotation.Add("No Annotation!"); } } } else if (this.radioButton2.Checked) { string strConnPFAM; strConnPFAM = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + System.Windows.Forms.Application.StartupPath + "/PFAM.xlsx" + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection OleConnPFAM = new OleDbConnection(strConnPFAM); OleConnPFAM.Open(); String sqlPFAM = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter OleDaExcelPFAM = new OleDbDataAdapter(sqlPFAM, OleConnPFAM); app.OleDsExclePFAM = new DataSet(); OleDaExcelPFAM.Fill(app.OleDsExclePFAM, "Sheet1"); OleConnPFAM.Close(); for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < app.OleDsExclePFAM.Tables[0].Rows.Count; j++) { if (string.Equals(FeatureName[i], app.OleDsExclePFAM.Tables[0].Rows[j][0].ToString())) { Annotation.Add(app.OleDsExclePFAM.Tables[0].Rows[j][1].ToString()); } } if (Annotation.Count < i + 1) { Annotation.Add("No Annotation!"); } } } } DataTable dt = new DataTable(); dt.Columns.Add("Feature", typeof(string)); for (int i = 0; i < SampleNum; i++) { dt.Columns.Add(SampleName[i], typeof(double));; } dt.Columns.Add("group1", typeof(string)); dt.Columns.Add("group2", typeof(string)); dt.Columns.Add("p.value", typeof(double)); dt.Columns.Add("bonferroni.p", typeof(double)); dt.Columns.Add("fdr.p", typeof(double)); dt.Columns.Add("Annotation", typeof(string)); for (int i = 0; i < SampleNum; i++) { dt.Columns.Add(SampleNameFreq[i], typeof(double)); } for (int i = 0; i < FeatureNum; i++) { DataRow dr = dt.NewRow(); dr[0] = FeatureName[i]; for (int j = 1; j <= SampleNum; j++) { dr[j] = app.CountMatrix[i, j - 1]; } dr[SampleNum + 1] = s1_stat[i]; dr[SampleNum + 2] = s2_stat[i]; if (double.IsNaN(pvalue[i])) { dr[SampleNum + 3] = DBNull.Value; dr[SampleNum + 4] = DBNull.Value; dr[SampleNum + 5] = DBNull.Value; } else { dr[SampleNum + 3] = pvalue[i]; dr[SampleNum + 4] = bonferroni[i]; dr[SampleNum + 5] = fdr[i]; } if (this.checkBox1.Checked) { dr[SampleNum + 6] = Annotation[i]; } else { dr[SampleNum + 6] = null; } for (int j = 0; j < SampleNum; j++) { dr[j + SampleNum + 7] = app.FreqMatrix[i, j]; } dt.Rows.Add(dr); } DataTable dtCopy = dt.Copy(); DataTable dttemp = dt.Copy(); dttemp.Clear(); DataView dv = dt.DefaultView; dv.Sort = "p.value"; dtCopy = dv.ToTable(); for (int i = 0; i < NAnum; i++) { DataRow row = dtCopy.Rows[i]; dttemp.Rows.Add(row.ItemArray); } for (int i = 0; i < NAnum; i++) { dtCopy.Rows.RemoveAt(0); } Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; Microsoft.Office.Interop.Excel.Range range; long totalCount = dtCopy.Rows.Count; long rowRead = 0; float percent = 0; for (int i = 0; i < dtCopy.Columns.Count - SampleNum; i++) { worksheet.Cells[1, i + 1] = dtCopy.Columns[i].ColumnName; range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]; range.Interior.ColorIndex = 15; range.Font.Bold = true; } for (int r = 0; r < dtCopy.Rows.Count; r++) { for (int i = 0; i < dtCopy.Columns.Count - SampleNum; i++) { worksheet.Cells[r + 2, i + 1] = dtCopy.Rows[r][i].ToString(); } rowRead++; percent = ((float)(100 * rowRead)) / totalCount; } xlApp.Visible = true; int pnum = 0; for (int i = 0; i < FeatureNum; i++) { try { if (double.Parse(dtCopy.Rows[i][SampleNum + 3].ToString()) < double.Parse(this.textBox1.Text.ToString())) { pnum++; } } catch { } } double[,] df = new double[Math.Min(10, FeatureNum), SampleNum]; for (int i = 0; i < Math.Min(10, FeatureNum); i++) { for (int j = 0; j < SampleNum; j++) { df[i, j] = double.Parse(dtCopy.Rows[i][SampleNum + 7 + j].ToString()); } } if (this.checkBox2.Checked) { string[] rownamesdf = new string[Math.Min(10, FeatureNum)]; for (int i = 0; i < Math.Min(10, FeatureNum); i++) { rownamesdf[i] = dtCopy.Rows[i][0].ToString(); } CharacterVector Rrownamesdf = TGS.CreateCharacterVector(rownamesdf); TGS.SetSymbol("Rownamedf", Rrownamesdf); NumericMatrix Rdf = TGS.CreateNumericMatrix(df); TGS.SetSymbol("Freqdf", Rdf); NumericVector RRow = TGS.CreateNumeric(Math.Min(10, FeatureNum)); TGS.SetSymbol("selrow", RRow); TGS.Evaluate("Freqdf <- as.data.frame(Freqdf)"); TGS.Evaluate("rownames(Freqdf) <- Rownamedf"); TGS.Evaluate("colnames(Freqdf) <- SampleName"); TGS.Evaluate("colournum <- rainbow(dim(Freqdf)[2])"); TGS.Evaluate("plotdata <- t(Freqdf)"); TGS.Evaluate("windows()"); TGS.Evaluate("barplot(plotdata,main=\"features with top varition\",ylab=\"Freq\",beside=TRUE,horiz=FALSE, cex.names=0.6,col=colournum)"); TGS.Evaluate("legend(\"topright\",SampleName,fill=colournum)"); } if (pnum > 0) { double[,] dfall = new double[pnum, SampleNum]; for (int i = 0; i < pnum; i++) { for (int j = 0; j < SampleNum; j++) { dfall[i, j] = double.Parse(dtCopy.Rows[i][SampleNum + 7 + j].ToString()); } } string[] rownamesall = new string[pnum]; for (int i = 0; i < pnum; i++) { rownamesall[i] = dtCopy.Rows[i][0].ToString(); } CharacterVector Rrownamesall = TGS.CreateCharacterVector(rownamesall); TGS.SetSymbol("Rownameall", Rrownamesall); NumericMatrix Rdfall = TGS.CreateNumericMatrix(dfall); TGS.SetSymbol("Freqdfall", Rdfall); NumericVector RRowall = TGS.CreateNumeric(pnum); TGS.SetSymbol("selrowall", RRowall); TGS.Evaluate("Freqdfall <- as.data.frame(Freqdfall)"); TGS.Evaluate("rownames(Freqdfall) <- Rownameall"); TGS.Evaluate("colnames(Freqdfall) <- SampleName"); TGS.Evaluate("distance <- as.dist(1-abs(cor(Freqdfall)))"); if (this.checkBox3.Checked) { TGS.Evaluate("fit <- cmdscale(distance, eig=TRUE, k=2)"); TGS.Evaluate("x <- fit$points[,1]"); TGS.Evaluate("y <- fit$points[,2]"); TGS.Evaluate("minx <- min(x)"); TGS.Evaluate("miny <- min(y)"); TGS.Evaluate("maxx <- max(x)"); TGS.Evaluate("maxy <- max(y)"); TGS.Evaluate("randx <- maxx - minx"); TGS.Evaluate("randy <- maxy - miny"); TGS.Evaluate("llimx <- minx - randx/10"); TGS.Evaluate("hlimx <- maxx + randx/3"); TGS.Evaluate("llimy <- miny - randy/10"); TGS.Evaluate("hlimy <- maxy + randy/3"); TGS.Evaluate("windows()"); TGS.Evaluate("plot(x,y,xlab=\"Coordinate 1\",ylab=\"Coordinate 2\",main=\"MDS\", pch=c(rep(0,Groupsep),rep(1,(length(SampleName)-Groupsep))),col=c(rep(\"red\",Groupsep),rep(\"green\",(length(SampleName)-Groupsep))), type=\"p\",xlim = c(llimx,hlimx), ylim = c(llimy,hlimy))"); if (this.comboBox3.SelectedIndex == 0) { TGS.Evaluate("legend(\"topright\",colnames(Freqdfall),pch=c(rep(0,Groupsep),rep(1,(length(SampleName)-Groupsep))),col=c(rep(\"red\",Groupsep),rep(\"green\",(length(SampleName)-Groupsep))),cex = 0.8)"); } else if (this.comboBox3.SelectedIndex == 1) { TGS.Evaluate("text(x,y,labels=SampleName,pos=4)"); } } if (this.checkBox4.Checked) { TGS.Evaluate("windows()"); TGS.Evaluate("plot(hclust(distance),main =\"Samples Clust\")"); } } else { MessageBox.Show("No differntially abundant features!!"); } if (this.checkBox5.Checked) { int Rownum = 0; for (int i = 0; i < FeatureNum; i++) { double tempSum = 0; double tempMean = 0; for (int j = 0; j < SampleNum; j++) { tempSum = tempSum + app.FreqMatrix[i, j]; } tempMean = tempSum / (SampleNum); if (tempSum > 0) { FreqSum.Add(tempSum); List <double> tempRow = new List <double>(); for (int j = 0; j < SampleNum; j++) { tempRow.Add(app.FreqMatrix[i, j] / tempMean); } Freqtemp.Add(tempRow); Rownum = Rownum + 1; } } for (int i = 0; i < Rownum; i++) { for (int j = 0; j < SampleNum; j++) { Freqtemp[i][j] = Math.Log(Freqtemp[i][j], 2); if (Freqtemp[i][j] > 1) { Freqtemp[i][j] = 1; } else if (Freqtemp[i][j] < -1) { Freqtemp[i][j] = -1; } } } double[,] dfhm = new double[Math.Min(500, Rownum), SampleNum]; for (int i = 0; i < Math.Min(500, Rownum); i++) { for (int j = 0; j < SampleNum; j++) { dfhm[i, j] = double.Parse(Freqtemp[i][j].ToString()); } } string[] rownameshm = new string[Math.Min(500, Rownum)]; for (int i = 0; i < Math.Min(500, Rownum); i++) { rownameshm[i] = dtCopy.Rows[i][0].ToString(); } CharacterVector Rrownameshm = TGS.CreateCharacterVector(rownameshm); TGS.SetSymbol("Rownamehm", Rrownameshm); NumericMatrix Rdfhm = TGS.CreateNumericMatrix(dfhm); TGS.SetSymbol("Freqdfhm", Rdfhm); NumericVector RRowhm = TGS.CreateNumeric(Math.Min(500, Rownum)); TGS.SetSymbol("plotnum", RRowhm); TGS.Evaluate("Freqdfhm <- as.data.frame(Freqdfhm)"); TGS.Evaluate("rownames(Freqdfhm) <- Rownamehm"); TGS.Evaluate("colnames(Freqdfhm) <- SampleName"); TGS.Evaluate("Freqdfhm <- as.matrix(Freqdfhm)"); TGS.Evaluate("library(pheatmap)"); TGS.Evaluate("windows()"); if (this.checkBox6.Checked) { if (this.checkBox7.Checked) { TGS.Evaluate("pheatmap(Freqdfhm[1:plotnum,],show_rownames=T,cluster_rows=T)"); } else { TGS.Evaluate("pheatmap(Freqdfhm[1:plotnum,],show_rownames=F,cluster_rows=T)"); } } else { if (this.checkBox7.Checked) { TGS.Evaluate("pheatmap(Freqdfhm[1:plotnum,],show_rownames=T,cluster_rows=F)"); } else { TGS.Evaluate("pheatmap(Freqdfhm[1:plotnum,],show_rownames=F,cluster_rows=F)"); } } } } else if (this.comboBox1.SelectedIndex == 6) { double Sum1 = 0; double Sum2 = 0; for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < GroupNum; j++) { Sum1 = Sum1 + app.CountMatrix[i, j]; } for (int j = GroupNum; j < SampleNum - 1; j++) { Sum2 = Sum2 + app.CountMatrix[i, j]; } } TGS.SetSymbol("Sum1", TGS.CreateNumeric(Sum1)); TGS.SetSymbol("Sum2", TGS.CreateNumeric(Sum2)); TGS.Evaluate("R <- Sum1/Sum2"); TGS.Evaluate("treatadd <- R/(R+1)"); TGS.Evaluate("controladd <- 1/(R+1)"); for (int i = 0; i < FeatureNum; i++) { double n11 = 0; double n12 = 0; double n21 = 0; double n22 = 0; for (int j = 0; j < GroupNum; j++) { n11 = n11 + app.Count[i][j]; } for (int j = GroupNum; j < SampleNum - 1; j++) { n21 = n21 + app.Count[i][j]; } if ((n11 < GroupNum) && (n21 < SampleNum - 1 - GroupNum)) { OddRatio.Add(null); absOddRatio.Add(null); } else { n12 = Sum1 - n11; n22 = Sum2 - n21; TGS.SetSymbol("n11", TGS.CreateNumeric(n11)); TGS.SetSymbol("n12", TGS.CreateNumeric(n12)); TGS.SetSymbol("n21", TGS.CreateNumeric(n21)); TGS.SetSymbol("n22", TGS.CreateNumeric(n22)); TGS.Evaluate("odd_ratio <- log2(((n11+treatadd)*(n22+controladd))/((n21+controladd)*(n12+treatadd )))"); OddRatio.Add(double.Parse(TGS.GetSymbol("odd_ratio").ToString())); absOddRatio.Add(Math.Abs(double.Parse(TGS.GetSymbol("odd_ratio").ToString()))); } } List <string> Annotation = new List <string>(); if (this.checkBox1.Checked) { if (this.radioButton1.Checked) { string strConnCOG; strConnCOG = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + System.Windows.Forms.Application.StartupPath + "/COG.xlsx" + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection OleConnCOG = new OleDbConnection(strConnCOG); OleConnCOG.Open(); String sqlCOG = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter OleDaExcelCOG = new OleDbDataAdapter(sqlCOG, OleConnCOG); app.OleDsExcleCOG = new DataSet(); OleDaExcelCOG.Fill(app.OleDsExcleCOG, "Sheet1"); OleConnCOG.Close(); for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < app.OleDsExcleCOG.Tables[0].Rows.Count; j++) { if (string.Equals(FeatureName[i], app.OleDsExcleCOG.Tables[0].Rows[j][0].ToString())) { Annotation.Add(app.OleDsExcleCOG.Tables[0].Rows[j][1].ToString()); } } if (Annotation.Count < i + 1) { Annotation.Add("No Annotation!"); } } } else if (this.radioButton2.Checked) { string strConnPFAM; strConnPFAM = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + System.Windows.Forms.Application.StartupPath + "/PFAM.xlsx" + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection OleConnPFAM = new OleDbConnection(strConnPFAM); OleConnPFAM.Open(); String sqlPFAM = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter OleDaExcelPFAM = new OleDbDataAdapter(sqlPFAM, OleConnPFAM); app.OleDsExclePFAM = new DataSet(); OleDaExcelPFAM.Fill(app.OleDsExclePFAM, "Sheet1"); OleConnPFAM.Close(); for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < app.OleDsExclePFAM.Tables[0].Rows.Count; j++) { if (string.Equals(FeatureName[i], app.OleDsExclePFAM.Tables[0].Rows[j][0].ToString())) { Annotation.Add(app.OleDsExclePFAM.Tables[0].Rows[j][1].ToString()); } } if (Annotation.Count < i + 1) { Annotation.Add("No Annotation!"); } } } } DataTable dt = new DataTable(); dt.Columns.Add("Feature", typeof(string)); for (int i = 0; i < SampleNum; i++) { dt.Columns.Add(SampleName[i], typeof(double));; } dt.Columns.Add("Odd_Ratio", typeof(double)); dt.Columns.Add("abs_Odd_Ratio", typeof(double)); dt.Columns.Add("Annotation", typeof(string)); for (int i = 0; i < FeatureNum; i++) { DataRow dr = dt.NewRow(); dr[0] = FeatureName[i]; for (int j = 1; j <= SampleNum; j++) { dr[j] = app.CountMatrix[i, j - 1]; } if (OddRatio[i] == null) { dr[SampleNum] = DBNull.Value; dr[SampleNum + 1] = DBNull.Value; } else { dr[SampleNum] = OddRatio[i]; dr[SampleNum + 1] = absOddRatio[i]; } if (this.checkBox1.Checked) { dr[SampleNum + 2] = Annotation[i]; } else { dr[SampleNum + 2] = null; } dt.Rows.Add(dr); } DataTable dtCopy = dt.Copy(); DataView dv = dt.DefaultView; dv.Sort = "abs_Odd_Ratio DESC"; dtCopy = dv.ToTable(); Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; Microsoft.Office.Interop.Excel.Range range; long totalCount = dtCopy.Rows.Count; long rowRead = 0; float percent = 0; for (int i = 0; i < dtCopy.Columns.Count; i++) { worksheet.Cells[1, i + 1] = dtCopy.Columns[i].ColumnName; range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]; range.Interior.ColorIndex = 15; range.Font.Bold = true; } for (int r = 0; r < dtCopy.Rows.Count; r++) { for (int i = 0; i < dtCopy.Columns.Count; i++) { worksheet.Cells[r + 2, i + 1] = dtCopy.Rows[r][i].ToString(); } rowRead++; percent = ((float)(100 * rowRead)) / totalCount; } xlApp.Visible = true; } this.Close(); } }
public static void Start(REngine engine) { Console.WriteLine("\n\nImporting Objects\n\n"); string RCodeString = string.Empty; //R character vector -- R.NET RDotNet.CharacterVector RCodeString = "mycharvector<-c(\"hello\",\"bye\",\"OSIsoft\")"; Console.WriteLine("\nR Code: " + RCodeString); engine.Evaluate(RCodeString); CharacterVector myCharacterVector = engine.GetSymbol("mycharvector").AsCharacter(); string[] myStringArray = myCharacterVector.ToArray(); Console.WriteLine("\nmyCharacterVector: "); int i = 1; foreach (string myCharacter in myCharacterVector) { Console.WriteLine(i + " value: " + myCharacter); i++; } //R int vector -- R.NET RDotNet.IntegerVector RCodeString = "myintvector<-1:10"; Console.WriteLine("\nR Code: " + RCodeString); IntegerVector myIntegerVector = engine.Evaluate(RCodeString).AsInteger(); int[] myIntegerArray = myIntegerVector.ToArray(); Console.WriteLine("\nInteger Vector: "); i = 1; foreach (int myInteger in myIntegerVector) { Console.WriteLine(i + " value=" + myInteger); i++; } //R real vector -- R.NET RDotNet.NumericVector RCodeString = "myrealvector<-rnorm(5, 0, 1)"; Console.WriteLine("\nR Code: " + RCodeString); NumericVector myNumericVector = engine.Evaluate(RCodeString).AsNumeric(); double[] myDoubleArray = myNumericVector.ToArray(); Console.WriteLine("\nNumeric Vector: "); i = 1; foreach (double myNumeric in myNumericVector) { Console.WriteLine(i + " value=" + myNumeric); i++; } //R complex vector -- R.NET RDotNet.ComplexVector RCodeString = "mycomplexvector<- 1:2 + 1i*(8:9)"; Console.WriteLine("\nR Code: " + RCodeString); ComplexVector myComplexVector = engine.Evaluate(RCodeString).AsComplex(); Complex[] myComplexArray = myComplexVector.ToArray(); Console.WriteLine("\nComplex Vector: "); i = 1; foreach (Complex myComplex in myComplexVector) { Console.WriteLine(i + " value=" + myComplex.Imaginary + "i + " + myComplex.Real); i++; } //R raw vector -- R.NET RDotNet.RawVector RCodeString = "myrawvector<-charToRaw(\"u03a0\")"; Console.WriteLine("\nR Code: " + RCodeString); RawVector myRawVector = engine.Evaluate(RCodeString).AsRaw(); Console.WriteLine("\nRaw Vector: "); i = 1; foreach (Byte myByte in myRawVector) { Console.WriteLine(i + " value=" + myByte); i++; } //R logical vector -- R.NET RDotNet.LogicalVector RCodeString = "mylogicalvector<-c(FALSE, TRUE, FALSE, TRUE, FALSE)"; Console.WriteLine("\nR Code: " + RCodeString); LogicalVector myLogicalVector = engine.Evaluate("c(FALSE, TRUE, FALSE, TRUE, FALSE)").AsLogical(); Boolean[] myBooleanArray = myLogicalVector.ToArray(); Console.WriteLine("\nLogical Vector: \n"); i = 1; foreach (Boolean myBoolean in myLogicalVector) { Console.WriteLine(i + " value=" + myBoolean.ToString()); i++; } //Close R.NET connection engine.Dispose(); }
private void button3_Click(object sender, EventArgs e) { string filePath = this.textBox2.Text; DataTable dt = new DataTable(); FileStream fs = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); StreamReader sr = new StreamReader(fs, Encoding.UTF8); string strLine = ""; string[] aryLine = null; string[] tableHead = null; int columnCount = 0; bool IsFirst = true; while ((strLine = sr.ReadLine()) != null) { if (IsFirst == true) { tableHead = strLine.Split('\t'); IsFirst = false; columnCount = tableHead.Length; for (int i = 0; i < columnCount; i++) { tableHead[i] = tableHead[i].Replace("\"", ""); DataColumn dc = new DataColumn(tableHead[i]); dt.Columns.Add(dc); } } else { aryLine = strLine.Split('\t'); DataRow dr = dt.NewRow(); for (int j = 0; j < columnCount; j++) { dr[j] = aryLine[j].Replace("\"", ""); } dt.Rows.Add(dr); } } sr.Close(); fs.Close(); app.EFProfile = dt; app.FactorName = new string[app.EFProfile.Columns.Count - 1]; for (int i = 0; i < app.EFProfile.Columns.Count - 1; i++) { app.FactorName[i] = app.EFProfile.Columns[i + 1].ColumnName; } int FactorNum = app.FactorName.GetLength(0); int SampleNum = app.EFProfile.Rows.Count; app.EFMatrix = new double[SampleNum, FactorNum]; for (int i = 0; i < SampleNum; i++) { for (int j = 0; j < FactorNum; j++) { app.EFMatrix[i, j] = Convert.ToDouble(app.EFProfile.Rows[i][j + 1]); } } app.Allid = new List <List <int> >(); app.pvalue = new List <List <double> >(); app.Rvalue = new List <List <double> >(); app.Fvalue = new List <double>(); float alpha = float.Parse(this.textBox1.Text.ToString()); app.alphaen = alpha; if ((app.EFMatrix == null) || (app.SamName.GetLength(0) != SampleNum)) { MessageBox.Show("No Environmental Factors information or improper Environmental Factors information!!", "Warning!!!", MessageBoxButtons.OK); } else { REngine.SetEnvironmentVariables(); REngine EF = REngine.GetInstance(); EF.Initialize(); if (this.checkBox1.Checked) { app.FinalFactorCount = new List <List <double> >(); app.FinalFactorName = new List <string>(); for (int i = 0; i < app.EFMatrix.GetLength(0); i++) { List <double> rowfactor = new List <double>(); for (int j = 0; j < app.EFMatrix.GetLength(1); j++) { rowfactor.Add(app.EFMatrix[i, j]); } for (int j = 0; j < app.EFMatrix.GetLength(1) - 1; j++) { for (int k = j + 1; k < app.EFMatrix.GetLength(1); k++) { rowfactor.Add(app.EFMatrix[i, j] * app.EFMatrix[i, k]); } } app.FinalFactorCount.Add(rowfactor); } for (int i = 0; i < app.FactorName.GetLength(0); i++) { app.FinalFactorName.Add(app.FactorName[i]); } for (int i = 0; i < app.FactorName.GetLength(0); i++) { for (int j = i + 1; j < app.FactorName.GetLength(0); j++) { app.FinalFactorName.Add(app.FactorName[i] + "&" + app.FactorName[j]); } } } else { app.FinalFactorCount = new List <List <double> >(); app.FinalFactorName = new List <string>(); for (int i = 0; i < app.EFMatrix.GetLength(0); i++) { List <double> rowfactor = new List <double>(); for (int j = 0; j < app.EFMatrix.GetLength(1); j++) { rowfactor.Add(app.EFMatrix[i, j]); } app.FinalFactorCount.Add(rowfactor); } for (int i = 0; i < app.FactorName.GetLength(0); i++) { app.FinalFactorName.Add(app.FactorName[i]); } } double[][] Factortemp = new double[app.FinalFactorCount.Count][]; for (int i = 0; i < app.FinalFactorCount.Count; i++) { Factortemp[i] = new double[app.FinalFactorCount[i].Count]; for (int j = 0; j < app.FinalFactorCount[i].Count; j++) { Factortemp[i][j] = app.FinalFactorCount[i][j]; } } double[][] TFactorCount = app.TMatrix(Factortemp); for (int i = 0; i < TFactorCount.GetLength(0); i++) { double mean = app.MEAN(TFactorCount[i]); double sd = app.sd(TFactorCount[i]); for (int j = 0; j < TFactorCount[i].GetLength(0); j++) { TFactorCount[i][j] = (TFactorCount[i][j] - mean) / sd; } } double[][] Factor = app.TMatrix(TFactorCount); int n = Factor.GetLength(0); for (int i = 1; i < n; i++) { EF.SetSymbol("alpha", EF.CreateNumeric(alpha)); EF.SetSymbol("df1value", EF.CreateNumeric(1)); EF.SetSymbol("df2value", EF.CreateNumeric(i)); EF.Evaluate("Fvalue <- qf(1 - alpha ,df1 = df1value ,df2 = df2value)"); app.Fvalue.Add(EF.GetSymbol("Fvalue").AsNumeric().First()); } for (int l = 0; l < app.FeaName.GetLength(0); l++) { double[] Ynor = new double[app.SamName.GetLength(0)]; for (int i = 0; i < Ynor.GetLength(0); i++) { Ynor[i] = app.CountMatrix[l, i]; } double mean = app.MEAN(Ynor); double sd = app.sd(Ynor); for (int i = 0; i < Ynor.GetLength(0); i++) { Ynor[i] = (Ynor[i] - mean) / sd; } double[][] Y = new double[app.SamName.GetLength(0)][]; for (int i = 0; i < app.SamName.GetLength(0); i++) { Y[i] = new double[1]; Y[i][0] = Ynor[i]; } List <int> idNum = new List <int>(); List <double> rowP = new List <double>(); List <double> rowR = new List <double>(); double[][] whole = new double[Factor.GetLength(0)][]; for (int i = 0; i < whole.GetLength(0); i++) { whole[i] = new double[Factor[i].GetLength(0) + 1]; for (int j = 0; j < Factor[i].GetLength(0); j++) { whole[i][j] = Factor[i][j]; } whole[i][Factor[i].GetLength(0)] = Y[i][0]; } double[][] Rmatrix = new double[Factor[0].GetLength(0) + 1][]; for (int i = 0; i < Rmatrix.GetLength(0); i++) { Rmatrix[i] = new double[Rmatrix.GetLength(0)]; } Rmatrix = app.Cormatrix(whole); while (app.Add_Factors(Factor, Y, alpha, Rmatrix, idNum) != 0) { int addindex = app.Add_Factors(Factor, Y, alpha, Rmatrix, idNum); idNum.Add(addindex); Rmatrix = app.Rconvert(Rmatrix, addindex); if (app.Delete_Factors(Factor, Y, alpha, Rmatrix, idNum) != 0) { int deletindex = app.Delete_Factors(Factor, Y, alpha, Rmatrix, idNum); for (int i = 0; i < idNum.Count; i++) { if (idNum[i] == deletindex) { idNum.RemoveAt(i); } } Rmatrix = app.Rconvert(Rmatrix, deletindex); while (app.Check_Factors(Factor, Y, alpha, Rmatrix, idNum) != 0) { deletindex = app.Check_Factors(Factor, Y, alpha, Rmatrix, idNum); for (int i = 0; i < idNum.Count; i++) { if (idNum[i] == deletindex) { idNum.RemoveAt(i); } } Rmatrix = app.Rconvert(Rmatrix, deletindex); } } } int p = idNum.Count; for (int i = 0; i < idNum.Count; i++) { double u = Math.Pow(Rmatrix[idNum[i] - 1][Rmatrix[0].GetLength(0) - 1], 2) / Rmatrix[idNum[i] - 1][idNum[i] - 1]; double f = u / (Rmatrix[Rmatrix.GetLength(0) - 1][Rmatrix[0].GetLength(0) - 1] / (n - p - 1)); EF.SetSymbol("Fvalue", EF.CreateNumeric(f)); EF.SetSymbol("df1value", EF.CreateNumeric(1)); EF.SetSymbol("df2value", EF.CreateNumeric(n - p - 1)); EF.Evaluate("pvalue <- 1 - pf(Fvalue , df1 = df1value , df2 = df2value)"); rowP.Add(EF.GetSymbol("pvalue").AsNumeric().First()); double[] x = new double[n]; double[] y = new double[n]; double[] xy = new double[n]; double[] xx = new double[n]; double[] yy = new double[n]; for (int k = 0; k < n; k++) { x[k] = app.FinalFactorCount[k][idNum[i] - 1]; y[k] = app.CountMatrix[l, k]; xx[k] = app.FinalFactorCount[k][idNum[i] - 1] * app.FinalFactorCount[k][idNum[i] - 1]; yy[k] = app.CountMatrix[l, k] * app.CountMatrix[l, k]; xy[k] = app.FinalFactorCount[k][idNum[i] - 1] * app.CountMatrix[l, k]; } double R = (app.MEAN(xy) - app.MEAN(x) * app.MEAN(y)) / Math.Sqrt((app.MEAN(xx) - app.MEAN(x) * app.MEAN(x)) * (app.MEAN(yy) - app.MEAN(y) * app.MEAN(y))); double R_square = R * R; rowR.Add(R_square); } app.Allid.Add(idNum); app.pvalue.Add(rowP); app.Rvalue.Add(rowR); } app.B = new double[app.FeaName.GetLength(0)][][]; for (int i = 0; i < app.FeaName.GetLength(0); i++) { app.B[i] = new double[app.FinalFactorName.Count + 1][]; for (int j = 0; j < app.FinalFactorName.Count + 1; j++) { app.B[i][j] = new double[1]; } } app.T = new double[app.FeaName.GetLength(0)][]; for (int i = 0; i < app.FeaName.GetLength(0); i++) { app.T[i] = new double[app.FinalFactorName.Count + 1]; } app.P = new double[app.FeaName.GetLength(0)]; app.R_square = new double[app.FeaName.GetLength(0)]; for (int j = 0; j < app.FeaName.GetLength(0); j++) { if (app.Allid[j].Count != 0) { double[][] X = new double[app.FinalFactorCount.Count][]; for (int i = 0; i < X.Length; i++) { X[i] = new double[app.Allid[j].Count + 1]; X[i][0] = 1; for (int k = 1; k <= app.Allid[j].Count; k++) { X[i][k] = app.FinalFactorCount[i][app.Allid[j][k - 1] - 1]; } } double[][] Y = new double[app.SamName.GetLength(0)][]; for (int i = 0; i < app.SamName.GetLength(0); i++) { Y[i] = new double[1]; Y[i][0] = app.CountMatrix[j, i]; } double[][] B = new double[app.FinalFactorName.Count + 1][]; for (int i = 0; i < app.FinalFactorName.Count + 1; i++) { B[i] = new double[1]; } double[][] C = new double[app.FinalFactorName.Count + 1][]; for (int i = 0; i < app.FinalFactorName.Count + 1; i++) { C[i] = new double[app.FinalFactorName.Count + 1]; } double[][] E = new double[app.SamName.GetLength(0)][]; for (int i = 0; i < app.SamName.GetLength(0); i++) { E[i] = new double[1]; } C = app.InverseMatrix(app.MultipleMatrix(app.TMatrix(X), X)); B = app.MultipleMatrix(app.MultipleMatrix(C, app.TMatrix(X)), Y); app.B[j] = B; E = app.MinusMatrix(Y, app.MultipleMatrix(X, B)); double sigma = 0; for (int i = 0; i < app.SamName.GetLength(0); i++) { sigma = sigma + Math.Pow(E[i][0], 2); } sigma = Math.Sqrt(sigma / (app.SamName.GetLength(0) - app.FactorName.GetLength(0) - 1)); for (int i = 0; i < app.Allid[j].Count + 1; i++) { app.T[j][i] = Math.Abs(B[i][0] / (sigma * Math.Sqrt(C[i][i]))); } double y_mean = 0; double[][] y_predict = new double[app.SamName.GetLength(0)][]; for (int i = 0; i < app.SamName.GetLength(0); i++) { y_predict[i] = new double[1]; } for (int i = 0; i < app.SamName.GetLength(0); i++) { y_mean = y_mean + Y[i][0]; } y_mean = y_mean / (app.SamName.GetLength(0)); y_predict = app.MultipleMatrix(X, B); double SSR = 0; double SSE = 0; for (int i = 0; i < app.SamName.GetLength(0); i++) { SSR = SSR + Math.Pow((y_predict[i][0] - y_mean), 2); } for (int i = 0; i < app.SamName.GetLength(0); i++) { SSE = SSE + Math.Pow((Y[i][0] - y_predict[i][0]), 2); } double F = (SSR / (app.FinalFactorName.Count)) / (SSE / (app.SamName.GetLength(0) - app.FinalFactorName.Count - 1)); int p = app.Allid[j].Count; EF.SetSymbol("Fvalue", EF.CreateNumeric(F)); EF.SetSymbol("df1value", EF.CreateNumeric(p)); EF.SetSymbol("df2value", EF.CreateNumeric(n - p - 1)); EF.Evaluate("pvalue_whole <- 1 - pf(Fvalue , df1 = df1value , df2 = df2value)"); app.P[j] = EF.GetSymbol("pvalue_whole").AsNumeric().First(); double SST = SSR + SSE; app.R_square[j] = SSR / SST; if (app.P[j] >= alpha) { app.P[j] = 2; app.R_square[j] = 2; } } else { app.P[j] = 2; app.R_square[j] = 2; } } app.EFAcheck = this.checkBox2.Checked; app.EFAradio1 = this.radioButton1.Checked; app.EFAradio2 = this.radioButton2.Checked; Environment_Output f14 = new Environment_Output(); f14.MdiParent = this.MdiParent; f14.Show(); this.Close(); } }
void LoadPlot() { PlotModel plot = new PlotModel() { LegendSymbolLength = 24.0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Inside, LegendPosition = LegendPosition.TopCenter, LegendBackground = OxyColor.FromAColor(200, OxyColors.White), LegendBorder = OxyColors.Black }; var x_axis = new OxyPlot.Axes.DateTimeAxis { Position = OxyPlot.Axes.AxisPosition.Bottom, MajorStep = 50, Title = "Date", StringFormat = "yyyyMMdd", MajorGridlineStyle = LineStyle.Solid, MinorGridlineStyle = LineStyle.Dot }; x_axis.TextColor = OxyColors.White; x_axis.TitleColor = OxyColors.White; plot.Axes.Add(x_axis); var y_axis = new OxyPlot.Axes.LinearAxis { Position = OxyPlot.Axes.AxisPosition.Left, Title = "Price", MajorGridlineStyle = LineStyle.Solid, MinorGridlineStyle = LineStyle.Dot }; y_axis.TextColor = OxyColors.White; y_axis.TitleColor = OxyColors.White; plot.Axes.Add(y_axis); try { CharacterVector symbol = _engine.CreateCharacterVector(new[] { _symbol }); CharacterVector from = _engine.CreateCharacterVector(new[] { _fromdate }); CharacterVector to = _engine.CreateCharacterVector(new[] { _todate }); _engine.SetSymbol("symbol", symbol); _engine.SetSymbol("from", from); _engine.SetSymbol("to", to); _engine.Evaluate("getSymbols(symbol, from=from, to=to)"); NumericMatrix bars = _engine.GetSymbol(_symbol).AsNumericMatrix(); // 1970-01-01 = 0 DateTime rootdate = new DateTime(1970, 1, 1); IntegerVector dates = _engine.Evaluate("index(" + _symbol + ")").AsInteger(); CandleStickSeries candleStickSeries = new CandleStickSeries { Title = _symbol, CandleWidth = 5, Color = OxyColors.DarkGray, IncreasingFill = OxyColors.DarkGreen, DecreasingFill = OxyColors.Red, TrackerFormatString = "Date: {1:yyyyMMdd}\nHigh: {2:0.00}\nLow: {3:0.00}\nOpen: {4:0.00}\nClose: {5:0.00}" }; // add to bars for (int i = 0; i < dates.Count(); i++) { DateTime d = rootdate.AddDays(dates[i]); int dint = TradingBase.Util.ToIntDate(d); candleStickSeries.Items.Add(new HighLowItem(OxyPlot.Axes.DateTimeAxis.ToDouble(d), bars[i, 1], bars[i, 2], bars[i, 0], bars[i, 3])); } plot.Series.Add(candleStickSeries); MyPlot = plot; } catch (Exception e) { Console.WriteLine(e.Message); } }
private void button4_Click(object sender, EventArgs e) { int FeatureNum = app.FeaName.GetLength(0); int SampleNum = app.SamName.GetLength(0); List <double> prob = new List <double>(); List <double> stat = new List <double>(); List <double> pvalue = new List <double>(); double[] bonferroni = new double[FeatureNum]; double[] fdr = new double[FeatureNum]; //int length; int NAnum = 0; REngine.SetEnvironmentVariables(); REngine MSS = REngine.GetInstance(); MSS.Initialize(); NumericMatrix Freq = MSS.CreateNumericMatrix(app.FreqMatrix); MSS.SetSymbol("Freq", Freq); NumericMatrix Count = MSS.CreateNumericMatrix(app.CountMatrix); MSS.SetSymbol("Count", Count); CharacterVector SampleName = MSS.CreateCharacterVector(app.SamName); CharacterVector FeatureName = MSS.CreateCharacterVector(app.FeaName); MSS.SetSymbol("FeatureName", FeatureName); MSS.SetSymbol("SampleName", SampleName); List <string> SampleNameFreq = new List <string>(); for (int i = 0; i < SampleNum; i++) { SampleNameFreq.Add(SampleName[i] + "Freq"); } IntegerVector RFeaNum = MSS.CreateInteger(FeatureNum); NumericVector Ralpha = MSS.CreateNumeric(double.Parse(this.textBox1.Text.ToString())); MSS.SetSymbol("n", RFeaNum); MSS.SetSymbol("alpha", Ralpha); List <List <double> > Freqtemp = new List <List <double> >(); List <double> FreqSum = new List <double>(); MSS.Evaluate("leastnum = ceiling ( qnorm(alpha/2)^2 )"); double leastnum = MSS.Evaluate("leastnum").AsNumeric().First(); if (this.comboBox1.SelectedIndex == 0) { for (int i = 0; i < FeatureNum; i++) { pvalue.Add(100); for (int j = 0; j < SampleNum - 1; j++) { for (int k = j + 1; k < SampleNum; k++) { double probtemp = (app.CountMatrix[i, j] + app.CountMatrix[i, k]) / (app.SampleTotal[j] + app.SampleTotal[k]); double stattemp = (app.FreqMatrix[i, j] - app.FreqMatrix[i, k]) / Math.Sqrt(probtemp * (1 - probtemp) * (1 / app.SampleTotal[j] + 1 / app.SampleTotal[k])); if (double.IsNaN(stattemp)) { stattemp = 0; } NumericVector Rstat = MSS.CreateNumeric(stattemp); MSS.SetSymbol("stat", Rstat); MSS.Evaluate("p.value <- 2*(pnorm(-abs(stat)))"); double pvaluetemp; if ((this.comboBox2.SelectedIndex == 1) && (app.CountMatrix[i, j] < leastnum) && (app.CountMatrix[i, k] < leastnum)) { pvaluetemp = 100; } else { pvaluetemp = MSS.GetSymbol("p.value").AsNumeric().First(); } if (pvaluetemp != 100) { pvalue[i] = Math.Min((double)pvalue[i], (double)pvaluetemp); } } } } NumericVector Rpvalue = MSS.CreateNumericVector(pvalue); MSS.SetSymbol("p.value", Rpvalue); MSS.Evaluate("NAnum = length(p.value[p.value == 100])"); NAnum = Convert.ToInt32(MSS.GetSymbol("NAnum").AsNumeric().First()); MSS.Evaluate("p.value[p.value == 100] = NA"); MSS.Evaluate("bonferroni.p <- p.adjust(p.value,\"bonferroni\")"); MSS.Evaluate("bonferroni.p[which(bonferroni.p == NA)] = 100"); MSS.Evaluate("fdr.p <- p.adjust(p.value,\"fdr\")"); MSS.Evaluate("fdr.p[which(fdr.p == NA)] = 100"); for (int i = 0; i < FeatureNum; i++) { bonferroni[i] = MSS.GetSymbol("bonferroni.p").AsNumeric()[i]; fdr[i] = MSS.GetSymbol("fdr.p").AsNumeric()[i]; } } else if (this.comboBox1.SelectedIndex == 1) { for (int i = 0; i < FeatureNum; i++) { pvalue.Add(100); } for (int j = 0; j < SampleNum - 1; j++) { for (int k = 1; k < SampleNum; k++) { double Sum1 = 0; double Sum2 = 0; for (int i = 0; i < FeatureNum; i++) { Sum1 = Sum1 + app.CountMatrix[i, j]; Sum2 = Sum2 + app.CountMatrix[i, k]; } for (int i = 0; i < FeatureNum; i++) { NumericVector n11 = MSS.CreateNumeric(app.CountMatrix[i, j]); NumericVector n21 = MSS.CreateNumeric(app.CountMatrix[i, k]); NumericVector n12 = MSS.CreateNumeric(Sum1 - app.CountMatrix[i, j]); NumericVector n22 = MSS.CreateNumeric(Sum2 - app.CountMatrix[i, k]); MSS.SetSymbol("n11", n11); MSS.SetSymbol("n12", n12); MSS.SetSymbol("n21", n21); MSS.SetSymbol("n22", n22); MSS.Evaluate("compare <- matrix(c(n11,n12,n21,n22),nr=2)"); MSS.Evaluate("p.value <- fisher.test(compare)$p.value"); double pvaluetemp = MSS.GetSymbol("p.value").AsNumeric().First(); pvalue[i] = Math.Min((double)pvalue[i], (double)pvaluetemp); } } } MSS.Evaluate("bonferroni.p <- p.adjust(p.value,\"bonferroni\")"); MSS.Evaluate("fdr.p <- p.adjust(p.value,\"fdr\")"); for (int i = 0; i < FeatureNum; i++) { bonferroni[i] = MSS.GetSymbol("bonferroni.p").AsNumeric()[i]; fdr[i] = MSS.GetSymbol("fdr.p").AsNumeric()[i]; } } List <string> Annotation = new List <string>(); if (this.checkBox1.Checked) { if (this.radioButton2.Checked) { string strConnCOG; strConnCOG = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + System.Windows.Forms.Application.StartupPath + "/COG.xlsx" + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection OleConnCOG = new OleDbConnection(strConnCOG); OleConnCOG.Open(); String sqlCOG = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter OleDaExcelCOG = new OleDbDataAdapter(sqlCOG, OleConnCOG); app.OleDsExcleCOG = new DataSet(); OleDaExcelCOG.Fill(app.OleDsExcleCOG, "Sheet1"); OleConnCOG.Close(); for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < app.OleDsExcleCOG.Tables[0].Rows.Count; j++) { if (string.Equals(FeatureName[i], app.OleDsExcleCOG.Tables[0].Rows[j][0].ToString())) { Annotation.Add(app.OleDsExcleCOG.Tables[0].Rows[j][1].ToString()); } } if (Annotation.Count < i + 1) { Annotation.Add("No Annotation!"); } } } else if (this.radioButton1.Checked) { string strConnPFAM; strConnPFAM = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + System.Windows.Forms.Application.StartupPath + "/PFAM.xlsx" + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection OleConnPFAM = new OleDbConnection(strConnPFAM); OleConnPFAM.Open(); String sqlPFAM = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter OleDaExcelPFAM = new OleDbDataAdapter(sqlPFAM, OleConnPFAM); app.OleDsExclePFAM = new DataSet(); OleDaExcelPFAM.Fill(app.OleDsExclePFAM, "Sheet1"); OleConnPFAM.Close(); for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < app.OleDsExclePFAM.Tables[0].Rows.Count; j++) { if (string.Equals(FeatureName[i], app.OleDsExclePFAM.Tables[0].Rows[j][0].ToString())) { Annotation.Add(app.OleDsExclePFAM.Tables[0].Rows[j][1].ToString()); } } if (Annotation.Count < i + 1) { Annotation.Add("No Annotation!"); } } } } DataTable dt = new DataTable(); dt.Columns.Add("Feature", typeof(string)); for (int i = 0; i < SampleNum; i++) { dt.Columns.Add(app.SamName[i], typeof(double)); } dt.Columns.Add("p.value", typeof(double)); dt.Columns.Add("bonferroni.p", typeof(double)); dt.Columns.Add("fdr.p", typeof(double)); dt.Columns.Add("Annotation", typeof(string)); for (int i = 0; i < SampleNum; i++) { dt.Columns.Add(SampleNameFreq[i], typeof(double)); } for (int i = 0; i < FeatureNum; i++) { DataRow dr = dt.NewRow(); dr[0] = FeatureName[i]; for (int j = 1; j < SampleNum + 1; j++) { dr[j] = app.CountMatrix[i, j - 1]; } if (pvalue[i] == 100) { dr[SampleNum + 1] = DBNull.Value; dr[SampleNum + 2] = DBNull.Value; dr[SampleNum + 3] = DBNull.Value; } else { dr[SampleNum + 1] = pvalue[i]; dr[SampleNum + 2] = bonferroni[i]; dr[SampleNum + 3] = fdr[i]; } if (this.checkBox1.Checked) { dr[SampleNum + 4] = Annotation[i]; } else { dr[SampleNum + 4] = null; } for (int j = 0; j < SampleNum; j++) { dr[j + SampleNum + 5] = app.FreqMatrix[i, j]; } dt.Rows.Add(dr); } DataTable dtCopy = dt.Copy(); DataTable dttemp = dt.Copy(); dttemp.Clear(); DataView dv = dt.DefaultView; dv.Sort = "p.value"; dtCopy = dv.ToTable(); for (int i = 0; i < NAnum; i++) { DataRow row = dtCopy.Rows[i]; dttemp.Rows.Add(row.ItemArray); } for (int i = 0; i < NAnum; i++) { dtCopy.Rows.RemoveAt(0); } dtCopy.Merge(dttemp); Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; Microsoft.Office.Interop.Excel.Range range; long totalCount = dtCopy.Rows.Count; long rowRead = 0; float percent = 0; for (int i = 0; i < dtCopy.Columns.Count - SampleNum; i++) { worksheet.Cells[1, i + 1] = dtCopy.Columns[i].ColumnName; range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]; range.Interior.ColorIndex = 15; range.Font.Bold = true; } for (int r = 0; r < dtCopy.Rows.Count; r++) { for (int i = 0; i < dtCopy.Columns.Count - SampleNum; i++) { worksheet.Cells[r + 2, i + 1] = dtCopy.Rows[r][i].ToString(); } rowRead++; percent = ((float)(100 * rowRead)) / totalCount; } xlApp.Visible = true; int pnum = 0; for (int i = 0; i < FeatureNum; i++) { try { if (double.Parse(dtCopy.Rows[i][SampleNum].ToString()) < double.Parse(this.textBox1.Text.ToString())) { pnum++; } } catch { } } double[,] df = new double[Math.Min(10, FeatureNum), SampleNum]; for (int i = 0; i < Math.Min(10, FeatureNum); i++) { for (int j = 0; j < SampleNum; j++) { df[i, j] = double.Parse(dtCopy.Rows[i][SampleNum + 5 + j].ToString()); } } if (this.checkBox2.Checked) { string[] rownamesdf = new string[Math.Min(10, FeatureNum)]; for (int i = 0; i < Math.Min(10, FeatureNum); i++) { rownamesdf[i] = dtCopy.Rows[i][0].ToString(); } CharacterVector Rrownamesdf = MSS.CreateCharacterVector(rownamesdf); MSS.SetSymbol("Rownamedf", Rrownamesdf); NumericMatrix Rdf = MSS.CreateNumericMatrix(df); MSS.SetSymbol("Freqdf", Rdf); NumericVector RRow = MSS.CreateNumeric(Math.Min(10, FeatureNum)); MSS.SetSymbol("selrow", RRow); MSS.Evaluate("Freqdf <- as.data.frame(Freqdf)"); MSS.Evaluate("rownames(Freqdf) <- Rownamedf"); MSS.Evaluate("colnames(Freqdf) <- SampleName"); MSS.Evaluate("colournum <- rainbow(dim(Freqdf)[2])"); MSS.Evaluate("plotdata <- t(Freqdf)"); MSS.Evaluate("windows()"); MSS.Evaluate("barplot(plotdata,main=\"features with top varition\",ylab=\"Freq\",beside=TRUE,horiz=FALSE, cex.names=0.6,col=colournum)"); MSS.Evaluate("legend(\"topright\",SampleName,fill=colournum)"); } if (pnum > 0) { double[,] dfall = new double[pnum, SampleNum]; for (int i = 0; i < pnum; i++) { for (int j = 0; j < SampleNum; j++) { dfall[i, j] = double.Parse(dtCopy.Rows[i][SampleNum + 5 + j].ToString()); } } string[] rownamesall = new string[pnum]; for (int i = 0; i < pnum; i++) { rownamesall[i] = dtCopy.Rows[i][0].ToString(); } CharacterVector Rrownamesall = MSS.CreateCharacterVector(rownamesall); MSS.SetSymbol("Rownameall", Rrownamesall); NumericMatrix Rdfall = MSS.CreateNumericMatrix(dfall); MSS.SetSymbol("Freqdfall", Rdfall); NumericVector RRowall = MSS.CreateNumeric(pnum); MSS.SetSymbol("selrowall", RRowall); MSS.Evaluate("Freqdfall <- as.data.frame(Freqdfall)"); MSS.Evaluate("rownames(Freqdfall) <- Rownameall"); MSS.Evaluate("colnames(Freqdfall) <- SampleName"); MSS.Evaluate("distance <- as.dist(1-abs(cor(Freqdfall)))"); if (this.checkBox3.Checked) { MSS.Evaluate("fit <- cmdscale(distance, eig=TRUE, k=2)"); MSS.Evaluate("x <- fit$points[,1]"); MSS.Evaluate("y <- fit$points[,2]"); MSS.Evaluate("minx <- min(x)"); MSS.Evaluate("miny <- min(y)"); MSS.Evaluate("maxx <- max(x)"); MSS.Evaluate("maxy <- max(y)"); MSS.Evaluate("randx <- maxx - minx"); MSS.Evaluate("randy <- maxy - miny"); MSS.Evaluate("llimx <- minx - randx/10"); MSS.Evaluate("hlimx <- maxx + randx/3"); MSS.Evaluate("llimy <- miny - randy/10"); MSS.Evaluate("hlimy <- maxy + randy/3"); MSS.Evaluate("windows()"); MSS.Evaluate("plot(x,y,xlab=\"Coordinate 1\",ylab=\"Coordinate 2\",main=\"MDS\", pch=c(0,1,2,5,6), col=rainbow(7), type=\"p\",xlim = c(llimx,hlimx), ylim = c(llimy,hlimy))"); if (this.comboBox3.SelectedIndex == 0) { MSS.Evaluate("legend(\"topright\",colnames(Freqdfall),pch=c(0,1,2,5,6),col=rainbow(7),cex = 0.8)"); } else if (this.comboBox3.SelectedIndex == 1) { MSS.Evaluate("text(x,y,labels=SampleName,pos=4)"); } } if (this.checkBox4.Checked) { MSS.Evaluate("windows()"); MSS.Evaluate("plot(hclust(distance),main =\"Samples Clust\")"); } } else { MessageBox.Show("No differntially abundant features!!"); } if (this.checkBox5.Checked) { int Rownum = 0; for (int i = 0; i < FeatureNum; i++) { double tempSum = 0; double tempMean = 0; for (int j = 0; j < SampleNum; j++) { tempSum = tempSum + app.FreqMatrix[i, j]; } tempMean = tempSum / (SampleNum); if (tempSum > 0) { FreqSum.Add(tempSum); List <double> tempRow = new List <double>(); for (int j = 0; j < SampleNum; j++) { tempRow.Add(app.FreqMatrix[i, j] / tempMean); } Freqtemp.Add(tempRow); Rownum = Rownum + 1; } } for (int i = 0; i < Rownum; i++) { for (int j = 0; j < SampleNum; j++) { Freqtemp[i][j] = Math.Log(Freqtemp[i][j], 2); if (Freqtemp[i][j] > 1) { Freqtemp[i][j] = 1; } else if (Freqtemp[i][j] < -1) { Freqtemp[i][j] = -1; } } } double[,] dfhm = new double[Math.Min(500, Rownum), SampleNum]; for (int i = 0; i < Math.Min(500, Rownum); i++) { for (int j = 0; j < SampleNum; j++) { dfhm[i, j] = double.Parse(Freqtemp[i][j].ToString()); } } string[] rownameshm = new string[Math.Min(500, Rownum)]; for (int i = 0; i < Math.Min(500, Rownum); i++) { rownameshm[i] = dtCopy.Rows[i][0].ToString(); } CharacterVector Rrownameshm = MSS.CreateCharacterVector(rownameshm); MSS.SetSymbol("Rownamehm", Rrownameshm); NumericMatrix Rdfhm = MSS.CreateNumericMatrix(dfhm); MSS.SetSymbol("Freqdfhm", Rdfhm); NumericVector RRowhm = MSS.CreateNumeric(Math.Min(500, Rownum)); MSS.SetSymbol("plotnum", RRowhm); MSS.Evaluate("Freqdfhm <- as.data.frame(Freqdfhm)"); MSS.Evaluate("rownames(Freqdfhm) <- Rownamehm"); MSS.Evaluate("colnames(Freqdfhm) <- SampleName"); MSS.Evaluate("Freqdfhm <- as.matrix(Freqdfhm)"); MSS.Evaluate("library(pheatmap)"); MSS.Evaluate("windows()"); if (this.checkBox6.Checked) { if (this.checkBox7.Checked) { MSS.Evaluate("pheatmap(Freqdfhm[1:plotnum,],show_rownames=T,cluster_rows=T)"); } else { MSS.Evaluate("pheatmap(Freqdfhm[1:plotnum,],show_rownames=F,cluster_rows=T)"); } } else { if (this.checkBox7.Checked) { MSS.Evaluate("pheatmap(Freqdfhm[1:plotnum,],show_rownames=T,cluster_rows=F)"); } else { MSS.Evaluate("pheatmap(Freqdfhm[1:plotnum,],show_rownames=F,cluster_rows=F)"); } } } this.Close(); }
private void button4_Click(object sender, EventArgs e) { int FeatureNum = app.FeaName.GetLength(0); int SampleNum = app.SamName.GetLength(0); List <double> prob = new List <double>(); List <double> stat = new List <double>(); List <double> pvalue = new List <double>(); double[] bonferroni = new double[FeatureNum]; double[] fdr = new double[FeatureNum]; int NAnum = 0; if (SampleNum == 2) { REngine.SetEnvironmentVariables(); REngine TSS = REngine.GetInstance(); TSS.Initialize(); NumericMatrix Freq = TSS.CreateNumericMatrix(app.FreqMatrix); TSS.SetSymbol("Freq", Freq); NumericMatrix Count = TSS.CreateNumericMatrix(app.CountMatrix); TSS.SetSymbol("Count", Count); CharacterVector SampleName = TSS.CreateCharacterVector(app.SamName); CharacterVector FeatureName = TSS.CreateCharacterVector(app.FeaName); TSS.SetSymbol("FeatureName", FeatureName); TSS.SetSymbol("SampleName", SampleName); List <string> SampleNameFreq = new List <string>(); for (int i = 0; i < SampleNum; i++) { SampleNameFreq.Add(SampleName[i] + "Freq"); } IntegerVector RFeaNum = TSS.CreateInteger(FeatureNum); NumericVector Ralpha = TSS.CreateNumeric(double.Parse(this.textBox1.Text.ToString())); TSS.SetSymbol("n", RFeaNum); TSS.SetSymbol("alpha", Ralpha); TSS.Evaluate("leastnum = ceiling ( qnorm(alpha/2)^2 )"); double leastnum = TSS.Evaluate("leastnum").AsNumeric().First(); if (this.comboBox1.SelectedIndex == 0) { for (int i = 0; i < FeatureNum; i++) { double temp = app.FreqMatrix[i, 0] - app.FreqMatrix[i, 1]; prob.Add(temp); double P = (app.CountMatrix[i, 0] + app.CountMatrix[i, 1]) / (app.SampleTotal[0] + app.SampleTotal[1]); double S = Math.Sqrt(P * (1 - P) * (1 / app.SampleTotal[0] + 1 / app.SampleTotal[1])); double temp0 = prob[i] / S; if (double.IsNaN(temp0)) { temp0 = 0; } stat.Add(temp0); } for (int i = 0; i < FeatureNum; i++) { NumericVector Rstat = TSS.CreateNumeric(stat[i]); TSS.SetSymbol("stat", Rstat); TSS.Evaluate("p.value <- 2*(pnorm(-abs(stat)))"); if ((this.comboBox2.SelectedIndex == 1) && (app.CountMatrix[i, 0] < leastnum) && (app.CountMatrix[i, 1] < leastnum)) { pvalue.Add(100); } else { pvalue.Add(TSS.GetSymbol("p.value").AsNumeric().First()); } } NumericVector Rpvalue = TSS.CreateNumericVector(pvalue); TSS.SetSymbol("p.value", Rpvalue); TSS.Evaluate("NAnum = length(p.value[p.value == 100])"); NAnum = Convert.ToInt32(TSS.GetSymbol("NAnum").AsNumeric().First()); TSS.Evaluate("p.value[p.value == 100] = NA"); TSS.Evaluate("bonferroni.p <- p.adjust(p.value,\"bonferroni\")"); TSS.Evaluate("bonferroni.p[which(bonferroni.p == NA)] = 100"); //double[] temp1 = (double[])hc1.GetSymbol("bonferroni.p"); TSS.Evaluate("fdr.p <- p.adjust(p.value,\"fdr\")"); TSS.Evaluate("fdr.p[which(fdr.p == NA)] = 100"); for (int i = 0; i < FeatureNum; i++) { bonferroni[i] = TSS.GetSymbol("bonferroni.p").AsNumeric()[i]; fdr[i] = TSS.GetSymbol("fdr.p").AsNumeric()[i]; } } else if (this.comboBox1.SelectedIndex == 1) { double Sum1 = 0; double Sum2 = 0; for (int i = 0; i < FeatureNum; i++) { Sum1 = Sum1 + app.CountMatrix[i, 0]; Sum2 = Sum2 + app.CountMatrix[i, 1]; } for (int i = 0; i < FeatureNum; i++) { NumericVector n11 = TSS.CreateNumeric(app.CountMatrix[i, 0]); NumericVector n21 = TSS.CreateNumeric(app.CountMatrix[i, 1]); NumericVector n12 = TSS.CreateNumeric(Sum1 - app.CountMatrix[i, 0]); NumericVector n22 = TSS.CreateNumeric(Sum2 - app.CountMatrix[i, 1]); TSS.SetSymbol("n11", n11); TSS.SetSymbol("n12", n12); TSS.SetSymbol("n21", n21); TSS.SetSymbol("n22", n22); TSS.Evaluate("compare <- matrix(c(n11,n12,n21,n22),nr=2)"); TSS.Evaluate("p.value <- fisher.test(compare)$p.value"); pvalue.Add(TSS.GetSymbol("p.value").AsNumeric().First()); } NumericVector Rpvalue = TSS.CreateNumericVector(pvalue); TSS.SetSymbol("p.value", Rpvalue); TSS.Evaluate("bonferroni.p <- p.adjust(p.value,\"bonferroni\")"); TSS.Evaluate("fdr.p <- p.adjust(p.value,\"fdr\")"); for (int i = 0; i < FeatureNum; i++) { bonferroni[i] = TSS.GetSymbol("bonferroni.p").AsNumeric()[i]; fdr[i] = TSS.GetSymbol("fdr.p").AsNumeric()[i]; } } List <string> Annotation = new List <string>(); if (this.checkBox1.Checked) { if (this.radioButton1.Checked) { string strConnCOG; strConnCOG = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + System.Windows.Forms.Application.StartupPath + "/COG.xlsx" + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection OleConnCOG = new OleDbConnection(strConnCOG); OleConnCOG.Open(); String sqlCOG = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter OleDaExcelCOG = new OleDbDataAdapter(sqlCOG, OleConnCOG); app.OleDsExcleCOG = new DataSet(); OleDaExcelCOG.Fill(app.OleDsExcleCOG, "Sheet1"); OleConnCOG.Close(); for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < app.OleDsExcleCOG.Tables[0].Rows.Count; j++) { if (string.Equals(FeatureName[i], app.OleDsExcleCOG.Tables[0].Rows[j][0].ToString())) { Annotation.Add(app.OleDsExcleCOG.Tables[0].Rows[j][1].ToString()); } } if (Annotation.Count < i + 1) { Annotation.Add("No Annotation!"); } } } else if (this.radioButton2.Checked) { string strConnPFAM; strConnPFAM = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + System.Windows.Forms.Application.StartupPath + "/PFAM.xlsx" + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection OleConnPFAM = new OleDbConnection(strConnPFAM); OleConnPFAM.Open(); String sqlPFAM = "SELECT * FROM [Sheet1$]"; OleDbDataAdapter OleDaExcelPFAM = new OleDbDataAdapter(sqlPFAM, OleConnPFAM); app.OleDsExclePFAM = new DataSet(); OleDaExcelPFAM.Fill(app.OleDsExclePFAM, "Sheet1"); OleConnPFAM.Close(); for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < app.OleDsExclePFAM.Tables[0].Rows.Count; j++) { if (string.Equals(FeatureName[i], app.OleDsExclePFAM.Tables[0].Rows[j][0].ToString())) { Annotation.Add(app.OleDsExclePFAM.Tables[0].Rows[j][1].ToString()); } } if (Annotation.Count < i + 1) { Annotation.Add("No Annotation!"); } } } } DataTable dt = new DataTable(); dt.Columns.Add("Feature", typeof(string)); for (int i = 0; i < SampleNum; i++) { dt.Columns.Add(app.SamName[i], typeof(double)); } dt.Columns.Add("p.value", typeof(double)); dt.Columns.Add("bonferroni.p", typeof(double)); dt.Columns.Add("fdr.p", typeof(double)); dt.Columns.Add("Annotation", typeof(string)); for (int i = 0; i < SampleNum; i++) { dt.Columns.Add(SampleNameFreq[i], typeof(double)); } for (int i = 0; i < FeatureNum; i++) { DataRow dr = dt.NewRow(); dr[0] = FeatureName[i]; for (int j = 1; j < SampleNum + 1; j++) { dr[j] = app.CountMatrix[i, j - 1]; } if (pvalue[i] == 100) { dr[3] = DBNull.Value; dr[4] = DBNull.Value; dr[5] = DBNull.Value; } else { dr[3] = pvalue[i]; dr[4] = bonferroni[i]; dr[5] = fdr[i]; } if (this.checkBox1.Checked) { dr[SampleNum + 4] = Annotation[i]; } else { dr[SampleNum + 4] = null; } for (int j = 0; j < SampleNum; j++) { dr[j + SampleNum + 5] = app.FreqMatrix[i, j]; } dt.Rows.Add(dr); } DataTable dtCopy = dt.Copy(); DataTable dttemp = dt.Copy(); dttemp.Clear(); DataView dv = dt.DefaultView; dv.Sort = "p.value"; dtCopy = dv.ToTable(); for (int i = 0; i < NAnum; i++) { DataRow row = dtCopy.Rows[i]; dttemp.Rows.Add(row.ItemArray); } for (int i = 0; i < NAnum; i++) { dtCopy.Rows.RemoveAt(0); } Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture; System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; Microsoft.Office.Interop.Excel.Range range; long totalCount = dtCopy.Rows.Count; long rowRead = 0; float percent = 0; for (int i = 0; i < dtCopy.Columns.Count - SampleNum; i++) { worksheet.Cells[1, i + 1] = dtCopy.Columns[i].ColumnName; range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1]; range.Interior.ColorIndex = 15; range.Font.Bold = true; } for (int r = 0; r < dtCopy.Rows.Count; r++) { for (int i = 0; i < dtCopy.Columns.Count - SampleNum; i++) { worksheet.Cells[r + 2, i + 1] = dtCopy.Rows[r][i].ToString(); } rowRead++; percent = ((float)(100 * rowRead)) / totalCount; } xlApp.Visible = true; double[,] df = new double[Math.Min(10, FeatureNum), SampleNum]; for (int i = 0; i < Math.Min(10, FeatureNum); i++) { for (int j = 0; j < SampleNum; j++) { df[i, j] = double.Parse(dtCopy.Rows[i][SampleNum + 5 + j].ToString()); } } string[] rownames = new string[Math.Min(10, FeatureNum)]; for (int i = 0; i < Math.Min(10, FeatureNum); i++) { rownames[i] = dtCopy.Rows[i][0].ToString(); } CharacterVector Rrownames = TSS.CreateCharacterVector(rownames); TSS.SetSymbol("Rowname", Rrownames); NumericMatrix Rdf = TSS.CreateNumericMatrix(df); TSS.SetSymbol("Freqdf", Rdf); NumericVector RRow = TSS.CreateNumeric(Math.Min(10, FeatureNum)); TSS.SetSymbol("selrow", RRow); TSS.Evaluate("Freqdf <- as.data.frame(Freqdf)"); TSS.Evaluate("rownames(Freqdf) <- Rowname"); TSS.Evaluate("colnames(Freqdf) <- SampleName"); TSS.Evaluate("colournum <- rainbow(dim(Freqdf)[2])"); TSS.Evaluate("plotdata <- t(Freqdf)"); TSS.Evaluate("windows()"); TSS.Evaluate("barplot(plotdata,main=\"features with top varition\",ylab=\"Freq\",beside=TRUE,horiz=FALSE, cex.names=0.6,col=colournum)"); TSS.Evaluate("legend(\"topright\",SampleName,fill=colournum)"); } else { MessageBox.Show("Sample number is more than two!!"); } this.Close(); }
public DataTable getCorpTable(string Rname, int stocknum) { engine.Initialize(); string fullRFilePath = Path.Combine(currentPath, Rname + ".R"); if (!File.Exists(fullRFilePath)) { return(null); } var curPath = engine.CreateCharacter(currentPath); engine.SetSymbol("stocknum", engine.CreateInteger(stocknum)); engine.SetSymbol("curPath", curPath); engine.Evaluate("setwd(curPath)"); engine.Evaluate(String.Format("source(\"{0}\")", Rname + ".R")); DataFrame output = engine.GetSymbol("output").AsDataFrame(); DataTable table = new DataTable(); table.Columns.Add("Included", typeof(bool)); foreach (var name in output.ColumnNames) { Type t; switch (output[name].Type) { case SymbolicExpressionType.NumericVector: t = typeof(double); break; case SymbolicExpressionType.IntegerVector: t = typeof(Int32); break; case SymbolicExpressionType.CharacterVector: t = typeof(string); break; case SymbolicExpressionType.LogicalVector: t = typeof(bool); break; case SymbolicExpressionType.RawVector: t = typeof(byte); break; default: t = null; break; } table.Columns.Add(name); if (t != null) { table.Columns[name].DataType = t; } } foreach (DataFrameRow row in output.GetRows()) { DataRow newRow = table.Rows.Add(); newRow["Included"] = true; foreach (var name in output.ColumnNames) { if ((output[name].Type == SymbolicExpressionType.NumericVector || output[name].Type == SymbolicExpressionType.IntegerVector) && !(name.Contains("현재가") || name.Contains("배당") || name.Contains("RANK"))) { newRow[name] = (double.Parse(row[name].ToString())) / 1e8; } else { newRow[name] = row[name]; } } } return(table); }