Debian Codegraph @

src/dr/inference/trace/SteppingStoneSamplingAnalysis.java

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