]> git.donarmstrong.com Git - mothur.git/blob - weighted.cpp
added root parameter to the unifrac commands so you can choose to include the entire...
[mothur.git] / weighted.cpp
1 /*
2  *  weighted.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 2/9/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "weighted.h"
11
12 /**************************************************************************************************/
13
14 EstOutput Weighted::getValues(Tree* t, int p, string o) {
15     try {
16                 globaldata = GlobalData::getInstance();
17                 
18                 data.clear(); //clear out old values
19                 int numGroups;
20                 vector<double> D;
21                 processors = p;
22                 outputDir = o;
23                 
24                 numGroups = globaldata->Groups.size();
25                 
26                 if (m->control_pressed) { return data; }
27                 
28                 //calculate number of comparisons i.e. with groups A,B,C = AB, AC, BC = 3;
29                 vector< vector<string> > namesOfGroupCombos;
30                 for (int i=0; i<numGroups; i++) { 
31                         for (int l = 0; l < i; l++) {   
32                                 //initialize weighted scores
33                                 //WScore[globaldata->Groups[i]+globaldata->Groups[l]] = 0.0;
34                                 vector<string> groups; groups.push_back(globaldata->Groups[i]); groups.push_back(globaldata->Groups[l]);
35                                 namesOfGroupCombos.push_back(groups);
36                         }
37                 }
38                 
39                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
40                         if(processors == 1){
41                                 data = driver(t, namesOfGroupCombos, 0, namesOfGroupCombos.size());
42                         }else{
43                                 int numPairs = namesOfGroupCombos.size();
44                                 
45                                 int numPairsPerProcessor = numPairs / processors;
46                                 
47                                 for (int i = 0; i < processors; i++) {
48                                         int startPos = i * numPairsPerProcessor;
49                                         if(i == processors - 1){
50                                                 numPairsPerProcessor = numPairs - i * numPairsPerProcessor;
51                                         }
52                                         lines.push_back(linePair(startPos, numPairsPerProcessor));
53                                 }
54
55                                 data = createProcesses(t, namesOfGroupCombos);
56                                 
57                                 lines.clear();
58                         }
59                 #else
60                         data = driver(t, namesOfGroupCombos, 0, namesOfGroupCombos.size());
61                 #endif
62                 
63                 return data;
64         }
65         catch(exception& e) {
66                 m->errorOut(e, "Weighted", "getValues");
67                 exit(1);
68         }
69 }
70 /**************************************************************************************************/
71
72 EstOutput Weighted::createProcesses(Tree* t, vector< vector<string> > namesOfGroupCombos) {
73         try {
74 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
75                 int process = 1;
76                 vector<int> processIDS;
77                 
78                 EstOutput results;
79                 
80                 //loop through and create all the processes you want
81                 while (process != processors) {
82                         int pid = fork();
83                         
84                         if (pid > 0) {
85                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
86                                 process++;
87                         }else if (pid == 0){
88         
89                                 EstOutput Myresults;
90                                 Myresults = driver(t, namesOfGroupCombos, lines[process].start, lines[process].num);
91                         
92                                 m->mothurOut("Merging results."); m->mothurOutEndLine();
93                                 
94                                 //pass numSeqs to parent
95                                 ofstream out;
96
97                                 string tempFile = outputDir + toString(getpid()) + ".weighted.results.temp";
98         
99                                 m->openOutputFile(tempFile, out);
100         
101                                 out << Myresults.size() << endl;
102                                 for (int i = 0; i < Myresults.size(); i++) {  out << Myresults[i] << '\t';  } out << endl;
103                                 out.close();
104                                 
105                                 exit(0);
106                         }else { 
107                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
108                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
109                                 exit(0);
110                         }
111                 }
112         
113                 results = driver(t, namesOfGroupCombos, lines[0].start, lines[0].num);
114         
115                 //force parent to wait until all the processes are done
116                 for (int i=0;i<(processors-1);i++) { 
117                         int temp = processIDS[i];
118                         wait(&temp);
119                 }
120         
121                 if (m->control_pressed) { return results; }
122                 
123                 //get data created by processes
124                 for (int i=0;i<(processors-1);i++) { 
125                         ifstream in;
126                         string s = outputDir + toString(processIDS[i]) + ".weighted.results.temp";
127                         m->openInputFile(s, in);
128                         
129                         //get quantiles
130                         while (!in.eof()) {
131                                 int num;
132                                 in >> num; m->gobble(in);
133                                 
134                                 if (m->control_pressed) { break; }
135
136                                 double w; 
137                                 for (int j = 0; j < num; j++) {
138                                         in >> w;
139                                         results.push_back(w);
140                                 }
141                                 m->gobble(in);
142                         }
143                         in.close();
144                         remove(s.c_str());
145                 }
146                 
147                 m->mothurOut("DONE."); m->mothurOutEndLine(); m->mothurOutEndLine();
148                 
149                 return results;
150 #endif          
151         }
152         catch(exception& e) {
153                 m->errorOut(e, "Weighted", "createProcesses");
154                 exit(1);
155         }
156 }
157 /**************************************************************************************************/
158 EstOutput Weighted::driver(Tree* t, vector< vector<string> > namesOfGroupCombos, int start, int num) { 
159  try {
160                 EstOutput results;
161                 vector<double> D;
162                 
163                 int count = 0;
164                 for (int h = start; h < (start+num); h++) {
165                 
166                         if (m->control_pressed) { return results; }
167                 
168                         //initialize weighted score
169                         string groupA = namesOfGroupCombos[h][0]; 
170                         string groupB = namesOfGroupCombos[h][1];
171                         
172                         set<int> validBranches;
173                         WScore[groupA+groupB] = 0.0;
174                         D.push_back(0.0000); //initialize a spot in D for each combination
175                         
176                         //adding the wieghted sums from group i
177                         for (int j = 0; j < t->groupNodeInfo[groupA].size(); j++) { //the leaf nodes that have seqs from group i
178                                 map<string, int>::iterator it = t->tree[t->groupNodeInfo[groupA][j]].pcount.find(groupA);
179                                 int numSeqsInGroupI = it->second;
180                                 
181                                 double sum = getLengthToRoot(t, t->groupNodeInfo[groupA][j], groupA, groupB);
182                                 double weightedSum = ((numSeqsInGroupI * sum) / (double)tmap->seqsPerGroup[groupA]);
183                         
184                                 D[count] += weightedSum;
185                         }
186                         
187                         //adding the wieghted sums from group l
188                         for (int j = 0; j < t->groupNodeInfo[groupB].size(); j++) { //the leaf nodes that have seqs from group l
189                                 map<string, int>::iterator it = t->tree[t->groupNodeInfo[groupB][j]].pcount.find(groupB);
190                                 int numSeqsInGroupL = it->second;
191                                 
192                                 double sum = getLengthToRoot(t, t->groupNodeInfo[groupB][j], groupA, groupB);
193                                 double weightedSum = ((numSeqsInGroupL * sum) / (double)tmap->seqsPerGroup[groupB]);
194                         
195                                 D[count] += weightedSum;
196                         }
197                         count++;
198                 }
199          
200                 //calculate u for the group comb 
201                 for (int h = start; h < (start+num); h++) {     
202                         //report progress
203                         //m->mothurOut("Processing combo: " + toString(h)); m->mothurOutEndLine();
204                                                 
205                         string groupA = namesOfGroupCombos[h][0]; 
206                         string groupB = namesOfGroupCombos[h][1];
207                         
208                         //calculate u for the group comb 
209                         for(int i=0;i<t->getNumNodes();i++){
210                                 
211                                 if (m->control_pressed) { return data; }
212                                 
213                                 double u;
214                                 //int pcountSize = 0;
215                                 //does this node have descendants from groupA
216                                 it = t->tree[i].pcount.find(groupA);
217                                 //if it does u = # of its descendants with a certain group / total number in tree with a certain group
218                                 if (it != t->tree[i].pcount.end()) {
219                                         u = (double) t->tree[i].pcount[groupA] / (double) tmap->seqsPerGroup[groupA];
220                                 }else { u = 0.00; }
221                                 
222                                 
223                                 //does this node have descendants from group l
224                                 it = t->tree[i].pcount.find(groupB);
225                                 
226                                 //if it does subtract their percentage from u
227                                 if (it != t->tree[i].pcount.end()) {
228                                         u -= (double) t->tree[i].pcount[groupB] / (double) tmap->seqsPerGroup[groupB];
229                                 }
230                                 
231                                 if (includeRoot) {
232                                         if (t->tree[i].getBranchLength() != -1) {
233                                                 u = abs(u * t->tree[i].getBranchLength());
234                                                 WScore[(groupA+groupB)] += u; 
235                                         }
236                                 }else {
237                                         //if this is not the root then add it
238                                         if (rootForGrouping[namesOfGroupCombos[h]].count(i) == 0) {
239                                                 if (t->tree[i].getBranchLength() != -1) {
240                                                         u = abs(u * t->tree[i].getBranchLength());
241                                                         WScore[(groupA+groupB)] += u; 
242                                                 }
243                                         }
244                                 }
245                         }
246                         
247                 }
248                 
249                 /********************************************************/
250                 //calculate weighted score for the group combination
251                 double UN;      
252                 count = 0;
253                 for (int h = start; h < (start+num); h++) {
254                         UN = (WScore[namesOfGroupCombos[h][0]+namesOfGroupCombos[h][1]] / D[count]);
255                         if (isnan(UN) || isinf(UN)) { UN = 0; } 
256                         results.push_back(UN);
257                         count++;
258                 }
259                                 
260                 return results; 
261         }
262         catch(exception& e) {
263                 m->errorOut(e, "Weighted", "driver");
264                 exit(1);
265         }
266 }
267 /**************************************************************************************************/
268 EstOutput Weighted::getValues(Tree* t, string groupA, string groupB) { 
269  try {
270                 globaldata = GlobalData::getInstance();
271                 
272                 data.clear(); //clear out old values
273                 
274                 if (m->control_pressed) { return data; }
275                 
276                 //initialize weighted score
277                 WScore[(groupA+groupB)] = 0.0;
278                 double D = 0.0;
279                 set<int> validBranches;
280                 
281                 vector<string> groups; groups.push_back(groupA); groups.push_back(groupB);
282                 
283                 //adding the wieghted sums from group i
284                 for (int j = 0; j < t->groupNodeInfo[groups[0]].size(); j++) { //the leaf nodes that have seqs from group i
285                         map<string, int>::iterator it = t->tree[t->groupNodeInfo[groups[0]][j]].pcount.find(groups[0]);
286                         int numSeqsInGroupI = it->second;
287                         
288                         double sum = getLengthToRoot(t, t->groupNodeInfo[groups[0]][j], groups[0], groups[1]);
289                         double weightedSum = ((numSeqsInGroupI * sum) / (double)tmap->seqsPerGroup[groups[0]]);
290                 
291                         D += weightedSum;
292                 }
293                 
294                 //adding the wieghted sums from group l
295                 for (int j = 0; j < t->groupNodeInfo[groups[1]].size(); j++) { //the leaf nodes that have seqs from group l
296                         map<string, int>::iterator it = t->tree[t->groupNodeInfo[groups[1]][j]].pcount.find(groups[1]);
297                         int numSeqsInGroupL = it->second;
298                         
299                         double sum = getLengthToRoot(t, t->groupNodeInfo[groups[1]][j], groups[0], groups[1]);
300                         double weightedSum = ((numSeqsInGroupL * sum) / (double)tmap->seqsPerGroup[groups[1]]);
301                 
302                         D += weightedSum;
303                 }
304                                 
305                 //calculate u for the group comb 
306                 for(int i=0;i<t->getNumNodes();i++){
307                  
308                         if (m->control_pressed) { return data; }
309                         
310                         double u;
311                         //int pcountSize = 0;
312                         //does this node have descendants from groupA
313                         it = t->tree[i].pcount.find(groupA);
314                         //if it does u = # of its descendants with a certain group / total number in tree with a certain group
315                         if (it != t->tree[i].pcount.end()) {
316                                 u = (double) t->tree[i].pcount[groupA] / (double) tmap->seqsPerGroup[groupA];
317                         }else { u = 0.00; }
318                         
319                         
320                         //does this node have descendants from group l
321                         it = t->tree[i].pcount.find(groupB);
322                         //if it does subtract their percentage from u
323                         if (it != t->tree[i].pcount.end()) {
324                                 u -= (double) t->tree[i].pcount[groupB] / (double) tmap->seqsPerGroup[groupB];
325                         }
326                         
327                         if (includeRoot) {
328                                 if (t->tree[i].getBranchLength() != -1) {
329                                         u = abs(u * t->tree[i].getBranchLength());
330                                         WScore[(groupA+groupB)] += u;
331                                 }
332                         }else{
333                                 //if this is not the root then add it
334                                 if (rootForGrouping[groups].count(i) == 0) {
335                                         if (t->tree[i].getBranchLength() != -1) {
336                                                 u = abs(u * t->tree[i].getBranchLength());
337                                                 WScore[(groupA+groupB)] += u;
338                                         }
339                                 }
340                         }
341                 }               
342                 /********************************************************/
343          
344                 //calculate weighted score for the group combination
345                 double UN;      
346                 UN = (WScore[(groupA+groupB)] / D);
347                 
348                 if (isnan(UN) || isinf(UN)) { UN = 0; } 
349                 data.push_back(UN);
350                                 
351                 return data; 
352         }
353         catch(exception& e) {
354                 m->errorOut(e, "Weighted", "getValues");
355                 exit(1);
356         }
357 }
358 /**************************************************************************************************/
359 double Weighted::getLengthToRoot(Tree* t, int v, string groupA, string groupB) { 
360         try {
361                 
362                 double sum = 0.0;
363                 int index = v;
364         
365                 //you are a leaf
366                 if(t->tree[index].getBranchLength() != -1){     sum += abs(t->tree[index].getBranchLength());   }
367                 double tempTotal = 0.0;
368                 index = t->tree[index].getParent();     
369                 
370                 vector<string> grouping; grouping.push_back(groupA); grouping.push_back(groupB);
371                 
372                 rootForGrouping[grouping].insert(index);
373                         
374                 //while you aren't at root
375                 while(t->tree[index].getParent() != -1){
376
377                         if (m->control_pressed) {  return sum; }
378                         
379                         int parent = t->tree[index].getParent();
380                         
381                         if (includeRoot) { //add everyone
382                                 if(t->tree[index].getBranchLength() != -1){     sum += abs(t->tree[index].getBranchLength());   }
383                         }else {
384                                 
385                                 //am I the root for this grouping? if so I want to stop "early"
386                                 //does my sibling have descendants from the users groups? 
387                                 int lc = t->tree[parent].getLChild();
388                                 int rc = t->tree[parent].getRChild();
389                                 
390                                 int sib = lc;
391                                 if (lc == index) { sib = rc; }
392                                 
393                                 map<string, int>::iterator itGroup;
394                                 int pcountSize = 0;
395                                 itGroup = t->tree[sib].pcount.find(groupA);
396                                 if (itGroup != t->tree[sib].pcount.end()) { pcountSize++;  } 
397                                 itGroup = t->tree[sib].pcount.find(groupB);
398                                 if (itGroup != t->tree[sib].pcount.end()) { pcountSize++;  } 
399                                 
400                                 //if yes, I am not the root so add me
401                                 if (pcountSize != 0) {
402                                         if (t->tree[index].getBranchLength() != -1) {
403                                                 sum += abs(t->tree[index].getBranchLength()) + tempTotal;
404                                                 tempTotal = 0.0;
405                                         }else {
406                                                 sum += tempTotal;
407                                                 tempTotal = 0.0;
408                                         }
409                                         rootForGrouping[grouping].clear();
410                                         rootForGrouping[grouping].insert(parent);
411                                 }else { //if no, I may be the root so add my br to tempTotal until I am proven innocent
412                                         if (t->tree[index].getBranchLength() != -1) {
413                                                 tempTotal += abs(t->tree[index].getBranchLength()); 
414                                         }
415                                 }
416                         }
417                         
418                         index = parent; 
419                 }
420                 
421                 //get all nodes above the root to add so we don't add their u values above
422                 index = *(rootForGrouping[grouping].begin());
423                 
424                 while(t->tree[index].getParent() != -1){
425                         int parent = t->tree[index].getParent();
426                         rootForGrouping[grouping].insert(parent);
427                         index = parent;
428                 }
429                 return sum;
430         }
431         catch(exception& e) {
432                 m->errorOut(e, "Weighted", "getBranchLengthSums");
433                 exit(1);
434         }
435 }
436 /**************************************************************************************************/
437
438