Debian Codegraph @

src/dr/app/tools/DensityMap.java

raw symbols SCIP
1 /*
2 * DensityMap.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.app.tools;
27
28 import dr.evolution.tree.NodeRef;
29 import dr.evolution.tree.Tree;
30 import dr.evomodel.continuous.MultivariateDiffusionModel;
31 import dr.inference.model.MatrixParameter;
32 import dr.math.matrixAlgebra.Matrix;
33 import dr.util.TIFFWriter;
34
35 import java.io.DataOutputStream;
36 import java.io.FileOutputStream;
37
38 /**
39 * @author Marc Suchard
40 * Based on the class CalculateSplitRates in JEBL
41 */
42 class DensityMap {
43 private final String SEP = "\t";
44 private final String DBL = "%5.4f";
45
46 private int binX;
47 private int binY;
48
49 private int[][] data;
50 private double[] average;
51 private double[] testStatistic;
52 private int[] counts;
53 private int[] singleTreeCounts;
54 private int count;
55 private double startX;
56 private double endX;
57 private double startY;
58 private double endY;
59 private double scaleX;
60 private double scaleY;
61
62 private double minX = Double.POSITIVE_INFINITY;
63 private double maxX = Double.NEGATIVE_INFINITY;
64 private double minY = Double.POSITIVE_INFINITY;
65 private double maxY = Double.NEGATIVE_INFINITY;
66
67 private double upperX;
68 private double lowerX;
69 private double upperY;
70 private double lowerY;
71
72 private boolean jointDensity = false;
73 private boolean isCalibrated = false;
74
75 private int slice;
76
77 public DensityMap(int slice, int binX, int binY,
78 double upperX, double lowerX,
79 double upperY, double lowerY, boolean logScale) {
80 setUp(slice, binX, binY, upperX, lowerX, upperY, lowerY, logScale);
81 }
82
83 private void setUp(int slice, int binX, int binY,
84 double upperX, double lowerX,
85 double upperY, double lowerY, boolean logScale) {
86 this.slice = slice;
87 this.binX = binX;
88 this.binY = binY;
89 data = new int[binX][binY];
90 counts = new int[binX];
91 count = 0;
92 this.upperX = upperX;
93 this.lowerX = lowerX;
94 this.upperY = upperY;
95 this.lowerY = lowerY;
96 this.logScale = logScale;
97 }
98
99 public DensityMap(int binX, int binY, double[] ptX, double[] ptY) {
100
101 // double maxX = Double.MIN_VALUE;
102 // double maxY = Double.MIN_VALUE;
103 // double minX = Double.MAX_VALUE;
104 // double minY = Double.MAX_VALUE;
105
106 if (ptX.length != ptY.length) {
107 throw new RuntimeException("Attempting to construct an unbalanced DensityMap");
108 }
109
110 int len = ptX.length;
111
112 for (int i = 0; i < len; i++) {
113 if (ptX[i] < minX) minX = ptX[i];
114 if (ptY[i] < minY) minY = ptY[i];
115 if (ptX[i] > maxX) maxX = ptX[i];
116 if (ptY[i] > maxY) maxY = ptY[i];
117 }
118
119 double scaleX = (maxX - minX) / (double) (binX - 1); // -1 necessary to ensure that maxValue falls in the last box
120 double scaleY = (maxY - minY) / (double) (binY - 1);
121
122 minX -= 1.5 * scaleX; // Ensures that all boarder cells have zero mass
123 maxX += 0.5 * scaleX;
124 minY -= 1.5 * scaleY;
125 maxY += 0.5 * scaleY;
126
127
128 setUp(0, binX, binY, maxX, minX, maxY, minY, false);
129 // this.minX =
130 checkCalibration();
131
132 for (int i = 0; i < len; i++) {
133 addPoint(ptX[i], ptY[i]);
134 // System.err.println("Added: "+ptX[i]+":"+ptY[i]);
135 }
136
137 }
138
139 public double[] getXMidPoints() {
140 if (!isCalibrated)
141 throw new RuntimeException("Density map is not calibrated");
142 double[] pts = new double[binX];
143 pts[0] = startX + 0.5 * scaleX;
144 for (int i = 1; i < binX; i++)
145 pts[i] = pts[i - 1] + scaleX;
146 return pts;
147 }
148
149 public double[] getYMidPoints() {
150 if (!isCalibrated)
151 throw new RuntimeException("Density map is not calibrated");
152 double[] pts = new double[binY];
153 pts[0] = startY + 0.5 * scaleY;
154 for (int i = 1; i < binY; i++)
155 pts[i] = pts[i - 1] + scaleY;
156 return pts;
157 }
158
159 private boolean logScale = false;
160
161 public void setLogScale(boolean logscale) {
162 this.logScale = logscale;
163 }
164
165 private double transform(double d) {
166 if (logScale)
167 return Math.log(d);
168 return d;
169 }
170
171 public void calibrate(Tree tree, String attributeName) {
172 boolean foundAttribute = false;
173
174 if (isCalibrated) {
175 throw new RuntimeException("Already calibrated");
176 }
177
178 if (jointDensity) {
179 throw new RuntimeException("Already calibrated as a joint density map");
180 }
181
182 double height = tree.getNodeHeight(tree.getRoot());
183 if (height > maxX) {
184 maxX = height;
185 }
186 minX = 0.0;
187 for (int i = 0; i < tree.getNodeCount(); i++) {
188 NodeRef node = tree.getNode(i);
189 if (node != tree.getRoot()) {
190 Double value = (Double) tree.getNodeAttribute(node, attributeName);
191 if (value != null) {
192 value = transform(value);
193 if (value < minY)
194 minY = value;
195 if (value > maxY)
196 maxY = value;
197 foundAttribute = true;
198 }
199 }
200 }
201 if (!foundAttribute) {
202 throw new RuntimeException("Can't find any attributes, " + attributeName + ", in tree " + tree.getId());
203 }
204 // System.out.println("Calibrated to:");
205 // System.out.println("\tminX = "+minX);
206 // System.out.println("\tmaxX = "+maxX);
207 // System.out.println("\tminY = "+minY);
208 // System.out.println("\tmaxY = "+maxY);
209
210 }
211
212 public void calibrate(Tree tree, String attributeName1, String attributeName2) {
213 boolean foundAttribute1 = false;
214 boolean foundAttribute2 = false;
215
216 jointDensity = true;
217
218 if (isCalibrated) {
219 throw new RuntimeException("Already calibrated");
220 }
221
222 // double height = tree.getNodeHeight(tree.getRoot());
223 // if (height > maxX) {
224 // maxX = height;
225 // }
226 for (int i = 0; i < tree.getNodeCount(); i++) {
227 NodeRef node = tree.getNode(i);
228 if (node != tree.getRoot()) {
229 Double value = (Double) tree.getNodeAttribute(node, attributeName1);
230 if (value != null) {
231 value = transform(value);
232 if (value < minX)
233 minX = value;
234 if (value > maxX)
235 maxX = value;
236 foundAttribute1 = true;
237 }
238 value = (Double) tree.getNodeAttribute(node, attributeName2);
239 if (value != null) {
240 value = transform(value);
241 if (value < minY)
242 minY = value;
243 if (value > maxY)
244 maxY = value;
245 foundAttribute2 = true;
246 }
247 }
248 }
249 if (!foundAttribute1) {
250 throw new RuntimeException("Can't find any attributes, " + attributeName1 + ", in tree " + tree.getId());
251 }
252
253 if (!foundAttribute2) {
254 throw new RuntimeException("Can't find any attributes, " + attributeName2 + ", in tree " + tree.getId());
255 }
256 // System.err.printf("Calibrated: minY = %3.2f, maxY = %3.2f, minX = %3.2f, maxX = %3.2f\n",minY,maxY,minX,maxX);
257 // System.exit(-1);
258 }
259
260 public void addTree(Tree tree, String attributeName) {
261
262 checkCalibration();
263
264 for (int i = 0; i < tree.getNodeCount(); i++) {
265 NodeRef node = tree.getNode(i);
266 if (node != tree.getRoot()) {
267 Double value = (Double) tree.getNodeAttribute(node, attributeName);
268 if (value != null) {
269 value = transform(value);
270 addBranch(tree.getNodeHeight(node), tree.getNodeHeight(tree.getParent(node)), value);
271 }
272 }
273 }
274 }
275
276 private void checkCalibration() {
277 if (!isCalibrated) {
278 startX = minX;
279 if (lowerX != Double.NEGATIVE_INFINITY) {
280 startX = lowerX;
281 }
282
283 endX = maxX;
284 if (upperX != Double.POSITIVE_INFINITY) {
285 endX = upperX;
286 }
287
288 startY = minY;
289 if (lowerY != Double.NEGATIVE_INFINITY) {
290 startY = lowerY;
291 }
292
293 endY = maxY;
294 if (upperY != Double.POSITIVE_INFINITY) {
295 endY = upperY;
296 }
297
298 scaleX = (endX - startX) / (double) (binX - 1); // -1 necessary to ensure that maxValue falls in the last box
299 scaleY = (endY - startY) / (double) (binY - 1);
300
301 isCalibrated = true;
302 }
303
304
305 }
306
307 public void addTree(Tree tree, double sampleTime, String attributeName1, String attributeName2) {
308
309 checkCalibration();
310
311 double[][] variance = null;
312 Object[] obj = (Object[]) tree.getAttribute(MultivariateDiffusionModel.PRECISION_TREE_ATTRIBUTE);
313 if (obj != null) {
314 variance = new Matrix(
315 MatrixParameter.parseFromSymmetricDoubleArray(obj).getParameterAsMatrix()
316 ).inverse().toComponents();
317 }
318 for (int i = 0; i < tree.getNodeCount(); i++) {
319 NodeRef node = tree.getNode(i);
320 if (node != tree.getRoot()) {
321 NodeRef parent = tree.getParent(node);
322 double t1 = tree.getNodeHeight(node);
323 double t2 = tree.getNodeHeight(parent);
324 if (t1 <= sampleTime && t2 >= sampleTime) {
325 Double valueX1 = transform((Double) tree.getNodeAttribute(node, attributeName1));
326 Double valueY1 = transform((Double) tree.getNodeAttribute(node, attributeName2));
327 Double valueX2 = transform((Double) tree.getNodeAttribute(parent, attributeName1));
328 Double valueY2 = transform((Double) tree.getNodeAttribute(parent, attributeName2));
329 if (valueX1 != null && valueY1 != null && valueX2 != null && valueY2 != null) {
330 addPoint(sampleTime, t1, t2, valueX1, valueY1, valueX2, valueY2, variance);
331 }
332 }
333 }
334 }
335 }
336
337 public int[][] getDensityMap() {
338 return data;
339 }
340
341 private void addBranch(double start, double end, double y) {
342 if (start >= endX || end <= startX) {
343 // branch is outside bounds...
344 return;
345 }
346 if (y > endY || y < startY) {
347 // value is outside bounds...
348 return;
349 }
350
351 // clip the branch to the bounds
352 if (start < startX) {
353 start = startX;
354 }
355 if (end > endX) {
356 end = endX;
357 }
358
359 // determine bin for y
360 int Y = (int) ((y - startY) / scaleY);
361 // determine start and end bin for x
362 int START = (int) ((start - startX) / scaleX);
363 int END = (int) ((end - startX) / scaleX);
364
365 // System.out.println(start+":"+end+" -> "+START+":"+END);
366 for (int i = START; i <= END; i++) {
367 data[i][Y] += 1;
368 counts[i] += 1;
369 // average[i] += y;
370 }
371 }
372
373 private void addPoint(double x, double y) {
374 if (x > endX || x < startX || y > endY || y < startY)
375 return;
376 int X = (int) ((x - startX) / scaleX);
377 int Y = (int) ((y - startY) / scaleY);
378
379 data[X][Y] += 1;
380 count += 1;
381 }
382
383 private void addPoint(double t, double startTime, double endTime, double x0, double y0, double x1, double y1, double[][] variance) {
384 double t0 = t - startTime;
385 double t1 = endTime - t;
386 double x, y;
387 if (t0 == 0) {
388 x = x0;
389 y = y0;
390 } else if (t1 == 0) {
391 x = x1;
392 y = y1;
393 } else {
394 x = ((x0 / t0) + (x1 / t1)) / ((1.0 / t0) + (1.0 / t1));
395 y = ((y0 / t0) + (y1 / t1)) / ((1.0 / t0) + (1.0 / t1));
396
397 if (variance != null) {
398 // todo add stochastic noise
399 }
400 }
401
402 if (x > endX || x < startX || y > endY || y < startY) {
403 // point is outside bounds...
404 return;
405 }
406
407 // determine bin for x
408 int X = (int) ((x - startX) / scaleX);
409 // determine bin for y
410 int Y = (int) ((y - startY) / scaleY);
411
412 data[X][Y] += 1;
413 count += 1;
414 }
415
416 public String toString() {
417 return toString(true);
418 }
419
420 public void writeAsTIFF(String fileName) {
421
422 double[][] matrix = normalize(255);
423 try {
424 DataOutputStream tiffOut = new DataOutputStream(new FileOutputStream(fileName));
425 TIFFWriter.writeDoubleArray(tiffOut, matrix);
426 tiffOut.close();
427 } catch (Exception e) {
428 throw new RuntimeException(e.getMessage());
429 }
430 }
431
432
433 public double[][] getNormalizedDensity(double max) {
434 if (!isCalibrated)
435 throw new RuntimeException("Density map is not yet calibrated");
436 return normalize(max);
437 }
438
439 private double[][] normalize(double max) {
440
441 double[][] matrix = new double[binX][binY];
442
443 double maxValue = 0;
444 for (int i = 0; i < binY; i++) {
445 for (int j = 0; j < binX; j++) {
446 if (data[j][i] > maxValue) {
447 maxValue = data[j][i];
448 }
449 }
450 }
451
452 for (int i = 0; i < binY; i++) {
453 for (int j = 0; j < binX; j++) {
454 matrix[j][i] = ((double) data[j][i] / maxValue) * max;
455 // double dblCount;
456 // if (jointDensity) {
457 // dblCount = (double) count;
458 // } else {
459 // dblCount = (double) counts[j];
460 // }
461 // if (dblCount > 0) {
462 // matrix[j][i] = (double) data[j][i] / dblCount * max;
463 // } else {
464 // matrix[j][i] = 0.0;
465 // }
466 }
467 }
468
469 return matrix;
470
471 }
472
473 public String toString(boolean printHeaders) {
474
475 StringBuilder sb = new StringBuilder();
476 if (printHeaders) {
477 sb.append(String.format("%7.5f", (double) slice)); // todo should return 3rd dimension coordinate
478 for (int i = 0; i < binX; i++) {
479 sb.append(SEP);
480 sb.append(String.format("%7.5f", startX + scaleX * i));
481 }
482 sb.append("\n");
483 }
484
485 double[][] matrix = normalize(1.0);
486
487 for (int i = 0; i < binY; i++) {
488 if (printHeaders)
489 sb.append(String.format("%7.5f", startY + scaleY * i));
490
491 for (int j = 0; j < binX; j++) {
492
493 if (j > 0 || printHeaders)
494 sb.append(SEP);
495
496 // double dblCount;
497 // if (jointDensity) {
498 // dblCount = (double) count;
499 // } else {
500 // dblCount = (double) counts[j];
501 // }
502 // if (dblCount > 0) {
503 // sb.append(String.format(DBL,
504 // (double) data[j][i] / dblCount
505 // ));
506 // } else {
507 // sb.append(String.format(DBL, 0.0));
508 // }
509 sb.append(String.format(DBL, matrix[j][i]));
510 }
511 sb.append("\n");
512 }
513 return sb.toString();
514 }
515
516 }