5 * Created by westcott on 7/6/11.
6 * Copyright 2011 Schloss Lab. All rights reserved.
10 #include "mothurmetastats.h"
11 #include "mothurfisher.h"
14 /***********************************************************/
15 MothurMetastats::MothurMetastats(double t, int n) {
17 m = MothurOut::getInstance();
21 }catch(exception& e) {
22 m->errorOut(e, "MothurMetastats", "MothurMetastats");
26 /***********************************************************/
27 MothurMetastats::~MothurMetastats() {}
28 /***********************************************************/
29 //main metastats function
30 int MothurMetastats::runMetastats(string outputFileName, vector< vector<double> >& data, int secGroupingStart) {
32 row = data.size(); //numBins
33 column = data[0].size(); //numGroups in subset
34 secondGroupingStart = secGroupingStart; //g
36 vector< vector<double> > Pmatrix; Pmatrix.resize(row);
37 for (int i = 0; i < row; i++) { Pmatrix[i].resize(column, 0.0); } // the relative proportion matrix
38 vector< vector<double> > C1; C1.resize(row);
39 for (int i = 0; i < row; i++) { C1[i].resize(3, 0.0); } // statistic profiles for class1 and class 2
40 vector< vector<double> > C2; C2.resize(row); // mean[1], variance[2], standard error[3]
41 for (int i = 0; i < row; i++) { C2[i].resize(3, 0.0); }
42 vector<double> T_statistics; T_statistics.resize(row, 1); // a place to store the true t-statistics
43 vector<double> pvalues; pvalues.resize(row, 1); // place to store pvalues
44 vector<double> qvalues; qvalues.resize(row, 1); // stores qvalues
46 //*************************************
47 // convert to proportions
49 //*************************************
50 vector<double> totals; totals.resize(column, 0); // sum of columns
51 //total[i] = total abundance for group[i]
52 for (int i = 0; i < column; i++) {
53 for (int j = 0; j < row; j++) {
54 totals[i] += data[j][i];
58 for (int i = 0; i < column; i++) {
59 for (int j = 0; j < row; j++) {
60 Pmatrix[j][i] = data[j][i]/totals[i];
65 //#********************************************************************************
66 //# ************************** STATISTICAL TESTING ********************************
67 //#********************************************************************************
69 if (column == 2){ //# then we have a two sample comparison
70 //#************************************************************
71 //# generate p values fisher's exact test
72 //#************************************************************
73 double total1, total2;
74 //total for first grouping
75 for (int i = 0; i < secondGroupingStart; i++) { total1 += totals[i]; }
77 //total for second grouping
78 for (int i = secondGroupingStart; i < column; i++) { total2 += totals[i]; }
80 vector<double> fish; fish.resize(row, 0.0);
81 vector<double> fish2; fish2.resize(row, 0.0);
83 for(int i = 0; i < row; i++){
85 for(int j = 0; j < secondGroupingStart; j++) { fish[i] += data[i][j]; }
86 for(int j = secondGroupingStart; j < column; j++) { fish2[i] += data[i][j]; }
88 double f11, f12, f21, f22;
91 f21 = total1 - fish[i];
92 f22 = total2 - fish2[i];
95 double pre = fisher.fexact(f11, f12, f21, f22);
96 if (pre > 0.999999999) { pre = 1.0; }
98 if (m->control_pressed) { return 1; }
103 //#*************************************
104 //# calculate q values from p values
105 //#*************************************
106 qvalues = calc_qvalues(pvalues);
108 }else { //we have multiple subjects per population
110 //#*************************************
111 //# generate statistics mean, var, stderr
112 //#*************************************
113 for(int i = 0; i < row; i++){ // for each taxa
114 //# find the mean of each group
115 double g1Total = 0.0; double g2Total = 0.0;
116 for (int j = 0; j < secondGroupingStart; j++) { g1Total += Pmatrix[i][j]; }
117 C1[i][0] = g1Total/(double)(secondGroupingStart);
118 for (int j = secondGroupingStart; j < column; j++) { g2Total += Pmatrix[i][j]; }
119 C2[i][0] = g2Total/(double)(column-secondGroupingStart);
121 //# find the variance of each group
122 double g1Var = 0.0; double g2Var = 0.0;
123 for (int j = 0; j < secondGroupingStart; j++) { g1Var += pow((Pmatrix[i][j]-C1[i][0]), 2); }
124 C1[i][1] = g1Var/(double)(secondGroupingStart-1);
125 for (int j = secondGroupingStart; j < column; j++) { g2Var += pow((Pmatrix[i][j]-C2[i][0]), 2); }
126 C2[i][1] = g2Var/(double)(column-secondGroupingStart-1);
128 //# find the std error of each group -std err^2 (will change to std err at end)
129 C1[i][2] = C1[i][1]/(double)(secondGroupingStart);
130 C2[i][2] = C2[i][1]/(double)(column-secondGroupingStart);
133 //#*************************************
134 //# two sample t-statistics
135 //#*************************************
136 for(int i = 0; i < row; i++){ // # for each taxa
137 double xbar_diff = C1[i][0] - C2[i][0];
138 double denom = sqrt(C1[i][2] + C2[i][2]);
139 T_statistics[i] = xbar_diff/denom; // calculate two sample t-statistic
142 /*for (int i = 0; i < row; i++) {
143 for (int j = 0; j < 3; j++) {
144 cout << "C1[" << i+1 << "," << j+1 << "]=" << C1[i][j] << ";" << endl;
145 cout << "C2[" << i+1 << "," << j+1 << "]=" << C2[i][j] << ";" << endl;
147 cout << "T_statistics[" << i+1 << "]=" << T_statistics[i] << ";" << endl;
149 //#*************************************
150 //# generate initial permuted p-values
151 //#*************************************
152 pvalues = permuted_pvalues(Pmatrix, T_statistics, data);
154 //#*************************************
155 //# generate p values for sparse data
156 //# using fisher's exact test
157 //#*************************************
158 double total1, total2;
159 //total for first grouping
160 for (int i = 0; i < secondGroupingStart; i++) { total1 += totals[i]; }
162 //total for second grouping
163 for (int i = secondGroupingStart; i < column; i++) { total2 += totals[i]; }
165 vector<double> fish; fish.resize(row, 0.0);
166 vector<double> fish2; fish2.resize(row, 0.0);
168 for(int i = 0; i < row; i++){
170 for(int j = 0; j < secondGroupingStart; j++) { fish[i] += data[i][j]; }
171 for(int j = secondGroupingStart; j < column; j++) { fish2[i] += data[i][j]; }
173 if ((fish[1] < secondGroupingStart) && (fish2[i] < (column-secondGroupingStart))) {
174 double f11, f12, f21, f22;
177 f21 = total1 - fish[i];
178 f22 = total2 - fish2[i];
181 double pre = fisher.fexact(f11, f12, f21, f22);
182 if (pre > 0.999999999) { pre = 1.0; }
184 if (m->control_pressed) { return 1; }
190 //#*************************************
191 //# calculate q values from p values
192 //#*************************************
193 qvalues = calc_qvalues(pvalues);
195 //#*************************************
196 //# convert stderr^2 to std error
197 //#*************************************
198 for(int i = 0; i < row; i++){
199 C1[i][2] = sqrt(C1[i][2]);
200 C2[i][2] = sqrt(C2[i][2]);
204 // And now we write the files to a text file.
206 time_t t; t = time(NULL);
207 local = localtime(&t);
210 m->openOutputFile(outputFileName, out);
211 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
213 out << "Local time and date of test: " << asctime(local) << endl;
214 out << "# rows = " << row << ", # col = " << column << ", g = " << secondGroupingStart << endl << endl;
215 out << numPermutations << " permutations" << endl << endl;
217 //output column headings - not really sure... documentation labels 9 columns, there are 10 in the output file
218 //storage 0 = meanGroup1 - line 529, 1 = varGroup1 - line 532, 2 = err rate1 - line 534, 3 = mean of counts group1?? - line 291, 4 = meanGroup2 - line 536, 5 = varGroup2 - line 539, 6 = err rate2 - line 541, 7 = mean of counts group2?? - line 292, 8 = pvalues - line 293
219 out << "OTU\tmean(group1)\tvariance(group1)\tstderr(group1)\tmean(group2)\tvariance(group2)\tstderr(group2)\tp-value\tq-value\n";
221 for(int i = 0; i < row; i++){
222 if (m->control_pressed) { out.close(); return 0; }
224 //if there are binlabels use them otherwise count.
225 if (m->binLabelsInFile.size() == row) { out << m->binLabelsInFile[i] << '\t'; }
226 else { out << (i+1) << '\t'; }
228 out << C1[i][0] << '\t' << C1[i][1] << '\t' << C1[i][2] << '\t' << C2[i][0] << '\t' << C2[i][1] << '\t' << C2[i][2] << '\t' << pvalues[i] << '\t' << qvalues[i] << endl;
238 }catch(exception& e) {
239 m->errorOut(e, "MothurMetastats", "runMetastats");
243 /***********************************************************/
244 vector<double> MothurMetastats::permuted_pvalues(vector< vector<double> >& Imatrix, vector<double>& tstats, vector< vector<double> >& Fmatrix) {
246 //# matrix stores tstats for each taxa(row) for each permuted trial(column)
247 vector<double> ps; ps.resize(row, 0.0); //# to store the pvalues
248 vector< vector<double> > permuted_ttests; permuted_ttests.resize(numPermutations);
249 for (int i = 0; i < numPermutations; i++) { permuted_ttests[i].resize(row, 0.0); }
251 //# calculate null version of tstats using B permutations.
252 for (int i = 0; i < numPermutations; i++) {
253 permuted_ttests[i] = permute_and_calc_ts(Imatrix);
256 //# calculate each pvalue using the null ts
257 if ((secondGroupingStart) < 8 || (column-secondGroupingStart) < 8){
258 vector< vector<double> > cleanedpermuted_ttests; cleanedpermuted_ttests.resize(numPermutations); //# the array pooling just the frequently observed ts
259 //# then pool the t's together!
260 //# count how many high freq taxa there are
262 for (int i = 0; i < row; i++) { // # for each taxa
263 double group1Total = 0.0; double group2Total = 0.0;
264 for(int j = 0; j < secondGroupingStart; j++) { group1Total += Fmatrix[i][j]; }
265 for(int j = secondGroupingStart; j < column; j++) { group2Total += Fmatrix[i][j]; }
267 if (group1Total >= secondGroupingStart || group2Total >= (column-secondGroupingStart)){
269 for (int j = 0; j < numPermutations; j++) { cleanedpermuted_ttests[j].push_back(permuted_ttests[j][i]); }
274 for (int i = 0; i < row; i++) {
275 //number of cleanedpermuted_ttests greater than tstat[i]
277 for (int j = 0; j < numPermutations; j++) {
278 for (int k = 0; k < hfc; k++) {
279 if (cleanedpermuted_ttests[j][k] > abs(tstats[i])) { numGreater++; }
283 ps[i] = (1/(double)(numPermutations*hfc))*numGreater;
286 for (int i = 0; i < row; i++) {
287 //number of permuted_ttests[i] greater than tstat[i] //(sum(permuted_ttests[i,] > abs(tstats[i]))+1)
289 for (int j = 0; j < numPermutations; j++) { if (permuted_ttests[j][i] > abs(tstats[i])) { numGreater++; } }
290 ps[i] = (1/(double)(numPermutations+1))*numGreater;
296 }catch(exception& e) {
297 m->errorOut(e, "MothurMetastats", "permuted_pvalues");
301 /***********************************************************/
302 vector<double> MothurMetastats::permute_and_calc_ts(vector< vector<double> >& Imatrix) {
304 vector< vector<double> > permutedMatrix = Imatrix;
306 //randomize columns, ie group abundances.
307 for (int i = 0; i < permutedMatrix.size(); i++) { random_shuffle(permutedMatrix[i].begin(), permutedMatrix[i].end()); }
310 vector< vector<double> > C1; C1.resize(row);
311 for (int i = 0; i < row; i++) { C1[i].resize(3, 0.0); } // statistic profiles for class1 and class 2
312 vector< vector<double> > C2; C2.resize(row); // mean[1], variance[2], standard error[3]
313 for (int i = 0; i < row; i++) { C2[i].resize(3, 0.0); }
314 vector<double> Ts; Ts.resize(row, 0.0); // a place to store the true t-statistics
316 //#*************************************
317 //# generate statistics mean, var, stderr
318 //#*************************************
319 for(int i = 0; i < row; i++){ // for each taxa
320 //# find the mean of each group
321 double g1Total = 0.0; double g2Total = 0.0;
322 for (int j = 0; j < secondGroupingStart; j++) { g1Total += permutedMatrix[i][j]; }
323 C1[i][0] = g1Total/(double)(secondGroupingStart);
324 for (int j = secondGroupingStart; j < column; j++) { g2Total += permutedMatrix[i][j]; }
325 C2[i][0] = g2Total/(double)(column-secondGroupingStart);
327 //# find the variance of each group
328 double g1Var = 0.0; double g2Var = 0.0;
329 for (int j = 0; j < secondGroupingStart; j++) { g1Var += pow((permutedMatrix[i][j]-C1[i][0]), 2); }
330 C1[i][1] = g1Var/(double)(secondGroupingStart-1);
331 for (int j = secondGroupingStart; j < column; j++) { g2Var += pow((permutedMatrix[i][j]-C2[i][0]), 2); }
332 C2[i][1] = g2Var/(double)(column-secondGroupingStart-1);
334 //# find the std error of each group -std err^2 (will change to std err at end)
335 C1[i][2] = C1[i][1]/(double)(secondGroupingStart);
336 C2[i][2] = C2[i][1]/(double)(column-secondGroupingStart);
339 //#*************************************
340 //# two sample t-statistics
341 //#*************************************
342 for(int i = 0; i < row; i++){ // # for each taxa
343 double xbar_diff = C1[i][0] - C2[i][0];
344 double denom = sqrt(C1[i][2] + C2[i][2]);
345 Ts[i] = abs(xbar_diff/denom); // calculate two sample t-statistic
351 }catch(exception& e) {
352 m->errorOut(e, "MothurMetastats", "permuted_ttests");
356 /***********************************************************/
357 vector<double> MothurMetastats::calc_qvalues(vector<double>& pValues) {
360 /* cout << "x <- c(" << pValues[0];
361 for (int l = 1; l < pValues.size(); l++){
362 cout << ", " << pValues[l];
366 int numRows = pValues.size();
367 vector<double> qvalues(numRows, 0.0);
369 //fill lambdas with 0.00, 0.01, 0.02... 0.95
370 vector<double> lambdas(96, 0);
371 for (int i = 1; i < lambdas.size(); i++) { lambdas[i] = lambdas[i-1] + 0.01; }
373 vector<double> pi0_hat(lambdas.size(), 0);
376 for (int l = 0; l < lambdas.size(); l++){ // for each lambda value
378 for (int i = 0; i < numRows; i++){ // for each p-value in order
379 if (pValues[i] > lambdas[l]){ count++; }
381 pi0_hat[l] = count/(double)(numRows*(1-lambdas[l]));
384 double pi0 = smoothSpline(lambdas, pi0_hat, 3);
387 vector<double> ordered_qs = qvalues;
388 vector<int> ordered_ps(pValues.size(), 0);
389 for (int i = 1; i < ordered_ps.size(); i++) { ordered_ps[i] = ordered_ps[i-1] + 1; }
390 vector<double> tempPvalues = pValues;
391 OrderPValues(0, numRows-1, tempPvalues, ordered_ps);
393 ordered_qs[numRows-1] = min((pValues[ordered_ps[numRows-1]]*pi0), 1.0);
394 for (int i = (numRows-2); i >= 0; i--){
395 double p = pValues[ordered_ps[i]];
396 double temp = p*numRows*pi0/(double)(i+1);
398 ordered_qs[i] = min(temp, ordered_qs[i+1]);
401 //re-distribute calculated qvalues to appropriate rows
402 for (int i = 0; i < numRows; i++){
403 qvalues[ordered_ps[i]] = ordered_qs[i];
408 }catch(exception& e) {
409 m->errorOut(e, "MothurMetastats", "calc_qvalues");
413 /***********************************************************/
414 int MothurMetastats::OrderPValues(int low, int high, vector<double>& p, vector<int>& order) {
420 int pivot = (low+high) / 2;
422 swapElements(low, pivot, p, order); //puts pivot in final spot
429 /* find member above ... */
430 while((i <= high) && (p[i] <= key)) { i++; }
432 /* find element below ... */
433 while((j >= low) && (p[j] > key)) { j--; }
436 swapElements(i, j, p, order);
440 swapElements(low, j, p, order);
443 OrderPValues(low, j-1, p, order);
444 OrderPValues(j+1, high, p, order);
449 }catch(exception& e) {
450 m->errorOut(e, "MothurMetastats", "OrderPValues");
454 /***********************************************************/
455 int MothurMetastats::swapElements(int i, int j, vector<double>& p, vector<int>& order) {
468 }catch(exception& e) {
469 m->errorOut(e, "MothurMetastats", "swapElements");
473 /***********************************************************/
474 double MothurMetastats::smoothSpline(vector<double>& x, vector<double>& y, int df) {
479 vector<double> w(n, 1);
480 double* xb = new double[n];
481 double* yb = new double[n];
482 double* wb = new double[n];
484 for (int i = 0; i < n; i++) {
487 yssw += (w[i] * y[i] * y[i]) - wb[i] * (yb[i] * yb[i]);
488 xb[i] = (x[i] - x[0]) / (x[n-1] - x[0]);
491 vector<double> knot = sknot1(xb, n);
492 int nk = knot.size() - 4;
494 double low = -1.5; double high = 1.5; double tol = 1e-04; double eps = 2e-08; int maxit = 500;
495 int ispar = 0; int icrit = 3; double dofoff = 3.0;
496 double penalty = 1.0;
497 int ld4 = 4; int isetup = 0; int ldnk = 1; int ier; double spar = 1.0; double crit;
499 double* knotb = new double[knot.size()];
500 double* coef1 = new double[nk];
501 double* lev1 = new double[n];
502 double* sz1 = new double[n];
503 for (int i = 0; i < knot.size(); i++) { knotb[i] = knot[i]; }
506 spline.sbart(&penalty, &dofoff, &xb[0], &yb[0], &wb[0], &yssw, &n, &knotb[0], &nk, &coef1[0], &sz1[0], &lev1[0], &crit,
507 &icrit, &spar, &ispar, &maxit, &low, &high, &tol, &eps, &isetup, &ld4, &ldnk, &ier);
509 result = coef1[nk-1];
522 }catch(exception& e) {
523 m->errorOut(e, "MothurMetastats", "smoothSpline");
527 /***********************************************************/
528 vector<double> MothurMetastats::sknot1(double* x, int n) {
530 vector<double> knots;
533 //R equivalent - rep(x[1L], 3L)
534 knots.push_back(x[0]); knots.push_back(x[0]); knots.push_back(x[0]);
536 //generate a sequence of nk equally spaced values from 1 to n. R equivalent = seq.int(1, n, length.out = nk)
537 vector<int> indexes = getSequence(0, n-1, nk);
538 for (int i = 0; i < indexes.size(); i++) { knots.push_back(x[indexes[i]]); }
540 //R equivalent - rep(x[n], 3L)
541 knots.push_back(x[n-1]); knots.push_back(x[n-1]); knots.push_back(x[n-1]);
545 }catch(exception& e) {
546 m->errorOut(e, "MothurMetastats", "sknot1");
550 /***********************************************************/
551 vector<int> MothurMetastats::getSequence(int start, int end, int length) {
553 vector<int> sequence;
554 double increment = (end-start) / (double) (length-1);
556 sequence.push_back(start);
557 for (int i = 1; i < length-1; i++) {
558 sequence.push_back(int(i*increment));
560 sequence.push_back(end);
564 }catch(exception& e) {
565 m->errorOut(e, "MothurMetastats", "getSequence");
569 /***********************************************************/
570 //not right, havent fully figured out the variable types yet...
571 int MothurMetastats::nkn(int n) {
574 if (n < 50) { return n; }
576 double a1 = log2(50);
577 double a2 = log2(100);
578 double a3 = log2(140);
579 double a4 = log2(200);
582 return (int)pow(2.0, (a1 + (a2 - a1) * (n - 50)/(float)150));
584 return (int)pow(2.0, (a2 + (a3 - a2) * (n - 200)/(float)600));
585 }else if (n < 3200) {
586 return (int)pow(2.0, (a3 + (a4 - a3) * (n - 800)/(float)2400));
588 return (int)pow((double)(200 + (n - 3200)), 0.2);
594 }catch(exception& e) {
595 m->errorOut(e, "MothurMetastats", "nkn");
599 /***********************************************************/