Debian Codegraph @

src/dr/geo/AbstractPolygon2D.java

raw symbols SCIP
1 /*
2 * AbstractPolygon2D.java
3 *
4 * Copyright (c) 2002-2017 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 dr.geo.cartogram.CartogramMapping;
29 import dr.util.HeapSort;
30 import dr.xml.*;
31 import org.jdom.Document;
32 import org.jdom.Element;
33 import org.jdom.JDOMException;
34 import org.jdom.input.SAXBuilder;
35
36 import java.awt.*;
37 import java.awt.geom.GeneralPath;
38 import java.awt.geom.Point2D;
39 import java.awt.geom.Rectangle2D;
40 import java.io.File;
41 import java.io.IOException;
42 import java.util.*;
43 import java.util.List;
44
45 /**
46 * @author Guy Baele
47 */
48 public abstract class AbstractPolygon2D {
49
50 public static final String POLYGON = "polygon";
51 public static final String CLOSED = "closed";
52 public static final String FILL_VALUE = "fillValue";
53 public static final String CIRCLE = "circle";
54 public static final String NUMBER_OF_POINTS = "numberOfPoints";
55 public static final String RADIUS = "radius";
56 public static final String CENTER = "center";
57 public static final String LATITUDE = "latitude";
58 public static final String LONGITUDE = "longitude";
59
60 public String getID() {
61 return id;
62 }
63
64 protected void parseCoordinates(Element element) {
65
66 if (element.getName().equalsIgnoreCase(KMLCoordinates.COORDINATES)) {
67 String value = element.getTextTrim();
68 StringTokenizer st1 = new StringTokenizer(value, KMLCoordinates.POINT_SEPARATORS);
69 int count = st1.countTokens();
70 // System.out.println(count + " tokens");
71
72 point2Ds = new ArrayList<Point2D>(count);
73 for (int i = 0; i < count; i++) {
74 String line = st1.nextToken();
75 StringTokenizer st2 = new StringTokenizer(line, KMLCoordinates.SEPARATOR);
76 if (st2.countTokens() < 2 || st2.countTokens() > 3)
77 throw new IllegalArgumentException("All KML coordinates must contain (X,Y) or (X,Y,Z) values. Error in element '" + line + "'");
78 final double x = Double.valueOf(st2.nextToken());
79 final double y = Double.valueOf(st2.nextToken());
80 point2Ds.add(new Point2D.Double(x, y));
81 }
82 convertPointsToArrays();
83 length = point2Ds.size() - 1;
84 } else {
85 for (Object child : element.getChildren()) {
86
87 if (child instanceof Element) {
88 parseCoordinates((Element) child);
89 }
90 }
91 }
92 }
93
94 Shape getShape() {
95 GeneralPath path = new GeneralPath();
96
97 java.util.List<Point2D> points = point2Ds;
98 path.moveTo((float) points.get(0).getX(), (float) points.get(0).getY());
99
100 for (int i = 1; i < points.size(); i++) {
101 path.lineTo((float) points.get(i).getX(), (float) points.get(i).getY());
102 }
103 path.closePath();
104 return path;
105 }
106
107 protected void convertPointsToArrays() {
108 final int length = point2Ds.size();
109 if (x == null || x.length != length) {
110 x = new double[length];
111 y = new double[length];
112 }
113 Iterator<Point2D> it = point2Ds.iterator();
114 for (int i = 0; i < length; i++) {
115 final Point2D point = it.next();
116 x[i] = point.getX();
117 y[i] = point.getY();
118 }
119 }
120
121 public void addPoint2D(Point2D point2D) {
122 if (point2Ds.size() == 0)
123 point2Ds.add(point2D);
124 else if (point2Ds.size() == 1) {
125 point2Ds.add(point2D);
126 point2Ds.add(point2Ds.get(0));
127 } else {
128 Point2D last = point2Ds.remove(point2Ds.size() - 1);
129 point2Ds.add(point2D);
130 if (!last.equals(point2D))
131 point2Ds.add(last);
132 }
133 convertPointsToArrays();
134 length = point2Ds.size() - 1;
135 }
136
137 public Point2D getPoint2D(int x) {
138 if (x > length +1) {
139 throw new RuntimeException("Polygon only has length"+length);
140 } else {
141 return point2Ds.get(x);
142 }
143 }
144
145 private void computeBoundingBox() {
146 min = new double[2];
147 max = new double[2];
148
149 min[0] = min(x);
150 max[0] = max(x);
151 min[1] = min(y);
152 max[1] = max(y);
153 }
154
155 private static double min(double[] x) {
156 double min = x[0];
157 for (int i = 1; i < x.length; ++i) {
158 if (x[i] < min) {
159 min = x[i];
160 }
161 }
162 return min;
163 }
164
165 private static double max(double[] x) {
166 double max = x[0];
167 for (int i = 1; i < x.length; ++i) {
168 if (x[i] > max) {
169 max = x[i];
170 }
171 }
172 return max;
173 }
174
175 public boolean roughContainsPoint2D(Point2D point2D) {
176 if (max == null || min == null) {
177 computeBoundingBox();
178 }
179 final double x = point2D.getX();
180 final double y = point2D.getY();
181 if (x < min[0]
182 || x > max[0]
183 || y < min[1]
184 || y > max[1]) {
185 return false;
186 } else {
187 return true;
188 }
189 }
190
191 private static boolean TRY_ROUGH = false;
192
193 public abstract double getProbability(Point2D Point2D, boolean outside);
194
195 public abstract double getLogProbability(Point2D Point2D, boolean outside);
196
197 public boolean containsPoint2D(Point2D Point2D) {
198
199 if (TRY_ROUGH) {
200 if (!roughContainsPoint2D(Point2D)) {
201 return false;
202 }
203 }
204
205 final double inX = Point2D.getX();
206 final double inY = Point2D.getY();
207 boolean contains = false;
208
209 // Take a horizontal ray from (inX,inY) to the right.
210 // If ray across the polygon edges an odd # of times, the point is inside.
211 for (int i = 0, j = length - 1; i < length; j = i++) {
212 if ((((y[i] <= inY) && (inY < y[j])) ||
213 ((y[j] <= inY) && (inY < y[i]))) &&
214 (inX < (x[j] - x[i]) * (inY - y[i]) / (y[j] - y[i]) + x[i]))
215 contains = !contains;
216 }
217 return contains;
218 }
219
220 // public boolean containsPoint2D(Point2D Point2D) { // this takes 3 times as long as the above code, why???
221 //
222 // final double inX = Point2D.getX();
223 // final double inY = Point2D.getY();
224 // boolean contains = false;
225 //
226 // // Take a horizontal ray from (inX,inY) to the right.
227 // // If ray across the polygon edges an odd # of times, the Point2D is inside.
228 //
229 // final Point2D end = point2Ds.get(length-1); // assumes closed
230 // double xi = end.getX();
231 // double yi = end.getY();
232 //
233 // Iterator<Point2D> listIterator = point2Ds.iterator();
234 //
235 // for(int i=0; i<length; i++) {
236 //
237 // final double xj = xi;
238 // final double yj = yi;
239 //
240 // final Point2D next = listIterator.next();
241 // xi = next.getX();
242 // yi = next.getY();
243 //
244 // if ((((yi <= inY) && (inY < yj)) ||
245 // ((yj <= inY) && (inY < yi))) &&
246 // (inX < (xj - xi) * (inY - yi) / (yj - yi) + xi))
247 // contains = !contains;
248 // }
249 // return contains;
250 // }
251
252 public boolean bordersPoint2D(Point2D Point2D) {
253 boolean borders = false;
254
255 Iterator<Point2D> it = point2Ds.iterator();
256 for (int i = 0; i < length; i++) {
257 Point2D point = it.next();
258 if (point.equals(Point2D)) {
259 borders = true;
260 }
261 }
262 return borders;
263 }
264
265 public void transformByMapping(CartogramMapping mapping) {
266 for (int i = 0; i < length + 1; i++) {
267 point2Ds.set(i, mapping.map(point2Ds.get(i)));
268 }
269 convertPointsToArrays();
270 }
271
272 public void swapXYs() {
273 for (int i = 0; i < length + 1; i++) {
274 point2Ds.set(i, new Point2D.Double(point2Ds.get(i).getY(), point2Ds.get(i).getX()));
275 }
276 convertPointsToArrays();
277 }
278
279 public void rescale(double longMin, double longwidth, double gridXSize, double latMax, double latwidth, double gridYSize) {
280 for (int i = 0; i < length + 1; i++) {
281 point2Ds.set(i, new Point2D.Double(((point2Ds.get(i).getX() - longMin) * (gridXSize / longwidth)), ((latMax - point2Ds.get(i).getY()) * (gridYSize / latwidth))));
282 }
283 convertPointsToArrays();
284 }
285
286 public void rescaleToPositiveCoordinates() {
287
288 double[][] xyMinMax = getXYMinMax();
289 double shiftX = 0;
290 double shiftY = 0;
291
292 if (xyMinMax[0][0] < 0){
293 shiftX = -xyMinMax[0][0];
294 }
295 if (xyMinMax[1][0] < 0){
296 shiftY = -xyMinMax[1][0];
297 }
298
299 if ((shiftX < 0) || (shiftY < 0)) {
300 for (int i = 0; i < length + 1; i++) {
301 point2Ds.set(i, new Point2D.Double(point2Ds.get(i).getX()+shiftX, point2Ds.get(i).getY()+shiftY));
302 }
303 convertPointsToArrays();
304 }
305 }
306
307 public double[][] getXYMinMax(){
308
309 if (minMax == null) {
310 int[] indicesX = new int[x.length];
311 int[] indicesY = new int[y.length];
312 HeapSort.sort(x, indicesX);
313 HeapSort.sort(y, indicesY);
314
315 minMax = new double[2][2];
316 minMax[0][0] = x[indicesX[0]];
317 minMax[0][1] = x[indicesX[indicesX.length - 1]];
318 minMax[1][0] = y[indicesY[0]];
319 minMax[1][1] = y[indicesY[indicesY.length - 1]];
320 }
321
322 double[][] returnMatrix = new double[2][2];
323 returnMatrix[0][0] = minMax[0][0];
324 returnMatrix[0][1] = minMax[0][1];
325 returnMatrix[1][0] = minMax[1][0];
326 returnMatrix[1][1] = minMax[1][1];
327
328 return returnMatrix;
329 }
330
331 private double[][] minMax = null;
332
333 // Here is a formula for the area of a polygon with vertices {(xk,yk): k = 1,...,n}:
334 // Area = 1/2 [(x1*y2 - x2*y1) + (x2*y3 - x3*y2) + ... + (xn*y1 - x1*yn)].
335 // This formula appears in an Article by Gil Strang of MIT
336 // on p. 253 of the March 1993 issue of The American Mathematical Monthly, with the note that it is
337 // "known, but not well known". There is also a very brief discussion of proofs and other references,
338 // including an article by Bart Braden of Northern Kentucky U., a known Mathematica enthusiast.
339 public double calculateArea() {
340
341 // rescaleToPositiveCoordinates();
342
343 double area = 0;
344 //we can implement it like this because the polygon is closed (point2D.get(0) = point2D.get(length + 1)
345 for (int i = 0; i < length; i++) {
346 area += (x[i] * y[i + 1] - x[i + 1] * y[i]);
347 }
348
349 return (Math.abs(area / 2));
350 }
351
352 public Point2D getCentroid() {
353
354 // rescaleToPositiveCoordinates();
355
356 Point2D centroid = new Point2D.Double();
357 double area = calculateArea();
358 double cx=0,cy=0;
359
360 double factor;
361
362 //we can implement it like this because the polygon is closed (point2D.get(0) = point2D.get(length + 1)
363 for (int i = 0; i < length; i++) {
364 factor = (x[i] * y[i + 1] - x[i + 1] * y[i]);
365 cx += (x[i] * x[i + 1])*factor;
366 cy += (y[i] * y[i + 1])*factor;
367 }
368 double constant = 1/(area*6);
369 cx*=constant;
370 cy*=constant;
371 centroid.setLocation(cx,cy);
372 System.out.println("centroid = "+cx+","+cy);
373 return centroid;
374 }
375
376 private static LinkedList<Point2D> getCirclePoints(double centerLat, double centerLong, int numberOfPoints, double radius) {
377
378 LinkedList<Point2D> Point2Ds = new LinkedList<Point2D>();
379
380 double lat1, long1;
381 double d_rad;
382 double delta_pts;
383 double radial, lat_rad, dlon_rad, lon_rad;
384
385 // convert coordinates to radians
386 lat1 = Math.toRadians(centerLat);
387 long1 = Math.toRadians(centerLong);
388
389 //radius is in meters
390 d_rad = radius / 6378137;
391
392 // loop through the array and write points
393 for (int i = 0; i <= numberOfPoints; i++) {
394 delta_pts = 360 / (double) numberOfPoints;
395 radial = Math.toRadians((double) i * delta_pts);
396
397 //This algorithm is limited to distances such that dlon < pi/2
398 lat_rad = Math.asin(Math.sin(lat1) * Math.cos(d_rad) + Math.cos(lat1) * Math.sin(d_rad) * Math.cos(radial));
399 dlon_rad = Math.atan2(Math.sin(radial) * Math.sin(d_rad) * Math.cos(lat1), Math.cos(d_rad) - Math.sin(lat1) * Math.sin(lat_rad));
400 lon_rad = ((long1 + dlon_rad + Math.PI) % (2 * Math.PI)) - Math.PI;
401
402 Point2Ds.add(new Point2D.Double(Math.toDegrees(lat_rad), Math.toDegrees(lon_rad)));
403
404 }
405 return Point2Ds;
406 }
407
408 protected enum Side {
409 left, right, top, bottom
410 }
411
412 protected static boolean isInsideClip(Point2D p, Side side, Rectangle2D boundingBox) {
413 if (side == Side.top)
414 return (p.getY() <= boundingBox.getMaxY());
415 else if (side == Side.bottom)
416 return (p.getY() >= boundingBox.getMinY());
417 else if (side == Side.left)
418 return (p.getX() >= boundingBox.getMinX());
419 else if (side == Side.right)
420 return (p.getX() <= boundingBox.getMaxX());
421 else
422 throw new RuntimeException("Error in Polygon");
423 }
424
425
426 protected static Point2D intersectionPoint2D(Side side, Point2D p1, Point2D p2, Rectangle2D boundingBox) {
427
428 if (side == Side.top) {
429 final double topEdge = boundingBox.getMaxY();
430 return new Point2D.Double(p1.getX() + (topEdge - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()), topEdge);
431 } else if (side == Side.bottom) {
432 final double bottomEdge = boundingBox.getMinY();
433 return new Point2D.Double(p1.getX() + (bottomEdge - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()), bottomEdge);
434 } else if (side == Side.right) {
435 final double rightEdge = boundingBox.getMaxX();
436 return new Point2D.Double(rightEdge, p1.getY() + (rightEdge - p1.getX()) * (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()));
437 } else if (side == Side.left) {
438 final double leftEdge = boundingBox.getMinX();
439 return new Point2D.Double(leftEdge, p1.getY() + (leftEdge - p1.getX()) * (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()));
440 }
441 return null;
442 }
443
444 public AbstractPolygon2D clip(Rectangle2D boundingBox) {
445
446 LinkedList<Point2D> clippedPolygon = new LinkedList<Point2D>();
447
448 Point2D p; // current Point2D
449 Point2D p2; // next Point2D
450
451 // make copy of original polygon to work with
452 LinkedList<Point2D> workPoly = new LinkedList<Point2D>(point2Ds);
453
454 // loop through all for clipping edges
455 for (Side side : Side.values()) {
456 clippedPolygon.clear();
457 for (int i = 0; i < workPoly.size() - 1; i++) {
458 p = workPoly.get(i);
459 p2 = workPoly.get(i + 1);
460 if (isInsideClip(p, side, boundingBox)) {
461 if (isInsideClip(p2, side, boundingBox))
462 // here both point2Ds are inside the clipping window so add the second one
463 clippedPolygon.add(p2);
464 else
465 // the seond Point2D is outside so add the intersection Point2D
466 clippedPolygon.add(intersectionPoint2D(side, p, p2, boundingBox));
467 } else {
468 // so first Point2D is outside the window here
469 if (isInsideClip(p2, side, boundingBox)) {
470 // the following Point2D is inside so add the insection Point2D and also p2
471 clippedPolygon.add(intersectionPoint2D(side, p, p2, boundingBox));
472 clippedPolygon.add(p2);
473 }
474 }
475 }
476 // make sure that first and last element are the same, we want a closed polygon
477 if (!clippedPolygon.getFirst().equals(clippedPolygon.getLast()))
478 clippedPolygon.add(clippedPolygon.getFirst());
479 // we have to keep on working with our new clipped polygon
480 workPoly = new LinkedList<Point2D>(clippedPolygon);
481 }
482 //return new Polygon2D(clippedPolygon, true);
483 return new Polygon2DFactory().createPolygon2D(clippedPolygon, true);
484 }
485
486 public String toString() {
487 StringBuffer sb = new StringBuffer();
488 sb.append(POLYGON).append("[\n");
489 for (Point2D pt : point2Ds) {
490 sb.append("\t");
491 sb.append(pt);
492 sb.append("\n");
493 }
494 sb.append("]");
495 return sb.toString();
496 }
497
498 public abstract void setFillValue(double value);
499
500 public abstract double getFillValue();
501
502 public abstract double getLogFillValue();
503
504 public abstract boolean hasFillValue();
505
506 public double getLength() {
507 return length;
508 }
509
510 public static void readKMLElement(Element element, List<AbstractPolygon2D> polygons) {
511
512 if (element.getName().equalsIgnoreCase(POLYGON)) {
513 //Polygon2D polygon = new Polygon2D(element);
514 AbstractPolygon2D polygon = new Polygon2DFactory().createPolygon2D(element);
515 polygons.add(polygon);
516 } else {
517 for (Object child : element.getChildren()) {
518
519 if (child instanceof Element) {
520 readKMLElement((Element) child, polygons);
521 }
522 }
523
524 }
525 }
526
527 public static List<AbstractPolygon2D> readKMLFile(String fileName) {
528
529 List<AbstractPolygon2D> polygons = new ArrayList<AbstractPolygon2D>();
530 try {
531
532 SAXBuilder builder = new SAXBuilder();
533 builder.setValidation(false);
534 builder.setIgnoringElementContentWhitespace(true);
535 Document doc = builder.build(new File(fileName));
536 Element root = doc.getRootElement();
537 if (!root.getName().equalsIgnoreCase("KML"))
538 throw new RuntimeException("Not a KML file");
539
540 readKMLElement(root, polygons);
541
542 } catch (IOException e) {
543 e.printStackTrace();
544 } catch (JDOMException e) {
545 e.printStackTrace();
546 }
547 return polygons;
548 }
549
550 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
551
552 public String getParserName() {
553 return POLYGON;
554 }
555
556 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
557
558 LinkedList<Point2D> Point2Ds = new LinkedList<Point2D>();
559 boolean closed;
560 Polygon2D polygon;
561
562 if (xo.getChild(Polygon2D.class) != null) { // This is a regular polygon
563
564 polygon = (Polygon2D) xo.getChild(Polygon2D.class);
565
566 } else { // This is an arbitrary polygon
567
568 KMLCoordinates coordinates = (KMLCoordinates) xo.getChild(KMLCoordinates.class);
569 closed = xo.getAttribute(CLOSED, false);
570
571 if ((!closed && coordinates.length < 3) ||
572 (closed && coordinates.length < 4))
573 throw new XMLParseException("Insufficient point2Ds in polygon '" + xo.getId() + "' to define a polygon in 2D");
574
575 for (int i = 0; i < coordinates.length; i++)
576 Point2Ds.add(new Point2D.Double(coordinates.x[i], coordinates.y[i]));
577
578 polygon = new Polygon2D(Point2Ds, closed);
579
580 }
581
582 polygon.setFillValue(xo.getAttribute(FILL_VALUE, 0.0));
583
584 return polygon;
585 }
586
587 //************************************************************************
588 // AbstractXMLObjectParser implementation
589 //************************************************************************
590
591 public String getParserDescription() {
592 return "This element represents a polygon.";
593 }
594
595 public Class getReturnType() {
596 return Polygon2D.class;
597 }
598
599 public XMLSyntaxRule[] getSyntaxRules() {
600 return rules;
601 }
602
603 private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
604 new XORRule(
605 new ElementRule(KMLCoordinates.class),
606 new ElementRule(Polygon2D.class)
607 ),
608 AttributeRule.newBooleanRule(CLOSED, true),
609 AttributeRule.newDoubleRule(FILL_VALUE, true),
610 };
611 };
612
613 public static XMLObjectParser CIRCLE_PARSER = new AbstractXMLObjectParser() {
614
615 public String getParserName() {
616 return CIRCLE;
617 }
618
619 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
620
621 double latitude = xo.getDoubleAttribute(LATITUDE);
622 double longitude = xo.getDoubleAttribute(LONGITUDE);
623 double radius = xo.getDoubleAttribute(RADIUS);
624 int num = xo.getAttribute(NUMBER_OF_POINTS, 50); // default = 50
625
626 LinkedList<Point2D> Point2Ds = getCirclePoints(latitude,
627 longitude,
628 num,
629 radius);
630
631 return new Polygon2D(Point2Ds, true);
632 }
633
634 //************************************************************************
635 // AbstractXMLObjectParser implementation
636 //************************************************************************
637
638 public String getParserDescription() {
639 return "This element represents a regular circle polygon.";
640 }
641
642 public Class getReturnType() {
643 return Polygon2D.class;
644 }
645
646 public XMLSyntaxRule[] getSyntaxRules() {
647 return rules;
648 }
649
650 private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
651 AttributeRule.newDoubleRule(LATITUDE),
652 AttributeRule.newDoubleRule(LONGITUDE),
653 AttributeRule.newDoubleRule(RADIUS),
654 AttributeRule.newIntegerRule(NUMBER_OF_POINTS, true),
655 };
656 };
657
658 protected List<Point2D> point2Ds;
659
660 protected int length;
661
662 protected String id;
663
664 protected double[] x;
665 protected double[] y;
666
667 protected double[] max;
668 protected double[] min;
669
670 }