]> git.donarmstrong.com Git - mothur.git/blob - weighted.cpp
24adbba9de929382c8bbcaa3efc2272365c73f24
[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                         
198                         count++;
199                 }
200                 
201                 //calculate u for the group comb 
202                 
203                 for (int h = start; h < (start+num); h++) {     
204                         //report progress
205                         m->mothurOut("Processing combo: " + toString(h)); m->mothurOutEndLine();
206                                                 
207                         string groupA = namesOfGroupCombos[h][0]; 
208                         string groupB = namesOfGroupCombos[h][1];
209                         
210                         //calculate u for the group comb 
211                         for(int i=0;i<t->getNumNodes();i++){
212                                 
213                                 if (m->control_pressed) { return data; }
214                                 
215                                 double u;
216                                 //int pcountSize = 0;
217                                 //does this node have descendants from groupA
218                                 it = t->tree[i].pcount.find(groupA);
219                                 //if it does u = # of its descendants with a certain group / total number in tree with a certain group
220                                 if (it != t->tree[i].pcount.end()) {
221                                         u = (double) t->tree[i].pcount[groupA] / (double) tmap->seqsPerGroup[groupA];
222                                 }else { u = 0.00; }
223                                 
224                                 
225                                 //does this node have descendants from group l
226                                 it = t->tree[i].pcount.find(groupB);
227                                 //if it does subtract their percentage from u
228                                 if (it != t->tree[i].pcount.end()) {
229                                         u -= (double) t->tree[i].pcount[groupB] / (double) tmap->seqsPerGroup[groupB];
230                                 }
231                                 
232                                 //if this is not the root then add it
233                                 if (rootForGrouping[namesOfGroupCombos[h]].count(i) == 0) {
234                                         u = abs(u * t->tree[i].getBranchLength());
235                                         WScore[(groupA+groupB)] += u; 
236                                 }
237                                 
238                         }
239                 }
240                 
241                 /********************************************************/
242                 //calculate weighted score for the group combination
243                 double UN;      
244                 count = 0;
245                 for (int h = start; h < (start+num); h++) {
246                         UN = (WScore[namesOfGroupCombos[h][0]+namesOfGroupCombos[h][1]] / D[count]);
247                 
248                         if (isnan(UN) || isinf(UN)) { UN = 0; } 
249                         results.push_back(UN);
250                         count++;
251                 }
252                                 
253                 return results; 
254         }
255         catch(exception& e) {
256                 m->errorOut(e, "Weighted", "driver");
257                 exit(1);
258         }
259 }
260 /**************************************************************************************************/
261 EstOutput Weighted::getValues(Tree* t, string groupA, string groupB) { 
262  try {
263                 globaldata = GlobalData::getInstance();
264                 
265                 data.clear(); //clear out old values
266                 
267                 if (m->control_pressed) { return data; }
268                 
269                 //initialize weighted score
270                 WScore[(groupA+groupB)] = 0.0;
271                 double D = 0.0;
272                 set<int> validBranches;
273                 
274                 vector<string> groups; groups.push_back(groupA); groups.push_back(groupB);
275                 
276                 //adding the wieghted sums from group i
277                 for (int j = 0; j < t->groupNodeInfo[groups[0]].size(); j++) { //the leaf nodes that have seqs from group i
278                         map<string, int>::iterator it = t->tree[t->groupNodeInfo[groups[0]][j]].pcount.find(groups[0]);
279                         int numSeqsInGroupI = it->second;
280                         
281                         double sum = getLengthToRoot(t, t->groupNodeInfo[groups[0]][j], groups[0], groups[1]);
282                         double weightedSum = ((numSeqsInGroupI * sum) / (double)tmap->seqsPerGroup[groups[0]]);
283                 
284                         D += weightedSum;
285                 }
286                 
287                 //adding the wieghted sums from group l
288                 for (int j = 0; j < t->groupNodeInfo[groups[1]].size(); j++) { //the leaf nodes that have seqs from group l
289                         map<string, int>::iterator it = t->tree[t->groupNodeInfo[groups[1]][j]].pcount.find(groups[1]);
290                         int numSeqsInGroupL = it->second;
291                         
292                         double sum = getLengthToRoot(t, t->groupNodeInfo[groups[1]][j], groups[0], groups[1]);
293                         double weightedSum = ((numSeqsInGroupL * sum) / (double)tmap->seqsPerGroup[groups[1]]);
294                 
295                         D += weightedSum;
296                 }
297                 
298                 int numLeaves = t->getNumLeaves();
299                 
300                 //calculate u for the group comb 
301                 for(int i=0;i<t->getNumNodes();i++){
302                  
303                         if (m->control_pressed) { return data; }
304                         
305                         double u;
306                         //int pcountSize = 0;
307                         //does this node have descendants from groupA
308                         it = t->tree[i].pcount.find(groupA);
309                         //if it does u = # of its descendants with a certain group / total number in tree with a certain group
310                         if (it != t->tree[i].pcount.end()) {
311                                 u = (double) t->tree[i].pcount[groupA] / (double) tmap->seqsPerGroup[groupA];
312                         }else { u = 0.00; }
313                         
314                         
315                         //does this node have descendants from group l
316                         it = t->tree[i].pcount.find(groupB);
317                         //if it does subtract their percentage from u
318                         if (it != t->tree[i].pcount.end()) {
319                                 u -= (double) t->tree[i].pcount[groupB] / (double) tmap->seqsPerGroup[groupB];
320                         }
321                         
322                         //if this is not the root then add it
323                         if (rootForGrouping[groups].count(i) == 0) {
324                                 u = abs(u * t->tree[i].getBranchLength());
325                                 WScore[(groupA+groupB)] += u; 
326                         }
327                 }               
328                 /********************************************************/
329                 
330                 //calculate weighted score for the group combination
331                 double UN;      
332                 UN = (WScore[(groupA+groupB)] / D);
333                 
334                 if (isnan(UN) || isinf(UN)) { UN = 0; } 
335                 data.push_back(UN);
336                                 
337                 return data; 
338         }
339         catch(exception& e) {
340                 m->errorOut(e, "Weighted", "getValues");
341                 exit(1);
342         }
343 }
344 /**************************************************************************************************/
345 double Weighted::getLengthToRoot(Tree* t, int v, string groupA, string groupB) { 
346         try {
347                 
348                 double sum = 0.0;
349                 int index = v;
350         
351                 //you are a leaf
352                 if(t->tree[index].getBranchLength() != -1){     sum += abs(t->tree[index].getBranchLength());   }
353                 double tempTotal = 0.0;
354                 index = t->tree[index].getParent();     
355                 
356                 vector<string> grouping; grouping.push_back(groupA); grouping.push_back(groupB);
357                 
358                 rootForGrouping[grouping].insert(index);
359                         
360                 //while you aren't at root
361                 while(t->tree[index].getParent() != -1){
362
363                         if (m->control_pressed) {  return sum; }
364                                 
365                         //am I the root for this grouping? if so I want to stop "early"
366                         //does my sibling have descendants from the users groups? 
367                         int parent = t->tree[index].getParent();
368                         int lc = t->tree[parent].getLChild();
369                         int rc = t->tree[parent].getRChild();
370                         
371                         int sib = lc;
372                         if (lc == index) { sib = rc; }
373                         
374                         map<string, int>::iterator itGroup;
375                         int pcountSize = 0;
376                         itGroup = t->tree[sib].pcount.find(groupA);
377                         if (itGroup != t->tree[sib].pcount.end()) { pcountSize++;  } 
378                         itGroup = t->tree[sib].pcount.find(groupB);
379                         if (itGroup != t->tree[sib].pcount.end()) { pcountSize++;  } 
380                                                         
381                         //if yes, I am not the root so add me
382                         if (pcountSize != 0) {
383                                 if (t->tree[index].getBranchLength() != -1) {
384                                         sum += abs(t->tree[index].getBranchLength()) + tempTotal;
385                                         tempTotal = 0.0;
386                                 }else {
387                                         sum += tempTotal;
388                                         tempTotal = 0.0;
389                                 }
390                                 rootForGrouping[grouping].clear();
391                                 rootForGrouping[grouping].insert(parent);
392                         }else { //if no, I may be the root so add my br to tempTotal until I am proven innocent
393                                 if (t->tree[index].getBranchLength() != -1) {
394                                         tempTotal += abs(t->tree[index].getBranchLength()); 
395                                 }
396                         }
397                         
398                         index = parent; 
399                 }
400                 
401                 //get all nodes above the root to add so we don't add their u values above
402                 index = *(rootForGrouping[grouping].begin());
403                 while(t->tree[index].getParent() != -1){
404                         int parent = t->tree[index].getParent();
405                         rootForGrouping[grouping].insert(parent);
406                         index = parent;
407                 }
408                 
409                 return sum;
410         }
411         catch(exception& e) {
412                 m->errorOut(e, "Weighted", "getBranchLengthSums");
413                 exit(1);
414         }
415 }
416 /**************************************************************************************************/
417
418