Debian Codegraph @

src/dr/app/realtime/CheckPointUpdaterApp.java

raw symbols SCIP
1 /*
2 * CheckPointUpdater.java
3 *
4 * Copyright (c) 2002-2017 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.realtime;
27
28 import dr.app.beast.BeastParser;
29 import dr.app.checkpoint.BeastCheckpointer;
30 import dr.app.util.Arguments;
31 import dr.evolution.alignment.PatternList;
32 import dr.evolution.distance.DistanceMatrix;
33 import dr.evolution.distance.F84DistanceMatrix;
34 import dr.evolution.distance.JukesCantorDistanceMatrix;
35 import dr.evolution.util.Taxon;
36 import dr.inference.loggers.Logger;
37 import dr.inference.loggers.MCLogger;
38 import dr.inference.markovchain.MarkovChain;
39 import dr.inference.mcmc.MCMC;
40 import dr.inference.model.Likelihood;
41 import dr.util.Transform;
42 import dr.xml.XMLParseException;
43 import dr.xml.XMLParser;
44 import org.xml.sax.SAXException;
45
46 import javax.xml.parsers.ParserConfigurationException;
47 import java.io.FileNotFoundException;
48 import java.io.FileReader;
49 import java.io.IOException;
50 import java.util.ArrayList;
51 import java.util.Collections;
52 import java.util.Locale;
53 import java.util.Set;
54
55 /**
56 * @author Guy Baele
57 */
58 public class CheckPointUpdaterApp {
59
60 private final boolean ADD_TAXA = true;
61
62 private final boolean VERBOSE = true;
63 private final boolean PARSER_WARNINGS = true;
64 private final boolean STRICT_XML = false;
65
66 public enum UpdateChoice {
67 JC69DISTANCE("JC69Distance", new JukesCantorDistanceMatrix()), F84DISTANCE("F84Distance", new F84DistanceMatrix()), SIMPLE("Simple", new SimpleDistanceMatrix());
68
69 private String name;
70 private DistanceMatrix matrix;
71
72 UpdateChoice(String name, DistanceMatrix matrix) {
73 this.name = name;
74 this.matrix = matrix;
75 }
76
77 public void setPatterns(PatternList patterns) {
78 this.matrix.setPatterns(patterns);
79 }
80
81 public Taxon getClosestTaxon(Taxon taxon) {
82 if (matrix == null) {
83 throw new RuntimeException("Patterns need to be set first.");
84 }
85 int taxonIndex = matrix.getTaxonIndex(taxon);
86 int closestIndex = 0;
87 double minimumDistance = Double.MAX_VALUE;
88 for (int i = 0; i < matrix.getColumnCount(); i++) {
89 if (i != taxonIndex) {
90 if (matrix.getElement(taxonIndex, i) < minimumDistance) {
91 minimumDistance = matrix.getElement(taxonIndex, i);
92 closestIndex = i;
93 }
94 }
95 }
96 return matrix.getTaxon(closestIndex);
97 }
98
99 public Taxon getClosestTaxon(Taxon taxon, ArrayList<Taxon> taxa) {
100 if (matrix == null) {
101 throw new RuntimeException("Patterns need to be set first.");
102 }
103 int taxonIndex = matrix.getTaxonIndex(taxon);
104 int closestIndex = 0;
105 double minimumDistance = Double.MAX_VALUE;
106 for (int i = 0; i < matrix.getColumnCount(); i++) {
107 if (i != taxonIndex) {
108 if ((matrix.getElement(taxonIndex, i) < minimumDistance) && (taxa.contains(matrix.getTaxon(i)))) {
109 minimumDistance = matrix.getElement(taxonIndex, i);
110 closestIndex = i;
111 }
112 }
113 }
114 return matrix.getTaxon(closestIndex);
115 }
116
117 public double getDistance(Taxon taxonOne, Taxon taxonTwo) {
118 System.out.println("taxon 1: " + taxonOne + " (" + matrix.getTaxonIndex(taxonOne) + ")");
119 System.out.println("taxon 2: " + taxonTwo + " (" + matrix.getTaxonIndex(taxonTwo) + ")");
120 return matrix.getElement(matrix.getTaxonIndex(taxonOne), matrix.getTaxonIndex(taxonTwo));
121 }
122
123 public String getName() {
124 return this.name;
125 }
126
127 public DistanceMatrix getMatrix() {
128 return this.matrix;
129 }
130
131 public String toString() {
132 return this.name;
133 }
134 }
135
136 /**
137 * The goal is to modify an existing checkpoint file with additional information and generate a novel checkpoint file.
138 * Running the MCMC chain after parsing the file(s) should not happen.
139 * @param beastXMLFileName
140 */
141 public CheckPointUpdaterApp(String beastXMLFileName, String debugStateFile, UpdateChoice choice) {
142 //no additional parsers, we don't need BEAGLE at the moment just yet
143 XMLParser parser = new BeastParser(new String[]{beastXMLFileName}, null, VERBOSE, PARSER_WARNINGS, STRICT_XML, null);
144 try {
145 FileReader fileReader = new FileReader(beastXMLFileName);
146
147 //Don't run the analysis, so set the argument to false
148 //parser.parse(fileReader, false);
149
150 //get the MCMC object
151 MCMC mcmc = (MCMC) parser.parse(fileReader, MCMC.class);
152 MarkovChain mc = mcmc.getMarkovChain();
153
154 //make sure that no output files (i.e. logs) are being created
155 Logger[] loggers = mcmc.getLoggers();
156 for (int j = 0; j < loggers.length; j++) {
157 ((MCLogger) loggers[j]).setFormatters(Collections.EMPTY_LIST);
158 }
159
160 // Install the checkpointer. This creates a factory that returns
161 // appropriate savers and loaders according to the user's options.
162 // BeastCheckpointer checkpoint = new BeastCheckpointer();
163
164 CheckPointModifier checkpoint = new CheckPointModifier();
165
166 //load the stored checkpoint file
167 //this will/should also copy any trait information present in the checkpoint file
168 //TODO Check if this works for multiple trees (e.g. for multiple partitions)
169 long state = checkpoint.loadState(mc, new double[]{Double.NaN});
170
171 //TODO Check if this can be uncommented again
172 //System.out.println("Pre-checking likelihood values ...");
173 //probably don't need this but it's good to check
174 //double logL = mc.evaluate();
175 //System.out.println("likelihood = " + logL);
176 //mc.getLikelihood().makeDirty();
177 //logL = mc.evaluate();
178 //System.out.println("likelihood = " + logL);
179
180 double logL;
181
182 if (ADD_TAXA) {
183
184 checkpoint.extendLoadState(choice);
185
186 mc.getLikelihood().makeDirty();
187 logL = mc.evaluate();
188 System.out.println("likelihood = " + logL);
189 mc.getLikelihood().makeDirty();
190 logL = mc.evaluate();
191 System.out.println("likelihood = " + logL);
192
193 //TODO Print full compoundLikelihood evaluation
194 Set<Likelihood> likelihoodSet = mc.getLikelihood().getLikelihoodSet();
195 for (Likelihood l : likelihoodSet) {
196 System.out.println(" " + l.getLogLikelihood());
197 }
198
199 }
200
201 checkpoint.saveState(mc, state, logL);
202
203 //TODO .log and .trees files are being created; not necessary here as we're not running an analysis
204
205 fileReader.close();
206
207 } catch (FileNotFoundException fnf) {
208 System.out.println(fnf);
209 } catch (IOException io) {
210 System.out.println(io);
211 io.printStackTrace();
212 } catch (SAXException sax) {
213 System.out.println(sax);
214 } catch (XMLParseException xml) {
215 System.out.println(xml);
216 } catch (ParserConfigurationException pce) {
217 System.out.println(pce);
218 }
219 }
220
221 public static void main(String[] args) throws java.io.IOException {
222
223 // There is a major issue with languages that use the comma as a decimal separator.
224 // To ensure compatibility between programs in the package, enforce the US locale.
225 Locale.setDefault(Locale.US);
226
227 Arguments arguments = new Arguments(
228 new Arguments.Option[]{
229 new Arguments.StringOption("BEAST_XML", "FILENAME", "Specify a BEAST XML file"),
230 new Arguments.StringOption("load_state", "FILENAME", "Specify a filename to load a state from"),
231 new Arguments.StringOption("output_file", "FILENAME", "Specify a filename for the output file"),
232 new Arguments.StringOption("update_choice", "UPDATECHOICE", "Specify a function by which to update the tree"),
233 new Arguments.Option("help", "Print this information and stop")
234 });
235
236 try {
237 arguments.parseArguments(args);
238 } catch (Arguments.ArgumentException ae) {
239 System.out.println();
240 System.out.println(ae.getMessage());
241 System.out.println();
242 //printUsage(arguments);
243 System.exit(1);
244 }
245
246 String inputFile = null;
247
248 if (arguments.hasOption("BEAST_XML")) {
249 inputFile = arguments.getStringOption("BEAST_XML");
250 } else {
251 throw new RuntimeException("No BEAST XML file specified.");
252 }
253
254 String debugStateFile;
255 if (arguments.hasOption("load_state")) {
256 debugStateFile = arguments.getStringOption("load_state");
257 //pass on as argument
258 System.setProperty(BeastCheckpointer.LOAD_STATE_FILE, debugStateFile);
259 } else {
260 throw new RuntimeException("No state file specified.");
261 }
262
263 String choice = "";
264 if (arguments.hasOption("update_choice")) {
265 choice = arguments.getStringOption("update_choice");
266 } else {
267 throw new RuntimeException("Update mechanism needs to be specified.");
268 }
269 UpdateChoice chosen = null;
270 for (UpdateChoice ch : UpdateChoice.values()) {
271 if (choice.equals(ch.getName())) {
272 chosen = ch;
273 break;
274 }
275 }
276 if (chosen == null) {
277 throw new RuntimeException("Incorrect update mechanism specified.");
278 }
279
280 if (arguments.hasOption("output_file")) {
281 String outputStateFile = arguments.getStringOption("output_file");
282 //pass on as argument
283 System.setProperty(BeastCheckpointer.SAVE_STATE_FILE, outputStateFile);
284 } else {
285 throw new RuntimeException("No output file specified.");
286 }
287
288 new CheckPointUpdaterApp(inputFile, debugStateFile, chosen);
289
290 System.exit(0);
291
292 }
293
294 }
295
296