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