Debian Codegraph @

src/dr/geo/GeoSpatialDistribution.java

raw symbols SCIP
1 /*
2 * GeoSpatialDistribution.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.inference.distribution.CachedDistributionLikelihood;
29 import dr.inference.distribution.MultivariateDistributionLikelihood;
30 import dr.inference.model.Parameter;
31 import dr.math.distributions.MultivariateDistribution;
32 import dr.util.Author;
33 import dr.util.Citable;
34 import dr.util.Citation;
35 import dr.xml.*;
36
37 import java.awt.geom.Point2D;
38 import java.util.ArrayList;
39 import java.util.List;
40 import java.util.logging.Logger;
41
42 /**
43 * @author Marc A. Suchard
44 * @author Philippe Lemey
45 * @author Alexei J. Drummond
46 */
47
48 public class GeoSpatialDistribution implements MultivariateDistribution, Citable {
49
50 public static final String FLAT_SPATIAL_DISTRIBUTION = "flatGeoSpatialPrior";
51 public static final String DATA = "data";
52 public static final String TYPE = "geoSpatial";
53 public static final String NODE_LABEL = "taxon";
54 public static final String KML_FILE = "kmlFileName";
55 public static final String INSIDE = "inside";
56 public static final String UNION = "union";
57 public static final String CACHE = "cache";
58 private static final String DEFAULT_LABEL = "";
59
60 public static final int dimPoint = 2; // Assumes 2D points only
61
62 public GeoSpatialDistribution(String label) {
63 this.label = label;
64 }
65
66 public GeoSpatialDistribution(String label, AbstractPolygon2D region, boolean inside) {
67 this.label = label;
68 this.region = region;
69 this.outside = !inside;
70 }
71
72 public double logPdf(double[] x) {
73 /*final boolean contains = region.containsPoint2D(new Point2D.Double(x[0], x[1]));
74 if (region.hasFillValue()) {
75 if (contains) {
76 return region.getLogFillValue();
77 } else {
78 return Double.NEGATIVE_INFINITY;
79 }
80 } else if (outside ^ contains)
81 return 0;
82 return Double.NEGATIVE_INFINITY;*/
83
84 return region.getLogProbability(new Point2D.Double(x[0], x[1]), this.outside);
85 }
86
87 public double[][] getScaleMatrix() {
88 return null;
89 }
90
91 public double[] getMean() {
92 return null;
93 }
94
95 public String getType() {
96 return TYPE;
97 }
98
99 public String getLabel() {
100 return label;
101 }
102
103 public boolean getOutside() {
104 return outside;
105 }
106
107 public AbstractPolygon2D getRegion() {
108 return region;
109 }
110
111 protected AbstractPolygon2D region;
112 protected String label = null;
113 private boolean outside = false;
114
115 public static XMLObjectParser FLAT_GEOSPATIAL_PRIOR_PARSER = new AbstractXMLObjectParser() {
116
117 public String getParserName() {
118 return FLAT_SPATIAL_DISTRIBUTION;
119 }
120
121 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
122
123 String label = xo.getAttribute(NODE_LABEL, DEFAULT_LABEL);
124
125 boolean inside = xo.getAttribute(INSIDE, true);
126 boolean union = xo.getAttribute(UNION, false);
127 boolean readFromFile = false;
128 boolean cache = xo.getAttribute(CACHE, false);
129
130 List<GeoSpatialDistribution> geoSpatialDistributions = new ArrayList<GeoSpatialDistribution>();
131
132 boolean overAllFill = false;
133 if (xo.hasAttribute(KML_FILE)) {
134 // read file
135 String kmlFileName = xo.getStringAttribute(KML_FILE);
136 List<AbstractPolygon2D> polygons = Polygon2D.readKMLFile(kmlFileName);
137 //check if all the polygons have either a fillValue or do not have this fillValue
138 AbstractPolygon2D first = polygons.get(0);
139 boolean equalFills = first.hasFillValue();
140 if (polygons.size() > 1) {
141 for (int i = 1; i < polygons.size(); i++) {
142 if (!(equalFills == polygons.get(i).hasFillValue())) {
143 throw new XMLParseException("Inconsistent fillValue attributes provided.");
144 }
145 }
146 }
147 if (equalFills) {
148 double sum = 0.0;
149 for (AbstractPolygon2D region : polygons) {
150 sum += region.getFillValue();
151 }
152 if (Math.abs(sum - 1.0) > 1E-12) {
153 throw new XMLParseException("Fill values in " + kmlFileName + " do not sum to 1 : " + sum);
154 }
155 }
156 overAllFill = equalFills;
157 for (AbstractPolygon2D region : polygons) {
158 geoSpatialDistributions.add(new GeoSpatialDistribution(label, region, inside));
159 }
160 readFromFile = true;
161 } else {
162
163 for (int i = 0; i < xo.getChildCount(); i++) {
164 if (xo.getChild(i) instanceof Polygon2D) {
165 Polygon2D region = (Polygon2D) xo.getChild(i);
166 geoSpatialDistributions.add(
167 new GeoSpatialDistribution(label, region, inside)
168 );
169 }
170 }
171 }
172
173 List<Parameter> parameters = new ArrayList<Parameter>();
174 XMLObject cxo = xo.getChild(DATA);
175 for (int j = 0; j < cxo.getChildCount(); j++) {
176 Parameter spatialParameter = (Parameter) cxo.getChild(j);
177 parameters.add(spatialParameter);
178 }
179
180 //changes with fillValue attribute do not apply here
181 if (geoSpatialDistributions.size() == 1) {
182 MultivariateDistributionLikelihood likelihood = new MultivariateDistributionLikelihood(geoSpatialDistributions.get(0));
183 for (Parameter spatialParameter : parameters) {
184 if (spatialParameter.getDimension() % dimPoint != 0)
185 throw new XMLParseException("Spatial priors currently only work in " + dimPoint + "D");
186
187 if (!label.equals(DEFAULT_LABEL)) { // For a tip-taxon
188 likelihood.addData(spatialParameter);
189 return likelihood;
190 } else {
191 Logger.getLogger("dr.geo").info(
192 "\nConstructing a GeoSpatialCollectionModel:\n" +
193 "\tParameter: " + spatialParameter.getId() + "\n" +
194 "\tNumber of regions: " + geoSpatialDistributions.size() + "\n\n");
195
196 return new GeoSpatialCollectionModel(xo.getId(), spatialParameter, geoSpatialDistributions, !union);
197 }
198 }
199 }
200
201 if (geoSpatialDistributions.size() == 0) {
202 throw new XMLParseException("Error constructing geo spatial distributions in " + xo.getId());
203 }
204
205 if (parameters.size() == 1) {
206 Parameter parameter = parameters.get(0);
207 if (parameter.getDimension() % dimPoint != 0)
208 throw new XMLParseException("Spatial priors currently only work in " + dimPoint + "D");
209
210 if (!label.equals(DEFAULT_LABEL)) { // For a tip-taxon
211 Logger.getLogger("dr.geo").info(
212 "\nConstructing a multiple-region spatial prior:\n" +
213 "\tTaxon: " + label + "\n" +
214 "\tNumber of regions: " + geoSpatialDistributions.size() + "\n\n");
215 MultivariateDistributionLikelihood likelihood = new MultivariateDistributionLikelihood(
216 new MultiRegionGeoSpatialDistribution(label, geoSpatialDistributions, union, overAllFill));
217 likelihood.addData(parameter);
218 likelihood.setId(xo.getId());
219 if (cache) {
220 return new CachedDistributionLikelihood(xo.getId(), likelihood, parameter);
221 } else {
222 return likelihood;
223 }
224
225 } else {
226
227 Logger.getLogger("dr.geo").info(
228 "\nConstructing a GeoSpatialCollectionModel:\n" +
229 "\tParameter: " + parameter.getId() + "\n" +
230 "\tNumber of regions: " + geoSpatialDistributions.size() + "\n\n");
231
232 return new GeoSpatialCollectionModel(xo.getId(), parameter, geoSpatialDistributions, !union);
233 }
234 }
235
236 throw new XMLParseException("Multiple separate parameters and multiple regions not yet implemented");
237 }
238
239 public XMLSyntaxRule[] getSyntaxRules() {
240 return rules;
241 }
242
243 private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
244 AttributeRule.newStringRule(NODE_LABEL, true),
245 AttributeRule.newBooleanRule(INSIDE, true),
246 AttributeRule.newBooleanRule(UNION, true),
247 AttributeRule.newBooleanRule(CACHE, true),
248 new XORRule(
249 AttributeRule.newStringRule(KML_FILE),
250 new ElementRule(Polygon2D.class, 1, Integer.MAX_VALUE)
251 ),
252 new ElementRule(DATA,
253 new XMLSyntaxRule[]{new ElementRule(Parameter.class, 1, Integer.MAX_VALUE)}
254 )
255 };
256
257 public String getParserDescription() {
258 return "Calculates the likelihood of some data under a 2D geospatial distribution.";
259 }
260
261 public Class getReturnType() {
262 return MultivariateDistributionLikelihood.class;
263 }
264 };
265
266 @Override
267 public Citation.Category getCategory() {
268 return Citation.Category.PRIOR_MODELS;
269 }
270
271 @Override
272 public String getDescription() {
273 return "Integrated continuous traits over polygons";
274 }
275
276 public List<Citation> getCitations() {
277 List<Citation> citationList = new ArrayList<Citation>();
278 citationList.add(new Citation(
279 new Author[] {
280 new Author("S", "Nylinder"),
281 new Author("P", "Lemey"),
282 new Author("M", "de Bruyn"),
283 new Author("MA", "Suchard"),
284 new Author("BE", "Pfeil"),
285 new Author("N", "Walsh"),
286 new Author("AA", "Anderberg")
287 },
288 "On the biogeography of Centipeda: a species-tree diffusion approach",
289 2014,
290 "Systematic Biology",
291 63,
292 178, 191,
293 Citation.Status.PUBLISHED
294 ));
295 return citationList;
296 }
297
298 public static void main(String[] args) {
299
300 //test reading in KML file with multiple polygons and fillValue attribute
301 List<AbstractPolygon2D> polygons = Polygon2D.readKMLFile("Multiple_polygons/9.285_105.7244444.kml");
302 System.out.println(polygons.size() + " polygons found.");
303
304 //check if all the polygons have either a fillValue or do not have this fillValue
305 AbstractPolygon2D first = polygons.get(0);
306 boolean equalFills = first.hasFillValue();
307 if (polygons.size() > 1) {
308 for (int i = 1; i < polygons.size(); i++) {
309 if (!(equalFills == polygons.get(i).hasFillValue())) {
310 System.out.println("Inconsistent fillValue attributes provided.");
311 }
312 }
313 }
314
315 if (equalFills) {
316 double sum = 0.0;
317 for (AbstractPolygon2D region : polygons) {
318 sum += region.getFillValue();
319 }
320 if (Math.abs(sum - 1.0) > 1E-12) {
321 System.out.println("\nFill values do not sum to 1 : " + sum);
322 }
323 }
324
325 boolean overAllFill = equalFills;
326 List<GeoSpatialDistribution> geoSpatialDistributions = new ArrayList<GeoSpatialDistribution>();
327 for (AbstractPolygon2D region : polygons) {
328 geoSpatialDistributions.add(new GeoSpatialDistribution("test", region, false));
329 }
330
331 MultivariateDistributionLikelihood likelihood = new MultivariateDistributionLikelihood(
332 new MultiRegionGeoSpatialDistribution("multi", geoSpatialDistributions, false, overAllFill));
333
334 Parameter.Default parameter = new Parameter.Default("coordinate", 2);
335 likelihood.addData(parameter);
336 double logL = likelihood.calculateLogLikelihood();
337
338 System.out.println("\n(" + parameter.getParameterValue(0) + "," + parameter.getParameterValue(1) + ")");
339 System.out.println("logL = " + logL);
340 System.out.println("L = " + Math.exp(logL));
341
342 parameter.setParameterValue(0, 11.40);
343 parameter.setParameterValue(1, 106.90);
344
345 likelihood.makeDirty();
346 logL = likelihood.calculateLogLikelihood();
347
348 System.out.println("\n(" + parameter.getParameterValue(0) + "," + parameter.getParameterValue(1) + ")");
349 System.out.println("logL = " + logL);
350 System.out.println("L = " + Math.exp(logL));
351
352
353 //test reading in KML file with a single polygon without fillValue attribute
354 polygons = Polygon2D.readKMLFile("Districts_polygons/21.035_106.063.kml");
355 System.out.println("\n" + polygons.size() + " polygons found.");
356
357 first = polygons.get(0);
358 equalFills = first.hasFillValue();
359 if (polygons.size() > 1) {
360 for (int i = 1; i < polygons.size(); i++) {
361 if (!(equalFills == polygons.get(i).hasFillValue())) {
362 System.out.println("Inconsistent fillValue attributes provided.");
363 }
364 }
365 }
366
367 if (equalFills) {
368 double sum = 0.0;
369 for (AbstractPolygon2D region : polygons) {
370 sum += region.getFillValue();
371 }
372 if (Math.abs(sum - 1.0) > 1E-12) {
373 System.out.println("\nFill values do not sum to 1 : " + sum);
374 }
375 }
376
377 overAllFill = equalFills;
378 geoSpatialDistributions = new ArrayList<GeoSpatialDistribution>();
379 for (AbstractPolygon2D region : polygons) {
380 geoSpatialDistributions.add(new GeoSpatialDistribution("test", region, false));
381 }
382
383 likelihood = new MultivariateDistributionLikelihood(
384 new MultiRegionGeoSpatialDistribution("multi", geoSpatialDistributions, false, overAllFill));
385
386 likelihood.addData(parameter);
387 logL = likelihood.calculateLogLikelihood();
388
389 System.out.println("\n(" + parameter.getParameterValue(0) + "," + parameter.getParameterValue(1) + ")");
390 System.out.println("logL = " + logL);
391 System.out.println("L = " + Math.exp(logL));
392
393 parameter.setParameterValue(0, 21.0);
394 parameter.setParameterValue(1, 106.03);
395
396 likelihood.makeDirty();
397 logL = likelihood.calculateLogLikelihood();
398
399 System.out.println("\n(" + parameter.getParameterValue(0) + "," + parameter.getParameterValue(1) + ")");
400 System.out.println("logL = " + logL);
401 System.out.println("L = " + Math.exp(logL));
402
403 parameter.setParameterValue(0, 21.0);
404 parameter.setParameterValue(1, 106.10);
405
406 likelihood.makeDirty();
407 logL = likelihood.calculateLogLikelihood();
408
409 System.out.println("\n(" + parameter.getParameterValue(0) + "," + parameter.getParameterValue(1) + ")");
410 System.out.println("logL = " + logL);
411 System.out.println("L = " + Math.exp(logL));
412
413 }
414
415 }