| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
package dr.math; |
| 27 |
|
| 28 |
import java.util.Arrays; |
| 29 |
import java.util.HashMap; |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
public class MultivariateMonteCarloIntegral implements MultivariateIntegral { |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
public MultivariateMonteCarloIntegral(int sampleSize, int bins) { |
| 45 |
this.sampleSize = sampleSize; |
| 46 |
this.bins = bins; |
| 47 |
} |
| 48 |
|
| 49 |
public MultivariateMonteCarloIntegral(int sampleSize) { |
| 50 |
this(sampleSize, 1); |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
public double integrate(MultivariateFunction f, double[] mins, double[] maxes) { |
| 61 |
|
| 62 |
int dim = f.getNumArguments(); |
| 63 |
int totalBins = bins*dim; |
| 64 |
double[] steps = new double[dim]; |
| 65 |
double totalArea=1; |
| 66 |
|
| 67 |
|
| 68 |
for(int i=0; i<dim; i++){ |
| 69 |
totalArea *= (maxes[i]-mins[i]); |
| 70 |
} |
| 71 |
|
| 72 |
HashMap<Integer, double[]> binCorners = new HashMap<Integer, double[]>(); |
| 73 |
double[] currentCorner = new double[dim]; |
| 74 |
|
| 75 |
|
| 76 |
for(int index=0; index<totalBins; index++){ |
| 77 |
binCorners.put(index, Arrays.copyOf(currentCorner, dim)); |
| 78 |
|
| 79 |
int dimToCheck = 0; |
| 80 |
while(dimToCheck<dim){ |
| 81 |
if(currentCorner[dimToCheck]+steps[dimToCheck]<maxes[dimToCheck]){ |
| 82 |
currentCorner[dimToCheck] += steps[dimToCheck]; |
| 83 |
break; |
| 84 |
} else { |
| 85 |
currentCorner[dimToCheck] = mins[dimToCheck]; |
| 86 |
} |
| 87 |
dimToCheck++; |
| 88 |
} |
| 89 |
} |
| 90 |
|
| 91 |
double integral = 0.0; |
| 92 |
|
| 93 |
for(int i=0; i<totalBins; i++){ |
| 94 |
|
| 95 |
for (int j=1; j <= sampleSize; j++) { |
| 96 |
|
| 97 |
double[] sample = new double[dim]; |
| 98 |
for(int k=0; k<sample.length; k++){ |
| 99 |
sample[k] = binCorners.get(i)[k] + MathUtils.nextDouble()*(steps[k]); |
| 100 |
} |
| 101 |
|
| 102 |
integral += f.evaluate(sample); |
| 103 |
} |
| 104 |
|
| 105 |
} |
| 106 |
integral *= totalArea/((double)sampleSize*totalBins); |
| 107 |
return integral; |
| 108 |
} |
| 109 |
|
| 110 |
protected int getSampleSize(){ |
| 111 |
return sampleSize; |
| 112 |
} |
| 113 |
protected int getBins(){ |
| 114 |
return bins; |
| 115 |
} |
| 116 |
|
| 117 |
private int sampleSize; |
| 118 |
private int bins; |
| 119 |
} |