//Engine.Evaluate($"png('{ImagePath.Replace('\\', '/') + imagePath + ".png"}', {900}, {600})"); internal static double[] GenerateNormalDistribution(double min, double max, int numberOfFeatures) { try { /* Engine.Evaluate($"rnorm.between <- function(n, minimum = 0, maximum = 1)"); * Engine.Evaluate("{"); * Engine.Evaluate($"x <- rnorm(n)"); * Engine.Evaluate($"max_x <- max(x)"); * Engine.Evaluate($"min_x <- min(x)"); * Engine.Evaluate($"x <- x - min_x"); * Engine.Evaluate($"x <- x / (max_x - min_x)"); * Engine.Evaluate($"x <- x * (maximum - minimum)"); * Engine.Evaluate($"x <- x + minimum"); * Engine.Evaluate($"return (x)"); * Engine.Evaluate("}"); */ //var func = Engine.Evaluate("function (n, min, max) {x <- rnorm(n, mean = 0, sd = 1); x <- x - -3; x <- x / (6); x <- x * (min - max); y <- x + min; return (y) }").AsFunction(); var func = Engine.Evaluate(@"function (n, min, max) { x <- rnorm(n, mean = 0, sd = 1) x <- x - -3 x <- x / (6) x <- x * (max - min) x <- x + min return (x) }").AsFunction(); var param1 = Engine.CreateInteger(numberOfFeatures); var param2 = Engine.CreateNumeric(min); var param3 = Engine.CreateNumeric(max); return(func.Invoke(new SymbolicExpression[] { param1, param2, param3 }).AsNumeric().ToArray()); //return Engine.Evaluate($"result <- rnorm.between({numberOfFeatures}, {min}, {max})").AsNumeric().ToArray(); } catch (Exception e) { Console.WriteLine(e.ToString()); return(new double[] { 0 }); } }
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)); }
public override void SetSymbol(REngine rEngine, string name, object value) { rEngine.SetSymbol(name, rEngine.CreateInteger((int)value)); }
private void runTask() { string basedir = AppDomain.CurrentDomain.BaseDirectory; string mapPath = basedir + "/tmp/"; // string mapPath = HttpContext.Current.Server.MapPath("~/tmp/"); REngine engine = Utils.getREngineInstance(); string primer3path = System.Web.Configuration.WebConfigurationManager.AppSettings["primer3Home"]; string processNum = System.Web.Configuration.WebConfigurationManager.AppSettings["processNum"]; string isDeleteTempDir = System.Web.Configuration.WebConfigurationManager.AppSettings["deleteTempDir"]; while (true) { if (task_queue.Count != 0) { Application.Lock(); CustomTask customTask = (CustomTask)task_queue.Dequeue(); Application.UnLock(); customTask.waitQueue = 0; Object[] task_queue_array = task_queue.ToArray(); for (int i = 0; i < task_queue_array.Length; i++) { CustomTask tmpTask = (CustomTask)task_queue_array[i]; tmpTask.waitQueue = i + 1; } Application["running_task"] = customTask; string fileName = customTask.url; fileName = basedir + "/" + customTask.url; DataTable dt = read_primer_sequence(fileName); string[,] primerMat = getPrimerMat(dt); customTask.status = "preparing ..."; WriteLog(customTask.key, customTask); CharacterMatrix primer = engine.CreateCharacterMatrix(primerMat); string rand_file = System.IO.Path.GetRandomFileName(); string tmp_path = mapPath + rand_file; //string primer3path = "D:/Install/primer3-win-bin-2.3.6"; if (Directory.Exists(tmp_path)) { DirectoryInfo di = new DirectoryInfo(tmp_path); di.Delete(true); } else if (File.Exists(tmp_path)) { FileInfo fi = new FileInfo(tmp_path); fi.Delete(); } Directory.CreateDirectory(tmp_path); engine.Evaluate("library(xlsx)"); customTask.percent = 8; string script_path = basedir + "/primer_dimer_check.R"; script_path = script_path.Replace(@"\", @"/"); engine.Evaluate("source(\"" + script_path + "\")"); customTask.percent = 10; engine.SetSymbol("primer", primer); engine.SetSymbol("tmp_dir", engine.CreateCharacter(tmp_path)); engine.SetSymbol("primer", primer); engine.SetSymbol("primer3dir", engine.CreateCharacter(primer3path)); int?nProcess = Convert.ToInt32(processNum); if (nProcess != null) { engine.SetSymbol("nprocess", engine.CreateInteger(Convert.ToInt32(nProcess))); } else { engine.SetSymbol("nprocess", engine.CreateInteger(4)); } engine.SetSymbol("outputfile", engine.CreateCharacter(fileName)); string[] bat_cmds = engine.Evaluate("prepare_bat(tmp_dir,primer,primer3dir,nprocess)").AsCharacter().ToArray(); customTask.status = "dimer calculating ..."; customTask.percent = 20; WriteLog(customTask.key, customTask); AutoResetEvent[] resets = new AutoResetEvent[bat_cmds.Length]; for (int i = 0; i < bat_cmds.Length; i++) { resets[i] = new AutoResetEvent(false); Global.ThreadTransfer transfer = new Global.ThreadTransfer(bat_cmds[i], resets[i]); Thread thread = new Thread(new ParameterizedThreadStart(run_cmd)); thread.Start(transfer); } foreach (var v in resets) { v.WaitOne(); customTask.percent += 60 / resets.Length; } customTask.status = "result generating ..."; customTask.percent = 80; WriteLog(customTask.key, customTask); engine.Evaluate("output_result(tmp_dir,primer,outputfile)"); if (isDeleteTempDir == "true") { DirectoryInfo di = new DirectoryInfo(tmp_path); di.Delete(true); } customTask.status = "complete"; customTask.percent = 100; WriteLog(customTask.key, customTask); Application["running_task"] = null; } } }
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(); }
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); }
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(); }