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