Debian Codegraph @

src/dr/app/tools/AncestralSequenceAnnotator.java

raw symbols SCIP
1 /*
2 * AncestralSequenceAnnotator.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.tools;
27
28
29 import dr.evomodel.branchmodel.HomogeneousBranchModel;
30 import dr.evomodelxml.siteratemodel.GammaSiteModelParser;
31 import dr.evomodel.substmodel.FrequencyModel;
32 import dr.evomodel.substmodel.GeneralSubstitutionModel;
33 import dr.evomodel.substmodel.aminoacid.EmpiricalAminoAcidModel;
34 import dr.evomodel.substmodel.aminoacid.JTT;
35 import dr.evomodel.substmodel.aminoacid.LG;
36 import dr.evomodel.substmodel.aminoacid.WAG;
37 import dr.evomodel.substmodel.codon.GY94CodonModel;
38 import dr.evomodel.substmodel.nucleotide.GTR;
39 import dr.evomodel.substmodel.nucleotide.HKY;
40 import dr.app.beast.BeastVersion;
41 import dr.app.util.Arguments;
42 import dr.app.util.Utils;
43 import dr.evolution.alignment.Alignment;
44 import dr.evolution.alignment.ConvertAlignment;
45 import dr.evolution.alignment.PatternList;
46 import dr.evolution.alignment.SimpleAlignment;
47 //import dr.evolution.datatype.AminoAcids;
48 //import dr.evolution.datatype.GeneralDataType;
49 import dr.evolution.datatype.*;
50 import dr.evolution.io.*;
51 import dr.evolution.sequence.Sequence;
52 import dr.evolution.tree.*;
53 import dr.evolution.util.Taxon;
54 import dr.evolution.util.TaxonList;
55 import dr.evomodel.branchratemodel.BranchRateModel;
56 import dr.evomodel.branchratemodel.StrictClockBranchRates;
57 import dr.evomodel.substmodel.SubstitutionModel;
58 import dr.evomodel.tree.TreeModel;
59 import dr.oldevomodelxml.substmodel.GeneralSubstitutionModelParser;
60 import dr.inference.model.Parameter;
61 import dr.stats.DiscreteStatistics;
62 import dr.util.HeapSort;
63 import dr.util.Version;
64
65
66 import dr.evomodel.siteratemodel.GammaSiteRateModel;
67 import dr.evomodel.treelikelihood.PartialsRescalingScheme;
68 import dr.evomodel.treelikelihood.AncestralStateBeagleTreeLikelihood;
69
70 import java.io.*;
71 import java.util.*;
72 import java.util.logging.Logger;
73
74 /*
75 * @author Marc A. Suchard
76 * @author Wai Lok Sibon Li
77 */
78
79 public class AncestralSequenceAnnotator {
80
81 private final static Version version = new BeastVersion();
82
83 public final static int MAX_CLADE_CREDIBILITY = 0;
84 public final static int MAX_SUM_CLADE_CREDIBILITY = 1;
85 public final static int USER_TARGET_TREE = 2;
86
87 public final static int KEEP_HEIGHTS = 0;
88 public final static int MEAN_HEIGHTS = 1;
89 public final static int MEDIAN_HEIGHTS = 2;
90
91 public final String[] GENERAL_MODELS_LIST = {"EQU"};
92 public final String[] NUCLEOTIDE_MODELS_LIST = {"HKY", "TN", "GTR"};
93 public final String[] AMINO_ACID_MODELS_LIST = {"JTT1992", "WAG2001", "LG2008", "Empirical\\(.+\\)"};
94 public final String[] TRIPLET_MODELS_LIST = {"HKYx3", "TNx3", "GTRx3"};
95 public final String[] CODON_MODELS_LIST = {"M0HKY", "M0TN", "M0GTR"};//"M0", "M0\\[.+\\]", ""};
96
97 public AncestralSequenceAnnotator(int burnin,
98 int heightsOption,
99 double posteriorLimit,
100 int targetOption,
101 String targetTreeFileName,
102 String inputFileName,
103 String outputFileName,
104 String kalignExecutable
105 ) throws IOException {
106
107 this.posteriorLimit = posteriorLimit;
108
109 this.kalignExecutable = kalignExecutable;
110
111 attributeNames.add("height");
112 attributeNames.add("length");
113
114 System.out.println("Reading trees and simulating internal node states...");
115
116 CladeSystem cladeSystem = new CladeSystem();
117
118 boolean firstTree = true;
119 FileReader fileReader = new FileReader(inputFileName);
120 TreeImporter importer = new NexusImporter(fileReader);
121
122 TreeExporter exporter;
123 if (outputFileName != null)
124 exporter = new NexusExporter(new PrintStream(new FileOutputStream(outputFileName)));
125 else
126 exporter = new NexusExporter(System.out);
127
128 TreeExporter simulationResults = new NexusExporter(new PrintStream(new FileOutputStream(inputFileName + ".out")));
129 List<Tree> simulatedTree = new ArrayList<Tree>();
130
131 // burnin = 0;
132 // java.util.logging.Logger.getLogger("dr.evomodel").
133
134 try {
135 while (importer.hasTree()) {
136 Tree tree = importer.importNextTree();
137
138 if (firstTree) {
139 Tree unprocessedTree = tree;
140 tree = processTree(tree);
141 setupTreeAttributes(tree);
142 setupAttributes(tree);
143 tree = unprocessedTree; //This actually does nothing since unprocessedTree was a reference to processedTree in the first place
144 firstTree = false;
145 }
146
147 if (totalTrees >= burnin) {
148 addTreeAttributes(tree);
149 // Tree savedTree = tree;
150 tree = processTree(tree);
151 // System.err.println(Tree.Utils.newick(tree));
152 exporter.exportTree(tree);
153 // simulationResults.exportTree(tree);
154 // System.exit(-1);
155 simulatedTree.add(tree);
156 cladeSystem.add(tree);
157
158 totalTreesUsed += 1;
159 }
160 totalTrees += 1;
161
162 }
163 } catch (Importer.ImportException e) {
164 System.err.println("Error Parsing Input Tree: " + e.getMessage());
165 return;
166 }
167 fileReader.close();
168
169 cladeSystem.calculateCladeCredibilities(totalTreesUsed);
170
171 System.out.println("\tTotal trees read: " + totalTrees);
172 if (burnin > 0) {
173 System.out.println("\tIgnoring first " + burnin + " trees.");
174 }
175
176 simulationResults.exportTrees(simulatedTree.toArray(new Tree[simulatedTree.size()]));
177
178 MutableTree targetTree;
179
180 if (targetOption == USER_TARGET_TREE) {
181 if (targetTreeFileName != null) {
182 System.out.println("Reading user specified target tree, " + targetTreeFileName);
183
184 importer = new NexusImporter(new FileReader(targetTreeFileName));
185 try {
186 targetTree = new FlexibleTree(importer.importNextTree());
187 } catch (Importer.ImportException e) {
188 System.err.println("Error Parsing Target Tree: " + e.getMessage());
189 return;
190 }
191 } else {
192 System.err.println("No user target tree specified.");
193 return;
194 }
195 } else if (targetOption == MAX_CLADE_CREDIBILITY) {
196 System.out.println("Finding maximum credibility tree...");
197 targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, false));
198 } else if (targetOption == MAX_SUM_CLADE_CREDIBILITY) {
199 System.out.println("Finding maximum sum clade credibility tree...");
200 targetTree = new FlexibleTree(summarizeTrees(burnin, cladeSystem, inputFileName, true));
201 } else {
202 throw new RuntimeException("Unknown target tree option");
203 }
204
205 System.out.println("Annotating target tree... (this may take a long time)");
206
207 // System.out.println("Starting processing....");
208
209 // System.out.println("calling annotateTree");
210 // System.out.println("targetTree has "+targetTree.getNodeCount()+" nodes.");
211 cladeSystem.annotateTree(targetTree, targetTree.getRoot(), null, heightsOption);
212
213 System.out.println("Processing ended.");
214
215 System.out.println("Writing annotated tree....");
216 if (outputFileName != null) {
217 exporter = new NexusExporter(new PrintStream(new FileOutputStream(outputFileName)));
218 exporter.exportTree(targetTree);
219 } else {
220 exporter = new NexusExporter(System.out);
221 exporter.exportTree(targetTree);
222 }
223
224
225 }
226
227
228
229 private abstract class SubstitutionModelLoader {
230
231
232 public final char[] AA_ORDER = AminoAcids.AMINOACID_CHARS;
233 public final char[] NUCLEOTIDE_ORDER = Nucleotides.NUCLEOTIDE_CHARS;
234 public final String[] CODON_ORDER = Codons.CODON_TRIPLETS;
235
236 protected SubstitutionModel substModel;
237 protected FrequencyModel freqModel;
238 private String modelType;
239 protected String substModelName;
240 protected String[] charList;
241 protected DataType dataType;
242
243 SubstitutionModelLoader(Tree tree, String modelType, DataType dataType) {
244 this.dataType = dataType;
245 this.modelType = modelType;
246 load(tree, modelType);
247 }
248
249 /* An artifact of old code? */
250 SubstitutionModelLoader(String name) {
251 this.substModelName = name;
252 }
253
254 public SubstitutionModel getSubstitutionModel() {
255 return substModel;
256 }
257
258 public FrequencyModel getFrequencyModel() {
259 return freqModel;
260 }
261
262 public String getModelType() {
263 return modelType;
264 }
265
266 public String getSubstModel() {
267 return substModelName;
268 }
269
270 public String[] getCharList() {
271 return charList;
272 }
273 public void setCharList(String[] cl) {
274 System.arraycopy(cl, 0, charList, 0, cl.length);
275 //charList = cl.clone();
276 }
277
278 public abstract DataType getDataType();
279
280 protected abstract void modelSpecifics(Tree tree, String modelType);
281
282 public void load(Tree tree, String modelType) {
283
284 substModelName = modelType.replaceFirst("\\*.+","").replaceFirst("\\+.+","").trim();
285
286 loadFrequencyModel(tree);
287
288 modelSpecifics(tree, modelType);
289 printLogLikelihood(tree);
290 }
291
292
293 private void loadFrequencyModel(Tree tree) {
294 final String[] AA_ORDER = {"A","C","D","E","F","G","H","I","K","L","M","N","P","Q","R",
295 "S","T","V","W","Y"}; //"ACDEFGHIKLMNPQRSTVWY".split("");//AminoAcids.AMINOACID_CHARS;
296 final String[] DNA_NUCLEOTIDE_ORDER = {"A", "C", "G", "T"};//"ACGT".split(""); //Nucleotides.NUCLEOTIDE_CHARS;
297 final String[] RNA_NUCLEOTIDE_ORDER = {"A", "C", "G", "U"};//"ACGU".split(""); //Nucleotides.NUCLEOTIDE_CHARS;
298 // final String[] CODON_ORDER = {"AAA", "AAC", "AAG", "AAT", "ACA", "ACC", "ACG", "ACT",
299 // "AGA", "AGC", "AGG", "AGT", "ATA", "ATC", "ATG", "ATT",
300 // "CAA", "CAC", "CAG", "CAT", "CCA", "CCC", "CCG", "CCT",
301 // "CGA", "CGC", "CGG", "CGT", "CTA", "CTC", "CTG", "CTT",
302 // "GAA", "GAC", "GAG", "GAT", "GCA", "GCC", "GCG", "GCT",
303 // "GGA", "GGC", "GGG", "GGT", "GTA", "GTC", "GTG", "GTT",
304 // "TAA", "TAC", "TAG", "TAT", "TCA", "TCC", "TCG", "TCT",
305 // "TGA", "TGC", "TGG", "TGT", "TTA", "TTC", "TTG", "TTT"};// Codons.CODON_TRIPLETS;
306 final String[] DNA_CODON_ORDER = {"AAA", "AAC", "AAG", "AAT", "ACA", "ACC", "ACG", "ACT",
307 "AGA", "AGC", "AGG", "AGT", "ATA", "ATC", "ATG", "ATT",
308 "CAA", "CAC", "CAG", "CAT", "CCA", "CCC", "CCG", "CCT",
309 "CGA", "CGC", "CGG", "CGT", "CTA", "CTC", "CTG", "CTT",
310 "GAA", "GAC", "GAG", "GAT", "GCA", "GCC", "GCG", "GCT",
311 "GGA", "GGC", "GGG", "GGT", "GTA", "GTC", "GTG", "GTT",
312 /*"TAA",*/ "TAC", /*"TAG",*/ "TAT", "TCA", "TCC", "TCG", "TCT", /* Minus the stop and start codons */
313 /*"TGA",*/ "TGC", "TGG", "TGT", "TTA", "TTC", "TTG", "TTT"};// Codons.CODON_TRIPLETS;
314
315 final String[] RNA_CODON_ORDER = {"AAA", "AAC", "AAG", "AAU", "ACA", "ACC", "ACG", "ACU",
316 "AGA", "AGC", "AGG", "AGU", "AUA", "AUC", "AUG", "AUU",
317 "CAA", "CAC", "CAG", "CAU", "CCA", "CCC", "CCG", "CCU",
318 "CGA", "CGC", "CGG", "CGU", "CUA", "CUC", "CUG", "CUU",
319 "GAA", "GAC", "GAG", "GAU", "GCA", "GCC", "GCG", "GCU",
320 "GGA", "GGC", "GGG", "GGU", "GUA", "GUC", "GUG", "GUU",
321 /*"UAA",*/ "UAC", /*"UAG",*/ "UAU", "UCA", "UCC", "UCG", "UCU", /* Minus the stop and start codons */
322 /*"UGA",*/ "UGC", "UGG", "UGU", "UUA", "UUC", "UUG", "UUU"};// Codons.CODON_TRIPLETS;
323
324 /* For BAli-Phy, even if F=constant, you can still extract the frequencies this way. */
325
326 /* Obtain the equilibrium base frequencies for the model */
327 double[] freq = new double[0];
328 String[] charOrder = new String[0];
329
330 if(getDataType().getClass().equals(GeneralDataType.class)) {
331 ArrayList<String> tempCharOrder = new ArrayList<String>(freq.length);
332 for (Iterator<String> i = tree.getAttributeNames(); i.hasNext();) {
333 String name = i.next();
334 if (name.startsWith("pi")) { /* the pi in the output files contains the frequencies */
335 String character = name.substring(2, name.length());
336 tempCharOrder.add(character);
337 }
338 }
339 charOrder = tempCharOrder.toArray(new String[tempCharOrder.size()]);
340 //this.charList = tempCharOrder.toArray(new String[tempCharOrder.size()]);
341 freq = new double[charOrder.length];
342
343 }
344 else if(getDataType().getClass().equals(Nucleotides.class)) {
345 if(tree.getAttribute("piT") != null) {
346 charOrder = DNA_NUCLEOTIDE_ORDER;
347 freq = new double[charOrder.length];
348 }
349 else if(tree.getAttribute("piU") != null) {
350 charOrder = RNA_NUCLEOTIDE_ORDER;
351 freq = new double[charOrder.length];
352 }
353 else {
354 throw new RuntimeException("Not proper nucleotide data");
355 }
356 }
357 else if(getDataType().getClass().equals(AminoAcids.class)) {
358
359 charOrder = AA_ORDER;
360 freq = new double[charOrder.length];
361 }
362
363 else if(getDataType().getClass().equals(Codons.class)) {
364 if(tree.getAttribute("piAAT") != null) {
365 charOrder = DNA_CODON_ORDER;
366 freq = new double[charOrder.length];
367 }
368 else if(tree.getAttribute("piAAU") != null) {
369 charOrder = RNA_CODON_ORDER;
370 freq = new double[charOrder.length];
371 }
372 else{
373 throw new RuntimeException("Base frequencies do not fit those for a codon model or not proper nucleotide data for codons\n" +
374 "If you are using F=nucleotides models for codon models, they are currently not supported in BEAST");
375 }
376
377 }
378 else {
379 throw new RuntimeException("Datatype unknown! (This error message should never be seen, contact Sibon)");
380 }
381 // // This if statement is reserved for triplet data
382 // else if(getDataType().getClass().equals(Nucleotides.class)) {
383 // // This is wrong because for triplets
384 // freq = new double[Nucleotides.NUCLEOTIDE_CHARS.length];
385 //
386 // }
387
388 int cnt = 0;
389 double sum = 0;
390 //charList = "";
391 ArrayList<String> tempCharList = new ArrayList<String>(freq.length);
392 for (Iterator<String> i = tree.getAttributeNames(); i.hasNext();) {
393 String name = i.next();
394 if (name.startsWith("pi")) { /* the pi in the output files contains the frequencies */
395 String character = name.substring(2, name.length());
396 tempCharList.add(character);
397 //charList = charList.concat(character);
398 Double value = (Double) tree.getAttribute(name);
399 freq[cnt++] = value;
400 sum += value;
401 }
402 }
403 charList = tempCharList.toArray(new String[tempCharList.size()]);
404
405 // for(int j=0; j<charList.length; j++) {
406 // System.out.println("charizard lists " + charList[j]);
407 // }
408
409 /* Order the frequencies correctly */
410 double[] freqOrdered = new double[freq.length];
411 for (int i = 0; i < freqOrdered.length; i++) {
412 int index = -5;
413 search: for (int j = 0; j < charList.length; j++) {
414 if(charList[j].equals(charOrder[i])) {
415 index = j;
416 break search;
417 }
418 }
419
420 freqOrdered[i] = freq[index] / sum;
421 //System.out.println(" no fried " + freqOrdered.length + "\t" + freq.length + "\t" + charOrder[i] + "\t" + freqOrdered[i]); //ddd
422 }
423 this.freqModel = new FrequencyModel(getDataType(), new Parameter.Default(freqOrdered));
424
425 }
426
427 protected boolean doPrint = false;
428 private void printLogLikelihood(Tree tree) {
429 if (doPrint) {
430 Double logLikelihood = Double.parseDouble(tree.getAttribute(LIKELIHOOD).toString());
431 if (logLikelihood != null)
432 System.err.printf("%5.1f", logLikelihood);
433 }
434 }
435 }
436
437 private class GeneralSubstitutionModelLoader extends SubstitutionModelLoader {
438
439 private final String EQU_TEXT = "EQU";
440
441
442 private GeneralSubstitutionModelLoader(Tree tree, String modelType) {
443 super(tree, modelType, new GeneralDataType(new String[0]));
444 setGeneralDataType();
445 throw new RuntimeException("General substitution model is currently not stable and should not be used");
446 }
447 protected void modelSpecifics(Tree tree, String modelType) {
448 if(substModelName.equals(EQU_TEXT)) {
449 if(freqModel.getFrequencyCount() != charList.length) {
450 System.err.println("Frequency model length does not match character list length, " +
451 "GeneralSubstitutionModelLoader");
452 System.exit(-1);
453 }
454
455 /* Equivalent to a JC model but for all states */
456 //TODO CHECK IF THIS IS CORRECT
457 double[] rates = new double[(charList.length * (charList.length - 1)) / 2];
458 for(int i=0; i<rates.length; i++) {
459 rates[i] = 1.0;
460 }
461 System.out.println("Number of site transition rate categories (debuggin): " + rates.length);
462 //substModel = new GeneralSubstitutionModel(freqModel.getDataType(), freqModel, new Parameter.Default(rates), 1);
463 substModel = new GeneralSubstitutionModel(GeneralSubstitutionModelParser.GENERAL_SUBSTITUTION_MODEL, freqModel.getDataType(), freqModel, new Parameter.Default(rates), 1, null);
464 }
465 }
466 public DataType getDataType() {
467 setGeneralDataType();
468 return dataType;
469 }
470
471 public void setGeneralDataType() {
472 if(charList!=null && dataType.getStateCount()!=charList.length) {
473 GeneralDataType gdt = new GeneralDataType(charList);
474 gdt.addAmbiguity("-", charList);
475 gdt.addAmbiguity("X", charList);
476 gdt.addAmbiguity("?", charList);
477 dataType = gdt;
478 }
479 }
480 }
481
482 private class NucleotideSubstitutionModelLoader extends SubstitutionModelLoader {
483 protected static final String HKY_TEXT = "HKY";
484 protected static final String TN_TEXT = "TN";
485 protected static final String GTR_TEXT = "GTR";
486
487 private NucleotideSubstitutionModelLoader(Tree tree, String modelType) {
488 super(tree, modelType, Nucleotides.INSTANCE);
489 }
490 protected void modelSpecifics(Tree tree, String modelType) {
491 if(substModelName.equals(HKY_TEXT)) {
492 double kappa = Double.parseDouble(tree.getAttribute("HKY_kappa").toString());
493 //double kappa = (Double) tree.getAttribute("HKY_kappa");
494 //double kappa = (Double) tree.getAttribute("HKY\\:\\:kappa");
495 //double kappa = (Double) tree.getAttribute("HKY::kappa");
496 //double kappa = (Double) tree.getAttribute("kappa");
497 substModel = new HKY(new Parameter.Default(kappa), freqModel);
498
499 }
500 if(substModelName.equals(TN_TEXT)) {
501
502 double kappa1 = Double.parseDouble(tree.getAttribute("TN_kappa(pur)").toString());
503 double kappa2 = Double.parseDouble(tree.getAttribute("TN_kappa(pyr)").toString());
504 //double kappa1 = (Double) tree.getAttribute("TN_kappa(pur)");
505 //double kappa2 = (Double) tree.getAttribute("TN_kappa(pyr)");
506 System.err.println("Sorry, TN substitution model is not yet implemented in BEAST-Beagle");
507 System.exit(0);
508
509 //TODO Tamura-Nei model
510 //substModel = new TN93(new Parameter.Default(kappa1), new Parameter.Default(kappa2), freqModel);
511 }
512 if(substModelName.equals(GTR_TEXT)) {
513 /* It should be noted that BAli-Phy uses TC instead of CT and GC instead of CG */
514 //double rateACValue = (Double) tree.getAttribute("GTR_AC");
515 //double rateAGValue = (Double) tree.getAttribute("GTR_AG");
516 //double rateATValue = (Double) tree.getAttribute("GTR_AT");
517 //double rateCGValue = (Double) tree.getAttribute("GTR_GC");
518 //double rateCTValue = (Double) tree.getAttribute("GTR_TC");
519 //double rateGTValue = (Double) tree.getAttribute("GTR_GT");
520 double rateACValue = Double.parseDouble(tree.getAttribute("GTR_AC").toString());
521 double rateAGValue = Double.parseDouble(tree.getAttribute("GTR_AG").toString());
522 double rateATValue = Double.parseDouble(tree.getAttribute("GTR_AT").toString());
523 double rateCGValue = Double.parseDouble(tree.getAttribute("GTR_GC").toString());
524 double rateCTValue = Double.parseDouble(tree.getAttribute("GTR_TC").toString());
525 double rateGTValue = Double.parseDouble(tree.getAttribute("GTR_GT").toString());
526
527
528 substModel = new GTR(new Parameter.Default(rateACValue), new Parameter.Default(rateAGValue),
529 new Parameter.Default(rateATValue), new Parameter.Default(rateCGValue),
530 new Parameter.Default(rateCTValue), new Parameter.Default(rateGTValue), freqModel);
531 }
532 }
533 public DataType getDataType() {
534 return dataType; //Potential
535 }
536 }
537
538 private class AminoAcidSubstitutionModelLoader extends SubstitutionModelLoader {
539
540 protected final String JTT_TEXT = "JTT1992";
541 protected final String WAG_TEXT = "WAG2001";
542 protected final String LG_TEXT = "LG2008";
543 protected final String Empirical_TEXT = "Empirical(.+).+";
544
545 private AminoAcidSubstitutionModelLoader(Tree tree, String modelType) {
546 super(tree, modelType, AminoAcids.INSTANCE);
547 }
548 protected void modelSpecifics(Tree tree, String modelType) {
549 if(substModelName.equals(JTT_TEXT)) {
550 substModel = new EmpiricalAminoAcidModel(JTT.INSTANCE, freqModel);
551 }
552 if(substModelName.equals(WAG_TEXT)) {
553 substModel = new EmpiricalAminoAcidModel(WAG.INSTANCE, freqModel);
554 }
555 if(substModelName.equals(LG_TEXT)) {
556 substModel = new EmpiricalAminoAcidModel(LG.INSTANCE, freqModel);
557 }
558 //todo Allow proper file input of Empirical amino-acid models
559 if(substModelName.matches(Empirical_TEXT)) {
560 String empiricalModelFileName = substModelName.replaceFirst("Empirical\\(", "").replaceFirst("\\).*","");
561 if (empiricalModelFileName.equals("wag.dat")) {
562 substModel = new EmpiricalAminoAcidModel(WAG.INSTANCE, freqModel);
563 } else if(empiricalModelFileName.equals("jtt.dat")) {
564 substModel = new EmpiricalAminoAcidModel(JTT.INSTANCE, freqModel);
565 } else if(empiricalModelFileName.equals("lg.dat")) {
566 substModel = new EmpiricalAminoAcidModel(LG.INSTANCE, freqModel);
567 } else {
568 System.err.println("Sorry, AncestralSequenceAnnotator does not currently support other files");
569 System.err.println("Soon, we will allow users to enter a file");
570 System.exit(0);
571 }
572 }
573 }
574 public DataType getDataType() {
575 return dataType; //Potential
576 }
577 }
578
579 private class TripletSubstitutionModelLoader extends SubstitutionModelLoader {
580
581 protected final String HKYx3_TEXT = "HKYx3";
582 protected final String TNx3_TEXT = "TNx3";
583 protected final String GTRx3_TEXT = "GTRx3";
584
585 private TripletSubstitutionModelLoader(Tree tree, String modelType) {
586 super(tree, modelType, Nucleotides.INSTANCE);
587 }
588 protected void modelSpecifics(Tree tree, String modelType) {
589 if(substModelName.equals(HKYx3_TEXT)) {
590 System.err.println("Sorry, HKYx3 substitution model is not yet implemented in BEAST");
591 System.exit(0);
592 //substModel = new HKY();
593 }
594 if(substModelName.equals(TNx3_TEXT)) {
595 System.err.println("Sorry, TNx3 substitution model is not yet implemented in BEAST");
596 System.exit(0);
597 //substModel = new TN93();
598 }
599 if(substModelName.equals(GTRx3_TEXT)) {
600 System.err.println("Sorry, GTRx3 substitution model is not yet implemented in BEAST");
601 System.exit(0);
602 //substModel = new GTR();
603 }
604 }
605 public DataType getDataType() {
606 return dataType; // Is this right?
607 }
608 }
609 private class CodonSubstitutionModelLoader extends SubstitutionModelLoader {
610
611 // private final String M0_TEXT = "M0"; // Not necessary since this never actually shows up in BAli-Phy output
612 protected final String M0_NUC_TEXT = "M0\\w+";
613 //private final String HKY_TEXT = "HKY";
614 //private final String TN_TEXT = "TN";
615 //private final String GTR_TEXT = "GTR";
616
617 private CodonSubstitutionModelLoader(Tree tree, String modelType) {
618 super(tree, modelType, Codons.UNIVERSAL); //Potential
619 }
620 protected void modelSpecifics(Tree tree, String modelType) {
621 //String codonNucleotideModel = substModelName.substring(substModelName.indexOf("\\\\[")+1, substModelName.indexOf("\\\\]"));
622 String codonNucleotideModel = substModelName.substring(substModelName.indexOf("M0")+2, substModelName.length());
623
624
625 // if(substModelName.equals(M0_TEXT)) {
626 // /* HKY is default */
627 // codonNucleotideModel = NucleotideSubstitutionModelLoader.HKY_TEXT;
628 //
629 //
630 // }
631 if(substModelName.matches(M0_NUC_TEXT)) {
632 /* M0_omega may be *M0_omega, depending on whether M2 etc. are used */
633 double omega = Double.parseDouble(tree.getAttribute("M0_omega").toString());
634 //omega = (Double) tree.getAttribute("\\M0_omega");
635 if(codonNucleotideModel.equals(NucleotideSubstitutionModelLoader.HKY_TEXT)) {
636 //double kappa = (Double) tree.getAttribute("HKY_kappa");
637 double kappa = Double.parseDouble(tree.getAttribute("HKY_kappa").toString());
638 //substModel = new YangCodonModel(Codons.UNIVERSAL, new Parameter.Default(omega),
639 //new Parameter.Default(kappa), freqModel);
640 substModel = new GY94CodonModel(Codons.UNIVERSAL, new Parameter.Default(omega),
641 new Parameter.Default(kappa), freqModel);
642 }
643 if(codonNucleotideModel.equals(NucleotideSubstitutionModelLoader.TN_TEXT)) {
644 //double kappa1 = (Double) tree.getAttribute("TN_kappa(pur)");
645 //double kappa2 = (Double) tree.getAttribute("TN_kappa(pyr)");
646 double kappa1 = Double.parseDouble(tree.getAttribute("TN_kappa(pur)").toString());
647 double kappa2 = Double.parseDouble(tree.getAttribute("TN_kappa(pyr)").toString());
648 System.err.println("Sorry, M0[TN] substitution model is not yet implemented in BEAST");
649 System.exit(0);
650 }
651 if(codonNucleotideModel.equals(NucleotideSubstitutionModelLoader.GTR_TEXT)) {
652 double rateACValue = Double.parseDouble(tree.getAttribute("GTR_AC").toString());
653 double rateAGValue = Double.parseDouble(tree.getAttribute("GTR_AG").toString());
654 double rateATValue = Double.parseDouble(tree.getAttribute("GTR_AT").toString());
655 double rateCGValue = Double.parseDouble(tree.getAttribute("GTR_GC").toString());
656 double rateCTValue = Double.parseDouble(tree.getAttribute("GTR_TC").toString());
657 double rateGTValue = Double.parseDouble(tree.getAttribute("GTR_GT").toString());
658 //double rateACValue = (Double) tree.getAttribute("GTR_AC");
659 //double rateAGValue = (Double) tree.getAttribute("GTR_AG");
660 //double rateATValue = (Double) tree.getAttribute("GTR_AT");
661 //double rateCGValue = (Double) tree.getAttribute("GTR_GC");
662 //double rateCTValue = (Double) tree.getAttribute("GTR_TC");
663 //double rateGTValue = (Double) tree.getAttribute("GTR_GT");
664 System.err.println("Sorry, M0[GTR] substitution model is not yet implemented in BEAST");
665 System.exit(0);
666 }
667 // If +m2 then *M0
668 }
669 }
670 public DataType getDataType() {
671 return dataType; // Is this right too? Just use the universal codon table?
672 }
673 }
674
675 /*
676 * This method is equivalent to the SubstitutionModelLoader without having to
677 * be object orientated and can be much more flexible.
678 */
679 private GammaSiteRateModel loadSiteModel(Tree tree) {
680
681 String modelType = (String) tree.getAttribute(SUBST_MODEL);
682
683 /* Identify the datatype and substitution model. Load the model */
684 SubstitutionModelLoader sml = null;
685 String substModelName = modelType.replaceFirst("\\*.+","").replaceFirst("\\+.+","").trim();
686 System.out.println("Basic Substitution Model is " + substModelName);
687 for(int i = 0; i<GENERAL_MODELS_LIST.length; i++) {
688 if(substModelName.matches(GENERAL_MODELS_LIST[i])) {
689 sml = new GeneralSubstitutionModelLoader(tree, modelType);
690 }
691 }
692 for(int i = 0; i<NUCLEOTIDE_MODELS_LIST.length; i++) {
693 if(substModelName.matches(NUCLEOTIDE_MODELS_LIST[i])) {
694 sml = new NucleotideSubstitutionModelLoader(tree, modelType);
695 }
696 }
697 for(int i = 0; i<AMINO_ACID_MODELS_LIST.length; i++) {
698 if(substModelName.matches(AMINO_ACID_MODELS_LIST[i])) {
699 sml = new AminoAcidSubstitutionModelLoader(tree, modelType);
700 }
701 }
702 for(int i = 0; i<TRIPLET_MODELS_LIST.length; i++) {
703 if(substModelName.matches(TRIPLET_MODELS_LIST[i])) {
704 sml = new TripletSubstitutionModelLoader(tree, modelType);
705 }
706 }
707 for(int i = 0; i<CODON_MODELS_LIST.length; i++) {
708 if(substModelName.matches(CODON_MODELS_LIST[i])) {
709 sml = new CodonSubstitutionModelLoader(tree, modelType);
710 }
711 }
712
713 if (sml.getSubstitutionModel() == null) {
714 System.err.println("Substitution model type '" + modelType + "' not implemented");
715 System.exit(-1);
716 }
717
718 //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), new Parameter.Default(1.0), null, 0, null);
719 //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), null, null, 0, null);
720
721 String siteRatesModels = modelType.substring(modelType.indexOf("+")+1, modelType.length());
722 //String[] siteRatesModels = siteRatesParameters.split(" + ");
723 System.out.println("Site rate models: " + siteRatesModels);
724 if(sml.getSubstitutionModel().getDataType().getClass().equals(Codons.class) &&
725 siteRatesModels.length() > 0) { /* For codon site models */
726
727 if(siteRatesModels.indexOf("+M2") >= 0) { /* M2 */
728 System.out.println("Site model - M2 Codon site model used");
729 Parameter m2FrequencyAAInv = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_f[AA INV]").toString()));
730 Parameter m2FrequencyNeutral = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_f[Neutral]").toString()));
731 Parameter m2FrequencySelected = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_f[Selected]").toString()));
732 Parameter m2Omega = new Parameter.Default(Double.parseDouble(tree.getAttribute("M2_omega").toString()));
733 //Parameter m2FrequencyAAInv = new Parameter.Default((Double) tree.getAttribute("M2_f[AA INV]"));
734 //Parameter m2FrequencyNeutral = new Parameter.Default((Double) tree.getAttribute("M2_f[Neutral]"));
735 //Parameter m2FrequencySelected = new Parameter.Default((Double) tree.getAttribute("M2_f[Selected]"));
736 //Parameter m2Omega = new Parameter.Default((Double) tree.getAttribute("M2_omega"));
737 System.err.println("Sorry, M2 substitution model is not yet implemented in BEAST");
738 System.exit(0);
739 }
740 else if(siteRatesModels.indexOf("+M3") >= 0) { /* M3 */
741 System.out.println("Site model - M3 Codon site model used");
742 int numberOfBins = Integer.parseInt(siteRatesModels.replaceFirst(".+M3\\[","").replaceFirst("\\].+", ""));
743 System.out.println(" + M3 n value: " + numberOfBins);
744 Parameter[] m3Frequencies = new Parameter[numberOfBins];
745 Parameter[] m3Omegas = new Parameter[numberOfBins];
746 for(int i=1; i<=numberOfBins; i++) {
747 m3Frequencies[i-1] = new Parameter.Default(Double.parseDouble(tree.getAttribute("M3_f"+i).toString()));
748 m3Omegas[i-1] = new Parameter.Default(Double.parseDouble(tree.getAttribute("M3_omega"+i).toString()));
749 //m3Frequencies[i-1] = new Parameter.Default((Double) tree.getAttribute("M3_f"+i));
750 //m3Omegas[i-1] = new Parameter.Default((Double) tree.getAttribute("M3_omega"+i));
751 }
752 System.err.println("Sorry, M3 substitution model is not yet implemented in BEAST");
753 System.exit(0);
754 }
755 else if(siteRatesModels.indexOf("+M0_omega~Beta(") >= 0) { /* M7 */
756 System.out.println("Site model - M7 Codon site model used");
757 int numberOfBins = Integer.parseInt(siteRatesModels.replaceFirst("M0_omega~Beta\\(","").replaceFirst("\\)", ""));
758 System.out.println(" + M7 n value: " + numberOfBins);
759 Parameter m7BetaMu = new Parameter.Default(Double.parseDouble(tree.getAttribute("beta_mu").toString()));
760 Parameter m7BetaVarMu = new Parameter.Default(Double.parseDouble(tree.getAttribute("beta_Var/mu").toString()));
761 //Parameter m7BetaMu = new Parameter.Default((Double) tree.getAttribute("beta_mu"));
762 //Parameter m7BetaVarMu = new Parameter.Default((Double) tree.getAttribute("beta_Var/mu"));
763 System.err.println("Sorry, M7 substitution model is not yet implemented in BEAST");
764 System.exit(0);
765 }
766 }
767 else if(siteRatesModels.length() > 0) { /* i.e. for other data types. */
768 /* Do gamma/lognormal + pinv */
769 Parameter pInvParameter = null;
770 int categories = -1;
771 Parameter alphaParameter = null;
772
773 //System.out.println("Greatest story ever told! " + siteRatesModels);
774
775 if(siteRatesModels.indexOf("+INV") >= 0) {
776 System.out.println("Site model - proportion of invariable sites used");
777 //pInvParameter = new Parameter.Default(((Double) tree.getAttribute("INV_p")).doubleValue());
778 pInvParameter = new Parameter.Default(Double.parseDouble(tree.getAttribute("INV_p").toString()));
779 }
780 if(siteRatesModels.indexOf("+rate~Gamma(") >= 0) {
781 System.out.println("Site model - gamma site rate heterogeneity used");
782 categories = Integer.parseInt(siteRatesModels.replaceFirst(".+rate~Gamma\\(", "").replaceFirst("\\).*",""));
783 //double sigmaMu = (Double) tree.getAttribute("gamma_sigma/mu");
784 double sigmaMu = Double.parseDouble(tree.getAttribute("gamma_sigma/mu").toString());
785 sigmaMu = (1.0/sigmaMu) * (1.0/sigmaMu); /* BAli-Phy is parameterised by sigma/mu instead of alpha */
786 alphaParameter = new Parameter.Default(sigmaMu);
787 }
788 else if(siteRatesModels.indexOf("+rate~LogNormal(") >= 0) {
789 // TODO implement lognormal site model
790 System.out.println("Site model - lognormal site rate heterogeneity used");
791 System.err.println("Sorry, lognormal site rates are not yet implemented in BEAST");
792 System.exit(0);
793
794 categories = Integer.parseInt(siteRatesModels.replaceFirst(".+rate~LogNormal\\(", "").replaceFirst("\\).*",""));
795 //double sigmaMu = (Double) tree.getAttribute("log-normal_sigma/mu");
796 double sigmaMu = Double.parseDouble(tree.getAttribute("log-normal_sigma/mu").toString());
797 sigmaMu = (1.0/sigmaMu) * (1.0/sigmaMu); /* BAli-Phy is parameterised by sigma/mu instead of alpha */
798 alphaParameter = new Parameter.Default(sigmaMu);
799 }
800 else if(siteRatesModels.indexOf("+GAMMA(") >= 0) { /* For BEAST output */
801 System.out.println("Site model - gamma site rate heterogeneity used");
802 categories = Integer.parseInt(siteRatesModels.replaceFirst(".+GAMMA\\(", "").replaceFirst("\\).*",""));
803 //double sigmaMu = (Double) tree.getAttribute("gamma_sigma/mu");
804 double alpha = Double.parseDouble(tree.getAttribute("alpha").toString());
805 alphaParameter = new Parameter.Default(alpha);
806 }
807
808 //System.out.println("alpha and pinv parameters: " + alphaParameter.getParameterValue(0) + "\t" + pInvParameter.getParameterValue(0));
809 //GammaSiteRateModel siteModel = new GammaSiteRateModel(sml.getSubstitutionModel(), new Parameter.Default(1.0), alphaParameter, categories, pInvParameter);
810 GammaSiteRateModel siteModel = new GammaSiteRateModel(GammaSiteModelParser.SITE_MODEL, new Parameter.Default(1.0), alphaParameter, categories, pInvParameter);
811 siteModel.setSubstitutionModel(sml.getSubstitutionModel());
812 //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), new Parameter.Default(1.0), new Parameter.Default(1.0), 1, new Parameter.Default(0.5));
813 //SiteModel siteModel = new GammaSiteModel(sml.getSubstitutionModel(), null, null, 0, null);
814 return siteModel;
815 }
816
817 /* Default with no gamma or pinv */
818 //SiteRateModel siteModel = new GammaSiteRateModel(sml.getSubstitutionModel());
819 GammaSiteRateModel siteModel = new GammaSiteRateModel(GammaSiteModelParser.SITE_MODEL);
820 siteModel.setSubstitutionModel(sml.getSubstitutionModel());
821 return siteModel;
822
823 }
824
825
826 public static final String KAPPA_STRING = "kappa";
827 //public static final String SEQ_STRING = "states"; // For BEAST input files
828 public static String SEQ_STRING = "seq";
829 //public static final String SEQ_STRING_2 = "states"; // For BEAST input files
830 public static final String NEW_SEQ = "newSeq";
831 public static final String TAG = "tag";
832 public static final String LIKELIHOOD = "lnL";
833 public static final String SUBST_MODEL = "subst";
834
835
836 // public static final String WAG_STRING = "Empirical(Data/wag.dat)*pi";
837 private final int die = 0;
838
839 private Tree processTree(Tree tree) {
840
841 // Remake tree to fix node ordering - Marc
842
843 GammaSiteRateModel siteModel = loadSiteModel(tree);
844
845 SimpleAlignment alignment = new SimpleAlignment();
846 alignment.setDataType(siteModel.getSubstitutionModel().getDataType());
847 if(siteModel.getSubstitutionModel().getDataType().getClass().equals(Codons.class)) {
848 //System.out.println("trololo");
849 alignment.setDataType(Nucleotides.INSTANCE);
850 }
851 //System.out.println("BOO BOO " + siteModel.getSubstitutionModel().getDataType().getClass().getName()+"\t" + Codons.UNIVERSAL.getClass().getName() + "\t" + alignment.getDataType().getClass().getName());
852
853
854 // Get sequences
855 String[] sequence = new String[tree.getNodeCount()];
856 for (int i = 0; i < tree.getNodeCount(); i++) {
857 NodeRef node = tree.getNode(i);
858 sequence[i] = (String) tree.getNodeAttribute(node, SEQ_STRING);
859 if (tree.isExternal(node)) {
860 Taxon taxon = tree.getNodeTaxon(node);
861 alignment.addSequence(new Sequence(taxon, sequence[i]));
862 //System.out.println("seq " + sequence[i]);
863 }
864 }
865
866 // Make evolutionary model
867
868 BranchRateModel rateModel = new StrictClockBranchRates(new Parameter.Default(1.0));
869 FlexibleTree flexTree;
870 if(siteModel.getSubstitutionModel().getDataType().getClass().equals(Codons.class)) {
871 ConvertAlignment convertAlignment = new ConvertAlignment(siteModel.getSubstitutionModel().getDataType(), ((Codons) siteModel.getSubstitutionModel().getDataType()).getGeneticCode(), alignment);
872 flexTree = sampleTree(tree, convertAlignment, siteModel, rateModel);
873 //flexTree = sampleTree(tree, alignment, siteModel, rateModel);
874 }
875 else {
876 flexTree = sampleTree(tree, alignment, siteModel, rateModel);
877 }
878 introduceGaps(flexTree, tree);
879
880 return flexTree;
881 }
882
883
884
885
886
887 private void introduceGaps(FlexibleTree flexTree, Tree gapTree) {
888 // I forget what this function was supposed to do. - Marc
889 }
890
891
892 public static final char GAP = '-';
893
894 boolean[] bit = null;
895
896 private FlexibleTree sampleTree(Tree tree, PatternList alignment, GammaSiteRateModel siteModel, BranchRateModel rateModel) {
897 FlexibleTree flexTree = new FlexibleTree(tree, true);
898 flexTree.adoptTreeModelOrdering();
899 FlexibleTree finalTree = new FlexibleTree(tree);
900 finalTree.adoptTreeModelOrdering();
901 TreeModel treeModel = new TreeModel(tree);
902
903 // Turn off noisy logging by TreeLikelihood constructor
904 Logger logger = Logger.getLogger("dr.evomodel");
905 boolean useParentHandlers = logger.getUseParentHandlers();
906 logger.setUseParentHandlers(false);
907
908 // AncestralStateTreeLikelihood likelihood = new AncestralStateTreeLikelihood(
909 // alignment,
910 // treeModel,
911 // siteModel,
912 // rateModel,
913 // false, true,
914 // alignment.getDataType(),
915 // TAG,
916 // false);
917 AncestralStateBeagleTreeLikelihood likelihood = new AncestralStateBeagleTreeLikelihood(
918 alignment,
919 treeModel,
920 new HomogeneousBranchModel(siteModel.getSubstitutionModel()),
921 siteModel,
922 rateModel,
923 null,
924 false,
925 PartialsRescalingScheme.DEFAULT,
926 true,
927 null,
928 alignment.getDataType(),
929 TAG,
930 false, true
931 );
932
933 // PatternList patternList, TreeModel treeModel,
934 // BranchSiteModel branchSiteModel,
935 // SiteRateModel siteRateModel,
936 // BranchRateModel branchRateModel,
937 // boolean useAmbiguities,
938 // PartialsRescalingScheme scalingScheme,
939 // Map<Set<String>, Parameter> partialsRestrictions,
940 // final DataType dataType,
941 // final String tag,
942 // SubstitutionModel substModel,
943 // boolean useMAP,
944 // boolean returnML) {
945
946 // PatternList patternList, TreeModel treeModel,
947 // SiteModel siteModel, BranchRateModel branchRateModel,
948 // boolean useAmbiguities, boolean storePartials,
949 // final DataType dataType,
950 // final String tag,
951 // boolean forceRescaling,
952 // boolean useMAP,
953 // boolean returnML) {
954
955
956 logger.setUseParentHandlers(useParentHandlers);
957
958 // Sample internal nodes
959 likelihood.makeDirty();
960 double logLikelihood = likelihood.getLogLikelihood();
961
962 System.out.println("The new and old Likelihood (this value should be roughly the same, debug?): " + logLikelihood + ", " + Double.parseDouble(tree.getAttribute(LIKELIHOOD).toString()));
963 if(Double.parseDouble(tree.getAttribute(LIKELIHOOD).toString()) != logLikelihood) {
964 /* Newly written check, not sure if this is correct. May need to round values at least */
965 //throw new RuntimeException("The values of likelihood are not identical");
966 }
967 // System.err.printf("New logLikelihood = %4.1f\n", logLikelihood);
968
969 flexTree.setAttribute(LIKELIHOOD, logLikelihood);
970
971 TreeTrait ancestralStates = likelihood.getTreeTrait(TAG);
972 for (int i = 0; i < treeModel.getNodeCount(); i++) {
973
974 NodeRef node = treeModel.getNode(i);
975 String sample = ancestralStates.getTraitString(treeModel, node);
976
977 String oldSeq = (String) flexTree.getNodeAttribute(flexTree.getNode(i), SEQ_STRING);
978
979 if (oldSeq != null) {
980
981 char[] seq = (sample.substring(1, sample.length() - 1)).toCharArray();
982
983 int length = oldSeq.length();
984 //System.out.println("length " + length + "\t" + sample.length() + "\t" + sample + "\t" + seq.length + "\t" + oldSeq);
985
986 for (int j = 0; j < length; j++) {
987 if (oldSeq.charAt(j) == GAP)
988 seq[j] = GAP;
989 }
990
991 String newSeq = new String(seq);
992
993 // if( newSeq.contains("MMMMMMM") ) {
994 // System.err.println("bad = "+newSeq);
995 // System.exit(-1);
996 // }
997
998 finalTree.setNodeAttribute(finalTree.getNode(i), NEW_SEQ, newSeq);
999
1000 }
1001
1002 // Taxon taxon = finalTree.getNodeTaxon(finalTree.getNode(i));
1003 // System.err.println("node: "+(taxon == null ? "null" : taxon.getId())+" "+
1004 // finalTree.getNodeAttribute(finalTree.getNode(i),NEW_SEQ));
1005
1006 }
1007 return finalTree;
1008 }
1009
1010
1011 private void setupAttributes(Tree tree) {
1012 for (int i = 0; i < tree.getNodeCount(); i++) {
1013 NodeRef node = tree.getNode(i);
1014 Iterator iter = tree.getNodeAttributeNames(node);
1015 if (iter != null) {
1016 while (iter.hasNext()) {
1017 String name = (String) iter.next();
1018 if (!attributeNames.contains(name))
1019 attributeNames.add(name);
1020 }
1021 }
1022 }
1023 }
1024
1025 private void setupTreeAttributes(Tree tree) {
1026 Iterator<String> iter = tree.getAttributeNames();
1027 if (iter != null) {
1028 while (iter.hasNext()) {
1029 String name = iter.next();
1030 treeAttributeNames.add(name);
1031 }
1032 }
1033 }
1034
1035 private void addTreeAttributes(Tree tree) {
1036 if (treeAttributeNames != null) {
1037 if (treeAttributeLists == null) {
1038 treeAttributeLists = new List[treeAttributeNames.size()];
1039 for (int i = 0; i < treeAttributeNames.size(); i++) {
1040 treeAttributeLists[i] = new ArrayList();
1041 }
1042 }
1043
1044 for (int i = 0; i < treeAttributeNames.size(); i++) {
1045 String attributeName = treeAttributeNames.get(i);
1046 Object value = tree.getAttribute(attributeName);
1047
1048 if (value != null) {
1049 treeAttributeLists[i].add(value);
1050 }
1051 }
1052 }
1053
1054 }
1055
1056
1057 private Tree summarizeTrees(int burnin, CladeSystem cladeSystem, String inputFileName, boolean useSumCladeCredibility) throws IOException {
1058
1059 Tree bestTree = null;
1060 double bestScore = Double.NEGATIVE_INFINITY;
1061
1062 // System.out.println("Analyzing " + totalTreesUsed + " trees...");
1063 // System.out.println("0 25 50 75 100");
1064 // System.out.println("|--------------|--------------|--------------|--------------|");
1065
1066 int stepSize = totalTrees / 60;
1067 if (stepSize < 1) stepSize = 1;
1068
1069 int counter = 0;
1070 TreeImporter importer = new NexusImporter(new FileReader(inputFileName));
1071 try {
1072 while (importer.hasTree()) {
1073 Tree tree = importer.importNextTree();
1074
1075 if (counter >= burnin) {
1076 double score = scoreTree(tree, cladeSystem, useSumCladeCredibility);
1077 // System.out.println(score);
1078 if (score > bestScore) {
1079 bestTree = tree;
1080 bestScore = score;
1081 }
1082 }
1083 if (counter > 0 && counter % stepSize == 0) {
1084 // System.out.print("*");
1085 // System.out.flush();
1086 }
1087 counter++;
1088 }
1089 } catch (Importer.ImportException e) {
1090 System.err.println("Error Parsing Input Tree: " + e.getMessage());
1091 return null;
1092 }
1093 // System.out.println();
1094 // System.out.println();
1095 if (useSumCladeCredibility) {
1096 System.out.println("\tHighest Sum Clade Credibility: " + bestScore);
1097 } else {
1098 System.out.println("\tHighest Log Clade Credibility: " + bestScore);
1099 }
1100
1101 return bestTree;
1102 }
1103
1104 private double scoreTree(Tree tree, CladeSystem cladeSystem, boolean useSumCladeCredibility) {
1105 if (useSumCladeCredibility) {
1106 return cladeSystem.getSumCladeCredibility(tree, tree.getRoot(), null);
1107 } else {
1108 return cladeSystem.getLogCladeCredibility(tree, tree.getRoot(), null);
1109 }
1110 }
1111
1112 private class CladeSystem {
1113 //
1114 // Public stuff
1115 //
1116
1117 /**
1118 */
1119 public CladeSystem() {
1120 }
1121
1122 /**
1123 * adds all the clades in the tree
1124 */
1125 public void add(Tree tree) {
1126 if (taxonList == null) {
1127 taxonList = tree;
1128 }
1129
1130 // Recurse over the tree and add all the clades (or increment their
1131 // frequency if already present). The root clade is added too (for
1132 // annotation purposes).
1133 addClades(tree, tree.getRoot(), null);
1134 addTreeAttributes(tree);
1135 }
1136
1137 public Map<BitSet, Clade> getCladeMap() {
1138 return cladeMap;
1139 }
1140
1141 public Clade getClade(NodeRef node) {
1142 return null;
1143 }
1144
1145
1146 private void addClades(Tree tree, NodeRef node, BitSet bits) {
1147
1148 BitSet bits2 = new BitSet();
1149
1150 if (tree.isExternal(node)) {
1151
1152 int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
1153 bits2.set(index);
1154
1155 } else {
1156
1157 for (int i = 0; i < tree.getChildCount(node); i++) {
1158
1159 NodeRef node1 = tree.getChild(node, i);
1160
1161 addClades(tree, node1, bits2);
1162 }
1163 }
1164
1165 addClade(bits2, tree, node);
1166
1167 if (bits != null) {
1168 bits.or(bits2);
1169 }
1170 }
1171
1172 private void addClade(BitSet bits, Tree tree, NodeRef node) {
1173 Clade clade = cladeMap.get(bits);
1174 if (clade == null) {
1175 clade = new Clade(bits);
1176 cladeMap.put(bits, clade);
1177 }
1178 clade.setCount(clade.getCount() + 1);
1179
1180 if (attributeNames != null) {
1181 if (clade.attributeLists == null) {
1182 clade.attributeLists = new List[attributeNames.size()];
1183 for (int i = 0; i < attributeNames.size(); i++) {
1184 clade.attributeLists[i] = new ArrayList();
1185 }
1186 }
1187
1188 for (int i = 0; i < attributeNames.size(); i++) {
1189 String attributeName = attributeNames.get(i);
1190 Object value;
1191 if (attributeName.equals("height")) {
1192 value = tree.getNodeHeight(node);
1193 } else if (attributeName.equals("length")) {
1194 value = tree.getBranchLength(node);
1195 } else {
1196 value = tree.getNodeAttribute(node, attributeName);
1197 }
1198
1199 if (value != null) {
1200 clade.attributeLists[i].add(value);
1201 }
1202 }
1203 }
1204 }
1205
1206 public void calculateCladeCredibilities(int totalTreesUsed) {
1207 for (Clade clade : cladeMap.values()) {
1208 clade.setCredibility(((double) clade.getCount()) / totalTreesUsed);
1209 }
1210 }
1211
1212 public double getSumCladeCredibility(Tree tree, NodeRef node, BitSet bits) {
1213
1214 double sum = 0.0;
1215
1216 if (tree.isExternal(node)) {
1217
1218 int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
1219 bits.set(index);
1220 } else {
1221
1222 BitSet bits2 = new BitSet();
1223 for (int i = 0; i < tree.getChildCount(node); i++) {
1224
1225 NodeRef node1 = tree.getChild(node, i);
1226
1227 sum += getSumCladeCredibility(tree, node1, bits2);
1228 }
1229
1230 sum += getCladeCredibility(bits2);
1231
1232 if (bits != null) {
1233 bits.or(bits2);
1234 }
1235 }
1236
1237 return sum;
1238 }
1239
1240 public double getLogCladeCredibility(Tree tree, NodeRef node, BitSet bits) {
1241
1242 double logCladeCredibility = 0.0;
1243
1244 if (tree.isExternal(node)) {
1245
1246 int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
1247 bits.set(index);
1248 } else {
1249
1250 BitSet bits2 = new BitSet();
1251 for (int i = 0; i < tree.getChildCount(node); i++) {
1252
1253 NodeRef node1 = tree.getChild(node, i);
1254
1255 logCladeCredibility += getLogCladeCredibility(tree, node1, bits2);
1256 }
1257
1258 logCladeCredibility += Math.log(getCladeCredibility(bits2));
1259
1260 if (bits != null) {
1261 bits.or(bits2);
1262 }
1263 }
1264
1265 return logCladeCredibility;
1266 }
1267
1268 private double getCladeCredibility(BitSet bits) {
1269 Clade clade = cladeMap.get(bits);
1270 if (clade == null) {
1271 return 0.0;
1272 }
1273 return clade.getCredibility();
1274 }
1275
1276 public void annotateTree(MutableTree tree, NodeRef node, BitSet bits, int heightsOption) {
1277
1278 BitSet bits2 = new BitSet();
1279
1280 if (tree.isExternal(node)) {
1281
1282 int index = taxonList.getTaxonIndex(tree.getNodeTaxon(node).getId());
1283 bits2.set(index);
1284
1285 annotateNode(tree, node, bits2, true, heightsOption);
1286 } else {
1287
1288 for (int i = 0; i < tree.getChildCount(node); i++) {
1289
1290 NodeRef node1 = tree.getChild(node, i);
1291
1292 annotateTree(tree, node1, bits2, heightsOption);
1293 }
1294
1295 annotateNode(tree, node, bits2, false, heightsOption);
1296 }
1297
1298 if (bits != null) {
1299 bits.or(bits2);
1300 }
1301 }
1302
1303 private void annotateNode(MutableTree tree, NodeRef node, BitSet bits, boolean isTip, int heightsOption) {
1304 Clade clade = cladeMap.get(bits);
1305 if (clade == null) {
1306 throw new RuntimeException("Clade missing");
1307 }
1308
1309 // System.err.println("annotateNode new: "+bits.toString()+" size = "+attributeNames.size());
1310 // for(String string : attributeNames) {
1311 // System.err.println(string);
1312 // }
1313 // System.exit(-1);
1314
1315
1316 boolean filter = false;
1317 if (!isTip) {
1318 double posterior = clade.getCredibility();
1319 tree.setNodeAttribute(node, "posterior", posterior);
1320 if (posterior < posteriorLimit) {
1321 filter = true;
1322 }
1323 }
1324
1325 for (int i = 0; i < attributeNames.size(); i++) {
1326 String attributeName = attributeNames.get(i);
1327
1328 double[] values = new double[clade.attributeLists[i].size()];
1329 HashMap<String, Integer> hashMap = new HashMap<String, Integer>(clade.attributeLists[i].size());
1330
1331 if (values.length > 0) {
1332 Object v = clade.attributeLists[i].get(0);
1333
1334 boolean isHeight = attributeName.equals("height");
1335 boolean isBoolean = v instanceof Boolean;
1336
1337 boolean isDiscrete = v instanceof String;
1338
1339 double minValue = Double.MAX_VALUE;
1340 double maxValue = -Double.MAX_VALUE;
1341 for (int j = 0; j < clade.attributeLists[i].size(); j++) {
1342 if (isDiscrete) {
1343 String value = (String) clade.attributeLists[i].get(j);
1344 if (value.startsWith("\"")) {
1345 value = value.replaceAll("\"", "");
1346 }
1347 if (attributeName.equals(NEW_SEQ)) {
1348 // Strip out gaps before storing
1349 value = value.replaceAll("-", "");
1350 }
1351 if (hashMap.containsKey(value)) {
1352 int count = hashMap.get(value);
1353 hashMap.put(value, count + 1);
1354 } else {
1355 hashMap.put(value, 1);
1356
1357 }
1358 } else if (isBoolean) {
1359 values[j] = (((Boolean) clade.attributeLists[i].get(j)) ? 1.0 : 0.0);
1360 } else {
1361 values[j] = ((Number) clade.attributeLists[i].get(j)).doubleValue();
1362 if (values[j] < minValue) minValue = values[j];
1363 if (values[j] > maxValue) maxValue = values[j];
1364 }
1365 }
1366 if (isHeight) {
1367 if (heightsOption == MEAN_HEIGHTS) {
1368 double mean = DiscreteStatistics.mean(values);
1369 tree.setNodeHeight(node, mean);
1370 } else if (heightsOption == MEDIAN_HEIGHTS) {
1371 double median = DiscreteStatistics.median(values);
1372 tree.setNodeHeight(node, median);
1373 } else {
1374 // keep the existing height
1375 }
1376 }
1377
1378 if (!filter) {
1379 if (!isDiscrete)
1380 annotateMeanAttribute(tree, node, attributeName, values);
1381 else
1382 annotateModeAttribute(tree, node, attributeName, hashMap);
1383 // if( tree.getNodeTaxon(node) != null &&
1384 // tree.getNodeTaxon(node).getId().compareTo("Calanus") == 0) {
1385 // System.err.println("size = "+hashMap.keySet().size());
1386 // System.err.println("count = "+hashMap.get(hashMap.keySet().toArray()[0]));
1387 // }
1388 // System.err.println();
1389 // ;
1390 if (!isBoolean && minValue < maxValue && !isDiscrete) {
1391 // Basically, if it is a boolean (0, 1) then we don't need the distribution information
1392 // Likewise if it doesn't vary.
1393 annotateMedianAttribute(tree, node, attributeName + "_median", values);
1394 annotateHPDAttribute(tree, node, attributeName + "_95%_HPD", 0.95, values);
1395 annotateRangeAttribute(tree, node, attributeName + "_range", values);
1396 }
1397 }
1398 }
1399 }
1400 }
1401
1402 private void annotateMeanAttribute(MutableTree tree, NodeRef node, String label, double[] values) {
1403 double mean = DiscreteStatistics.mean(values);
1404 tree.setNodeAttribute(node, label, mean);
1405 }
1406
1407 private void annotateMedianAttribute(MutableTree tree, NodeRef node, String label, double[] values) {
1408 double median = DiscreteStatistics.median(values);
1409 tree.setNodeAttribute(node, label, median);
1410
1411 }
1412
1413
1414 public static final String fileName = "junk";
1415 // public static final String execName = "/sw/bin/clustalw";
1416
1417 private int externalCalls = 0;
1418
1419 private void annotateModeAttribute(MutableTree tree, NodeRef node, String label, HashMap<String, Integer> values) {
1420 if (label.equals(NEW_SEQ)) {
1421 String consensusSeq = null;
1422 double[] support = null;
1423 int numElements = values.keySet().size();
1424 // System.err.println("size = "+numElements);
1425 if (numElements > 1) { // Essentially just finding the modal character
1426 try {
1427
1428 PrintWriter pw = new PrintWriter(new PrintStream(new FileOutputStream(fileName)));
1429 int i = 0;
1430
1431 int[] weight = new int[numElements];
1432
1433 // Iterator iter = values.keySet().iterator();
1434
1435 for (String key : values.keySet()) {
1436 int thisCount = values.get(key);
1437 weight[i] = thisCount;
1438 //TODO I THINK I FIXED IT?!?!
1439 pw.write(">" + i+"\n");// + " " + thisCount + "\n");
1440 pw.write(key + "\n");
1441 i++;
1442 }
1443 pw.close();
1444
1445 //Process p = Runtime.getRuntime().exec(kalignExecutable + " " + fileName + " -OUTPUT=NEXUS");
1446 //Process p = Runtime.getRuntime().exec(kalignExecutable + " " + fileName + " -fmsf -o"+fileName + ".fasta");
1447 // System.out.println("Command: " + kalignExecutable + " " + fileName + " -ffasta -o"+fileName + ".fasta");
1448 // Process p = Runtime.getRuntime().exec(kalignExecutable + " " + fileName + " -ffasta -o"+fileName + ".fasta");
1449 Process p = Runtime.getRuntime().exec(kalignExecutable + " " + fileName + " -ffasta -q -o"+fileName + ".fasta");
1450
1451 // ByteArrayOutputStream kalignOutput = new ByteArrayOutputStream();
1452 // StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERR");
1453 // StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), "OUT", kalignOutput);
1454 //
1455 // errorGobbler.start();
1456 // outputGobbler.start();
1457 //
1458 // int exitVal = p.waitFor();
1459
1460 BufferedReader input =
1461 new BufferedReader
1462 (new InputStreamReader(p.getInputStream()));
1463 {
1464
1465 // String line;
1466 while ((/*line = */input.readLine()) != null) {
1467 // System.out.println(line);
1468 }
1469 }
1470
1471 input.close();
1472 externalCalls++;
1473 // System.err.println("clustal call #" + externalCalls);
1474
1475 //NexusImporter importer = new NexusImporter(new FileReader(fileName + ".nxs"));
1476 // FastaImporter importer = new FastaImporter(new FileReader(new File(fileName + ".fasta")), Nucleotides.INSTANCE);
1477 FastaImporter importer = new FastaImporter(new FileReader(new File(fileName + ".fasta")), new GeneralDataType(new String[0]));//AminoAcids.INSTANCE);
1478 //new FastaImporter(new FileReader(), new AminoAcids.INSTANCE);
1479
1480 Alignment alignment = importer.importAlignment();
1481 // build index
1482 int[] index = new int[numElements];
1483 for (int j = 0; j < numElements; j++)
1484 index[j] = alignment.getTaxonIndex("" + j);
1485
1486 StringBuffer sb = new StringBuffer();
1487 support = new double[alignment.getPatternCount()];
1488
1489 // System.err.println(new dr.math.matrixAlgebra.Vector(weight));
1490
1491 for (int j = 0; j < alignment.getPatternCount(); j++) {
1492 int[] pattern = alignment.getPattern(j);
1493 // support[j] = appendNextConsensusCharacter(alignment,j,sb);
1494 // System.err.println(new dr.math.matrixAlgebra.Vector(pattern));
1495
1496 int[] siteWeight = new int[30]; // + 2 to handle ambiguous and gap
1497 int maxWeight = -1;
1498 int totalWeight = 0;
1499 int maxChar = -1;
1500 for (int k = 0; k < pattern.length; k++) {
1501 int whichChar = pattern[k];
1502 if (whichChar < 30) {
1503 int addWeight = weight[index[k]];
1504 //System.out.println(k + "\t" + addWeight + "\t" + whichChar + "\t" + siteWeight[whichChar]);
1505 siteWeight[whichChar] += addWeight;
1506 totalWeight += addWeight;
1507 // if( k >= alignment.getDataType().getStateCount()+2 ) {
1508 // System.err.println("k = "+k);
1509 // System.err.println("pattern = "+new dr.math.matrixAlgebra.Vector(pattern));
1510 // }
1511 if (siteWeight[whichChar] > maxWeight) {
1512
1513 maxWeight = siteWeight[whichChar];
1514 maxChar = whichChar;
1515 }
1516 } else {
1517 System.err.println("BUG");
1518 System.err.println("k = " + k);
1519 System.err.println("whichChar = " + whichChar);
1520 System.err.println("pattern = " + new dr.math.matrixAlgebra.Vector(pattern));
1521 }
1522 }
1523 sb.append(alignment.getDataType().getChar(maxChar));
1524 support[j] = (double) maxWeight / (double) totalWeight;
1525 }
1526
1527 // System.err.println("cSeq = " + sb.toString());
1528 consensusSeq = sb.toString();
1529
1530 // System.exit(-1);
1531 } catch (FileNotFoundException e) {
1532 System.err.println(e.getMessage());
1533 System.exit(-1);
1534 } catch (Importer.ImportException e) {
1535 System.err.println(e.getMessage());
1536 System.exit(-1);
1537 } catch (IOException e) {
1538 System.err.println(e.getMessage());
1539 System.exit(-1);
1540 }
1541 } else {
1542 consensusSeq = (String) values.keySet().toArray()[0];
1543 support = new double[consensusSeq.length()];
1544 for (int i = 0; i < support.length; i++)
1545 support[i] = 1.0;
1546 }
1547
1548 // Trim out gaps from consensus and support
1549 // ArrayList<Double> newSupport = new ArrayList<Double>(support.length);
1550 boolean noComma = true;
1551 StringBuffer newSupport = new StringBuffer("{");
1552 StringBuffer newSeq = new StringBuffer();
1553 if (consensusSeq.length() != support.length) {
1554 System.err.println("What happened here?");
1555 System.exit(-1);
1556 }
1557
1558 // Restripping all the sequences of gap characters since they may have been added in during clustal step
1559 for (int i = 0; i < support.length; i++) {
1560 if (consensusSeq.charAt(i) != GAP) {
1561 newSeq.append(consensusSeq.charAt(i));
1562 if (noComma)
1563 noComma = false;
1564 else
1565 newSupport.append(",");
1566 newSupport.append(String.format("%1.3f", support[i]));
1567 }
1568 }
1569 newSupport.append("}");
1570
1571 tree.setNodeAttribute(node, label, newSeq);
1572 // String num = Str
1573 tree.setNodeAttribute(node, label + ".prob", newSupport);
1574 } else {
1575 String mode = null;
1576 int maxCount = 0;
1577 int totalCount = 0;
1578
1579 for (String key : (String[]) values.keySet().toArray()) {
1580 int thisCount = values.get(key);
1581 if (thisCount == maxCount)
1582 mode = mode.concat("+" + key);
1583 else if (thisCount > maxCount) {
1584 mode = key;
1585 maxCount = thisCount;
1586 }
1587 totalCount += thisCount;
1588 }
1589 double freq = (double) maxCount / (double) totalCount;
1590 tree.setNodeAttribute(node, label, mode);
1591 tree.setNodeAttribute(node, label + ".prob", freq);
1592 }
1593 }
1594
1595 // private double appendNextConsensusCharacter(Alignment alignment, int j, StringBuffer sb, int[] weight) {
1596 // int[] pattern = alignment.getPattern(j);
1597 // int[] siteWeight = new int[alignment.getDataType().getStateCount()];
1598 // int maxWeight = -1;
1599 // int totalWeight = 0;
1600 // int maxChar = -1;
1601 // for (int k = 0; k < pattern.length; k++) {
1602 // int whichChar = pattern[k];
1603 // if (whichChar < alignment.getDataType().getStateCount()) {
1604 //
1605 // int addWeight = weight[index[k]];
1606 // siteWeight[whichChar] += addWeight;
1607 // totalWeight += addWeight;
1608 // if (siteWeight[k] > maxWeight) {
1609 // maxWeight = siteWeight[k];
1610 // maxChar = k;
1611 // }
1612 // }
1613 // }
1614 // sb.append(alignment.getDataType().getChar(maxChar));
1615 // return (double) maxWeight / (double) totalWeight;
1616 //
1617 // }
1618
1619 private void annotateRangeAttribute(MutableTree tree, NodeRef node, String label, double[] values) {
1620 double min = DiscreteStatistics.min(values);
1621 double max = DiscreteStatistics.max(values);
1622 tree.setNodeAttribute(node, label, new Object[]{min, max});
1623 }
1624
1625 private void annotateHPDAttribute(MutableTree tree, NodeRef node, String label, double hpd, double[] values) {
1626 int[] indices = new int[values.length];
1627 HeapSort.sort(values, indices);
1628
1629 double minRange = Double.MAX_VALUE;
1630 int hpdIndex = 0;
1631
1632 int diff = (int) Math.round(hpd * (double) values.length);
1633 for (int i = 0; i <= (values.length - diff); i++) {
1634 double minValue = values[indices[i]];
1635 double maxValue = values[indices[i + diff - 1]];
1636 double range = Math.abs(maxValue - minValue);
1637 if (range < minRange) {
1638 minRange = range;
1639 hpdIndex = i;
1640 }
1641 }
1642 double lower = values[indices[hpdIndex]];
1643 double upper = values[indices[hpdIndex + diff - 1]];
1644 tree.setNodeAttribute(node, label, new Object[]{lower, upper});
1645 }
1646
1647 class Clade {
1648 public Clade(BitSet bits) {
1649 this.bits = bits;
1650 count = 0;
1651 credibility = 0.0;
1652 }
1653
1654 public int getCount() {
1655 return count;
1656 }
1657
1658 public void setCount(int count) {
1659 this.count = count;
1660 }
1661
1662 public double getCredibility() {
1663 return credibility;
1664 }
1665
1666 public void setCredibility(double credibility) {
1667 this.credibility = credibility;
1668 }
1669
1670 public boolean equals(Object o) {
1671 if (this == o) return true;
1672 if (o == null || getClass() != o.getClass()) return false;
1673
1674 final Clade clade = (Clade) o;
1675
1676 return !(bits != null ? !bits.equals(clade.bits) : clade.bits != null);
1677
1678 }
1679
1680 public int hashCode() {
1681 return (bits != null ? bits.hashCode() : 0);
1682 }
1683
1684 int count;
1685 double credibility;
1686 BitSet bits;
1687 List[] attributeLists = null;
1688 }
1689
1690 //
1691 // Private stuff
1692 //
1693 TaxonList taxonList = null;
1694 Map<BitSet, Clade> cladeMap = new HashMap<BitSet, Clade>();
1695 }
1696
1697 int totalTrees = 0;
1698 int totalTreesUsed = 0;
1699 double posteriorLimit = 0.0;
1700 String kalignExecutable = null;
1701
1702 List<String> attributeNames = new ArrayList<String>();
1703 List<String> treeAttributeNames = new ArrayList<String>();
1704 List[] treeAttributeLists = null;
1705 TaxonList taxa = null;
1706
1707 public static void printTitle() {
1708 System.out.println();
1709 centreLine("Ancestral Sequence Annotator " + "v0.1" + ", " + "2008", 60);
1710 // version.getVersionString() + ", " + version.getDateString(), 60);
1711
1712 System.out.println();
1713 centreLine("by", 60);
1714 System.out.println();
1715 centreLine("Marc A. Suchard, Wai Lok Sibon Li", 60);
1716 System.out.println();
1717 centreLine("Departments of Biomathematics,", 60);
1718 centreLine("Biostatistics and Human Genetics", 60);
1719 centreLine("UCLA", 60);
1720 centreLine("[email protected]", 60);
1721 System.out.println();
1722 System.out.println();
1723 System.out.println("NB: I stole a substantial portion of this code from Andrew Rambaut.");
1724 System.out.println(" Please also give him due credit.");
1725 System.out.println();
1726 }
1727
1728 public static void centreLine(String line, int pageWidth) {
1729 int n = pageWidth - line.length();
1730 int n1 = n / 2;
1731 for (int i = 0; i < n1; i++) {
1732 System.out.print(" ");
1733 }
1734 System.out.println(line);
1735 }
1736
1737
1738 public static void printUsage(Arguments arguments) {
1739
1740 arguments.printUsage("ancestralsequenceannotator", "<input-file-name> <output-file-name>");
1741 System.out.println();
1742 System.out.println(" Example: ancestralsequenceannotator test.trees out.txt");
1743 System.out.println();
1744 }
1745
1746 //Main method
1747 public static void main(String[] args) throws IOException {
1748
1749 String targetTreeFileName = null;
1750 String inputFileName = null;
1751 String outputFileName = null;
1752
1753
1754 printTitle();
1755
1756 Arguments arguments = new Arguments(
1757 new Arguments.Option[]{
1758 //new Arguments.StringOption("target", new String[] { "maxclade", "maxtree" }, false, "an option of 'maxclade' or 'maxtree'"),
1759 new Arguments.StringOption("heights", new String[]{"keep", "median", "mean"}, false, "an option of 'keep', 'median' or 'mean'"),
1760 new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in'"),
1761 new Arguments.StringOption("beastInput", new String[]{"true", "false"}, false, "If the input is taken from BEAST rather than BAli-Phy"),
1762 new Arguments.RealOption("limit", "the minimum posterior probability for a node to be annotated"),
1763 new Arguments.StringOption("target", "target_file_name", "specifies a user target tree to be annotated"),
1764 new Arguments.Option("help", "option to print this message"),
1765 new Arguments.StringOption("kalign", "full_path_to_kalign", "specifies full path to the kalign executable file")
1766 });
1767
1768 try {
1769 arguments.parseArguments(args);
1770 } catch (Arguments.ArgumentException ae) {
1771 System.out.println(ae);
1772 printUsage(arguments);
1773 System.exit(1);
1774 }
1775
1776 if (arguments.hasOption("help")) {
1777 printUsage(arguments);
1778 System.exit(0);
1779 }
1780
1781 int heights = KEEP_HEIGHTS;
1782 if (arguments.hasOption("heights")) {
1783 String value = arguments.getStringOption("heights");
1784 if (value.equalsIgnoreCase("mean")) {
1785 heights = MEAN_HEIGHTS;
1786 } else if (value.equalsIgnoreCase("median")) {
1787 heights = MEDIAN_HEIGHTS;
1788 }
1789 }
1790
1791 int burnin = -1;
1792 if (arguments.hasOption("burnin")) {
1793 burnin = arguments.getIntegerOption("burnin");
1794 }
1795
1796 double posteriorLimit = 0.0;
1797 if (arguments.hasOption("limit")) {
1798 posteriorLimit = arguments.getRealOption("limit");
1799 }
1800 boolean beastInput = false;
1801 if(arguments.hasOption("beastInput") && arguments.getStringOption("beastInput").equals("true")) {
1802 SEQ_STRING = "states";
1803 }
1804
1805 int target = MAX_CLADE_CREDIBILITY;
1806 if (arguments.hasOption("target")) {
1807 target = USER_TARGET_TREE;
1808 targetTreeFileName = arguments.getStringOption("target");
1809 }
1810
1811 // String kalignExecutable = "/usr/local/bin/clustalw";
1812 String kalignExecutable = "/usr/local/bin/kalign";
1813 if (arguments.hasOption("kalign")) {
1814 kalignExecutable = arguments.getStringOption("kalign");
1815 }
1816
1817 String[] args2 = arguments.getLeftoverArguments();
1818
1819 if (args2.length > 2) {
1820 System.err.println("Unknown option: " + args2[2]);
1821 System.err.println();
1822 printUsage(arguments);
1823 System.exit(1);
1824 }
1825
1826 if (args2.length == 2) {
1827 targetTreeFileName = null;
1828 inputFileName = args2[0];
1829 outputFileName = args2[1];
1830 } else {
1831
1832 if (inputFileName == null) {
1833 // No input file name was given so throw up a dialog box...
1834 inputFileName = Utils.getLoadFileName("AncestralSequenceAnnotator " + version.getVersionString() + " - Select input file file to analyse");
1835 }
1836 if (outputFileName == null) {
1837 outputFileName = Utils.getSaveFileName("AncestralSequenceAnnotator " + version.getVersionString() + " - Select output file");
1838
1839 }
1840 }
1841 if(inputFileName == null || outputFileName == null) {
1842 System.err.println("Missing input or output file name");
1843 printUsage(arguments);
1844 System.exit(1);
1845
1846 }
1847
1848 new AncestralSequenceAnnotator(burnin,
1849 heights,
1850 posteriorLimit,
1851 target,
1852 targetTreeFileName,
1853 inputFileName,
1854 outputFileName,
1855 kalignExecutable);
1856
1857 System.exit(0);
1858 }
1859
1860 }
1861