Debian Codegraph @

src/dr/evomodelxml/treelikelihood/TreeTraitParserUtilities.java

raw symbols SCIP
1 /*
2 * TreeTraitParserUtilities.java
3 *
4 * Copyright (c) 2002-2016 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.evomodelxml.treelikelihood;
27
28 import dr.evolution.tree.Tree;
29 import dr.evomodel.continuous.StandardizeTraits;
30 import dr.inference.model.*;
31 import dr.math.MathUtils;
32 import dr.xml.*;
33
34 import java.util.*;
35 import java.util.logging.Logger;
36
37 /**
38 * @author Marc A. Suchard
39 */
40
41 public class TreeTraitParserUtilities {
42
43 public static final String TRAIT_PARAMETER = "traitParameter";
44 public static final String TRAIT_NAME = "traitName";
45 public static final String MISSING = "missingIndicator";
46 public static final String RANDOM_SAMPLE = "randomSample";
47 public static final String DEFAULT_TRAIT_NAME = "trait";
48
49 public static final String RANDOMIZE = "randomize";
50 public static final String RANDOMIZE_LOWER = "lower";
51 public static final String RANDOMIZE_UPPER = "upper";
52
53 public static final String ALLOW_IDENTICAL = "allowIdentical";
54 public static final String JITTER = "jitter";
55 public static final String WINDOW = "window";
56 public static final String DUPLICATES = "duplicatesOnly";
57 public static final String STANDARDIZE = "standardize";
58 public static final String SAMPLE_MISSING_TRAITS = "sampleMissingTraits";
59
60 public static final String LATENT_FROM = "latentFrom";
61 public static final String LATENT_TO = "latentTo";
62
63 public void randomize(Parameter trait, double[] lower, double[] upper) {
64 // Draws each dimension in each trait from U[lower, upper)
65 for (int i = 0; i < trait.getDimension(); i++) {
66 final int whichLower = i % lower.length;
67 final int whichUpper = i % upper.length;
68 final double newValue = MathUtils.uniform(lower[whichLower], upper[whichUpper]);
69 trait.setParameterValue(i, newValue);
70 }
71 }
72
73 // public void standardize(Parameter trait) {
74 // for (int i = 0; i < trait.)
75 // }
76
77 public static ElementRule randomizeRules(boolean optional) {
78 return new ElementRule(TreeTraitParserUtilities.RANDOMIZE, new XMLSyntaxRule[]{
79 AttributeRule.newDoubleRule(TreeTraitParserUtilities.RANDOMIZE_LOWER, true),
80 AttributeRule.newDoubleRule(TreeTraitParserUtilities.RANDOMIZE_UPPER, true),
81 new ElementRule(Parameter.class)
82 }, optional);
83 }
84
85 public static ElementRule jitterRules(boolean optional) {
86 return new ElementRule(JITTER, new XMLSyntaxRule[]{
87 AttributeRule.newDoubleArrayRule(WINDOW),
88 AttributeRule.newBooleanRule(DUPLICATES, true),
89 new ElementRule(Parameter.class),
90
91 }, optional);
92 }
93
94 public void jitter(XMLObject xo, int length, List<Integer> missingIndices) throws XMLParseException {
95 XMLObject cxo = xo.getChild(TreeTraitParserUtilities.JITTER);
96 Parameter traits = (Parameter) cxo.getChild(Parameter.class);
97 double[] window = cxo.getDoubleArrayAttribute(TreeTraitParserUtilities.WINDOW); // Must be included, no default value
98 boolean duplicates = cxo.getAttribute(TreeTraitParserUtilities.DUPLICATES, true); // default = true
99 jitter(traits, length, missingIndices, window, duplicates, true);
100 }
101
102 public void randomize(XMLObject xo) throws XMLParseException {
103 XMLObject cxo = xo.getChild(RANDOMIZE);
104 Parameter traits = (Parameter) cxo.getChild(Parameter.class);
105 double[] randomizeLower;
106 double[] randomizeUpper;
107 if (cxo.hasAttribute(RANDOMIZE_LOWER)) {
108 randomizeLower = cxo.getDoubleArrayAttribute(RANDOMIZE_LOWER);
109 } else {
110 randomizeLower = new double[]{-90.0};
111 }
112 if (cxo.hasAttribute(RANDOMIZE_UPPER)) {
113 randomizeUpper = cxo.getDoubleArrayAttribute(RANDOMIZE_UPPER);
114 } else {
115 randomizeUpper = new double[]{+90.0};
116 }
117 randomize(traits, randomizeLower, randomizeUpper);
118 }
119
120 private class DoubleArray implements Comparable {
121
122 double[] value;
123 int index;
124
125 DoubleArray(double[] value, int index) {
126 this.value = value;
127 this.index = index;
128 }
129
130 public double[] getValues() {
131 return value;
132 }
133
134 public int getIndex() {
135 return index;
136 }
137
138 public int compareTo(Object o) {
139 double[] x = ((DoubleArray) o).getValues();
140 for (int i = 0; i < value.length; i++) {
141 if (value[i] > x[i]) {
142 return 1;
143 } else if (value[i] < x[i]) {
144 return -1;
145 }
146 }
147 return 0;
148 }
149 }
150
151 public boolean hasIdenticalTraits(Parameter trait, List<Integer> missingIndices, int dim) {
152 int numTraits = trait.getDimension() / dim;
153
154 List<DoubleArray> traitArray = new ArrayList<DoubleArray>();
155 for (int i = 0; i < numTraits; i++) {
156
157 if (!missingIndices.contains(i * dim)) { // TODO Assumes completely missing traits
158 double[] x = new double[dim];
159 for (int j = 0; j < dim; j++) {
160 x[j] = trait.getParameterValue(i * dim + j);
161 }
162 traitArray.add(new DoubleArray(x, i));
163 }
164 }
165
166 DoubleArray[] sortedTraits = traitArray.toArray(new DoubleArray[0]);
167 Arrays.sort(sortedTraits);
168 // Mark duplicates
169 for (int i = 1; i < sortedTraits.length; i++) {
170 if (sortedTraits[i].compareTo(sortedTraits[i - 1]) == 0) {
171 return true;
172 }
173 }
174 return false;
175 }
176
177 public void jitter(Parameter trait, int dim, List<Integer> missingIndices, double[] window, boolean duplicates, boolean verbose) {
178 int numTraits = trait.getDimension() / dim;
179 boolean[] update = new boolean[numTraits];
180 if (!duplicates) {
181 Arrays.fill(update, true);
182 } else {
183 DoubleArray[] traitArray = new DoubleArray[numTraits];
184 for (int i = 0; i < numTraits; i++) {
185 double[] x = new double[dim];
186 for (int j = 0; j < dim; j++) {
187 x[j] = trait.getParameterValue(i * dim + j);
188 }
189 traitArray[i] = new DoubleArray(x, i);
190 }
191 Arrays.sort(traitArray);
192 // Mark duplicates
193 for (int i = 1; i < numTraits; i++) {
194 if (traitArray[i].compareTo(traitArray[i - 1]) == 0) {
195 update[traitArray[i - 1].getIndex()] = true;
196 update[traitArray[i].getIndex()] = true;
197 }
198 }
199 }
200 for (int i = 0; i < numTraits; i++) {
201 if (update[i]) {
202 StringBuffer sb1 = null;
203 StringBuffer sb2 = null;
204 if (verbose) {
205 sb1 = new StringBuffer();
206 sb2 = new StringBuffer();
207 }
208 boolean hitAtLeastOneComponent = false;
209 for (int j = 0; j < dim; j++) {
210 final double oldValue = trait.getParameterValue(i * dim + j);
211 final double newValue;
212 if (!missingIndices.contains(i * dim + j)) {
213 newValue = window[j % window.length] * (MathUtils.nextDouble() - 0.5) +
214 oldValue;
215 trait.setParameterValue(i * dim + j, newValue);
216 hitAtLeastOneComponent = true;
217 } else {
218 newValue = oldValue;
219 }
220 if (verbose) {
221 sb1.append(" ").append(oldValue);
222 sb2.append(" ").append(newValue);
223 }
224 }
225 if (verbose && hitAtLeastOneComponent) {
226 Logger.getLogger("dr.evomodel.continuous").info(
227 " Replacing trait #" + (i + 1) + " Old:" + sb1.toString() + " New: " + sb2.toString()
228 );
229 }
230 }
231 }
232 }
233
234 public class TraitsAndMissingIndices {
235 public CompoundParameter traitParameter;
236 public List<Integer> missingIndices;
237 public String traitName;
238 public Parameter sampleMissingParameter;
239 public boolean useMissingIndices;
240
241 TraitsAndMissingIndices(CompoundParameter traitParameter, List<Integer> missingIndices, String traitName,
242 Parameter sampleMissingParameter, boolean useMissingIndices) {
243 this.traitParameter = traitParameter;
244 this.missingIndices = missingIndices;
245 this.traitName = traitName;
246 this.sampleMissingParameter = sampleMissingParameter;
247 this.useMissingIndices = useMissingIndices;
248 }
249 }
250
251 public TraitsAndMissingIndices parseTraitsFromTaxonAttributes(
252 XMLObject xo,
253 String inTraitName,
254 Tree treeModel,
255 boolean integrateOutInternalStates) throws XMLParseException {
256
257 XMLObject xoc = xo.getChild(TRAIT_PARAMETER);
258 Parameter parameter = (Parameter) xoc.getChild(Parameter.class);
259 boolean existingTraitParameter = false;
260 int randomSampleSizeFlag = xo.getAttribute(RANDOM_SAMPLE, -1);
261
262 String traitName = inTraitName;
263
264 CompoundParameter traitParameter;
265 List<Integer> missingIndices = null;
266 Parameter sampleMissingParameter = null;
267
268 boolean isMatrixParameter = false;
269 if (parameter instanceof MatrixParameter || parameter instanceof FastMatrixParameter) {
270 traitParameter = (CompoundParameter) parameter;
271 isMatrixParameter = true;
272 } else
273
274
275 if (parameter instanceof CompoundParameter) {
276 // if we have been passed a CompoundParameter, this will be a leaf trait
277 // parameter from a tree model so use this to allow for individual sampling
278 // of leaf parameters.
279 traitParameter = (CompoundParameter) parameter;
280 existingTraitParameter = true;
281 } else {
282 // create a compound parameter of appropriate dimensions
283 traitParameter = new CompoundParameter(parameter.getId());
284 ParameterParser.replaceParameter(xoc, traitParameter);
285 }
286
287 if (xo.hasAttribute(TRAIT_NAME)) {
288
289 Map<Integer, Integer> randomSample = null;
290 traitName = xo.getStringAttribute(TRAIT_NAME);
291
292 StringBuilder warnings = new StringBuilder();
293 int warningLength = 0;
294 final int maxWarnings = 10;
295
296 // Fill in attributeValues
297 int taxonCount = treeModel.getTaxonCount();
298 for (int i = 0; i < taxonCount; i++) {
299 String taxonName = treeModel.getTaxonId(i);
300
301 // changed to just label the rows by the taxonName so it can be picked up elsewhere
302 String paramName = taxonName;
303 String altParamName = taxonName + "." + traitName;
304
305 String object = (String) treeModel.getTaxonAttribute(i, traitName);
306 if (object == null) {
307 throw new RuntimeException("Trait \"" + traitName + "\" not found for taxa \"" + taxonName + "\"");
308 } else {
309 StringTokenizer st = new StringTokenizer(object);
310 int count = st.countTokens();
311
312 Parameter traitParam;
313 if (existingTraitParameter) {
314 traitParam = getTraitParameterByName(traitParameter, paramName);
315 if (traitParam == null) {
316 // try the alternative param name
317 traitParam = getTraitParameterByName(traitParameter, altParamName);
318 if (traitParam == null) {
319 throw new RuntimeException("Missing trait parameters for taxon, " + paramName);
320 }
321 }
322 } else {
323 if (isMatrixParameter) {
324 traitParam = traitParameter.getParameter(i);
325 traitParam.setId(paramName);
326 } else {
327 // Make multidimensional, in earlier revisions only first dimension was stored
328 traitParam = new Parameter.Default(paramName, count);
329 traitParameter.addParameter(traitParam);
330 }
331 }
332
333
334 int sampleSize = count;
335 if (randomSampleSizeFlag > 0) {
336 if (randomSample == null) {
337 randomSample = drawRandomSample(randomSampleSizeFlag, count);
338 }
339 sampleSize = randomSampleSizeFlag;
340 }
341 if (sampleSize != traitParam.getDimension()) {
342 if (existingTraitParameter) {
343 throw new RuntimeException("Trait length must match trait parameter dimension for taxon, " +
344 taxonName + ": " +
345 sampleSize + " != " + traitParam.getDimension());
346 } else {
347 traitParam.setDimension(sampleSize);
348 }
349 }
350 int index = 0;
351 for (int j = 0; j < count; j++) {
352 String oneValue = st.nextToken();
353 if (randomSampleSizeFlag == -1 || randomSample.containsKey(j)) {
354 double value = Double.NaN;
355 if (oneValue.equals("NA") || oneValue.equals("?") ) {
356 if (warningLength < maxWarnings) {
357 warnings.append(
358 "Warning: Missing value in tip for taxon " + taxonName +
359 " (filling with 0 as starting value when sampling only)\n" // See comment below
360 );
361 ++warningLength;
362 }
363 } else {
364 try {
365 value = new Double(oneValue);
366 if (Double.isNaN(value)) {
367 if (warningLength < maxWarnings) {
368 warnings.append(
369 "Warning: Unrecognizable number " + oneValue + " for taxon " + taxonName + "\n"
370 );
371 ++warningLength;
372 }
373 }
374 } catch (NumberFormatException e) {
375 throw new RuntimeException(e.getMessage());
376 }
377 }
378
379 int replicates = 1;
380 if (randomSampleSizeFlag != -1) {
381 // Count how many times to add this datum
382 replicates = randomSample.get(j);
383 }
384 for (int k = 0; k < replicates; k++) {
385 traitParam.setParameterValue(index, value);
386 index++;
387 }
388 }
389 }
390 }
391 }
392
393 if (warningLength > 0) {
394 Logger.getLogger("dr.evomodel.continuous").info(warnings.toString());
395 if (warningLength == maxWarnings) {
396 Logger.getLogger("dr.evomodel.continuous").info("Warning: only first " + maxWarnings + " trait warnings were displayed\n");
397 }
398 }
399
400 // Standardize
401 if (xo.getAttribute(STANDARDIZE, false) && traitParameter instanceof MatrixParameterInterface) {
402
403 StandardizeTraits st = new StandardizeTraits((MatrixParameterInterface) traitParameter);
404 String message = st.doStandardization(false);
405
406 Logger.getLogger("dr.evomodel.continous").info(message);
407 }
408
409 // Find missing values
410 double[] allValues = traitParameter.getParameterValues();
411 missingIndices = new ArrayList<Integer>();
412 for (int i = 0; i < allValues.length; i++) {
413 if ((new Double(allValues[i])).isNaN()) {
414 traitParameter.setParameterValue(i, 0); // Here, missings are set to zero
415 missingIndices.add(i);
416 }
417 }
418
419 if (xo.hasChildNamed(MISSING)) {
420 XMLObject cxo = xo.getChild(MISSING);
421
422 Parameter missingParameter = new Parameter.Default(allValues.length, 0.0);
423 for (int i : missingIndices) {
424 missingParameter.setParameterValue(i, 1.0);
425 }
426
427 if (cxo.hasAttribute(LATENT_FROM) && cxo.hasAttribute(LATENT_TO)) {
428 int from = cxo.getIntegerAttribute(LATENT_FROM);
429 int to = cxo.getIntegerAttribute(LATENT_TO);
430
431 final int dimTrait = allValues.length / taxonCount;
432
433 if (from < 1 || to < 1 || from > dimTrait || to > dimTrait) {
434 throw new XMLParseException("Invalid latent dimension specification");
435 }
436
437 int index = 0;
438 for (int taxon = 0; taxon < taxonCount; ++taxon) {
439 for (int trait = from - 1; trait < to; ++trait) {
440 missingParameter.setParameterValue(index + trait, 1.0);
441 }
442 index += dimTrait;
443 }
444 }
445
446 missingParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, allValues.length));
447 ParameterParser.replaceParameter(cxo, missingParameter);
448 sampleMissingParameter = missingParameter;
449 }
450
451 // Give warnings if trait exist for internal and root nodes when integrating them out
452 if (false) {
453 int numTraits = traitParameter.getParameterCount();
454 if (numTraits != treeModel.getExternalNodeCount()) {
455 throw new XMLParseException(
456 "Dimensionality of '" + traitParameter.getId() + "' (" + numTraits + ") is not equal to the number" +
457 " of tree tips (" + treeModel.getExternalNodeCount() + ")");
458 }
459
460 for (int j = 0; j < numTraits; j++) {
461 String parameterName = traitParameter.getParameter(j).getId();
462 if (parameterName.startsWith("node") || parameterName.startsWith("root")) {
463 throw new XMLParseException(
464 "Internal/root node trait parameters are not allowed when " +
465 "using the integrated observed data likelihood");
466 }
467 }
468 }
469 }
470
471 boolean useMissingIndices = true;
472 if (xo.getAttribute(SAMPLE_MISSING_TRAITS, false) || xo.hasChildNamed(MISSING)) {
473 // missingIndices = new ArrayList<Integer>(); // return empty
474 useMissingIndices = false;
475
476 }
477
478 if (missingIndices == null || missingIndices.size() == 0) {
479 useMissingIndices = false;
480 }
481
482 return new TraitsAndMissingIndices(traitParameter, missingIndices, traitName,
483 sampleMissingParameter, useMissingIndices);
484 }
485
486 private Parameter getTraitParameterByName(CompoundParameter traits, String name) {
487
488 for (int i = 0; i < traits.getParameterCount(); i++) {
489 Parameter found = traits.getParameter(i);
490 if (found.getStatisticName().compareTo(name) == 0)
491 return found;
492 }
493 return null;
494 }
495
496 private Map<Integer, Integer> drawRandomSample(int total, int length) {
497 Map<Integer, Integer> thisMap = new HashMap<Integer, Integer>(total);
498 for (int i = 0; i < total; i++) {
499 int item = MathUtils.nextInt(length);
500 if (thisMap.containsKey(item)) {
501 thisMap.put(item, thisMap.get(item) + 1);
502 } else {
503 thisMap.put(item, 1);
504 }
505 }
506 return thisMap;
507 }
508 }