Debian Codegraph @

src/dr/evomodel/treelikelihood/utilities/CompleteHistoryLogger.java

raw symbols SCIP
1 /*
2 * CompleteHistoryLogger.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.evomodel.treelikelihood.utilities;
27
28 import dr.evomodel.treelikelihood.MarkovJumpsBeagleTreeLikelihood;
29 import dr.evomodel.treelikelihood.MarkovJumpsTraitProvider;
30 import dr.evolution.tree.NodeRef;
31 import dr.evolution.tree.Tree;
32 import dr.evolution.tree.TreeTrait;
33 import dr.inference.loggers.LogColumn;
34 import dr.inference.loggers.Loggable;
35 import dr.inference.markovjumps.StateHistory;
36 import dr.util.Citable;
37 import dr.util.Citation;
38 import dr.util.CommonCitations;
39
40 import java.awt.*;
41 import java.io.Serializable;
42 import java.util.*;
43 import java.util.List;
44 import java.util.logging.Logger;
45
46 /**
47 * A class to conveniently log a complete state history of a continuous-time Markov chain along a tree
48 * simulated using the Uniformization Method
49 * <p/>
50 * This work is supported by NSF grant 0856099
51 * <p/>
52 * Minin VN and Suchard MA (2008) Counting labeled transitions in continous-time Markov models of evolution.
53 * Journal of Mathematical Biology, 56, 391-412.
54 * <p/>
55 * Rodrigue N, Philippe H and Lartillot N (2006) Uniformization for sampling realizations of Markov processes:
56 * applications to Bayesian implementations of codon substitution models. Bioinformatics, 24, 56-62.
57 * <p/>
58 * Hobolth A and Stone E (2009) Simulation from endpoint-conditioned, continuous-time Markov chains on a finite
59 * state space, with applications to molecular evolution. Annals of Applied Statistics, 3, 1204-1231.
60 *
61 * @author Marc A. Suchard
62 * @author Philippe Lemey
63 * @author Andrew Rambaut
64 */
65 public class CompleteHistoryLogger implements Loggable, Citable {
66
67 public static final String TOTAL_COUNT_NAME = "totalChangeCount";
68 public static final String COMPLETE_HISTORY_NAME = "completeHistory";
69
70 public CompleteHistoryLogger(MarkovJumpsTraitProvider treeLikelihood, HistoryFilter filter, boolean internal, boolean external) {
71 this.tree = treeLikelihood.getTreeModel();
72 this.patternCount = treeLikelihood.getPatternCount();
73 this.internal = internal;
74 this.external = external;
75
76 treeTraitHistory = new TreeTrait[patternCount];
77 for (int site = 0; site < patternCount; ++site) {
78 String traitName = (patternCount == 1) ? MarkovJumpsBeagleTreeLikelihood.HISTORY : MarkovJumpsBeagleTreeLikelihood.HISTORY + "_" + (site + 1);
79 treeTraitHistory[site] = treeLikelihood.getTreeTrait(traitName);
80 if (treeTraitHistory[site] == null) {
81 throw new RuntimeException("Tree '" + treeLikelihood.getId() + "' does not have a complete history trait at site " + (site + 1));
82 }
83 }
84
85 treeTraitCount = treeLikelihood.getTreeTrait(MarkovJumpsBeagleTreeLikelihood.TOTAL_COUNTS);
86
87 if (treeTraitCount == null) {
88 throw new RuntimeException("No sum");
89 }
90
91 if (filter == null) {
92 this.filter = new HistoryFilter.Default();
93 } else {
94 this.filter = filter;
95 Logger.getLogger("dr.app.beagle").info("\tWith filter: " + filter.getDescription() + "\n");
96 }
97
98
99 }
100
101 private static int parseListString(String listString, int currentOffset, List list) {
102
103 while (currentOffset < listString.length()) {
104 // Skip leading separators
105 if (listString.startsWith(",", currentOffset)) {
106 currentOffset++;
107 }
108
109 if (listString.startsWith("{", currentOffset)) {
110 // Need to make a new list
111 List newList = new ArrayList();
112 currentOffset = parseListString(listString, currentOffset + 1, newList);
113 list.add(newList);
114 } else if (listString.startsWith("}", currentOffset)) {
115 // the list is ended
116 return currentOffset + 1;
117 } else {
118 // Parse until next ',' or '}'
119 int nextComma = listString.indexOf(",", currentOffset);
120 int nextClose = listString.indexOf("}", currentOffset);
121 if (nextComma < 0) nextComma = listString.length() - 1;
122 if (nextClose < 0) nextClose = listString.length() - 1;
123 int nextOffset = Math.min(nextComma, nextClose);
124
125 list.add(listString.substring(currentOffset, nextOffset).trim());
126 currentOffset = nextOffset;
127 }
128 }
129 return currentOffset;
130 }
131
132 public static Serializable parseValue(String value) {
133 List nestedParse = new ArrayList<Object>();
134 parseListString(value, 0, nestedParse);
135 return parseValueObject(nestedParse.get(0));
136 }
137
138 private static Serializable parseValueObject(Object objValue) {
139 if (objValue instanceof List) {
140 List newObjList = (List) objValue;
141 Object[] newObjects = new Object[newObjList.size()];
142 for (int i = 0; i < newObjList.size(); ++i) {
143 newObjects[i] = parseValueObject(newObjList.get(i));
144 }
145 return newObjects;
146 }
147
148 String value = (String) objValue;
149 if (value.startsWith("#")) {
150 // I am not sure whether this is a good idea but
151 // I am going to assume that a # denotes an RGB colour
152 try {
153 return Color.decode(value.substring(1));
154 } catch (NumberFormatException nfe1) {
155 // not a colour
156 }
157 }
158
159 if (value.equalsIgnoreCase("TRUE") || value.equalsIgnoreCase("FALSE")) {
160 return Boolean.valueOf(value);
161 }
162
163 // Attempt to format the value as an integer
164 try {
165 return new Integer(value);
166 } catch (NumberFormatException nfe1) {
167 // not an integer
168 }
169
170 // Attempt to format the value as a double
171 try {
172 return new Double(value);
173 } catch (NumberFormatException nfe2) {
174 // not a double
175 }
176
177 // return the trimmed string
178 return value;
179
180 }
181
182
183 public void setFilter(HistoryFilter filter) {
184 this.filter = filter;
185 }
186
187 public LogColumn[] getColumns() {
188
189 LogColumn[] columns = new LogColumn[1 + patternCount];
190 columns[0] = new LogColumn.Abstract(TOTAL_COUNT_NAME) {
191
192 @Override
193 protected String getFormattedValue() {
194 return treeTraitCount.getTraitString(tree, null);
195 }
196 };
197
198 for (int site = 0; site < patternCount; ++site) {
199
200 String name = (patternCount == 0) ? COMPLETE_HISTORY_NAME : COMPLETE_HISTORY_NAME + "_" + (site + 1);
201 final int anonSite = site;
202 columns[1 + site] = new LogColumn.Abstract(name) {
203
204 @Override
205 protected String getFormattedValue() {
206 boolean empty = true;
207 StringBuilder bf = new StringBuilder("{");
208 int count = 0;
209 for (int i = 0; i < tree.getNodeCount(); ++i) {
210 NodeRef node = tree.getNode(i);
211 if (!tree.isRoot(node)) {
212 if((tree.isExternal(node) && external) || (!tree.isExternal(node) && internal)){
213 NodeRef parent = tree.getParent(node);
214 double parentTime = tree.getNodeHeight(parent);
215 double childTime = tree.getNodeHeight(node);
216 double minTime = Math.min(parentTime, childTime);
217 double maxTime = Math.max(parentTime, childTime);
218 String trait = treeTraitHistory[anonSite].getTraitString(tree, node);
219 if (trait != null && trait.compareTo("{}") != 0) {
220 Object[] changes = (Object[]) parseValue(trait);
221 for (int j = 0; j < changes.length; ++j) {
222
223 Object[] change = (Object[]) changes[j];
224 int offset = (change.length == 4) ? 1 : 0;
225 String source = (String) change[1 + offset];
226 String dest = (String) change[2 + offset];
227 double thisTime = (Double) change[0 + offset];
228 if (thisTime < 0.0) {
229 throw new RuntimeException("negative time");
230 }
231 if (thisTime > maxTime || thisTime < minTime) {
232 throw new RuntimeException("Invalid simulation time");
233 }
234
235 // TODO Delegate to Filter(source, dest, thisTime). If filtered then
236 boolean filtered = filter.filter(source, dest, thisTime);
237 if (filtered) {
238 if (!empty) {
239 bf.append(",");
240 }
241 StateHistory.addEventToStringBuilder(bf, source, dest,
242 thisTime, anonSite + 1);
243 count++;
244 empty = false;
245 } else {
246 // Do nothing
247 }
248 }
249 }
250 }
251 }
252 }
253 bf.append("}").append(" ").append(count);
254 return bf.toString();
255 }
256 };
257 }
258 return columns;
259 }
260
261 @Override
262 public Citation.Category getCategory() {
263 return Citation.Category.COUNTING_PROCESSES;
264 }
265
266 @Override
267 public String getDescription() {
268 return "Complete history logger";
269 }
270
271 public List<Citation> getCitations() {
272 return Arrays.asList(//CommonCitations.LEMEY_2012, // TODO Find published Lemey paper
273 CommonCitations.MININ_2008_FAST, CommonCitations.BLOOM_2013_STABILITY);
274 }
275
276 final private Tree tree;
277 final private TreeTrait[] treeTraitHistory;
278 final private TreeTrait treeTraitCount;
279 final private int patternCount;
280 final private boolean internal;
281 final private boolean external;
282
283 private HistoryFilter filter;
284 }