Debian Codegraph @

src/dr/app/beauti/generator/BeastGenerator.java

raw symbols SCIP
1 /*
2 * BeastGenerator.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.app.beauti.generator;
27
28 import dr.app.beast.BeastVersion;
29 import dr.app.beauti.BeautiApp;
30 import dr.app.beauti.BeautiFrame;
31 import dr.app.beauti.components.ComponentFactory;
32 import dr.app.beauti.options.*;
33 import dr.app.beauti.types.*;
34 import dr.app.beauti.util.XMLWriter;
35 import dr.app.util.Arguments;
36 import dr.evolution.alignment.Alignment;
37 import dr.evolution.alignment.Patterns;
38 import dr.evolution.datatype.DataType;
39 import dr.evolution.datatype.Microsatellite;
40 import dr.evolution.util.Taxa;
41 import dr.evolution.util.Taxon;
42 import dr.evolution.util.TaxonList;
43 import dr.evolution.util.Units;
44 import dr.evomodelxml.speciation.MultiSpeciesCoalescentParser;
45 import dr.evomodelxml.speciation.SpeciationLikelihoodParser;
46 import dr.evoxml.AlignmentParser;
47 import dr.evoxml.DateParser;
48 import dr.evoxml.TaxaParser;
49 import dr.evoxml.TaxonParser;
50 import dr.inferencexml.distribution.MixedDistributionLikelihoodParser;
51 import dr.inferencexml.model.CompoundLikelihoodParser;
52 import dr.inferencexml.operators.SimpleOperatorScheduleParser;
53 import dr.util.Attribute;
54 import dr.util.Pair;
55 import dr.util.Version;
56 import dr.xml.AttributeParser;
57 import dr.xml.XMLParser;
58
59 import java.io.BufferedWriter;
60 import java.io.File;
61 import java.io.FileWriter;
62 import java.io.IOException;
63 import java.util.*;
64
65 /**
66 * This class holds all the data for the current BEAUti Document
67 *
68 * @author Andrew Rambaut
69 * @author Alexei Drummond
70 * @author Walter Xie
71 * @version $Id: BeastGenerator.java,v 1.4 2006/09/05 13:29:34 rambaut Exp $
72 */
73 public class BeastGenerator extends Generator {
74
75 private final static Version VERSION = new BeastVersion();
76 private static final String MESSAGE_CAL_YULE = "Calibrated Yule requires 1 calibrated internal node \n" +
77 "with a proper prior and monophyly enforced for each tree.";
78 private final String MESSAGE_CAL = "\nas another element (taxon, sequence, taxon set, species, etc.):\nAll ids should be unique.";
79
80 private final AlignmentGenerator alignmentGenerator;
81 private final PatternListGenerator patternListGenerator;
82 private final TreePriorGenerator treePriorGenerator;
83 private final TreeLikelihoodGenerator treeLikelihoodGenerator;
84 private final SubstitutionModelGenerator substitutionModelGenerator;
85 private final InitialTreeGenerator initialTreeGenerator;
86 private final TreeModelGenerator treeModelGenerator;
87 private final ClockModelGenerator clockModelGenerator;
88 private final OperatorsGenerator operatorsGenerator;
89 private final ParameterPriorGenerator parameterPriorGenerator;
90 private final LogGenerator logGenerator;
91 private final TMRCAStatisticsGenerator tmrcaStatisticsGenerator;
92
93 public BeastGenerator(BeautiOptions options, ComponentFactory[] components) {
94 super(options, components);
95
96 alignmentGenerator = new AlignmentGenerator(options, components);
97 patternListGenerator = new PatternListGenerator(options, components);
98 tmrcaStatisticsGenerator = new TMRCAStatisticsGenerator(options, components);
99 substitutionModelGenerator = new SubstitutionModelGenerator(options, components);
100 treePriorGenerator = new TreePriorGenerator(options, components);
101 treeLikelihoodGenerator = new TreeLikelihoodGenerator(options, components);
102
103 initialTreeGenerator = new InitialTreeGenerator(options, components);
104 treeModelGenerator = new TreeModelGenerator(options, components);
105 clockModelGenerator = new ClockModelGenerator(options, components);
106
107 operatorsGenerator = new OperatorsGenerator(options, components);
108 parameterPriorGenerator = new ParameterPriorGenerator(options, components);
109 logGenerator = new LogGenerator(options, components);
110
111 }
112
113 /**
114 * Checks various options to check they are valid. Throws IllegalArgumentExceptions with
115 * descriptions of the problems.
116 *
117 * @throws IllegalArgumentException if there is a problem with the current settings
118 */
119 public void checkOptions() throws GeneratorException {
120 //++++++++++++++ Microsatellite +++++++++++++++
121 // this has to execute before all checking below
122 // mask all ? from microsatellite data for whose tree only has 1 data partition
123
124 try{
125 if (options.contains(Microsatellite.INSTANCE)) {
126 // clear all masks
127 for (PartitionPattern partitionPattern : options.getPartitionPattern()) {
128 partitionPattern.getPatterns().clearMask();
129 }
130
131 // set mask
132 for (PartitionTreeModel model : options.getPartitionTreeModels()) {
133 // if a tree only has 1 data partition, which mostly mean unlinked trees
134 if (options.getDataPartitions(model).size() == 1) {
135 PartitionPattern partition = (PartitionPattern) options.getDataPartitions(model).get(0);
136 Patterns patterns = partition.getPatterns();
137
138 for (int i = 0; i < patterns.getTaxonCount(); i++) {
139 int state = patterns.getPatternState(i, 0);
140 // mask ? from data
141 if (state < 0) {
142 patterns.addMask(i);
143 }
144 }
145
146 // System.out.println("mask set = " + patterns.getMaskSet() + " in partition " + partition.getName());
147 }
148 }
149 }
150
151 //++++++++++++++++ Taxon List ++++++++++++++++++
152 TaxonList taxonList = options.taxonList;
153 Set<String> ids = new HashSet<String>();
154
155 ids.add(TaxaParser.TAXA);
156 ids.add(AlignmentParser.ALIGNMENT);
157
158 if (taxonList != null) {
159 if (taxonList.getTaxonCount() < 2) {
160 throw new GeneratorException("BEAST requires at least two taxa to run.");
161 }
162
163 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
164 Taxon taxon = taxonList.getTaxon(i);
165 if (ids.contains(taxon.getId())) {
166 throw new GeneratorException("A taxon has the same id," + taxon.getId() + MESSAGE_CAL);
167 }
168 ids.add(taxon.getId());
169 }
170 }
171
172 //++++++++++++++++ Taxon Sets ++++++++++++++++++
173 for (PartitionTreeModel model : options.getPartitionTreeModels()) {
174 // should be only 1 calibrated internal node with a proper prior and monophyletic for each tree at moment
175 if (model.getPartitionTreePrior().getNodeHeightPrior() == TreePriorType.YULE_CALIBRATION) {
176 if (options.treeModelOptions.isNodeCalibrated(model) < 0) // invalid node calibration
177 throw new GeneratorException(MESSAGE_CAL_YULE);
178
179 if (options.treeModelOptions.isNodeCalibrated(model) > 0) { // internal node calibration
180 List taxonSetsList = options.getKeysFromValue(options.taxonSetsTreeModel, model);
181 if (taxonSetsList.size() != 1 || !options.taxonSetsMono.get(taxonSetsList.get(0))) { // 1 tmrca per tree && monophyletic
182 throw new GeneratorException(MESSAGE_CAL_YULE, BeautiFrame.TAXON_SETS);
183 }
184 }
185 }
186 }
187
188 for (Taxa taxa : options.taxonSets) {
189 // AR - we should allow single taxon taxon sets...
190 if (taxa.getTaxonCount() < 1 // && !options.taxonSetsIncludeStem.get(taxa)
191 ) {
192 throw new GeneratorException(
193 "Taxon set, " + taxa.getId() + ", should contain \n" +
194 "at least one taxa. Please go back to Taxon Sets \n" +
195 "panel to correct this.", BeautiFrame.TAXON_SETS);
196 }
197 if (ids.contains(taxa.getId())) {
198 throw new GeneratorException("A taxon set has the same id," + taxa.getId() +
199 MESSAGE_CAL, BeautiFrame.TAXON_SETS);
200 }
201 ids.add(taxa.getId());
202 }
203
204 //++++++++++++++++ Traits ++++++++++++++++++
205 // missing data is not necessarily an issue...
206 // for (TraitData trait : options.traits) {
207 // for (int i = 0; i < trait.getTaxaCount(); i++) {
208 //// System.out.println("Taxon " + trait.getTaxon(i).getId() + " : [" + trait.getTaxon(i).getAttribute(trait.getName()) + "]");
209 // if (!trait.hasValue(i))
210 // throw new IllegalArgumentException("Taxon " + trait.getTaxon(i).getId() +
211 // " has no value for Trait " + trait.getName());
212 // }
213 // }
214
215 //++++++++++++++++ Tree Prior ++++++++++++++++++
216 // if (options.isShareSameTreePrior()) {
217 if (options.getPartitionTreeModels().size() > 1) { //TODO not allowed multi-prior yet
218 for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
219 if (prior.getNodeHeightPrior() == TreePriorType.GMRF_SKYRIDE) {
220 throw new GeneratorException("For the Skyride, tree model/tree prior combination not implemented by BEAST." +
221 "\nThe Skyride is only available for a single tree model partition in this release.", BeautiFrame.TREES);
222 }
223 }
224 }
225
226 for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
227 if (prior.getNodeHeightPrior() == TreePriorType.SKYGRID && Double.isNaN(prior.getSkyGridInterval())) {
228 throw new GeneratorException("The Skygrid cut-off time must be set and greater than 0.0.", BeautiFrame.TREES);
229 }
230 }
231
232 //+++++++++++++++ Starting tree ++++++++++++++++
233 for (PartitionTreeModel model : options.getPartitionTreeModels()) {
234 if (model.getStartingTreeType() == StartingTreeType.USER) {
235 if (model.getUserStartingTree() == null) {
236 throw new GeneratorException("Please select a starting tree in " + BeautiFrame.TREES + " panel, " +
237 "\nwhen choosing user specified starting tree option.", BeautiFrame.TREES);
238 }
239 }
240 }
241
242 //++++++++++++++++ Random local clock model validation ++++++++++++++++++
243 for (PartitionClockModel model : options.getPartitionClockModels()) {
244 // 1 random local clock CANNOT have different tree models
245 if (model.getClockType() == ClockType.RANDOM_LOCAL_CLOCK) { // || AUTOCORRELATED_LOGNORMAL
246 PartitionTreeModel treeModel = null;
247 for (AbstractPartitionData pd : options.getDataPartitions(model)) { // only the PDs linked to this tree model
248 if (treeModel != null && treeModel != pd.getPartitionTreeModel()) {
249 throw new GeneratorException("A single random local clock cannot be applied to multiple trees.", BeautiFrame.CLOCK_MODELS);
250 }
251 treeModel = pd.getPartitionTreeModel();
252 }
253 }
254 }
255
256 //++++++++++++++++ Tree Model ++++++++++++++++++
257 for (PartitionTreeModel model : options.getPartitionTreeModels()) {
258 int numOfTaxa = -1;
259 for (AbstractPartitionData pd : options.getDataPartitions(model)) {
260 if (pd.getTaxonCount() > 0) {
261 if (numOfTaxa > 0) {
262 if (numOfTaxa != pd.getTaxonCount()) {
263 throw new GeneratorException("Partitions with different taxa cannot share the same tree.", BeautiFrame.DATA_PARTITIONS);
264 }
265 } else {
266 numOfTaxa = pd.getTaxonCount();
267 }
268 }
269 }
270 }
271
272 //++++++++++++++++ Prior Bounds ++++++++++++++++++
273 for (Parameter param : options.selectParameters()) {
274 if (!Double.isNaN(param.getInitial()) ) {
275 if (param.isTruncated && (param.getInitial() < param.truncationLower || param.getInitial() > param.truncationUpper)) {
276 throw new GeneratorException("Parameter \"" + param.getName() + "\":" +
277 "\ninitial value " + param.getInitial() + " is NOT in the range [" + param.truncationLower + ", " + param.truncationUpper + "]," +
278 "\nor this range is wrong. Please check the Prior panel.", BeautiFrame.PRIORS);
279 } else if (param.priorType == PriorType.UNIFORM_PRIOR && (param.getInitial() < param.uniformLower || param.getInitial() > param.uniformUpper)) {
280 throw new GeneratorException("Parameter \"" + param.getName() + "\":" +
281 "\ninitial value " + param.getInitial() + " is NOT in the range [" + param.uniformLower + ", " + param.uniformUpper + "]," +
282 "\nor this range is wrong. Please check the Prior panel.", BeautiFrame.PRIORS);
283 }
284 if (param.isNonNegative && param.getInitial() < 0.0) {
285 throw new GeneratorException("Parameter \"" + param.getName() + "\":" +
286 "\ninitial value " + param.getInitial() + " should be non-negative. Please check the Prior panel.", BeautiFrame.PRIORS);
287 }
288
289 if (param.isZeroOne && (param.getInitial() < 0.0 || param.getInitial() > 1.0)) {
290 throw new GeneratorException("Parameter \"" + param.getName() + "\":" +
291 "\ninitial value " + param.getInitial() + " should lie in the interval [0, 1]. Please check the Prior panel.", BeautiFrame.PRIORS);
292 }
293 }
294 }
295
296 checkComponentOptions();
297
298 // add other tests and warnings here
299 // Speciation model with dated tips
300 // Sampling rates without dated tips or priors on rate or nodes
301
302 } catch (Exception e) {
303 // catch any other exceptions here and rethrow to generate messages
304 throw new GeneratorException(e.getMessage());
305 }
306
307
308 }
309
310 /**
311 * Generate a beast xml file from these beast options
312 *
313 * @param file File
314 * @throws java.io.IOException IOException
315 * @throws dr.app.util.Arguments.ArgumentException
316 * ArgumentException
317 */
318 public void generateXML(File file) throws GeneratorException, IOException, Arguments.ArgumentException {
319
320 XMLWriter writer = new XMLWriter(new BufferedWriter(new FileWriter(file)));
321
322 writer.writeText("<?xml version=\"1.0\" standalone=\"yes\"?>");
323 writer.writeComment("Generated by BEAUTi " + VERSION.getVersionString(),
324 " by Alexei J. Drummond, Andrew Rambaut and Marc A. Suchard",
325 " Department of Computer Science, University of Auckland and",
326 " Institute of Evolutionary Biology, University of Edinburgh",
327 " David Geffen School of Medicine, University of California, Los Angeles",
328 " http://beast.community/");
329 writer.writeOpenTag("beast", new Attribute.Default<String>("version", BeautiApp.VERSION.getVersion()) );
330 writer.writeText("");
331
332 // this gives any added implementations of the 'Component' interface a
333 // chance to generate XML at this point in the BEAST file.
334 generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_TAXA, writer);
335
336 if (options.originDate != null) {
337 // Create a dummy taxon whose job is to specify the origin date
338 Taxon originTaxon = new Taxon("originTaxon");
339 options.originDate.setUnits(options.units);
340 originTaxon.setDate(options.originDate);
341 writeTaxon(originTaxon, true, false, writer);
342 }
343
344
345 //++++++++++++++++ Taxon List ++++++++++++++++++
346 try {
347 // write complete taxon list
348 writeTaxa(options.taxonList, writer);
349
350 writer.writeText("");
351
352 if (!options.hasIdenticalTaxa()) {
353 // write all taxa in each gene tree regarding each data partition,
354 for (AbstractPartitionData partition : options.dataPartitions) {
355 if (partition.getTaxonList() != null) {
356 writeDifferentTaxa(partition, writer);
357 }
358 }
359 } else {
360 // microsat
361 for (PartitionPattern partitionPattern : options.getPartitionPattern()) {
362 if (partitionPattern.getTaxonList() != null && partitionPattern.getPatterns().hasMask()) {
363 writeDifferentTaxa(partitionPattern, writer);
364 }
365 }
366 }
367 } catch (Exception e) {
368 e.printStackTrace(System.err);
369 throw new GeneratorException("Taxon list generation has failed:\n" + e.getMessage());
370 }
371
372 //++++++++++++++++ Taxon Sets ++++++++++++++++++
373 List<Taxa> taxonSets = options.taxonSets;
374 try {
375 if (taxonSets != null && taxonSets.size() > 0) {
376 tmrcaStatisticsGenerator.writeTaxonSets(writer, taxonSets);
377 }
378 } catch (Exception e) {
379 e.printStackTrace();
380 throw new GeneratorException("Taxon sets generation has failed:\n" + e.getMessage());
381 }
382
383 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TAXA, writer);
384
385 //++++++++++++++++ Alignments ++++++++++++++++++
386 List<Alignment> alignments = new ArrayList<Alignment>();
387 try {
388 for (AbstractPartitionData partition : options.dataPartitions) {
389 Alignment alignment = null;
390 if (partition instanceof PartitionData) { // microsat has no alignment
391 alignment = ((PartitionData) partition).getAlignment();
392 }
393 if (alignment != null && !alignments.contains(alignment)) {
394 alignments.add(alignment);
395 }
396 }
397 if (alignments.size() > 0) {
398 alignmentGenerator.writeAlignments(alignments, writer);
399 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SEQUENCES, writer);
400 }
401 } catch (Exception e) {
402 e.printStackTrace();
403 throw new GeneratorException("Alignments generation has failed:\n" + e.getMessage());
404 }
405
406 //++++++++++++++++ Pattern Lists ++++++++++++++++++
407 try {
408 // Construct pattern lists even if sampling from a null alignment
409 //if (!options.samplePriorOnly) {
410 List<Microsatellite> microsatList = new ArrayList<Microsatellite>();
411 for (AbstractPartitionData partition : options.dataPartitions) { // Each PD has one TreeLikelihood
412 if (partition.getTaxonList() != null) {
413 switch (partition.getDataType().getType()) {
414 case DataType.NUCLEOTIDES:
415 case DataType.AMINO_ACIDS:
416 case DataType.CODONS:
417 case DataType.COVARION:
418 case DataType.TWO_STATES:
419 patternListGenerator.writePatternList((PartitionData) partition, writer);
420 break;
421
422 case DataType.GENERAL:
423 case DataType.CONTINUOUS:
424 // no patternlist for trait data - discrete (general) data type uses an
425 // attribute patterns which is generated next bit of this method.
426 break;
427
428 case DataType.MICRO_SAT:
429 // microsat does not have alignment
430 patternListGenerator.writePatternList((PartitionPattern) partition, microsatList, writer);
431 break;
432 default:
433 throw new IllegalArgumentException("Unsupported data type");
434 }
435 writer.writeText("");
436 }
437 }
438 //}
439 } catch (Exception e) {
440 e.printStackTrace();
441 throw new GeneratorException("Pattern lists generation has failed:\n" + e.getMessage());
442 }
443
444 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_PATTERNS, writer);
445
446 //++++++++++++++++ Tree Prior Model ++++++++++++++++++
447 try {
448 for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
449 treePriorGenerator.writeTreePriorModel(prior, writer);
450 writer.writeText("");
451 }
452 } catch (Exception e) {
453 e.printStackTrace();
454 throw new GeneratorException("Tree prior model generation has failed:\n" + e.getMessage());
455 }
456
457 //++++++++++++++++ Starting Tree ++++++++++++++++++
458 try {
459 for (PartitionTreeModel model : options.getPartitionTreeModels()) {
460 initialTreeGenerator.writeStartingTree(model, writer);
461 writer.writeText("");
462 }
463 } catch (Exception e) {
464 e.printStackTrace();
465 throw new GeneratorException("Starting tree generation has failed:\n" + e.getMessage());
466 }
467
468 //++++++++++++++++ Tree Model +++++++++++++++++++
469 try {
470 for (PartitionTreeModel model : options.getPartitionTreeModels()) {
471 treeModelGenerator.writeTreeModel(model, writer);
472 writer.writeText("");
473 }
474
475 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_MODEL, writer);
476 } catch (Exception e) {
477 e.printStackTrace();
478 throw new GeneratorException("Tree model generation has failed:\n" + e.getMessage());
479 }
480
481 //++++++++++++++++ Statistics ++++++++++++++++++
482 try {
483 if (taxonSets != null && taxonSets.size() > 0) {
484 tmrcaStatisticsGenerator.writeTMRCAStatistics(writer);
485 }
486 } catch (Exception e) {
487 e.printStackTrace();
488 throw new GeneratorException("TMRCA statistics generation has failed:\n" + e.getMessage());
489 }
490
491 //++++++++++++++++ Tree Prior Likelihood ++++++++++++++++++
492 try {
493 for (PartitionTreeModel model : options.getPartitionTreeModels()) {
494 treePriorGenerator.writePriorLikelihood(model, writer);
495 writer.writeText("");
496 }
497
498 for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
499 treePriorGenerator.writeMultiLociTreePriors(prior, writer);
500 }
501
502 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_PRIOR, writer);
503 } catch (Exception e) {
504 e.printStackTrace();
505 throw new GeneratorException("Tree prior likelihood generation has failed:\n" + e.getMessage());
506 }
507
508 //++++++++++++++++ Branch Rates Model ++++++++++++++++++
509 try {
510 for (PartitionClockModel model : options.getPartitionClockModels()) {
511 clockModelGenerator.writeBranchRatesModel(model, writer);
512 writer.writeText("");
513 }
514 } catch (Exception e) {
515 e.printStackTrace();
516 throw new GeneratorException("Branch rates model generation has failed:\n" + e.getMessage());
517 }
518
519 //++++++++++++++++ Substitution Model & Site Model ++++++++++++++++++
520 try {
521 for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
522 substitutionModelGenerator.writeSubstitutionSiteModel(model, writer);
523 writer.writeText("");
524 }
525
526 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SUBSTITUTION_MODEL, writer);
527 } catch (Exception e) {
528 e.printStackTrace();
529 throw new GeneratorException("Substitution model or site model generation has failed:\n" + e.getMessage());
530 }
531
532 //++++++++++++++++ AllMus parameter ++++++++++++++++++
533 try {
534 for (PartitionClockModel model : options.getPartitionClockModels()) {
535 clockModelGenerator.writeAllMus(model, writer);
536 }
537 } catch (Exception e) {
538 e.printStackTrace();
539 throw new GeneratorException("Clock model generation has failed:\n" + e.getMessage());
540 }
541
542 //++++++++++++++++ Site Model ++++++++++++++++++
543 // for (PartitionSubstitutionModel model : options.getPartitionSubstitutionModels()) {
544 // substitutionModelGenerator.writeSiteModel(model, writer); // site model
545 // substitutionModelGenerator.writeAllMus(model, writer); // allMus
546 // writer.writeText("");
547 // }
548
549 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_SITE_MODEL, writer);
550
551 //++++++++++++++++ Tree Likelihood ++++++++++++++++++
552 try {
553 Map<Pair<Pair<PartitionTreeModel, PartitionClockModel>, DataType>, List<PartitionData>> partitionLists = new HashMap<Pair<Pair<PartitionTreeModel, PartitionClockModel>, DataType>, List<PartitionData>>();
554 options.multiPartitionLists.clear();
555 options.otherPartitions.clear();
556
557 for (AbstractPartitionData partition : options.dataPartitions) {
558 // generate tree likelihoods for alignment data partitions
559 if (partition.getTaxonList() != null) {
560
561 if (treeLikelihoodGenerator.canUseMultiPartition(partition)) {
562 // all sequence partitions of the same type as the first into the list for use in a
563 // MultipartitionTreeDataLikelihood. Must also share the same tree, clock model and not be doing
564 // ancestral reconstruction or counting
565 Pair<Pair<PartitionTreeModel, PartitionClockModel>, DataType> key = new Pair(new Pair(partition.getPartitionTreeModel(),partition.getPartitionClockModel()), partition.getDataType());
566 List<PartitionData> partitions = partitionLists.get(key);
567
568 if (partitions == null) {
569 partitions = new ArrayList<PartitionData>();
570 options.multiPartitionLists.add(partitions);
571 }
572
573 partitions.add((PartitionData) partition);
574 partitionLists.put(key, partitions);
575
576 } else {
577 options.otherPartitions.add(partition);
578 }
579
580
581 }
582 }
583
584 treeLikelihoodGenerator.writeAllTreeLikelihoods(writer);
585
586 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TREE_LIKELIHOOD, writer);
587 } catch (Exception e) {
588 e.printStackTrace();
589 throw new GeneratorException("Tree likelihood generation has failed:\n" + e.getMessage());
590 }
591
592 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_TRAITS, writer);
593
594 //++++++++++++++++ Operators ++++++++++++++++++
595 try {
596 generateInsertionPoint(ComponentGenerator.InsertionPoint.BEFORE_OPERATORS, writer);
597
598 List<Operator> operators = options.selectOperators();
599 operatorsGenerator.writeOperatorSchedule(operators, writer);
600 writer.writeText("");
601
602 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_OPERATORS, writer);
603 } catch (Exception e) {
604 e.printStackTrace();
605 throw new GeneratorException("Operators generation has failed:\n" + e.getMessage());
606 }
607
608 //++++++++++++++++ MCMC ++++++++++++++++++
609 try {
610 // XMLWriter writer, List<PartitionSubstitutionModel> models,
611 writeMCMC(writer);
612 writer.writeText("");
613
614 generateInsertionPoint(ComponentGenerator.InsertionPoint.AFTER_MCMC, writer);
615 } catch (Exception e) {
616 e.printStackTrace();
617 throw new GeneratorException("MCMC or log generation has failed:\n" + e.getMessage());
618 }
619
620 //++++++++++++++++ ++++++++++++++++++
621 try {
622 writeTimerReport(writer);
623 writer.writeText("");
624 if (options.performTraceAnalysis) {
625 writeTraceAnalysis(writer);
626 }
627 if (options.generateCSV) {
628 for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
629 treePriorGenerator.writeEBSPAnalysisToCSVfile(prior, writer);
630 }
631 }
632 } catch (Exception e) {
633 e.printStackTrace();
634 throw new GeneratorException("The last part of XML generation has failed:\n" + e.getMessage());
635 }
636
637 writer.writeCloseTag("beast");
638 writer.flush();
639 writer.close();
640 }
641
642 /**
643 * Generate a taxa block from these beast options
644 *
645 * @param writer the writer
646 * @param taxonList the taxon list to write
647 * @throws dr.app.util.Arguments.ArgumentException
648 * ArgumentException
649 */
650 private void writeTaxa(TaxonList taxonList, XMLWriter writer) throws Arguments.ArgumentException {
651 // -1 (single taxa), 0 (1st gene of multi-taxa)
652
653 writer.writeComment("The list of taxa to be analysed (can also include dates/ages).",
654 "ntax=" + taxonList.getTaxonCount());
655 writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, TaxaParser.TAXA)});
656
657 boolean hasAttr = options.traits.size() > 0;
658
659 boolean firstDate = true;
660 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
661 Taxon taxon = taxonList.getTaxon(i);
662
663 boolean hasDate = false;
664 if (options.useTipDates) {
665 hasDate = TaxonList.Utils.hasAttribute(taxonList, i, dr.evolution.util.Date.DATE);
666 }
667
668 if (hasDate) {
669 dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
670
671 if (firstDate) {
672 options.units = date.getUnits();
673 firstDate = false;
674 } else {
675 if (options.units != date.getUnits()) {
676 System.err.println("Error: Units in dates do not match.");
677 }
678 }
679 }
680
681 writeTaxon(taxon, hasDate, hasAttr, writer);
682
683 }
684
685 writer.writeCloseTag(TaxaParser.TAXA);
686 }
687
688 /**
689 * Generate a taxa block from these beast options
690 *
691 * @param writer the writer
692 * @param taxon the taxon to write
693 * @throws dr.app.util.Arguments.ArgumentException
694 * ArgumentException
695 */
696 private void writeTaxon(Taxon taxon, boolean hasDate, boolean hasAttr, XMLWriter writer) throws Arguments.ArgumentException {
697
698 writer.writeTag(TaxonParser.TAXON, new Attribute[]{
699 new Attribute.Default<String>(XMLParser.ID, taxon.getId())},
700 !(hasDate || hasAttr)); // false if any of hasDate or hasAttr is true
701
702
703 if (hasDate) {
704 dr.evolution.util.Date date = (dr.evolution.util.Date) taxon.getAttribute(dr.evolution.util.Date.DATE);
705
706 Attribute[] attributes;
707 if (date.getUncertainty() > 0.0) {
708 attributes = new Attribute[] {
709 new Attribute.Default<Double>(DateParser.VALUE, date.getTimeValue()),
710 new Attribute.Default<String>(DateParser.DIRECTION, date.isBackwards() ? DateParser.BACKWARDS : DateParser.FORWARDS),
711 new Attribute.Default<String>(DateParser.UNITS, Units.Utils.getDefaultUnitName(options.units)),
712 new Attribute.Default<Double>(DateParser.UNCERTAINTY, date.getUncertainty())
713 };
714 } else {
715 attributes = new Attribute[] {
716 new Attribute.Default<Double>(DateParser.VALUE, date.getTimeValue()),
717 new Attribute.Default<String>(DateParser.DIRECTION, date.isBackwards() ? DateParser.BACKWARDS : DateParser.FORWARDS),
718 new Attribute.Default<String>(DateParser.UNITS, Units.Utils.getDefaultUnitName(options.units))
719 //new Attribute.Default("origin", date.getOrigin()+"")
720 };
721 }
722
723 writer.writeTag(dr.evolution.util.Date.DATE, attributes, true);
724 }
725
726 for (TraitData trait : options.traits) {
727 // there is no harm in allowing the species trait to be listed in the taxa
728 // if (!trait.getName().equalsIgnoreCase(TraitData.TRAIT_SPECIES)) {
729 writer.writeOpenTag(AttributeParser.ATTRIBUTE, new Attribute[]{
730 new Attribute.Default<String>(Attribute.NAME, trait.getName())});
731
732 // denotes missing data using '?'
733 writer.writeText(taxon.containsAttribute(trait.getName()) ? taxon.getAttribute(trait.getName()).toString() : "?");
734 writer.writeCloseTag(AttributeParser.ATTRIBUTE);
735 // }
736 }
737
738 generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_TAXON, taxon, writer);
739
740 if (hasDate || hasAttr) writer.writeCloseTag(TaxonParser.TAXON);
741
742 }
743
744 public void writeDifferentTaxa(AbstractPartitionData dataPartition, XMLWriter writer) {
745 TaxonList taxonList = dataPartition.getTaxonList();
746
747 String name = dataPartition.getPartitionTreeModel().getName();
748
749 writer.writeComment("gene name = " + name + ", ntax= " + taxonList.getTaxonCount());
750 writer.writeOpenTag(TaxaParser.TAXA, new Attribute[]{new Attribute.Default<String>(XMLParser.ID, name + "." + TaxaParser.TAXA)});
751
752 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
753 if ( !(dataPartition instanceof PartitionPattern && ((PartitionPattern) dataPartition).getPatterns().isMasked(i) ) ) {
754 final Taxon taxon = taxonList.getTaxon(i);
755 writer.writeIDref(TaxonParser.TAXON, taxon.getId());
756 }
757 }
758
759 writer.writeCloseTag(TaxaParser.TAXA);
760 }
761
762 /**
763 * Write the timer report block.
764 *
765 * @param writer the writer
766 */
767 public void writeTimerReport(XMLWriter writer) {
768 writer.writeOpenTag("report");
769 writer.writeOpenTag("property", new Attribute.Default<String>("name", "timer"));
770 writer.writeIDref("mcmc", "mcmc");
771 writer.writeCloseTag("property");
772 writer.writeCloseTag("report");
773 }
774
775 /**
776 * Write the trace analysis block.
777 *
778 * @param writer the writer
779 */
780 public void writeTraceAnalysis(XMLWriter writer) {
781 writer.writeTag(
782 "traceAnalysis",
783 new Attribute[]{
784 new Attribute.Default<String>("fileName", options.logFileName)
785 },
786 true
787 );
788 }
789
790 /**
791 * Write the MCMC block.
792 *
793 * @param writer XMLWriter
794 */
795 public void writeMCMC(XMLWriter writer) {
796 writer.writeComment("Define MCMC");
797
798 List<Attribute> attributes = new ArrayList<Attribute>();
799 attributes.add(new Attribute.Default<String>(XMLParser.ID, "mcmc"));
800 attributes.add(new Attribute.Default<Integer>("chainLength", options.chainLength));
801 attributes.add(new Attribute.Default<String>("autoOptimize", options.autoOptimize ? "true" : "false"));
802
803 if (options.operatorAnalysis) {
804 attributes.add(new Attribute.Default<String>("operatorAnalysis", options.operatorAnalysisFileName));
805 }
806
807 writer.writeOpenTag("mcmc", attributes);
808
809 if (options.hasData()) {
810 writer.writeOpenTag(CompoundLikelihoodParser.JOINT, new Attribute.Default<String>(XMLParser.ID, "joint"));
811 }
812
813 // write prior block
814 writer.writeOpenTag(CompoundLikelihoodParser.PRIOR, new Attribute.Default<String>(XMLParser.ID, "prior"));
815
816 parameterPriorGenerator.writeParameterPriors(writer);
817
818 for (PartitionTreeModel model : options.getPartitionTreeModels()) {
819 PartitionTreePrior prior = model.getPartitionTreePrior();
820 treePriorGenerator.writePriorLikelihoodReference(prior, model, writer);
821 writer.writeText("");
822 }
823
824 for (PartitionTreePrior prior : options.getPartitionTreePriors()) {
825 treePriorGenerator.writeMultiLociLikelihoodReference(prior, writer);
826 writer.writeText("");
827 }
828
829 clockModelGenerator.writeClockLikelihoodReferences(writer);
830
831 generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_PRIOR, writer);
832
833 writer.writeCloseTag(CompoundLikelihoodParser.PRIOR);
834
835 if (options.hasData()) {
836 // write likelihood block
837 writer.writeOpenTag(CompoundLikelihoodParser.LIKELIHOOD, new Attribute.Default<String>(XMLParser.ID, "likelihood"));
838
839 treeLikelihoodGenerator.writeTreeLikelihoodReferences(writer);
840
841 generateInsertionPoint(ComponentGenerator.InsertionPoint.IN_MCMC_LIKELIHOOD, writer);
842
843 writer.writeCloseTag(CompoundLikelihoodParser.LIKELIHOOD);
844
845 writer.writeCloseTag(CompoundLikelihoodParser.JOINT);
846 }
847
848 writer.writeIDref(SimpleOperatorScheduleParser.OPERATOR_SCHEDULE, "operators");
849
850 // write log to screen
851 logGenerator.writeLogToScreen(writer, clockModelGenerator, substitutionModelGenerator);
852
853 // write log to file
854 logGenerator.writeLogToFile(writer, treePriorGenerator, clockModelGenerator,
855 substitutionModelGenerator, treeLikelihoodGenerator, tmrcaStatisticsGenerator);
856
857 // write tree log to file
858 logGenerator.writeTreeLogToFile(writer);
859
860 writer.writeCloseTag("mcmc");
861 }
862
863 }