Debian Codegraph @

src/dr/geo/KernelDensityEstimator2D.java

raw symbols SCIP
1 /*
2 * KernelDensityEstimator2D.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.geo;
27
28 import cern.colt.list.DoubleArrayList;
29 import cern.jet.stat.Descriptive;
30 import dr.math.distributions.NormalDistribution;
31 import dr.math.matrixAlgebra.Matrix;
32 import dr.math.matrixAlgebra.Vector;
33 import dr.stats.DiscreteStatistics;
34 import dr.geo.contouring.ContourGenerator;
35 import dr.geo.contouring.ContourAttrib;
36 import dr.geo.contouring.ContourPath;
37 import dr.geo.contouring.ContourMaker;
38
39 import java.util.Arrays;
40
41 /**
42 * KernelDensityEstimator2D creates a bi-variate kernel density smoother for data
43 * @author Marc A. Suchard
44 * @author Philippe Lemey
45 */
46
47 public class KernelDensityEstimator2D implements ContourMaker {
48
49 // kde2d =
50 // function (x, y, h, n = 25, lims = c(range(x), range(y)))
51 // {
52 // nx <- length(x)
53 // if (length(y) != nx)
54 // stop("data vectors must be the same length")
55 // if (any(!is.finite(x)) || any(!is.finite(y)))
56 // stop("missing or infinite values in the data are not allowed")
57 // if (any(!is.finite(lims)))
58 // stop("only finite values are allowed in 'lims'")
59 // gx <- seq.int(lims[1], lims[2], length.out = n)
60 // gy <- seq.int(lims[3], lims[4], length.out = n)
61 // if (missing(h))
62 // h <- c(bandwidth.nrd(x), bandwidth.nrd(y))
63 // h <- h/4
64 // ax <- outer(gx, x, "-")/h[1]
65 // ay <- outer(gy, y, "-")/h[2]
66 // z <- matrix(dnorm(ax), n, nx) %*% t(matrix(dnorm(ay), n,
67 // nx))/(nx * h[1] * h[2])
68 // return(list(x = gx, y = gy, z = z))
69 // }
70
71 /*
72 * @param x x-coordinates of observations
73 * @param y y-coordinates of observations
74 * @param h bi-variate smoothing bandwidths
75 * @param n smoothed grid size
76 * @param lims bi-variate min/max for grid
77 */
78 public KernelDensityEstimator2D(final double[] x, final double[] y, final double[] h, final int n, final double[] lims) {
79 this(x, y, h, n, lims, false);
80 }
81
82 public KernelDensityEstimator2D(final double[] x, final double[] y, final double[] h, final int n, final double[] lims, boolean bandwdithLimited) {
83 this.x = x;
84 this.y = y;
85 if (x.length != y.length)
86 throw new RuntimeException("data vectors must be the same length");
87
88 this.nx = x.length;
89
90 if (n <= 0)
91 throw new RuntimeException("must have a positive number of grid points");
92 this.n = n;
93
94 if (lims != null)
95 this.lims = lims;
96 else
97 setupLims();
98
99 this.limitBandwidth = bandwdithLimited;
100 if (h != null)
101 this.h = h;
102 else
103 setupH();
104
105 doKDE2D();
106 }
107
108 public KernelDensityEstimator2D(final double[] x, final double[] y, boolean limitBandwidth) {
109 this(x,y,null,50,null,limitBandwidth);
110 }
111
112 public KernelDensityEstimator2D(final double[] x, final double[] y) {
113 this(x,y,null,50,null);
114 }
115
116 public KernelDensityEstimator2D(final double[] x, final double[] y, final int n) {
117 this(x,y,null,n,null);
118 }
119
120 public void doKDE2D() {
121 gx = makeSequence(lims[0], lims[1], n);
122 gy = makeSequence(lims[2], lims[3], n);
123 double[][] ax = outerMinusScaled(gx, x, h[0]);
124 double[][] ay = outerMinusScaled(gy, y, h[1]);
125 normalize(ax);
126 normalize(ay);
127 z = new double[n][n];
128 double scale = nx * h[0] * h[1];
129 for (int i = 0; i < n; i++) {
130 for (int j = 0; j < n; j++) {
131 double value = 0;
132 for (int k = 0; k < nx; k++) {
133 value += ax[i][k] * ay[j][k];
134 }
135 z[i][j] = value / scale;
136 }
137 }
138 }
139
140 public double findLevelCorrespondingToMass(double probabilityMass) {
141 double level = 0;
142 double[] sz = new double[n*n];
143 double[] c1 = new double[n*n];
144 for(int i=0; i<n; i++)
145 System.arraycopy(z[i],0,sz,i*n,n);
146 Arrays.sort(sz);
147 final double dx = gx[1] - gx[0];
148 final double dy = gy[1] - gy[0];
149 final double dxdy = dx * dy;
150 c1[0] = sz[0] * dxdy;
151 final double criticalValue = 1.0 - probabilityMass;
152 if (criticalValue < c1[0] || criticalValue >= 1.0)
153 throw new RuntimeException();
154 // do linearInterpolation on density (y) as function of cumulative sum (x)
155 for(int i=1; i<n*n; i++) {
156 c1[i] = sz[i] * dxdy + c1[i-1];
157 if (c1[i] > criticalValue) { // first largest point
158 final double diffC1 = c1[i] - c1[i-1];
159 final double diffSz = sz[i] - sz[i-1];
160 level = sz[i] - (c1[i]-criticalValue) / diffC1 * diffSz;
161 break;
162 }
163 }
164 return level;
165 }
166
167 public ContourPath[] getContourPaths(double hpdValue) {
168
169 double thresholdDensity = findLevelCorrespondingToMass(hpdValue);
170 ContourGenerator contour = new ContourGenerator(getXGrid(), getYGrid(), getKDE(),
171 new ContourAttrib[]{new ContourAttrib(thresholdDensity)});
172
173 ContourPath[] paths = null;
174 try {
175 paths = contour.getContours();
176 } catch (InterruptedException e) {
177 e.printStackTrace();
178 }
179 return paths;
180 }
181
182 public double[][] getKDE() {
183 return z;
184 }
185
186 public double[] getXGrid() {
187 return gx;
188 }
189
190 public double[] getYGrid() {
191 return gy;
192 }
193
194 public void normalize(double[][] X) {
195 for (int i = 0; i < X.length; i++) {
196 for (int j = 0; j < X[0].length; j++)
197 X[i][j] = NormalDistribution.pdf(X[i][j], 0, 1);
198 }
199 }
200
201 public double[][] outerMinusScaled(double[] X, double[] Y, double scale) {
202 double[][] A = new double[X.length][Y.length];
203 for (int indexX = 0; indexX < X.length; indexX++) {
204 for (int indexY = 0; indexY < Y.length; indexY++)
205 A[indexX][indexY] = (X[indexX] - Y[indexY]) / scale;
206 }
207 return A;
208 }
209
210 public double[] makeSequence(double start, double end, int length) {
211 double[] seq = new double[length];
212 double by = (end - start) / (length - 1);
213 double value = start;
214 for (int i = 0; i < length; i++, value += by) {
215 seq[i] = value;
216 }
217 return seq;
218 }
219
220 private double margin = 0.1;
221
222 private void setupLims() {
223 lims = new double[4];
224 lims[0] = DiscreteStatistics.min(x);
225 lims[1] = DiscreteStatistics.max(x);
226 lims[2] = DiscreteStatistics.min(y);
227 lims[3] = DiscreteStatistics.max(y);
228
229 double xDelta = (lims[1] - lims[0]) * margin;
230 double yDelta = (lims[3] - lims[2]) * margin;
231 lims[0] -= xDelta;
232 lims[1] += xDelta;
233 lims[2] -= yDelta;
234 lims[3] += yDelta;
235 }
236
237 private void setupH() {
238 h = new double[2];
239 h[0] = bandwidthNRD(x) / 4;
240 h[1] = bandwidthNRD(y) / 4;
241
242 if (limitBandwidth) {
243 if (h[0] > 0.5) {
244 h[0] = 0.5;
245 }
246 if (h[1] > 0.5) {
247 h[1] = 0.5;
248 }
249 }
250 }
251
252
253 // bandwidth.nrd =
254 // function (x)
255 // {
256 // r <- quantile(x, c(0.25, 0.75))
257 // h <- (r[2] - r[1])/1.34
258 // 4 * 1.06 * min(sqrt(var(x)), h) * length(x)^(-1/5)
259
260 // }
261 public double bandwidthNRD(double[] in) {
262
263 DoubleArrayList inList = new DoubleArrayList(in.length);
264 for (double d : in)
265 inList.add(d);
266 inList.sort();
267
268 final double h = (Descriptive.quantile(inList, 0.75) - Descriptive.quantile(inList, 0.25)) / 1.34;
269
270 return 4 * 1.06 *
271 Math.min(Math.sqrt(DiscreteStatistics.variance(in)), h) *
272 Math.pow(in.length, -0.2);
273 }
274
275 public static void main(String[] arg) {
276
277 double[] x = {3.4, 1.2, 5.6, 2.2, 3.1};
278 double[] y = {1.0, 2.0, 1.0, 2.0, 1.0};
279
280 KernelDensityEstimator2D kde = new KernelDensityEstimator2D(x, y, 4);
281
282 System.out.println(new Vector(kde.getXGrid()));
283 System.out.println(new Vector(kde.getYGrid()));
284 System.out.println(new Matrix(kde.getKDE()));
285 System.exit(-1);
286
287 }
288
289 public double[] getLims() { return lims; }
290
291 private final double[] x; // x coordinates
292 private final double[] y; // y coordinates
293 private double[] h; // h[0] x-bandwidth, h[1] y-bandwidth
294 private final int n; // grid size
295 private double[] lims; // x,y limits
296 private int nx; // length of vectors
297 private double[] gx; // x-grid points
298 private double[] gy; // y-grid points
299 private double[][] z; // KDE estimate;
300
301 private final boolean limitBandwidth;
302
303 }