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