Debian Codegraph @

src/dr/app/tools/NormaliseMeanTreeRate.java

raw symbols SCIP
1 /*
2 * NormaliseMeanTreeRate.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 import dr.util.Version;
29 import dr.app.beast.BeastVersion;
30 import dr.app.util.Arguments;
31 import dr.app.util.Utils;
32 import dr.inference.trace.TraceException;
33 import dr.inference.model.Parameter;
34 import dr.evolution.io.TreeImporter;
35 import dr.evolution.io.NexusImporter;
36 import dr.evolution.io.Importer;
37 import dr.evolution.tree.Tree;
38 import dr.evolution.tree.NodeRef;
39 import dr.evolution.tree.FlexibleTree;
40 import dr.evomodel.tree.TreeModel;
41 import dr.evomodel.tree.NodeTraitLogger;
42
43 import java.io.*;
44 import java.util.*;
45
46 /**
47 *
48 * Date: 27/08/2009
49 * Time: 16:43:14
50 *
51 * Standalone application, that also contains public methods, for normalising the rates (and the times) of trees
52 * to a have a mean rate value that is specified. This is required when using discretized branch rates. Setting
53 * normaliseMeanRateTo in logTree will trigger the normalisation whenever trees are logged
54 *
55 * @author Wai Lok Sibon Li
56 *
57 */
58 public class NormaliseMeanTreeRate {
59
60 private final static Version version = new BeastVersion();
61
62
63 public NormaliseMeanTreeRate(String inputFileName, String outputFileName, double normaliseMeanRateTo) throws java.io.IOException {
64
65 File parentFile = new File(inputFileName);
66
67 if (parentFile.isFile()) {
68 System.out.println("Analysing tree file: " + inputFileName);
69 } else {
70 System.err.println("File " + inputFileName + " does not exist!");
71 System.exit(0);
72 }
73
74 File outFile = new File(outputFileName);
75 if (outputFileName != null) {
76 FileOutputStream outputStream = new FileOutputStream(outFile);
77 System.setOut(new PrintStream(outputStream));
78 }
79
80 if(!outFile.canWrite()) {
81 System.err.println("Cannot write to file" + outFile.getAbsolutePath());
82 System.exit(0);
83 }
84
85 FileReader fileReader = new FileReader(parentFile);
86 TreeImporter importer = new NexusImporter(fileReader);
87 ArrayList<Tree> treeList = new ArrayList<Tree>();
88 ArrayList<String> treeNames = new ArrayList<String>();
89 try {
90 while (importer.hasTree()) {
91 Tree tree = importer.importNextTree();
92 analyze(tree, normaliseMeanRateTo);
93 treeList.add(tree);
94 treeNames.add(tree.getId());
95 }
96
97 NexusExporter exporter = new NexusExporter(System.out);
98 exporter.setSortedTranslationTable(true);
99 exporter.exportTrees(treeList.toArray(new Tree[treeList.size()]),
100 true, treeNames.toArray(new String[treeNames.size()]));
101
102 } catch (Importer.ImportException e) {
103 System.err.println("Error Parsing Input Tree: " + e.getMessage());
104 return;
105 }
106 }
107
108 /**
109 * Normalises individual trees to the mean rate
110 *
111 * @param tree tree to normalise
112 * @param normaliseMeanRateTo rate to normalise to
113 * if the trace file is in the wrong format or corrupted
114 */
115 public static void analyze(Tree tree, double normaliseMeanRateTo) {
116 double treeRate = 0;
117 double treeTime = 0;
118 for (int i = 0; i < tree.getNodeCount(); i++) {
119 NodeRef node = tree.getNode(i);
120
121 if(tree.getClass().getName().equals("dr.evomodel.tree.TreeModel")) {
122
123 throw new RuntimeException("Does not currently handle TreeModel");
124 }
125
126 if(!tree.isRoot(node)) {
127
128 if(tree.getNodeAttribute(node, "rate") == null) {
129 System.out.println("Tree file does not contain rate information. ");
130 System.setOut(System.out);
131 System.err.println("Tree file does not contain rate information. Program terminated");
132 System.exit(0);
133 }
134 treeRate += tree.getNodeRate(node) * tree.getBranchLength(node);
135 treeTime += tree.getBranchLength(node);
136 }
137 }
138
139 treeRate /= treeTime;
140
141 /* Normalise the rates here */
142 FlexibleTree modifiedTree = (FlexibleTree) tree;
143 for (int i = 0; i < modifiedTree.getNodeCount(); i++) {
144 NodeRef node = modifiedTree.getNode(i);
145 if(!modifiedTree.isRoot(node)) {
146 double nodeRate = normaliseMeanRateTo * modifiedTree.getNodeRate(node) / treeRate;
147 modifiedTree.setNodeAttribute(node, "rate", Double.valueOf(nodeRate));
148 double nodeTime = modifiedTree.getBranchLength(node);
149 nodeTime = nodeTime * treeRate / normaliseMeanRateTo;
150 modifiedTree.setBranchLength(node, nodeTime);
151
152 }
153 }
154 }
155
156 public static void printTitle() {
157 System.out.println();
158 centreLine("NormaliseMeanTreeRate " + version.getVersionString() + ", " + version.getDateString(), 60);
159 centreLine("MCMC Output analysis", 60);
160 centreLine("by", 60);
161 centreLine("Andrew Rambaut and Alexei J. Drummond", 60);
162 System.out.println();
163 centreLine("Institute of Evolutionary Biology", 60);
164 centreLine("University of Edinburgh", 60);
165 centreLine("[email protected]", 60);
166 System.out.println();
167 centreLine("Department of Computer Science", 60);
168 centreLine("University of Auckland", 60);
169 centreLine("[email protected]", 60);
170 System.out.println();
171 System.out.println();
172 }
173
174 public static void centreLine(String line, int pageWidth) {
175 int n = pageWidth - line.length();
176 int n1 = n / 2;
177 for (int i = 0; i < n1; i++) {
178 System.out.print(" ");
179 }
180 System.out.println(line);
181 }
182
183 public static void printUsage(Arguments arguments) {
184
185 arguments.printUsage("normaliseMeanTreeRate", "[-input-file-name <input-file-name>] [-output-file-name <output-file-name>] [-normaliseMeanRateTo <normaliseMeanRateTo>]");
186 System.out.println();
187 System.out.println(" Example: normaliseMeanTreeRate test.trees out.trees 1.0");
188 System.out.println();
189
190 }
191
192 //Main method
193 public static void main(String[] args) throws java.io.IOException, TraceException {
194
195 printTitle();
196
197 Arguments arguments = new Arguments(
198 new Arguments.Option[]{
199 new Arguments.StringOption("input-file-name", "infile", "Input file name"),
200 new Arguments.StringOption("output-file-name", "outfile", "Output file name"),
201 new Arguments.RealOption("normaliseMeanRateTo", "Mean rate we should normalise to"),
202 new Arguments.Option("help", "option to print this message")
203 });
204
205 try {
206 arguments.parseArguments(args);
207 } catch (Arguments.ArgumentException ae) {
208 System.out.println(ae);
209 printUsage(arguments);
210 System.exit(1);
211 }
212
213 if (arguments.hasOption("help")) {
214 printUsage(arguments);
215 System.exit(0);
216 }
217
218 String inputFileName = null;
219 if(arguments.hasOption("input-file-name")) {
220 inputFileName = arguments.getStringOption("input-file-name");
221 }
222
223 String outputFileName = null;
224 if(arguments.hasOption("output-file-name")) {
225 outputFileName = arguments.getStringOption("output-file-name");
226 }
227
228 double normaliseMeanRateTo = Double.NaN;
229 if(arguments.hasOption("normaliseMeanRateTo")) {
230 normaliseMeanRateTo = arguments.getRealOption("normaliseMeanRateTo");
231 }
232
233 if (inputFileName == null) {
234 // No input file name was given so throw up a dialog box...
235 inputFileName = Utils.getLoadFileName("NormaliseMeanTreeRate " + version.getVersionString() + " - Select log file to analyse");
236 }
237
238 if (outputFileName == null) {
239 // No input file name was given so throw up a dialog box...
240 outputFileName = Utils.getSaveFileName("NormaliseMeanTreeRate " + version.getVersionString() + " - Select file to save to");
241 }
242
243 if(Double.isNaN(normaliseMeanRateTo)) {
244 System.out.println("Enter rate value to normalise to: ");
245 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
246 normaliseMeanRateTo = Double.parseDouble(br.readLine());
247 }
248
249
250 new NormaliseMeanTreeRate(inputFileName, outputFileName, normaliseMeanRateTo);
251
252 System.out.println("Please bear in mind that the trees files are unchanged and results may vary slightly from if you ran them internally");
253
254 System.exit(0);
255 }
256
257 }