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