public void SetSymbolNumberMatrix(string name, double[,] value) { clsRCmdLog.LogRComment(string.Format("RdnConnectorClass.SetSymbolNumberMatrix:{0}", name)); var sym = _engine.CreateNumericMatrix(value); _engine.SetSymbol(name, sym); }
/// <summary> /// Run PCA in R engine /// </summary> static void PCAR() { const string directoryPath = @"C:\Users\Káťa\Desktop\Diplomka\mesh\meshes"; var matrix = loadFacesR(directoryPath); REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); NumericMatrix group1 = engine.CreateNumericMatrix(matrix); engine.SetSymbol("group1", group1); GenericVector testResult = engine.Evaluate("pr.out=prcomp(group1, scale=TRUE)").AsList(); var eigenVec = testResult["x"].AsNumericMatrix(); engine.Evaluate("pr.out$sdev"); engine.Evaluate("pr.var = pr.out$sdev ^ 2"); engine.Evaluate("pr.var"); engine.Evaluate("pve = pr.var / sum(pr.var)"); engine.Evaluate("pve"); engine.Evaluate("plot(cumsum(pve), xlab='Principal Component', ylab='Cumulative Proportion of Variance Explained', ylim=c(0,1),type='b')"); saveVector(eigenVec); // var eigenVec = testResult["pr.out&x"].AsNumericMatrix(); Console.ReadLine(); }
static void Main(string[] args) { const string directoryPath = @"C:\Users\Káťa\Desktop\Diplomka\mesh\meshes"; var matrix = loadFacesR(directoryPath); REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); NumericMatrix group1 = engine.CreateNumericMatrix(matrix); //List<float>[] faceMatrix = new List<float>[] { }; //double[,] squere = new double[,] { { 13, -4, 2 }, // {-4 , 11 , -2}, {2 , -2 , 8 } }; //runR(squere); //int[] i = new int[] {}; // pokus(); // var matrix = getDataMatrix(directoryPath); // runR(); //REngine.SetEnvironmentVariables(); //REngine engine = REngine.GetInstance(); //// REngine requires explicit initialization. //// You can set some parameters. //engine.Initialize(); //NumericMatrix group1 = engine.CreateNumericMatrix(new double[,] { // { 0, 0, 0, 0, 1 }, // { 0, 0, 0, 1, 1 }, // { 0, 0, 1, 1, 1 }, // { 0, 0, 0, 1, 1 }, // { 0, 0, 0, 0, 1 } //}); //engine.SetSymbol("group1", group1); //GenericVector testResult = engine.Evaluate("eigen(group1)").AsList(); //Console.WriteLine("P-value = {0}", group1); // //.NET Framework array to R vector. //NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 }); //engine.SetSymbol("group1", group1); //// Direct parsing from R script. //NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric(); //// Test difference of mean and get the P-value. //GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList(); //double p = testResult["p.value"].AsNumeric().First(); //Console.WriteLine("Group1: [{0}]", string.Join(", ", group1)); //Console.WriteLine("Group2: [{0}]", string.Join(", ", group2)); //Console.WriteLine("P-value = {0:0.000}", p); //you should always dispose of the REngine properly. // After disposing of the engine, you cannot reinitialize nor reuse it // engine.Dispose(); Console.ReadLine(); }
public static SymbolicExpression CreateDiffTimeMatrix(this REngine engine, TimeSpan[,] data) { var numeric = data.FromTimeSpan(); var sexp = engine.CreateNumericMatrix(numeric); return(sexp.AddDiffTimeAttributes()); }
public static SymbolicExpression CreatePosixctMatrix(this REngine engine, DateTime[,] data) { var numeric = data.ToTicks(out var tzone); var sexp = engine.CreateNumericMatrix(numeric); return(sexp.AddPosixctAttributes(tzone)); }
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)); }
private double[] BhattaDist(int intNClasses, int intNFeatures, IFeatureCursor pFCursor, int intEstIdx, int intVarIdx) { try { frmProgress pfrmProgress = new frmProgress(); if (intNFeatures > MaxFeaturesforPGB) { pfrmProgress.lblStatus.Text = "Calculate Bhattacharyya distance"; pfrmProgress.pgbProgress.Style = ProgressBarStyle.Blocks; pfrmProgress.pgbProgress.Value = 0; pfrmProgress.Show(); } double[] Cs = new double[intNClasses + 1]; arrEst = new double[intNFeatures]; double[] arrVar = new double[intNFeatures]; double[,] arrResults = new double[intNFeatures, intNFeatures]; IFeature pFeature = pFCursor.NextFeature(); int k = 0; while (pFeature != null) { arrEst[k] = Convert.ToDouble(pFeature.get_Value(intEstIdx)); arrVar[k] = Convert.ToDouble(pFeature.get_Value(intVarIdx)); k++; pFeature = pFCursor.NextFeature(); } for (int i = 0; i < intNFeatures; i++) { double dblsquaredVar1 = Math.Pow(arrVar[i], 2); for (int j = 0; j < intNFeatures; j++) { double dblsquaredVar2 = Math.Pow(arrVar[j], 2); double dblVarComp = Math.Log(0.25 * ((dblsquaredVar1 / dblsquaredVar2) + (dblsquaredVar2 / dblsquaredVar1) + 2)); double dblMeanComp = Math.Pow(arrEst[i] - arrEst[j], 2) / (dblsquaredVar1 + dblsquaredVar2); arrResults[i, j] = 0.25 * (dblVarComp + dblMeanComp); } if (intNFeatures > MaxFeaturesforPGB) { pfrmProgress.pgbProgress.Value = (i * 100) / intNFeatures; } } if (intNFeatures > MaxFeaturesforPGB) { pfrmProgress.pgbProgress.Value = 100; pfrmProgress.lblStatus.Text = "Show Results"; } NumericMatrix pBhattaDist = pEngine.CreateNumericMatrix(arrResults); pEngine.SetSymbol("Bhatta.diss", pBhattaDist); pEngine.Evaluate("library(cluster)"); pEngine.Evaluate("kmed.result <- pam(as.dist(Bhatta.diss), diss=TRUE, " + intNClasses.ToString() + ")"); NumericVector pClustering = pEngine.Evaluate("kmed.result$clustering").AsNumeric(); Cs[0] = arrEst.Min(); Cs[intNClasses] = arrEst.Max(); //double[] tempCs = new double[intNClasses + 1]; //tempCs[0] = Cs[0]; //tempCs[intNClasses] = Cs[intNClasses]; for (int i = 0; i < intNFeatures; i++) { for (int j = 1; j < intNClasses; j++) { if (pClustering[i] == j) { double tempClassMax = arrEst[i]; if (tempClassMax > Cs[j]) { Cs[j] = tempClassMax; } } } } pfrmProgress.Close(); return(Cs); } catch (Exception ex) { MessageBox.Show(this.Handle.ToString() + " Error:" + ex.Message); return(null); } }
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(); }
/// <summary> /// Does Arian's PCA-ANOVA idea. /// </summary> public double PcaAnova(IntensityMatrix source, Peak peak, Core core, List <GroupInfo> types, List <int> replicates) { Range times = GetOverlappingTimeRange(core, source, types); // Create a matrix thusly: // Control Replicate 1: <day1> <day2> <day3> ... // Control Replicate 2: <day1> <day2> <day3> ... // Control Replicate 3: <day1> <day2> <day3> ... // Drought Replicate 1: <day1> <day2> <day3> ... // Drought Replicate 2: <day1> <day2> <day3> ... // ... // Create and clear the matrix int rowCount = types.Count * replicates.Count; int colCount = times.Count; double[,] matrix = new double[rowCount, colCount]; for (int r = 0; r < rowCount; r++) { for (int c = 0; c < colCount; c++) { matrix[r, c] = double.NaN; } } // Create the group vector double[] groups = new double[rowCount]; for (int r = 0; r < rowCount; r++) { groups[r] = types[r / replicates.Count].Order; } IReadOnlyList <double> raw = source.Find(peak).Values; // TODO: Dirty // Fill out the values we know for (int i = 0; i < core.Observations.Count; i++) { ObservationInfo o = core.Observations[i]; int typeIndex = types.IndexOf(o.Group); int repIndex = replicates.IndexOf(o.Rep); if (times.Contains(o.Time) && typeIndex != -1 && repIndex != -1) { int timeIndex = o.Time - times.Min; int row = typeIndex * replicates.Count + repIndex; UiControls.Assert(double.IsNaN(matrix[row, timeIndex]), "Duplicate day/time/rep observations in dataset are not allowed."); matrix[row, timeIndex] = raw[i]; } } // Guess missing values for (int r = 0; r < rowCount; r++) { for (int c = 0; c < colCount; c++) { if (double.IsNaN(matrix[r, c])) { // Missing values - average other values for this point int repIndex = r % replicates.Count; int typeStart = r - repIndex; double total = 0; int count = 0; for (int rep = 0; rep < replicates.Count; rep++) { int newRow = typeStart + rep; if (!double.IsNaN(matrix[newRow, c])) { total += matrix[newRow, c]; count += 1; } } matrix[r, c] = total / count; } } } // Now do that R stuff... var rMatrix = _r.CreateNumericMatrix(matrix); var rVector = _r.CreateNumericVector(groups); _r.SetSymbol("a", rMatrix); _r.SetSymbol("g", rVector); //R.Evaluate("write.csv(a, file = \"E:/MJR/Project/05. PEAS/AbstressData/Leaf/Positive/CCor/LP1131.cs.csv\")"); try { double result = _r.Evaluate( @"p = prcomp(a) f = data.frame(y = p$x[,1], group = factor(g)) fit = lm(y ~ group, f) an = anova(fit) pval = an$""Pr(>F)""[1]").AsNumeric()[0]; return(result); } catch (Exception ex) { throw new Exception("Something went wrong calculating PCA-ANOVA statistics. See inner exception for details. (Note that this error can occur if only 1 replicate is specified and PCA-ANOVA is calculated with missing values - make sure the replicates are specified correctly.)", ex); } }
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(); }
static void runR(double[,] square) { REngine.SetEnvironmentVariables(); REngine engine = REngine.GetInstance(); // REngine requires explicit initialization. // You can set some parameters. engine.Initialize(); NumericMatrix group1 = engine.CreateNumericMatrix(square); //NumericMatrix group1 = engine.CreateNumericMatrix(new double[,] { // { 0, 0, 0, 0, 1 }, // { 0, 0, 0, 1, 1 }, // { 0, 0, 1, 1, 1 }, // { 0, 0, 0, 1, 1 }, // { 0, 0, 0, 0, 1 } //}); engine.SetSymbol("group1", group1); GenericVector testResult = engine.Evaluate("eigen(group1)").AsList(); Console.WriteLine(testResult); var hokus = testResult["values"].AsIntegerMatrix(); var eigenValues = testResult["values"].AsNumeric().ToArray(); var vectorOfVectors = testResult["vectors"].AsNumeric(); int indexNextEigenVector = 0; // double[] eigenVectors //for (int i = 0; i < eigenVectors.Length; i++) //{ // if () //} //Array.Sort(eigenValues, eigenVectors); //_allStatInfo.Sort(new Comparison<StatInfo>((x, y) => DateTime.Compare(x.date, y.date))); double sum = eigenValues.Sum(); double[] kumulative = new double[eigenValues.Length]; // bool firstOccurrence = false; int thresholdIndex = -1; double thresholdValue = 0.6; for (int i = 0; i < eigenValues.Length; i++) { double normalize = eigenValues[i] / sum; if (i == 0) { kumulative[i] = normalize; } else { kumulative[i] = normalize + kumulative[i - 1]; } if (kumulative[i] >= thresholdValue && firstOccurrence == false) { firstOccurrence = true; thresholdIndex = i; } } // engine.Evaluate("plot(group2, type = 'l', col = 'red', lwd = 10,ylab='eigen values')"); var normalizeEigenVaules = engine.CreateNumericVector(kumulative); engine.SetSymbol("v", normalizeEigenVaules); // ylim = c(0, 1),type = 'b') engine.Evaluate("plot(v, type = 'l', col = 'red', lwd = 10,ylab='eigen values',type = 'b')"); var hokz = testResult["values"].AsList().ToArray(); Console.WriteLine("P-value = {0}", hokus[1, 0]); // return eigenValues; }
private void btnGenerate_Click(object sender, EventArgs e) { try { frmProgress pfrmProgress = new frmProgress(); pfrmProgress.lblStatus.Text = "Processing:"; pfrmProgress.Show(); int intProgress = 0; REngine pEngine = mForm.pEngine; //Declare constants double dblDistError = Convert.ToDouble(txtDistance.Text); double dblDirection = Convert.ToDouble(txtDirections.Text); int intNSimulation = Convert.ToInt32(txtNSimulation.Text); string strX = cboX.Text; string strY = cboY.Text; mForm.strValue = cboFieldName.Text; //Load Source Layer string strLayerName = cboSourceLayer.Text; int intLIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, strLayerName); ILayer pLayer = mForm.axMapControl1.get_Layer(intLIndex); IFeatureLayer pFLayer = pLayer as IFeatureLayer; IFeatureClass pFClass = pFLayer.FeatureClass; int nFeature = pFClass.FeatureCount(null); IFeatureCursor pFCursor = pFLayer.Search(null, true); IFeature pFeature = pFCursor.NextFeature(); //Load Target Layer mForm.strTargetLayerName = cboTargetLayer.Text; int intTargetIndex = pSnippet.GetIndexNumberFromLayerName(pActiveView, mForm.strTargetLayerName); ILayer pTargetLayer = mForm.axMapControl1.get_Layer(intTargetIndex); IFeatureLayer pFTargetLayer = pTargetLayer as IFeatureLayer; IFeatureClass pFTargetClass = pFTargetLayer.FeatureClass; int nTargetFeature = pFTargetClass.FeatureCount(null); //Store X, Y and Value to array double[] vecValue = new double[nFeature]; double[,] arrXY = new double[nFeature, 2]; int intXIdx = pFClass.FindField(strX); int intYIdx = pFClass.FindField(strY); int intVIdx = pFClass.FindField(mForm.strValue); int i = 0; while (pFeature != null) { vecValue[i] = Convert.ToDouble(pFeature.get_Value(intVIdx)); arrXY[i, 0] = Convert.ToDouble(pFeature.get_Value(intXIdx)); arrXY[i, 1] = Convert.ToDouble(pFeature.get_Value(intYIdx)); i++; pFeature = pFCursor.NextFeature(); } pFCursor.Flush(); ////Plot command for R //StringBuilder plotCommmand = new StringBuilder(); //Get the file path and name to create spatial weight matrix string strNameR = pSnippet.FilePathinRfromLayer(pFTargetLayer); if (strNameR == null) { return; } //Load Library and Data pEngine.Evaluate("library(maptools);library(foreign);library(sp);library(circular);"); pEngine.Evaluate("ct.shp <- readShapePoly('" + strNameR + "')"); //Create Shapepointdataframe in R NumericMatrix nmXY = pEngine.CreateNumericMatrix(arrXY); pEngine.SetSymbol("xy.coord.old", nmXY); NumericVector nvValue = pEngine.CreateNumericVector(vecValue); pEngine.SetSymbol("LEAD", nvValue); pEngine.Evaluate("v.bll <- as.data.frame(LEAD)"); pEngine.Evaluate("old.points <- SpatialPointsDataFrame(xy.coord.old, v.bll)"); string strOverMethod = ""; if (cboStat.Text == "Mean") { strOverMethod = ", fn=mean"; } //Save Original value pEngine.Evaluate("n.obs <- nrow(v.bll)"); pEngine.Evaluate("ori.value <- as.matrix(over(ct.shp, old.points" + strOverMethod + "))"); NumericVector nvOriValue = pEngine.Evaluate("ori.value").AsNumeric(); mForm.arrOrivalue = new double[nTargetFeature]; nvOriValue.CopyTo(mForm.arrOrivalue, nTargetFeature); //Create Matrix to store simulation results pEngine.Evaluate("results.matrix <- matrix(NA, nrow=nrow(ct.shp), ncol=" + intNSimulation.ToString() + ")"); //Simulation for (int j = 1; j <= intNSimulation; j++) { //Progress bar intProgress = j * 100 / intNSimulation; pfrmProgress.pgbProgress.Value = intProgress; //pfrmProgress.pgbProgress.Refresh(); pfrmProgress.lblStatus.Text = "Processing (" + intProgress.ToString() + "%)"; //pfrmProgress.lblStatus.Refresh(); pfrmProgress.Invalidate(); //Create Direction from vonmises distribution pEngine.Evaluate("dir.new <- as.numeric(rvonmises(n.obs, mu=circular(" + txtDirections.Text + ", units='degrees'), kappa=" + txtConcetration.Text + "))"); //Add distance error if (rbtRandom.Checked == true) { pEngine.Evaluate("dist.error <- runif(n.obs, 0, " + txtDistance.Text + ")"); } else { pEngine.Evaluate("dist.error <- " + txtDistance.Text); } //Create New points and save to SpatialPointsDataFrame pEngine.Evaluate("x.new <- xy.coord.old[,1] + cos(dir.new)*dist.error; y.new <- xy.coord.old[,2]+ sin(dir.new)*dist.error"); pEngine.Evaluate("xy.coord <- cbind(x.new, y.new)"); pEngine.Evaluate("new.points <- SpatialPointsDataFrame(xy.coord, v.bll)"); //Save results <- have to insert options for summary statistics, (only possilbe by Mean) 1/29/15 pEngine.Evaluate("results.matrix[," + j.ToString() + "] <- as.matrix(over(ct.shp, new.points" + strOverMethod + "))"); } //Save Simulation results to Array NumericMatrix nmResults = pEngine.Evaluate("results.matrix").AsNumericMatrix(); mForm.arrSimuResults = new double[nTargetFeature, intNSimulation]; nmResults.CopyTo(mForm.arrSimuResults, nTargetFeature, intNSimulation); //Create matrix to save summary results(mean, var, mean/var) pfrmProgress.lblStatus.Text = "Creating Summary"; pfrmProgress.Invalidate(); pEngine.Evaluate("sum.mat <- matrix(NA,nrow=nrow(ct.shp), ncol=6)"); //Calculate mean and variance of simulation for (int j = 1; j <= nTargetFeature; j++) { pEngine.Evaluate("sum.mat[" + j.ToString() + ",1] <- mean(results.matrix[" + j.ToString() + ",])"); pEngine.Evaluate("sum.mat[" + j.ToString() + ",2] <- var(results.matrix[" + j.ToString() + ",])"); pEngine.Evaluate("sum.mat[" + j.ToString() + ",5] <- min(results.matrix[" + j.ToString() + ",])"); pEngine.Evaluate("sum.mat[" + j.ToString() + ",6] <- max(results.matrix[" + j.ToString() + ",])"); pEngine.Evaluate("diff.ori <- (results.matrix[" + j.ToString() + ",]- ori.value[" + j.ToString() + "])^2"); //Needs to be changed pEngine.Evaluate("sum.mat[" + j.ToString() + ",4] <- sum(diff.ori)/" + intNSimulation.ToString()); } //Calculate mean/variance pEngine.Evaluate("sum.mat[,3] <- sum.mat[,2]/sum.mat[,1]"); //Save summary results to array NumericMatrix nmSummary = pEngine.Evaluate("sum.mat").AsNumericMatrix(); arrSummary = new double[nTargetFeature, 6]; nmSummary.CopyTo(arrSummary, nTargetFeature, 6); //Remove all memory pEngine.Evaluate("rm(list=ls(all=TRUE))"); //Enable to the histogram identify tool for simulation results if (mForm.arrSimuResults != null) { chkEnable.Enabled = true; } //Add Summary data to Target feature Class //Create filed to store results if (pFTargetClass.FindField("Ori_Mean") == -1) { IFieldEdit addField = new FieldClass(); addField.Name_2 = "Ori_Mean"; addField.Type_2 = esriFieldType.esriFieldTypeDouble; pFTargetClass.AddField(addField); } if (pFTargetClass.FindField("Mean_val") == -1) { IFieldEdit addField = new FieldClass(); addField.Name_2 = "Mean_val"; addField.Type_2 = esriFieldType.esriFieldTypeDouble; pFTargetClass.AddField(addField); } if (pFTargetClass.FindField("Var_val") == -1) { IFieldEdit addField = new FieldClass(); addField.Name_2 = "Var_val"; addField.Type_2 = esriFieldType.esriFieldTypeDouble; pFTargetClass.AddField(addField); } if (pFTargetClass.FindField("Mean_Var") == -1) { IFieldEdit addField = new FieldClass(); addField.Name_2 = "Mean_Var"; addField.Type_2 = esriFieldType.esriFieldTypeDouble; pFTargetClass.AddField(addField); } if (pFTargetClass.FindField("Var_Ori") == -1) { IFieldEdit addField = new FieldClass(); addField.Name_2 = "Var_Ori"; addField.Type_2 = esriFieldType.esriFieldTypeDouble; pFTargetClass.AddField(addField); } if (pFTargetClass.FindField("MIN") == -1) { IFieldEdit addField = new FieldClass(); addField.Name_2 = "MIN"; addField.Type_2 = esriFieldType.esriFieldTypeDouble; pFTargetClass.AddField(addField); } if (pFTargetClass.FindField("MAX") == -1) { IFieldEdit addField = new FieldClass(); addField.Name_2 = "MAX"; addField.Type_2 = esriFieldType.esriFieldTypeDouble; pFTargetClass.AddField(addField); } //Save summary results to Target shapefile int intOriMeanIdx = pFTargetClass.FindField("Ori_Mean"); int intMeanIdx = pFTargetClass.FindField("Mean_val"); int intVarIdx = pFTargetClass.FindField("Var_val"); int intMVIdx = pFTargetClass.FindField("Mean_Var"); int intVOIdx = pFTargetClass.FindField("Var_Ori"); int intMaxIdx = pFTargetClass.FindField("MAX"); int intMinIdx = pFTargetClass.FindField("MIN"); IFeatureCursor pTFUCursor = pFTargetClass.Update(null, false); IFeature pTFeature = pTFUCursor.NextFeature(); i = 0; while (pTFeature != null) { pTFeature.set_Value(intOriMeanIdx, mForm.arrOrivalue[i]); pTFeature.set_Value(intMeanIdx, arrSummary[i, 0]); pTFeature.set_Value(intVarIdx, arrSummary[i, 1]); pTFeature.set_Value(intMVIdx, arrSummary[i, 2]); pTFeature.set_Value(intVOIdx, arrSummary[i, 3]); pTFeature.set_Value(intMinIdx, arrSummary[i, 4]); pTFeature.set_Value(intMaxIdx, arrSummary[i, 5]); pTFeature.Store(); i++; pTFeature = pTFUCursor.NextFeature(); } pfrmProgress.Close(); MessageBox.Show("Done"); } catch (Exception ex) { MessageBox.Show(this.Handle.ToString() + " Error:" + ex.Message); return; } }
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(); }
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(); } }
private void button1_Click(object sender, EventArgs e) { string[] FeatureName = (string[])app.FeaName; string[] SampleName = (string[])app.SamName; int FeatureNum = FeatureName.GetLength(0); int SampleNum = SampleName.GetLength(0); REngine.SetEnvironmentVariables(); REngine CLU = REngine.GetInstance(); CLU.Initialize(); NumericMatrix Freq = CLU.CreateNumericMatrix(app.FreqMatrix); CLU.SetSymbol("Freq", Freq); NumericMatrix Count = CLU.CreateNumericMatrix(app.CountMatrix); CLU.SetSymbol("Count", Count); NumericVector RFeatureNum = CLU.CreateNumeric(FeatureNum); NumericVector RSampleNum = CLU.CreateNumeric(SampleNum); CLU.SetSymbol("FeatureNum", RFeatureNum); CLU.SetSymbol("SampleNum", RSampleNum); CharacterVector RSampleName = CLU.CreateCharacterVector(app.SamName); CharacterVector RFeatureName = CLU.CreateCharacterVector(app.FeaName); CLU.SetSymbol("FeatureName", RFeatureName); CLU.SetSymbol("SampleName", RSampleName); CLU.Evaluate("CountMatrix <- as.data.frame(Count)"); CLU.Evaluate("names(CountMatrix) <- SampleName"); switch (this.comboBox1.SelectedIndex) { case 0: CLU.Evaluate("d <- dist(t(CountMatrix),method = \"euclidean\")"); break; case 1: CLU.Evaluate("d <- dist(t(CountMatrix),method = \"maximum\")"); break; case 2: CLU.Evaluate("d <- dist(t(CountMatrix),method = \"manhattan\")"); break; case 3: CLU.Evaluate("d <- dist(t(CountMatrix),method = \"canberra\")"); break; case 4: CLU.Evaluate("d <- dist(t(CountMatrix),method = \"binary\")"); break; case 5: CLU.Evaluate("d <- dist(t(CountMatrix),method = \"minkowski\")"); break; default: break; } switch (this.comboBox2.SelectedIndex) { case 0: CLU.Evaluate("hc <- hclust(d,method = \"ward\")"); break; case 1: CLU.Evaluate("hc <- hclust(d,method = \"single\")"); break; case 2: CLU.Evaluate("hc <- hclust(d,method = \"complete\")"); break; case 3: CLU.Evaluate("hc <- hclust(d,method = \"average\")"); break; case 4: CLU.Evaluate("hc <- hclust(d,method = \"mcquitty\")"); break; case 5: CLU.Evaluate("hc <- hclust(d,method = \"median\")"); break; case 6: CLU.Evaluate("hc <- hclust(d,method = \"centroid\")"); break; default: break; } CLU.Evaluate("plot(hc)"); this.Close(); }