Debian Codegraph @

src/dr/inference/trace/GeneralizedSteppingStoneSamplingAnalysis.java

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