Debian Codegraph @

src/dr/inference/trace/PathSamplingAnalysis.java

raw symbols SCIP
1 /*
2 * PathSamplingAnalysis.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.inference.trace;
27
28 import dr.inferencexml.trace.MarginalLikelihoodAnalysisParser;
29 import dr.util.Attribute;
30 import dr.util.FileHelpers;
31 import dr.xml.*;
32
33 import java.io.BufferedWriter;
34 import java.io.File;
35 import java.io.FileNotFoundException;
36 import java.io.FileWriter;
37 import java.util.*;
38
39 /**
40 * @author Marc A. Suchard
41 * @author Alexander Alekseyenko
42 * @author Guy Baele
43 */
44 public class PathSamplingAnalysis {
45
46 public static final String PATH_SAMPLING_ANALYSIS = "pathSamplingAnalysis";
47 public static final String RESULT_FILE_NAME = "resultsFileName";
48 public static final String LIKELIHOOD_COLUMN = "likelihoodColumn";
49 public static final String THETA_COLUMN = "thetaColumn";
50 public static final String FORMAT = "%5.5g";
51
52 PathSamplingAnalysis(String logLikelihoodName, List<Double> logLikelihoodSample, List<Double> thetaSample) {
53 this.logLikelihoodSample = logLikelihoodSample;
54 this.logLikelihoodName = logLikelihoodName;
55 this.thetaSample = thetaSample;
56 }
57
58 public double getLogBayesFactor() {
59 if (!logBayesFactorCalculated) {
60 calculateBF();
61 }
62 return logBayesFactor;
63 }
64
65 private void calculateBF() {
66
67 // R code from Alex Alekseyenko
68 //
69 // psMLE = function(likelihood, pathParameter){
70 // y=tapply(likelihood,pathParameter,mean)
71 // L = length(y)
72 // midpoints = (y[1:(L-1)] + y[2:L])/2
73 // x = as.double(names(y))
74 // widths = (x[2:L] - x[1:(L-1)])
75 // sum(widths*midpoints)
76 // }
77
78 Map<Double, List<Double>> map = new HashMap<Double, List<Double>>();
79 orderedTheta = new ArrayList<Double>();
80
81 for (int i = 0; i < logLikelihoodSample.size(); i++) {
82 if (!map.containsKey(thetaSample.get(i))) {
83 map.put(thetaSample.get(i), new ArrayList<Double>());
84 orderedTheta.add(thetaSample.get(i));
85 }
86 map.get(thetaSample.get(i)).add(logLikelihoodSample.get(i));
87 }
88
89 Collections.sort(orderedTheta);
90
91 meanLogLikelihood = new ArrayList<Double>();
92 for (double t : orderedTheta) {
93 double totalMean = 0;
94 int lengthMean = 0;
95 List<Double> values = map.get(t);
96 for (double v : values) {
97 totalMean += v;
98 lengthMean++;
99 }
100 meanLogLikelihood.add(totalMean / lengthMean);
101 }
102
103 mlContribution = new ArrayList<Double>();
104
105 logBayesFactor = 0;
106 innerArea = 0;
107 for (int i = 0; i < meanLogLikelihood.size() - 1; i++) {
108 double contribution = (meanLogLikelihood.get(i + 1) + meanLogLikelihood.get(i)) / 2.0 *
109 (orderedTheta.get(i + 1) - orderedTheta.get(i));
110 logBayesFactor += contribution;
111 mlContribution.add(contribution);
112 if (i > 0 && i < (meanLogLikelihood.size() - 1)) {
113 innerArea += (meanLogLikelihood.get(i + 1) + meanLogLikelihood.get(i)) / 2.0 *
114 (orderedTheta.get(i + 1) - orderedTheta.get(i));
115 }
116 }
117 logBayesFactorCalculated = true;
118 }
119
120 public String toString() {
121 double bf = getLogBayesFactor();
122 StringBuffer sb = new StringBuffer();
123 sb.append("PathParameter\tMeanPathLikelihood\tMLContribution\n");
124 for (int i = 0; i < orderedTheta.size(); ++i) {
125 sb.append(String.format(FORMAT, orderedTheta.get(i)));
126 sb.append("\t");
127 sb.append(String.format(FORMAT, meanLogLikelihood.get(i)));
128 sb.append("\t");
129 if (i != (orderedTheta.size()-1)) {
130 sb.append(String.format(FORMAT, mlContribution.get(i)));
131 }
132 sb.append("\n");
133 }
134
135 sb.append("\nlog marginal likelihood (using path sampling) from " + logLikelihoodName + " = " + bf + "\n");
136 sb.append("\nInner area for path parameter in ("
137 + String.format(FORMAT, orderedTheta.get(1)) + ","
138 + String.format(FORMAT, orderedTheta.get(orderedTheta.size() - 2)) + ") = "
139 + String.format(FORMAT, innerArea));
140 sb.append("\n");
141 return sb.toString();
142 }
143
144 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
145
146 public String getParserName() {
147 return PATH_SAMPLING_ANALYSIS;
148 }
149
150 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
151
152 String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
153 String resultFileName = null;
154 if (xo.hasAttribute(RESULT_FILE_NAME)) {
155 resultFileName = xo.getStringAttribute(RESULT_FILE_NAME);
156 }
157 StringTokenizer tokenFileName = new StringTokenizer(fileName);
158 int numberOfFiles = tokenFileName.countTokens();
159 System.out.println(numberOfFiles + " file(s) found with marginal likelihood samples");
160 try {
161
162 String likelihoodName = "";
163 List sampleLogLikelihood = null;
164 List sampleTheta = null;
165
166 for (int j = 0; j < numberOfFiles; j++) {
167
168 File file = new File(tokenFileName.nextToken());
169 String name = file.getName();
170 String parent = file.getParent();
171
172 if (!file.isAbsolute()) {
173 parent = System.getProperty("user.dir");
174 }
175
176 final String fileNamePrefix = System.getProperty("file.name.prefix");
177 final String fileSeparator = System.getProperty("file.separator");
178 if (fileNamePrefix != null) {
179 if (fileNamePrefix.trim().length() == 0 || fileNamePrefix.contains(fileSeparator)) {
180 throw new XMLParseException("The specified file name prefix is illegal.");
181 }
182 file = new File(parent, fileNamePrefix+name);
183 } else {
184 file = new File(parent, name);
185 }
186
187 fileName = file.getAbsolutePath();
188
189 XMLObject cxo = xo.getChild(LIKELIHOOD_COLUMN);
190 likelihoodName = cxo.getStringAttribute(Attribute.NAME);
191
192 cxo = xo.getChild(THETA_COLUMN);
193 String thetaName = cxo.getStringAttribute(Attribute.NAME);
194
195 LogFileTraces traces = new LogFileTraces(fileName, file);
196 traces.loadTraces();
197 long maxState = traces.getMaxState();
198
199 // leaving the burnin attribute off will result in 10% being used
200 long burnin = xo.getAttribute(MarginalLikelihoodAnalysisParser.BURN_IN, maxState / 5);
201
202 if (burnin < 0 || burnin >= maxState) {
203 burnin = maxState / 5;
204 System.out.println("WARNING: Burn-in larger than total number of states - using 20%");
205 }
206
207 burnin = 0;
208
209 traces.setBurnIn(burnin);
210
211 int traceIndexLikelihood = -1;
212 int traceIndexTheta = -1;
213 for (int i = 0; i < traces.getTraceCount(); i++) {
214 String traceName = traces.getTraceName(i);
215 if (traceName.trim().equals(likelihoodName)) {
216 traceIndexLikelihood = i;
217 }
218 if (traceName.trim().equals(thetaName)) {
219 traceIndexTheta = i;
220 }
221 }
222
223 if (traceIndexLikelihood == -1) {
224 throw new XMLParseException("Column '" + likelihoodName + "' can not be found for " + getParserName() + " element.");
225 }
226
227 if (traceIndexTheta == -1) {
228 throw new XMLParseException("Column '" + thetaName + "' can not be found for " + getParserName() + " element.");
229 }
230
231 if (sampleLogLikelihood == null && sampleTheta == null) {
232 sampleLogLikelihood = traces.getValues(traceIndexLikelihood);
233 sampleTheta = traces.getValues(traceIndexTheta);
234 } else {
235 sampleLogLikelihood.addAll(traces.getValues(traceIndexLikelihood));
236 sampleTheta.addAll(traces.getValues(traceIndexTheta));
237 }
238
239 }
240
241 PathSamplingAnalysis analysis = new PathSamplingAnalysis(likelihoodName, sampleLogLikelihood, sampleTheta);
242
243 System.out.println(analysis.toString());
244
245 if (resultFileName != null) {
246 FileWriter fw = new FileWriter(resultFileName, true);
247 BufferedWriter bw = new BufferedWriter(fw);
248 bw.write(analysis.toString());
249 bw.flush();
250 bw.close();
251 }
252
253 return analysis;
254
255 } catch (FileNotFoundException fnfe) {
256 throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
257 } catch (java.io.IOException ioe) {
258 throw new XMLParseException(ioe.getMessage());
259 } catch (TraceException e) {
260 throw new XMLParseException(e.getMessage());
261 }
262 }
263
264 //************************************************************************
265 // AbstractXMLObjectParser implementation
266 //************************************************************************
267
268 public String getParserDescription() {
269 return "Performs a trace analysis.";
270 }
271
272 public Class getReturnType() {
273 return PathSamplingAnalysis.class;
274 }
275
276 public XMLSyntaxRule[] getSyntaxRules() {
277 return rules;
278 }
279
280 private final XMLSyntaxRule[] rules = {
281 new StringAttributeRule(FileHelpers.FILE_NAME,
282 "The traceName of a BEAST log file (can not include trees, which should be logged separately)"),
283 new StringAttributeRule(RESULT_FILE_NAME,
284 "The name of the output file to which the path sampling estimate will be written", true),
285 new ElementRule(THETA_COLUMN, new XMLSyntaxRule[]{
286 new StringAttributeRule(Attribute.NAME, "The column name")}),
287 new ElementRule(LIKELIHOOD_COLUMN, new XMLSyntaxRule[]{
288 new StringAttributeRule(Attribute.NAME, "The column name")}),
289 };
290 };
291
292 private boolean logBayesFactorCalculated = false;
293 private double logBayesFactor;
294 private double innerArea;
295 private final List<Double> logLikelihoodSample;
296 private final List<Double> thetaSample;
297 private List<Double> meanLogLikelihood;
298 private List<Double> mlContribution;
299 private final String logLikelihoodName;
300 List<Double> orderedTheta;
301 }