]> git.donarmstrong.com Git - mothur.git/blob - sharedjsd.cpp
fixes while testing 1.33.0
[mothur.git] / sharedjsd.cpp
1 //
2 //  sharedjsd.cpp
3 //  Mothur
4 //
5 //  Created by SarahsWork on 12/9/13.
6 //  Copyright (c) 2013 Schloss Lab. All rights reserved.
7 //
8
9 #include "sharedjsd.h"
10
11 /***********************************************************************/
12 //KLD <- function(x,y) sum(x *log(x/y))
13 //JSD<- function(x,y) sqrt(0.5 * KLD(x, (x+y)/2) + 0.5 * KLD(y, (x+y)/2))
14 EstOutput JSD::getValues(vector<SharedRAbundVector*> shared) {
15         try {
16         
17                 data.resize(1,0);
18         
19         double KLD1 = 0.0;
20         double KLD2 = 0.0;
21
22         vector<int> countA = shared[0]->getAbundances();
23         vector<int> countB = shared[1]->getAbundances();
24         double totalA = 0;
25         double totalB = 0;
26         
27                 for (int i = 0; i < shared[0]->getNumBins(); i++) {
28             totalA += countA[i];
29             totalB += countB[i];
30         }
31
32         for (int i = 0; i < shared[0]->getNumBins(); i++) {
33             double tempA = countA[i] / totalA;
34             double tempB = countB[i] / totalB;
35             
36             tempA = countA[i] / totalA;
37             tempB = countB[i] / totalB;
38
39             if (tempA == 0) { tempA = 0.000001; }
40             if (tempB == 0) { tempB = 0.000001; }
41
42             double denom = (tempA+tempB)/(double)2.0;
43
44             if (tempA != 0) {  KLD1 += tempA * log(tempA/denom); } //KLD(x,m)
45             if (tempB != 0) {  KLD2 += tempB * log(tempB/denom); } //KLD(y,m)
46
47         }
48
49             
50         data[0] = ((0.5*KLD1) + (0.5*KLD2));
51                 
52                 if (isnan(data[0]) || isinf(data[0])) { data[0] = 0; }
53                 
54                 return data;
55         }
56         catch(exception& e) {
57                 m->errorOut(e, "JSD", "getValues");
58                 exit(1);
59         }
60 }
61
62 /***********************************************************************/