Debian Codegraph @

src/dr/evomodel/operators/DiscretizedLocationOperator.java

raw symbols SCIP
1 /*
2 * DiscretizedLocationOperator.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.operators;
27
28 import dr.evolution.tree.MutableTreeModel;
29 import dr.evolution.tree.NodeRef;
30 import dr.evomodel.continuous.AbstractMultivariateTraitLikelihood;
31 import dr.inference.operators.AbstractAdaptableOperator;
32 import dr.inference.operators.AdaptationMode;
33 import dr.inference.operators.MCMCOperator;
34 import dr.math.MathUtils;
35 import dr.xml.*;
36
37 import java.awt.geom.Point2D;
38 import java.util.*;
39 import java.util.logging.Logger;
40
41
42 /**
43 * @author Marc Suchard
44 */
45 public class DiscretizedLocationOperator extends AbstractAdaptableOperator {
46
47 public static final String GIBBS_OPERATOR = "discretizedLocationOperator";
48 public static final String INTERNAL_ONLY = "onlyInternalNodes";
49 public static final String DISK = "neighborhoodSize";
50 public static final String RANDOMIZE = "randomize";
51
52 public DiscretizedLocationOperator(AbstractMultivariateTraitLikelihood traitModel, boolean onlyInternalNodes, int disk, AdaptationMode mode) {
53 super(mode);
54 this.treeModel = traitModel.getTreeModel();
55 this.traitName = traitModel.getTraitName();
56 this.onlyInternalNodes = onlyInternalNodes;
57 allLocations = makeLocationList();
58 nearestNeighborMap = makeNearestNeighborMap();
59 this.disk = disk;
60 this.autoOptimize = convertToAutoOptimizeValue(disk);
61
62 if (disk > allLocations.size() - 2)
63 throw new RuntimeException("Neighborhood size is too large");
64
65 printInfo();
66 }
67
68 private Map<Point2D, List<WeightedPoint2D>> makeNearestNeighborMap() {
69 Map<Point2D, List<WeightedPoint2D>> map = new HashMap<Point2D, List<WeightedPoint2D>>();
70
71 for (Point2D location : allLocations) {
72
73 List<WeightedPoint2D> weightedNeighbors = new ArrayList<WeightedPoint2D>();
74 for (Point2D neighbor : allLocations) {
75 double distance = location.distance(neighbor);
76 if (distance > 0)
77 weightedNeighbors.add(
78 new WeightedPoint2D(neighbor.getX(), neighbor.getY(), distance)
79 );
80 }
81 Collections.sort(weightedNeighbors);
82
83 map.put(location, weightedNeighbors);
84 }
85
86 // for (Point2D location : map.keySet()) {
87 // List<WeightedPoint2D> neighbors = map.get(location);
88 // System.err.println("Location: "+location+"\n");
89 // System.err.println("\t");
90 // int count = 0;
91 // for (WeightedPoint2D neighbor : neighbors) {
92 // count++;
93 // if (count < 3)
94 // System.err.println(" "+neighbor);
95 // }
96 // System.err.println("\n");
97 // }
98
99 return map;
100 }
101
102
103 private void recursivelySetTrait(NodeRef node, double[] trait, NodeRef fromNode) {
104
105 treeModel.setMultivariateTrait(node, traitName, trait);
106
107 for (int i = 0; i < treeModel.getChildCount(node); i++) {
108 NodeRef child = treeModel.getChild(node, i);
109 if (child != fromNode && treeModel.getBranchLength(child) == 0) {
110 // System.err.println("recursing down");
111 recursivelySetTrait(child, trait, node);
112 }
113 }
114 if (!treeModel.isRoot(node) && treeModel.getBranchLength(node) == 0) {
115 // System.err.println("recursing up");
116 recursivelySetTrait(treeModel.getParent(node), trait, node);
117 }
118 }
119
120
121 public void randomizeNodes() {
122
123 List<Point2D> listLocations = new ArrayList<Point2D>();
124 listLocations.addAll(allLocations);
125
126 for (int i = 0; i < treeModel.getInternalNodeCount(); i++) {
127
128 NodeRef node = treeModel.getInternalNode(i);
129 double[] trait = treeModel.getMultivariateNodeTrait(node, traitName);
130
131 Point2D newPt = listLocations.get(MathUtils.nextInt(listLocations.size()));
132
133 trait[0] = newPt.getX();
134 trait[1] = newPt.getY();
135
136 recursivelySetTrait(node, trait, null);
137
138 // treeModel.setMultivariateTrait(node, traitName, trait);
139 }
140 System.err.println("Done with randomization");
141 // System.exit(-1);
142 }
143
144 private void printInfo() {
145 StringBuffer sb = new StringBuffer();
146 sb.append("\nCreating a discretized location sampler:\n");
147 sb.append("\tTip count: " + treeModel.getExternalNodeCount() + "\n");
148 sb.append("\tUnique locations: " + allLocations.size() + "\n");
149 sb.append("\tNeighborhood size: " + disk + "\n");
150 Logger.getLogger("dr.evomodel.operators").info(sb.toString());
151 }
152
153 private Set<Point2D> makeLocationList() {
154
155 Set<Point2D> uniquePoints = new HashSet<Point2D>();
156
157 for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
158 NodeRef node = treeModel.getExternalNode(i);
159 double[] leafTrait = treeModel.getMultivariateNodeTrait(node, traitName);
160
161 Point2D.Double point = new Point2D.Double(leafTrait[0], leafTrait[1]);
162 if (!uniquePoints.contains(point)) {
163 uniquePoints.add(point);
164 savedPt = point;
165 }
166 }
167
168 return uniquePoints;
169 }
170
171 public double doOperation() {
172
173 NodeRef node;
174
175 if (onlyInternalNodes)
176 node = treeModel.getInternalNode(MathUtils.nextInt(
177 treeModel.getInternalNodeCount()));
178 else
179 node = treeModel.getNode(MathUtils.nextInt(
180 treeModel.getNodeCount()));
181
182 double[] trait = treeModel.getMultivariateNodeTrait(node, traitName);
183 Point2D currentPt = new Point2D.Double(trait[0], trait[1]);
184
185 List<WeightedPoint2D> neighbors = nearestNeighborMap.get(currentPt);
186
187 if (neighbors == null)
188 throw new RuntimeException("Node location outside allowable values: " + currentPt);
189
190 // Point2D newPt = neighbors.get(MathUtils.nextInt(disk));
191 Point2D newPt = neighbors.get(MathUtils.nextInt(convertFromAutoOptimizeValue(autoOptimize)));
192
193 trait[0] = newPt.getX();
194 trait[1] = newPt.getY();
195
196 // treeModel.setMultivariateTrait(node, traitName, trait);
197 recursivelySetTrait(node, trait, null);
198
199 return 0;
200
201 }
202
203 private int convertFromAutoOptimizeValue(double value) {
204 return 1 + (int) Math.exp(autoOptimize);
205 }
206
207 private double convertToAutoOptimizeValue(int value) {
208 return Math.log(value - 1);
209 }
210
211 public double getAdaptableParameter() {
212 return autoOptimize;
213 }
214
215 public void setAdaptableParameter(double value) {
216 autoOptimize = value;
217 }
218
219 public double getRawParameter() {
220 return convertFromAutoOptimizeValue(autoOptimize);
221 }
222
223 @Override
224 public String getAdaptableParameterName() {
225 return null;
226 }
227
228 // public double getScaleFactor() {
229 // return scaleFactor;
230 // }
231
232 public double getTargetAcceptanceProbability() {
233 return 0.50;
234 }
235
236 public final String getPerformanceSuggestion() {
237
238 // double prob = MCMCOperator.Utils.getAcceptanceProbability(this);
239 // double targetProb = getTargetAcceptanceProbability();
240 // dr.util.NumberFormatter formatter = new dr.util.NumberFormatter(5);
241 // double sf = OperatorUtils.optimizeScaleFactor(autoOptimize, prob, targetProb);
242 // if (prob < getMinimumGoodAcceptanceLevel()) {
243 // return "Try setting scaleFactor to about " + formatter.format(sf);
244 // } else if (prob > getMaximumGoodAcceptanceLevel()) {
245 // return "Try setting scaleFactor to about " + formatter.format(sf);
246 // } else return "";
247 return "I have no idea.";
248 }
249
250
251 public String getOperatorName() {
252 return GIBBS_OPERATOR;
253 }
254
255 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
256
257 public String getParserName() {
258 return GIBBS_OPERATOR;
259 }
260
261 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
262
263 AdaptationMode mode = AdaptationMode.parseMode(xo);
264
265 double weight = xo.getDoubleAttribute(WEIGHT);
266 boolean onlyInternalNodes = xo.getAttribute(INTERNAL_ONLY, true);
267 int disk = xo.getAttribute(DISK, 4);
268
269
270 AbstractMultivariateTraitLikelihood traitModel = (AbstractMultivariateTraitLikelihood) xo.getChild(AbstractMultivariateTraitLikelihood.class);
271
272 DiscretizedLocationOperator operator = new DiscretizedLocationOperator(traitModel, onlyInternalNodes, disk, mode);
273 operator.setWeight(weight);
274
275 // Get node priors
276 // for (int i = 0; i < xo.getChildCount(); i++) {
277 // if (xo.getChild(i) instanceof MultivariateDistributionLikelihood) {
278 // MultivariateDistribution dist = ((MultivariateDistributionLikelihood) xo.getChild(i)).getDistribution();
279 // if (dist instanceof GeoSpatialDistribution) {
280 // GeoSpatialDistribution prior = (GeoSpatialDistribution) dist;
281 // String nodeLabel = prior.getLabel();
282 // TreeModel treeModel = traitModel.getTreeModel();
283 //
284 // // Get taxon node from tree
285 // int index = treeModel.getTaxonIndex(nodeLabel);
286 // if (index == -1) {
287 // throw new XMLParseException("taxon '" + nodeLabel + "' not found for geoSpatialDistribution element in traitGibbsOperator element");
288 // }
289 // NodeRef node = treeModel.getExternalNode(index);
290 //// operator.setTaxonPrior(node, prior);
291 // System.err.println("Adding truncated prior for " + node);
292 // }
293 // }
294 // }
295
296 boolean randomize = xo.getAttribute(RANDOMIZE, false);
297
298 if (randomize)
299 operator.randomizeNodes();
300
301 return operator;
302 }
303
304 //************************************************************************
305 // AbstractXMLObjectParser implementation
306 //************************************************************************
307
308 public String getParserDescription() {
309 return "This element returns a multivariate Gibbs operator on traits for possible all nodes.";
310 }
311
312 public Class getReturnType() {
313 return MCMCOperator.class;
314 }
315
316 public XMLSyntaxRule[] getSyntaxRules() {
317 return rules;
318 }
319
320 private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
321 AttributeRule.newDoubleRule(WEIGHT),
322 AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true),
323 AttributeRule.newBooleanRule(INTERNAL_ONLY, true),
324 new ElementRule(AbstractMultivariateTraitLikelihood.class),
325 AttributeRule.newIntegerRule(DISK, true),
326 AttributeRule.newBooleanRule(RANDOMIZE, true),
327 };
328
329 };
330
331 public class WeightedPoint2D extends Point2D.Double implements Comparable {
332
333 public double weight;
334
335 public WeightedPoint2D(double x, double y, double weight) {
336 super(x, y);
337 this.weight = weight;
338 }
339
340 public int compareTo(Object o) {
341 WeightedPoint2D pt = (WeightedPoint2D) o;
342 if (weight > pt.weight)
343 return 1;
344 if (weight < pt.weight)
345 return -1;
346 return 0;
347 }
348
349 public String toString() {
350 return super.toString() + "(" + weight + ")";
351 }
352 }
353
354 private Map<Point2D, List<WeightedPoint2D>> nearestNeighborMap;
355 private Set<Point2D> allLocations;
356 private final MutableTreeModel treeModel;
357 private String traitName;
358 private double autoOptimize;
359 private boolean onlyInternalNodes = true;
360 private int disk = 4;
361
362 private Point2D savedPt;
363
364 }