Debian Codegraph @

src/dr/evomodel/continuous/TopographicalMap.java

raw symbols SCIP
1 /*
2 * TopographicalMap.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.evomodel.continuous;
27
28 import dr.math.SparseMatrixExponential;
29 import dr.math.matrixAlgebra.Vector;
30 import org.jdom.Element;
31 import org.jdom.output.XMLOutputter;
32
33 import java.io.*;
34 import java.util.ArrayList;
35 import java.util.List;
36 import java.util.StringTokenizer;
37 import java.util.zip.GZIPInputStream;
38 import java.util.zip.GZIPOutputStream;
39
40 /**
41 * @author Marc A. Suchard
42 */
43 public class TopographicalMap {
44
45
46 public static final String FORMAT = "%3.2f";
47
48
49 public TopographicalMap(double xStart, double xEnd, double yStart, double yEnd, int xDim, int yDim) {
50 this.xStart = xStart;
51 this.xEnd = xEnd;
52 this.yStart = yStart;
53 this.yEnd = yEnd;
54
55 this.xDim = xDim;
56 this.yDim = yDim;
57 map = new double[xDim][yDim];
58
59 xDelta = (xEnd - xStart) / xDim;
60 yDelta = (yEnd - yStart) / yDim;
61 }
62
63 private double xStart;
64 private double xEnd;
65 private double yStart;
66 private double yEnd;
67 private double xDelta;
68 private double yDelta;
69
70 // public TopographicalMap(int xDim, int yDim) {
71 // TopographicalMap(0,1,0,1,xDim,yDim);
72 // }
73
74 public TopographicalMap(double[][] map) {
75 xDim = map.length;
76 yDim = map[0].length;
77 this.map = map;
78 order = setUpIndices();
79 setUpRandomWalkMatrix();
80 }
81
82 public int getXDim() {
83 return xDim;
84 }
85
86 public int getYDim() {
87 return yDim;
88 }
89
90 public int getOrder() {
91 return order;
92 }
93
94 public int getNonZeroSize() {
95 return nonZeroElements;
96 }
97
98
99 private int setUpIndices() {
100 int index = 0;
101 indexByXY = new int[xDim * yDim];
102 int[] tmpXYByIndex = new int[xDim * yDim];
103 for (int x = 0; x < xDim; x++) {
104 for (int y = 0; y < yDim; y++) {
105 final int xy = x * yDim + y;
106 if (!Double.isNaN(map[x][y])) {
107 tmpXYByIndex[index] = xy;
108 indexByXY[xy] = index;
109 index++;
110 } else
111 indexByXY[xy] = -1;
112 }
113 }
114 xyByIndex = new int[index];
115 xyByIndex = tmpXYByIndex;
116 return index;
117 }
118
119 public double getCTMCProbability(double[] start, double[] stop, double time) {
120 int startIndex = getIndex((int) start[0], (int) start[1]);
121 int stopIndex = getIndex((int) stop[0], (int) stop[1]);
122
123 // startIndex = stopIndex = 0;
124
125 if (startIndex == -1 || stopIndex == -1)
126 return 0;
127 // System.err.println("Indices: "+startIndex+" -> "+stopIndex);
128 // System.err.println("Time = "+time);
129 double prob = matrixExp.getExponentialEntry(startIndex, stopIndex, time);
130 // System.err.println("prob = "+prob);
131 return prob;
132 }
133
134
135 public SparseMatrixExponential getMatrix() {
136 return matrixExp;
137 }
138
139 public boolean isValidPoint(int x, int y) {
140 return (getIndex(x, y) != -1);
141 }
142
143 public int getIndex(int x, int y) {
144 if (x < 0 || x >= xDim || y < 0 || y >= yDim)
145 return -1;
146 return indexByXY[x * yDim + y];
147 }
148
149 public int getX(int index) {
150 return xyByIndex[index] / yDim;
151 }
152
153 public int getY(int index) {
154 final int xy = xyByIndex[index];
155 final int dim = yDim;
156 final int mod = xy % dim;
157 return mod;
158 }
159
160 private void setUpRandomWalkMatrix() {
161
162 List<GraphEdge> edgeList = new ArrayList<GraphEdge>();
163 for (int index = 0; index < order; index++) {
164 int x = getX(index);
165 int y = getY(index);
166 int dest;
167
168 dest = getIndex(x - 1, y - 1);
169 if (dest != -1)
170 edgeList.add(new GraphEdge(
171 index, dest, getWeight(x, y, x - 1, y - 1)
172 ));
173
174 dest = getIndex(x - 1, y);
175 if (dest != -1)
176 edgeList.add(new GraphEdge(
177 index, dest, getWeight(x, y, x - 1, y)
178 ));
179
180 dest = getIndex(x - 1, y + 1);
181 if (dest != -1)
182 edgeList.add(new GraphEdge(
183 index, dest, getWeight(x, y, x - 1, y + 1)
184 ));
185
186 dest = getIndex(x, y - 1);
187 if (dest != -1)
188 edgeList.add(new GraphEdge(
189 index, dest, getWeight(x, y, x, y - 1)
190 ));
191
192 dest = getIndex(x, y + 1);
193 if (dest != -1)
194 edgeList.add(new GraphEdge(
195 index, dest, getWeight(x, y, x, y + 1)
196 ));
197
198 dest = getIndex(x + 1, y - 1);
199 if (dest != -1)
200 edgeList.add(new GraphEdge(
201 index, dest, getWeight(x, y, x + 1, y - 1)
202 ));
203
204 dest = getIndex(x + 1, y);
205 if (dest != -1)
206 edgeList.add(new GraphEdge(
207 index, dest, getWeight(x, y, x + 1, y)
208 ));
209
210 dest = getIndex(x + 1, y + 1);
211 if (dest != -1)
212 edgeList.add(new GraphEdge(
213 index, dest, getWeight(x, y, x + 1, y + 1)
214 ));
215
216
217 }
218
219
220 double[] rowTotal = new double[order];
221 nonZeroElements = edgeList.size() + order; // don't forget the diagonals
222
223 matrixExp = new SparseMatrixExponential(order, nonZeroElements);
224
225 // int index = 0;
226 for (GraphEdge edge : edgeList) {
227 int start = edge.getStart();
228 int stop = edge.getStop();
229 double weight = edge.getWeight();
230 rowTotal[start] -= weight;
231 // bandMatrix.set(start, stop, weight);
232 matrixExp.addEntry(start, stop, weight);
233 }
234
235 double norm = 0;
236 for (int i = 0; i < order; i++) {
237 if (-2 * rowTotal[i] > norm)
238 norm = -2 * rowTotal[i];
239 // bandMatrix.set(i, i, rowTotal[i]);
240 matrixExp.addEntry(i, i, rowTotal[i]);
241
242 }
243
244 matrixExp.setNorm(norm);
245 }
246
247
248 public void doStuff() {
249 System.err.println(matrixExp.getExponentialEntry(0, 1, 1000));
250 System.err.println(matrixExp.getExponentialEntry(0, 0, 1000));
251
252
253 }
254
255 public static void writeEigenvectors(String file, double[][] mat) throws IOException {
256
257 PrintWriter writer;
258 if (file.endsWith("gz"))
259 writer = new PrintWriter(
260 new OutputStreamWriter
261 (new GZIPOutputStream
262 (new FileOutputStream(file))));
263 else
264 writer = new PrintWriter(new FileWriter(file));
265
266 final int dim = mat.length;
267 writer.println(dim);
268 for (int i = 0; i < dim; i++) {
269 for (int j = 0; j < dim; j++)
270 writer.println(mat[i][j]);
271 }
272 writer.close();
273
274 }
275
276 public static void writeEigenvalues(String file, double[] vec) throws IOException {
277
278 PrintWriter writer;
279 if (file.endsWith("gz"))
280 writer = new PrintWriter(
281 new OutputStreamWriter
282 (new GZIPOutputStream
283 (new FileOutputStream(file))));
284 else
285 writer = new PrintWriter(new FileWriter(file));
286
287 writer.println(vec.length);
288 for (double d : vec)
289 writer.println(d);
290 writer.close();
291
292 }
293
294 public static int extractInt(String line) {
295 StringTokenizer st = new StringTokenizer(line);
296 st.nextToken();
297 return Integer.parseInt(st.nextToken());
298 }
299
300 public static final String defaultInvalidString = "*";
301
302 public static double[][] readGRASSAscii(String file) throws IOException {
303 return readGRASSAscii(file, defaultInvalidString);
304 }
305
306 public static double[][] readGRASSAscii(String file, String invalidString) throws IOException {
307 double[][] map;
308 BufferedReader reader = getReader(file);
309 String northLine = reader.readLine();
310 String southLine = reader.readLine();
311 String eastLine = reader.readLine();
312 String westLine = reader.readLine();
313 int numberRows = extractInt(reader.readLine());
314 int numberCols = extractInt(reader.readLine());
315 map = new double[numberRows][numberCols];
316 for (int i = 0; i < numberRows; i++) {
317 String line = reader.readLine();
318 StringTokenizer st = new StringTokenizer(line);
319 for (int j = 0; j < numberCols; j++) {
320 String item = st.nextToken();
321 if (item.compareTo(invalidString) == 0) {
322 map[i][j] = Double.NaN;
323 } else {
324 map[i][j] = Double.parseDouble(item);
325 }
326 }
327 }
328 return map;
329 }
330
331 public String toString() {
332 return toCartogram();
333 }
334
335 public String toCartogram() {
336 StringBuffer sb = new StringBuffer();
337 for (int i = 0; i < xDim; i++) {
338 for (int j = 0; j < yDim; j++) {
339 sb.append(String.format(FORMAT, map[i][j]));
340 if (j < (yDim - 1))
341 sb.append(" ");
342 }
343 sb.append("\n");
344 }
345 return sb.toString();
346 }
347
348 public static BufferedReader getReader(String file) throws IOException {
349 BufferedReader reader;
350 if (file.endsWith("gz"))
351 reader = new BufferedReader
352 (new InputStreamReader
353 (new GZIPInputStream
354 (new FileInputStream(file))));
355 else
356 reader = new BufferedReader(new FileReader(file));
357 return reader;
358 }
359
360 public static BufferedWriter getWriter(String file) throws IOException {
361 BufferedWriter writer;
362 if (file.endsWith("gz"))
363 writer = new BufferedWriter(new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(file))));
364 else
365 writer = new BufferedWriter(new FileWriter(file));
366 return writer;
367 }
368
369 public static double[] readEigenvalues(String file) throws IOException {
370
371 BufferedReader reader = getReader(file);
372
373 final int dim = Integer.parseInt(reader.readLine());
374 double[] vec = new double[dim];
375 for (int i = 0; i < dim; i++)
376 vec[i] = Double.parseDouble(reader.readLine());
377 reader.close();
378
379 return vec;
380
381 }
382
383 public static double[][] readEigenvectors(String file) throws IOException {
384
385 BufferedReader reader = getReader(file);
386
387 final int dim = Integer.parseInt(reader.readLine());
388 double[][] mat = new double[dim][dim];
389 for (int i = 0; i < dim; i++) {
390 for (int j = 0; j < dim; j++)
391 mat[i][j] = Double.parseDouble(reader.readLine());
392 }
393 reader.close();
394
395 return mat;
396
397 }
398
399 /* Used for converting GRASS files to PathFinding XML */
400
401 public static final String TERRAIN = "terrain";
402 public static final String TYPE_TYPE = "tileTypes";
403 public static final String TYPE = "type";
404
405 public static String mapToXMLString(double[][] map, int numLevels) {
406 XMLOutputter outputter = new XMLOutputter(org.jdom.output.Format.getPrettyFormat());
407 return outputter.outputString(mapToXML(map, numLevels));
408 // root.toString();
409 }
410
411 // static
412
413
414 public static Element mapToXML(double[][] map, int numLevels) {
415
416 Element root = new Element(TERRAIN);
417 Element tileTypes = new Element(TYPE_TYPE);
418 Element size = new Element("size");
419 Element content = new Element("content");
420 root.addContent(tileTypes);
421 root.addContent(size);
422 root.addContent(content);
423
424 // Make sizes
425 size.addContent(new Element("rows").addContent(Integer.toString(map.length)));
426 size.addContent(new Element("columns").addContent(Integer.toString(map[0].length)));
427 size.addContent(new Element("height").addContent(Integer.toString(map.length)));
428 size.addContent(new Element("width").addContent(Integer.toString(map[0].length)));
429
430 // Make cutpoints
431 double min = Double.MAX_VALUE;
432 double max = Double.MIN_VALUE;
433
434 for (int i = 0; i < map.length; i++) {
435 for (int j = 0; j < map[0].length; j++) {
436 if (!Double.isNaN(map[i][j])) {
437 // System.err.println("die");
438 // System.exit(-1);
439 // }
440 if (map[i][j] < min)
441 min = map[i][j];
442 if (map[i][j] > max)
443 max = map[i][j];
444 }
445 }
446 }
447
448 // System.err.println("min = ");
449
450 double[] cuts = new double[numLevels];
451 // cuts[numLevels-1] = max;
452 double range = max - min;
453 double delta = range / numLevels;
454 for (int i = 0; i < numLevels; i++)
455 cuts[i] = min + delta * (i + 1);
456
457 int deltaColor = 255 / numLevels;
458
459 // Make tile types
460 double average = min + delta / 2;
461 int grey = 255 - deltaColor;
462 for (int i = 0; i < numLevels; i++) {
463 Element type = new Element("type");
464 type.addContent(new Element("name").addContent("L" + Integer.toString(i)));
465 type.addContent(new Element("cost").addContent(Integer.toString((int) average)));
466 Element color = new Element("color");
467 color.setAttribute("r", Integer.toString(grey));
468 color.setAttribute("g", Integer.toString(grey));
469 color.setAttribute("b", Integer.toString(grey));
470 type.addContent(color);
471 tileTypes.addContent(type);
472 average += delta;
473 grey -= deltaColor;
474 }
475 Element blocked = new Element("type");
476 blocked.addContent(new Element("name").addContent("B"));
477 blocked.addContent(new Element("blocked"));
478 Element color = new Element("color");
479 color.setAttribute("r", Integer.toString(255));
480 color.setAttribute("g", Integer.toString(255));
481 color.setAttribute("b", Integer.toString(255));
482 blocked.addContent(color);
483 tileTypes.addContent(blocked);
484
485 int count = 0;
486
487 // Make content
488 content.addContent(new Element("default").addContent("B"));
489 StringBuffer ascii = new StringBuffer();
490 boolean newLine = true;
491
492 for (int r = 0; r < map.length; r++) {
493 for (int c = 0; c < map[0].length; c++) {
494 if (!Double.isNaN(map[r][c])) {
495 count++;
496 double value = map[r][c];
497 // if( value != Double.NaN ) {
498 int cut = 0;
499 try {
500 while (value > cuts[cut])
501 cut++;
502 } catch (Exception e) {
503 System.err.println("Error: " + e);
504 System.err.println("value = " + value);
505 System.err.println("cuts = " + new Vector(cuts));
506 System.err.println("min = " + min);
507 System.err.println("max = " + max);
508 System.exit(-1);
509 }
510 Element cell = new Element("column");
511 cell.setAttribute("r", Integer.toString(r));
512 cell.setAttribute("c", Integer.toString(c));
513 cell.setAttribute("length", "1");
514 cell.addContent("L" + Integer.toString(cut));
515 // if( count < 10)
516 content.addContent(cell);
517 ascii.append((cut + 1) + " ");
518
519 // } else {
520 // System.err.println("about time");
521 // System.exit(-1);
522 } else {
523 ascii.append("NA ");
524 }
525
526 }
527 ascii.append("\n");
528 }
529
530 System.out.println(ascii);
531
532 return root;
533 }
534
535
536 public static void writeXML(String file) throws IOException {
537
538 }
539
540 // private double getProbability(int I, int J, double time) {
541 // double probability = 0;
542 // for (int k = 0; k < order; k++) {
543 // probability += eVec[I][k] * Math.exp(time * eVal[k]) * eVec[J][k];
544 // }
545 // return probability;
546 //
547 // }
548
549
550 public class GraphEdge {
551 private int start;
552 private int stop;
553 private double weight;
554
555 public GraphEdge(int start, int stop, double weight) {
556 this.start = start;
557 this.stop = stop;
558 this.weight = weight;
559 }
560
561 public int getStart() {
562 return start;
563 }
564
565 public void setStart(int start) {
566 this.start = start;
567 }
568
569 public int getStop() {
570 return stop;
571 }
572
573 public void setStop(int stop) {
574 this.stop = stop;
575 }
576
577 public double getWeight() {
578 return weight;
579 }
580
581 public void setWeight(double weight) {
582 this.weight = weight;
583 }
584 }
585
586 public double getWeight(int x0, int y0, int x1, int y1) {
587 return 1.0 / (100 * Math.abs(map[x0][y0] - map[x1][y1]) + 1.0);
588 }
589
590
591 public static void main(String[] args) {
592 double[][] map = null;
593 try {
594 // try {
595 map = readGRASSAscii(args[1]);
596 // } catch (IOException e) {
597 // e.printStackTrace();
598 // }
599 System.err.println("Read in GRASS file.");
600 System.err.println("Writing XML file.");
601 String xml = mapToXMLString(map, Integer.parseInt(args[0]));
602 PrintWriter writer = new PrintWriter(new FileWriter(args[2]));
603 writer.println(xml);
604 writer.close();
605 } catch (Exception e) {
606 System.err.println("Command-line error.");
607 System.err.println("USAGE: program_name <# of levels> <GRASS file> <XML file>");
608 }
609
610 // new TopographicalMap(map).doStuff();
611 }
612
613 private double[][] map;
614 private int[] indexByXY;
615 private int[] xyByIndex;
616 SparseMatrixExponential matrixExp;
617
618 private int xDim;
619 private int yDim;
620 private int order;
621 private int nonZeroElements;
622
623 public static double[][] sillyMap = {
624 {0.0, 100.0, 0.0, 100.0, 0.0},
625 {0.0, 0.0, 0.0, 100.0, 0.0},
626 {100.0, 0.0, 100.0, 100.0, 0.0},
627 {100.0, 0.0, 100.0, 100.0, 0.0},
628 {100.0, 0.0, 0.0, 0.0, 0.0}
629 };
630
631 }