Debian Codegraph @

src/dr/evomodelxml/tree/TreeLoggerParser.java

raw symbols SCIP
1 /*
2 * TreeLoggerParser.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.evomodelxml.tree;
27
28 import dr.evolution.colouring.TreeColouringProvider;
29 import dr.evolution.tree.*;
30 import dr.evomodel.tree.TreeLogger;
31 import dr.inference.loggers.LogFormatter;
32 import dr.inference.loggers.Loggable;
33 import dr.inference.loggers.TabDelimitedFormatter;
34 import dr.inference.model.Likelihood;
35 import dr.inference.model.Model;
36 import dr.inference.model.Parameter;
37 import dr.inferencexml.loggers.LoggerParser;
38 import dr.util.Identifiable;
39 import dr.xml.*;
40
41 import java.io.PrintWriter;
42 import java.text.NumberFormat;
43 import java.util.ArrayList;
44 import java.util.List;
45 import java.util.Locale;
46
47 /**
48 * @author Alexei Drummond
49 * @author Andrew Rambaut
50 */
51 public class TreeLoggerParser extends LoggerParser {
52
53 public static final String LOG_TREE = "logTree";
54 public static final String NEXUS_FORMAT = "nexusFormat";
55 // public static final String USING_RATES = "usingRates";
56 public static final String BRANCH_LENGTHS = "branchLengths";
57 public static final String TIME = "time";
58 public static final String SUBSTITUTIONS = "substitutions";
59 public static final String SORT_TRANSLATION_TABLE = "sortTranslationTable";
60 public static final String MAP_NAMES = "mapNamesToNumbers";
61 public static final String DECIMAL_PLACES = "dp";
62 // public static final String NORMALISE_MEAN_RATE_TO = "normaliseMeanRateTo";
63
64 public static final String FILTER_TRAITS = "traitFilter";
65 public static final String TREE_TRAIT = "trait";
66 public static final String NAME = "name";
67 public static final String TAG = "tag";
68
69 public String getParserName() {
70 return LOG_TREE;
71 }
72
73 protected void parseXMLParameters(XMLObject xo) throws XMLParseException
74 {
75 // reset this every time...
76 branchRates = null;
77
78 tree = (Tree) xo.getChild(Tree.class);
79
80 title = xo.getAttribute(TITLE, "");
81
82 nexusFormat = xo.getAttribute(NEXUS_FORMAT, false);
83
84 sortTranslationTable = xo.getAttribute(SORT_TRANSLATION_TABLE, true);
85
86 boolean substitutions = xo.getAttribute(BRANCH_LENGTHS, "").equals(SUBSTITUTIONS);
87
88 List<TreeAttributeProvider> taps = new ArrayList<TreeAttributeProvider>();
89 List<TreeTraitProvider> ttps = new ArrayList<TreeTraitProvider>();
90
91 // ttps2 are for TTPs that are not specified within a Trait element. These are only
92 // included if not already added through a trait element to avoid duplication of
93 // (in particular) the BranchRates which is required for substitution trees.
94 List<TreeTraitProvider> ttps2 = new ArrayList<TreeTraitProvider>();
95
96 for (int i = 0; i < xo.getChildCount(); i++) {
97 Object cxo = xo.getChild(i);
98
99 // This needs to be refactored into using a TreeTrait if Colouring is resurrected...
100 // if (cxo instanceof TreeColouringProvider) {
101 // final TreeColouringProvider colouringProvider = (TreeColouringProvider) cxo;
102 // baps.add(new BranchAttributeProvider() {
103 //
104 // public String getBranchAttributeLabel() {
105 // return "deme";
106 // }
107 //
108 // public String getAttributeForBranch(Tree tree, NodeRef node) {
109 // TreeColouring colouring = colouringProvider.getTreeColouring(tree);
110 // BranchColouring bcol = colouring.getBranchColouring(node);
111 // StringBuilder buffer = new StringBuilder();
112 // if (bcol != null) {
113 // buffer.append("{");
114 // buffer.append(bcol.getChildColour());
115 // for (int i = 1; i <= bcol.getNumEvents(); i++) {
116 // buffer.append(",");
117 // buffer.append(bcol.getBackwardTime(i));
118 // buffer.append(",");
119 // buffer.append(bcol.getBackwardColourAbove(i));
120 // }
121 // buffer.append("}");
122 // }
123 // return buffer.toString();
124 // }
125 // });
126 //
127 // } else
128
129 if (cxo instanceof Likelihood) {
130 final Likelihood likelihood = (Likelihood) cxo;
131 taps.add(new TreeAttributeProvider() {
132
133 public String[] getTreeAttributeLabel() {
134 return new String[] {"lnP"};
135 }
136
137 public String[] getAttributeForTree(Tree tree) {
138 return new String[] {Double.toString(likelihood.getLogLikelihood())};
139 }
140 });
141 }
142
143 if (cxo instanceof TreeAttributeProvider) {
144 taps.add((TreeAttributeProvider) cxo);
145 }
146 if (cxo instanceof TreeTraitProvider) {
147 if (xo.hasAttribute(FILTER_TRAITS)) {
148 String[] matches = ((String) xo.getAttribute(FILTER_TRAITS)).split("[\\s,]+");
149 TreeTraitProvider ttp = (TreeTraitProvider) cxo;
150 TreeTrait[] traits = ttp.getTreeTraits();
151 List<TreeTrait> filteredTraits = new ArrayList<TreeTrait>();
152 for (String match : matches) {
153 for (TreeTrait trait : traits) {
154 if (trait.getTraitName().startsWith(match)) {
155 filteredTraits.add(trait);
156 }
157 }
158 }
159 if (filteredTraits.size() > 0) {
160 ttps2.add(new TreeTraitProvider.Helper(filteredTraits));
161 }
162
163 } else {
164 // Add all of them
165 ttps2.add((TreeTraitProvider) cxo);
166 }
167 }
168 if (cxo instanceof XMLObject) {
169 XMLObject xco = (XMLObject)cxo;
170 if (xco.getName().equals(TREE_TRAIT)) {
171
172 TreeTraitProvider ttp = (TreeTraitProvider)xco.getChild(TreeTraitProvider.class);
173
174 if (xco.hasAttribute(NAME)) {
175 // a specific named trait is required (optionally with a tag to name it in the tree file)
176
177 String name = xco.getStringAttribute(NAME);
178 final TreeTrait trait = ttp.getTreeTrait(name);
179
180 if (trait == null) {
181 String childName = "TreeTraitProvider";
182
183 if (ttp instanceof Likelihood) {
184 childName = ((Likelihood)ttp).prettyName();
185 } else if (ttp instanceof Model) {
186 childName = ((Model)ttp).getModelName();
187 }
188
189 throw new XMLParseException("Trait named, " + name + ", not found for " + childName);
190 }
191
192 final String tag;
193 if (xco.hasAttribute(TAG)) {
194 tag = xco.getStringAttribute(TAG);
195 } else {
196 tag = name;
197 }
198
199 ttps.add(new TreeTraitProvider.Helper(tag, new TreeTrait() {
200
201 public String getTraitName() {
202 return tag;
203 }
204
205 public Intent getIntent() {
206 return trait.getIntent();
207 }
208
209 public Class getTraitClass() {
210 return trait.getTraitClass();
211 }
212
213 public Object getTrait(Tree tree, NodeRef node) {
214 return trait.getTrait(tree, node);
215 }
216
217 public String getTraitString(Tree tree, NodeRef node) {
218 return trait.getTraitString(tree, node);
219 }
220
221 public boolean getLoggable() {
222 return trait.getLoggable();
223 }
224 }));
225 } else if (xo.hasAttribute(FILTER_TRAITS)) {
226 // else a filter attribute is given to ask for all traits that starts with a specific
227 // string
228
229 String[] matches = ((String) xo.getAttribute(FILTER_TRAITS)).split("[\\s,]+");
230 TreeTrait[] traits = ttp.getTreeTraits();
231 List<TreeTrait> filteredTraits = new ArrayList<TreeTrait>();
232 for (String match : matches) {
233 for (TreeTrait trait : traits) {
234 if (trait.getTraitName().startsWith(match)) {
235 filteredTraits.add(trait);
236 }
237 }
238 }
239 if (filteredTraits.size() > 0) {
240 ttps.add(new TreeTraitProvider.Helper(filteredTraits));
241 }
242
243 } else {
244 // neither named or filtered traits so just add them all
245 ttps.add(ttp);
246 }
247 }
248 }
249 // Without this next block, branch rates get ignored :-(
250 // BranchRateModels are now TreeTraitProviders so this is not needed.
251 // if (cxo instanceof TreeTrait) {
252 // final TreeTrait trait = (TreeTrait)cxo;
253 // TreeTraitProvider ttp = new TreeTraitProvider() {
254 // public TreeTrait[] getTreeTraits() {
255 // return new TreeTrait[] { trait };
256 // }
257 //
258 // public TreeTrait getTreeTrait(String key) {
259 // if (key.equals(trait.getTraitName())) {
260 // return trait;
261 // }
262 // return null;
263 // }
264 // };
265 // ttps.add(ttp);
266 // }
267 //}
268
269 // be able to put arbitrary statistics in as tree attributes
270 if (cxo instanceof Loggable) {
271 final Loggable loggable = (Loggable) cxo;
272 taps.add(new TreeAttributeProvider() {
273
274 public String[] getTreeAttributeLabel() {
275 String[] labels = new String[loggable.getColumns().length];
276 for (int i = 0; i < loggable.getColumns().length; i++) {
277 labels[i] = loggable.getColumns()[i].getLabel();
278 }
279 return labels;
280 }
281
282 public String[] getAttributeForTree(Tree tree) {
283 String[] values = new String[loggable.getColumns().length];
284 for (int i = 0; i < loggable.getColumns().length; i++) {
285 values[i] = loggable.getColumns()[i].getFormatted();
286 }
287 return values;
288 }
289 });
290 }
291
292 }
293
294 // if we don't have any of the newer trait elements but we do have some tree trait providers
295 // included directly then assume the user wanted to log these as tree traits (it may be an older
296 // form XML).
297 // if (ttps.size() == 0 && ttps2.size() > 0) {
298 // ttps.addAll(ttps2);
299 // }
300
301 // The above code destroyed the logging of complete histories - which need to be logged by direct
302 // inclusion of the codon partitioned robust counting TTP...
303 if (ttps2.size() > 0) {
304 ttps.addAll(ttps2);
305 }
306
307 if (substitutions) {
308 branchRates = (BranchRates) xo.getChild(BranchRates.class);
309 }
310 if (substitutions && branchRates == null) {
311 throw new XMLParseException("To log trees in units of substitutions a BranchRateModel must be provided");
312 }
313
314 // logEvery of zero only displays at the end
315 logEvery = xo.getAttribute(LOG_EVERY, 0);
316
317 // double normaliseMeanRateTo = xo.getAttribute(NORMALISE_MEAN_RATE_TO, Double.NaN);
318
319 // decimal places
320 final int dp = xo.getAttribute(DECIMAL_PLACES, -1);
321 if (dp != -1) {
322 format = NumberFormat.getNumberInstance(Locale.ENGLISH);
323 format.setMaximumFractionDigits(dp);
324 }
325
326 final PrintWriter pw = getLogFile(xo, getParserName());
327
328 formatter = new TabDelimitedFormatter(pw);
329
330 treeAttributeProviders = new TreeAttributeProvider[taps.size()];
331 taps.toArray(treeAttributeProviders);
332 treeTraitProviders = new TreeTraitProvider[ttps.size()];
333 ttps.toArray(treeTraitProviders);
334
335 // I think the default should be to have names rather than numbers, thus the false default - AJD
336 // I think the default should be numbers - using names results in larger files and end user never
337 // sees the numbers anyway as any software loading the nexus files does the translation - JH
338 mapNames = xo.getAttribute(MAP_NAMES, true);
339
340 condition = logEvery == 0 ? (TreeLogger.LogUpon) xo.getChild(TreeLogger.LogUpon.class) : null;
341 }
342
343 /**
344 * @return an object based on the XML element it was passed.
345 */
346 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
347 parseXMLParameters(xo);
348
349 TreeLogger logger = new TreeLogger(tree, branchRates,
350 treeAttributeProviders, treeTraitProviders,
351 formatter, logEvery, nexusFormat, sortTranslationTable, mapNames, format, condition/*,
352 normaliseMeanRateTo*/);
353
354 if (title != null) {
355 logger.setTitle(title);
356 }
357
358 return logger;
359 }
360
361 protected Tree tree;
362 protected String title;
363 protected boolean nexusFormat;
364 protected boolean sortTranslationTable;
365 protected BranchRates branchRates;
366 protected NumberFormat format = null;
367 protected TreeLogger.LogUpon condition;
368 protected boolean mapNames;
369 protected LogFormatter formatter;
370 protected TreeAttributeProvider[] treeAttributeProviders;
371 protected TreeTraitProvider[] treeTraitProviders;
372 protected int logEvery;
373
374 //************************************************************************
375 // AbstractXMLObjectParser implementation
376 //************************************************************************
377 public XMLSyntaxRule[] getSyntaxRules() {
378 return rules;
379 }
380
381 private final XMLSyntaxRule[] rules = {
382 AttributeRule.newIntegerRule(LOG_EVERY, true),
383 AttributeRule.newBooleanRule(ALLOW_OVERWRITE_LOG, true),
384 new StringAttributeRule(FILE_NAME,
385 "The name of the file to send log output to. " +
386 "If no file name is specified then log is sent to standard output", true),
387 new StringAttributeRule(TITLE, "The title of the log", true),
388 AttributeRule.newBooleanRule(NEXUS_FORMAT, true,
389 "Whether to use the NEXUS format for the tree log"),
390 AttributeRule.newBooleanRule(SORT_TRANSLATION_TABLE, true,
391 "Whether the translation table is sorted."),
392 /*AttributeRule.newDoubleRule(NORMALISE_MEAN_RATE_TO, true,
393 "Value to normalise the mean rate to."),*/
394 new StringAttributeRule(BRANCH_LENGTHS, "What units should the branch lengths be in",
395 new String[]{TIME, SUBSTITUTIONS}, true),
396 AttributeRule.newStringRule(FILTER_TRAITS, true),
397 AttributeRule.newBooleanRule(MAP_NAMES, true),
398 AttributeRule.newIntegerRule(DECIMAL_PLACES, true),
399
400 new ElementRule(Tree.class, "The tree which is to be logged"),
401 // new ElementRule(BranchRates.class, true),
402 // new ElementRule(TreeColouringProvider.class, true),
403 new ElementRule(TREE_TRAIT,
404 new XMLSyntaxRule[] {
405 AttributeRule.newStringRule(NAME, false, "The name of the trait"),
406 AttributeRule.newStringRule(TAG, true, "The label of the trait to be used in the tree"),
407 new ElementRule(TreeAttributeProvider.class, "The trait provider")
408 }, 0, Integer.MAX_VALUE),
409 new ElementRule(Likelihood.class, true),
410 new ElementRule(Loggable.class, 0, Integer.MAX_VALUE),
411 new ElementRule(TreeAttributeProvider.class, 0, Integer.MAX_VALUE),
412 new ElementRule(TreeTraitProvider.class, 0, Integer.MAX_VALUE),
413 new ElementRule(TreeLogger.LogUpon.class, true)
414 };
415
416 public String getParserDescription() {
417 return "Logs a tree to a file";
418 }
419
420 public String getExample() {
421 final String name = getParserName();
422 return
423 "<!-- The " + name + " element takes a treeModel to be logged -->\n" +
424 "<" + name + " " + LOG_EVERY + "=\"100\" " + FILE_NAME + "=\"log.trees\" "
425 + NEXUS_FORMAT + "=\"true\">\n" +
426 " <treeModel idref=\"treeModel1\"/>\n" +
427 "</" + name + ">\n";
428 }
429
430 public Class getReturnType() {
431 return TreeLogger.class;
432 }
433 }