Debian Codegraph @

src/dr/evomodel/trace/CnCsPerSiteAnalysis.java

raw symbols SCIP
1 /*
2 * CnCsPerSiteAnalysis.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.trace;
27
28 import dr.inference.trace.LogFileTraces;
29 import dr.inference.trace.TraceDistribution;
30 import dr.inference.trace.TraceException;
31 import dr.inference.trace.TraceList;
32 import dr.util.*;
33 import dr.xml.*;
34
35 import java.io.File;
36 import java.io.FileNotFoundException;
37 import java.util.*;
38
39 /**
40 * @author Philippe Lemey
41 * @author Marc A. Suchard
42 */
43 public class CnCsPerSiteAnalysis implements Citable {
44 public static final String CNCS_PER_SITE_ANALYSIS = "cNcSPerSiteAnalysis";
45 public static final String BURN_IN = "burnin";
46 public static final String CUTOFF = "cutoff";
47 public static final String INCLUDE_SIGNIFICANT_SYMBOL = "includeSymbol";
48 public static final String INCLUDE_PVALUES = "includePValues";
49 public static final String INCLUDE_SITE_CLASSIFICATION = "includeClassification";
50 public static final String SEPARATOR_STRING = "separator";
51 public static final String INCLUDE_SIMULATION_OUTCOME = "simulationOutcome";
52 public static final String SITE_SIMULATION = "siteSimulation";
53
54 public CnCsPerSiteAnalysis(TraceList traceListN, TraceList traceListS) {
55 this.traceListN = traceListN;
56 this.traceListS = traceListS;
57 this.numSites = (traceListN.getTraceCount())/2;
58 this.format = new OutputFormat();
59
60
61 fieldWidth = 14;
62 firstField = 10;
63 numberFormatter = new NumberFormatter(6);
64 numberFormatter.setPadding(true);
65 numberFormatter.setFieldWidth(fieldWidth);
66 }
67
68 public void setIncludeMeans(boolean b) {
69 format.includeMeans = b;
70 }
71
72 public void setIncludeSignificantSymbol(boolean b) {
73 format.includeSignificantSymbol = b;
74 }
75
76 public void setincludePValues(boolean b) {
77 format.includePValues = b;
78 }
79
80 public void setIncludeSimulationOutcome(boolean b) {
81 format.includeSimulationOutcome = b;
82 }
83
84 public boolean getIncludeSimulationOutcome() {
85 return(format.includeSimulationOutcome);
86 }
87
88 public void setSiteSimulation(String[] d) {
89 format.siteSimulation = d;
90 }
91
92 public void setIncludeSiteClassification(boolean b) {
93 format.includeSiteClassification = b;
94 }
95
96 public void setCutoff(double d) {
97 format.cutoff = d;
98 }
99
100 public void setSeparator(String s) {
101 format.separator = s;
102 }
103
104 private String toStringSite(int index, OutputFormat format) {
105 StringBuilder sb = new StringBuilder();
106 traceListN.analyseTrace(index);
107 traceListN.analyseTrace((traceListN.getTraceCount()/2) + index);
108 traceListS.analyseTrace(index);
109 traceListS.analyseTrace((traceListS.getTraceCount()/2) + index);
110 TraceDistribution distributionCN = traceListN.getDistributionStatistics(index);
111 TraceDistribution distributionCS = traceListS.getDistributionStatistics(index);
112 TraceDistribution distributionUN = traceListN.getDistributionStatistics((traceListN.getTraceCount()/2) + index);
113 TraceDistribution distributionUS = traceListS.getDistributionStatistics((traceListS.getTraceCount()/2) + index);
114 double meanCN = distributionCN.getMean();
115 double meanCS = distributionCS.getMean();
116 double meanUN = distributionUN.getMean();
117 double meanUS = distributionUS.getMean();
118
119 sb.append(numberFormatter.formatToFieldWidth(Integer.toString(index + 1), firstField));
120
121 if (format.includeMeans) {
122 sb.append(format.separator);
123 sb.append(meanCN);
124 sb.append(format.separator);
125 sb.append(meanUN);
126 sb.append(format.separator);
127 sb.append(meanCS);
128 sb.append(format.separator);
129 sb.append(meanUS);
130 }
131
132 boolean isSignificant = false;
133 String classification = "0";
134
135 double negativeProb = 0;
136 if((meanCN+meanCS) == 0){
137 negativeProb = 1;
138 } else {
139 negativeProb = getCumExtBinProb(meanCS,(meanCN+meanCS),(meanUS/(meanUN+meanUS)));
140 }
141
142 if (negativeProb < format.cutoff) {
143 isSignificant = true;
144 classification = "-";
145 }
146
147 double positiveProb = 0;
148 if((meanCN+meanCS) == 0){
149 positiveProb = 1;
150 } else {
151 positiveProb = getCumExtBinProb(meanCN,(meanCN+meanCS),(meanUN/(meanUN+meanUS)));
152 }
153
154 if (positiveProb < format.cutoff) {
155 isSignificant = true;
156 classification = "+";
157 }
158
159 if (format.includePValues) {
160 sb.append(format.separator);
161 sb.append(negativeProb);
162 sb.append(format.separator);
163 sb.append(positiveProb);
164 }
165
166 if (format.includeSiteClassification) {
167 sb.append(format.separator);
168 sb.append(classification);
169 }
170
171
172 if (format.includeSignificantSymbol) {
173 sb.append(format.separator);
174 if (isSignificant) {
175 sb.append("*");
176 } else {
177 // Do nothing?
178 }
179 }
180
181 if (format.includeSimulationOutcome) {
182 sb.append(format.separator);
183 sb.append(format.siteSimulation[index]);
184 sb.append(format.separator);
185 if (format.siteSimulation[index].equals("+") || format.siteSimulation[index].equals("-")) {
186 if (classification.equals(format.siteSimulation[index])){
187 sb.append("TP"); // True Positive
188 } else {
189 sb.append("FN"); // True Negative
190 }
191 } else {
192 if (classification.equals(format.siteSimulation[index])){
193 sb.append("TN"); // True Negative
194 } else {
195 sb.append("FP"); // False Positive
196 }
197 }
198 }
199
200
201 sb.append("\n");
202 return sb.toString();
203 }
204
205 public String header(OutputFormat format) {
206 StringBuilder sb = new StringBuilder();
207 sb.append("# Some information here\n");
208 sb.append("# Please cite: " + Utils.getCitationString(this));
209
210
211 sb.append(numberFormatter.formatToFieldWidth("Site", firstField));
212
213 if (format.includeMeans) {
214 sb.append(format.separator);
215 sb.append(numberFormatter.formatToFieldWidth("Mean CN", fieldWidth));
216 sb.append(numberFormatter.formatToFieldWidth("Mean UN", fieldWidth));
217 sb.append(numberFormatter.formatToFieldWidth("Mean CS", fieldWidth));
218 sb.append(numberFormatter.formatToFieldWidth("Mean US", fieldWidth));
219 }
220
221 if (format.includePValues) {
222 sb.append(format.separator);
223 sb.append(numberFormatter.formatToFieldWidth("Neg_Pvalue", fieldWidth));
224 sb.append(format.separator);
225 sb.append(numberFormatter.formatToFieldWidth("Pos_Pvalue", fieldWidth));
226 }
227
228 if (format.includeSiteClassification) {
229 sb.append(format.separator);
230 sb.append(numberFormatter.formatToFieldWidth("Classification", fieldWidth));
231 }
232
233 if (format.includeSignificantSymbol) {
234 sb.append(format.separator);
235 sb.append(numberFormatter.formatToFieldWidth("Significant", fieldWidth));
236 }
237 if (format.includeSimulationOutcome) {
238 sb.append(format.separator);
239 sb.append(numberFormatter.formatToFieldWidth("Simulated", fieldWidth));
240 sb.append(format.separator);
241 sb.append(numberFormatter.formatToFieldWidth("Evaluation", fieldWidth));
242 }
243 sb.append("\n");
244 return sb.toString();
245 }
246
247 public String toString() {
248
249 StringBuilder sb = new StringBuilder();
250 sb.append(header(format));
251 for (int i = 0; i < numSites; ++i) {
252 sb.append(toStringSite(i, format));
253 }
254
255 return sb.toString();
256 }
257
258 @Override
259 public Citation.Category getCategory() {
260 return Citation.Category.COUNTING_PROCESSES;
261 }
262
263 @Override
264 public String getDescription() {
265 return "Renaissance counting";
266 }
267
268 @Override
269 public List<Citation> getCitations() {
270 return Collections.singletonList(CommonCitations.LEMEY_2012_RENAISSANCE);
271 }
272
273 private class OutputFormat {
274 boolean includeMeans;
275 // boolean includeHPD;
276 // boolean includeSignificanceLevel;
277 boolean includePValues;
278 boolean includeSignificantSymbol;
279 boolean includeSiteClassification;
280 boolean includeSimulationOutcome;
281 String[] siteSimulation;
282 double cutoff;
283 // double proportion;
284 // SignificanceTest test;
285 String separator;
286
287 OutputFormat() {
288 this(true, true, true, true, false, null, 0.05, "\t");
289 }
290
291 OutputFormat(boolean includeMeans,
292 boolean includePValues,
293 boolean includeSignificantSymbol,
294 boolean includeSiteClassification,
295 boolean includeSimulationOutcome,
296 String[] siteSimulation,
297 double cutoff,
298 String separator) {
299 this.includeMeans = includeMeans;
300 this.includePValues = includePValues;
301 this.includeSignificantSymbol = includeSignificantSymbol;
302 this.includeSiteClassification = includeSiteClassification;
303 this.includeSimulationOutcome = includeSimulationOutcome;
304 this.siteSimulation = siteSimulation;
305 this.cutoff = cutoff;
306 this.separator = separator;
307 }
308 }
309
310 private static double getCumExtBinProb(double x, double N, double P){
311 double cumProb = 0;
312 return cumProb;
313 }
314
315 private static double[] toPrimitiveDoubleArray(Double[] array){
316 double[] returnArray = new double[array.length];
317 for(int i = 0; i < array.length; i++ ){
318 returnArray[i] = array[i].doubleValue();
319 }
320 return returnArray;
321 }
322
323 private static String[] parseVariableLengthStringArray(String inString) {
324
325 List<String> returnList = new ArrayList<String>();
326 StringTokenizer st = new StringTokenizer(inString, ",");
327 while (st.hasMoreTokens()) {
328 returnList.add(st.nextToken());
329 }
330
331 if (returnList.size() > 0) {
332 String[] stringArray = new String[returnList.size()];
333 stringArray = returnList.toArray(stringArray);
334 return stringArray;
335 }
336 return null;
337 }
338
339 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
340
341 public String getParserName() {
342 return CNCS_PER_SITE_ANALYSIS;
343 }
344
345 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
346
347 String fileNameCN = xo.getStringAttribute(FileHelpers.FILE_NAME +"CN");
348 String fileNameCS = xo.getStringAttribute(FileHelpers.FILE_NAME +"CS");
349 try {
350
351 File fileCN = new File(fileNameCN);
352 File fileCS = new File(fileNameCS);
353 String nameCN = fileCN.getName();
354 String nameCS = fileCS.getName();
355 String parentCN = fileCN.getParent();
356 String parentCS = fileCS.getParent();
357
358 if (!fileCN.isAbsolute()) {
359 parentCN = System.getProperty("user.dir");
360 }
361 if (!fileCS.isAbsolute()) {
362 parentCS = System.getProperty("user.dir");
363 }
364
365 fileCN = new File(parentCN, nameCN);
366 fileCS = new File(parentCS, nameCS);
367
368 fileNameCS = fileCS.getAbsolutePath();
369
370 LogFileTraces tracesCN = new LogFileTraces(fileNameCN, fileCN);
371 LogFileTraces tracesCS = new LogFileTraces(fileNameCS, fileCS);
372 tracesCN.loadTraces();
373 tracesCS.loadTraces();
374
375 long maxStateCN = tracesCN.getMaxState();
376 long maxStateCS = tracesCS.getMaxState();
377
378 if (maxStateCN != maxStateCS){
379 System.err.println("max states in" + fileNameCN + "and" + fileNameCS + "are not equal");
380 }
381
382 // leaving the burnin attribute off will result in 10% being used
383 long burnin = xo.getAttribute(BURN_IN, maxStateCN / 10);
384 //TODO: implement custom burn-in
385
386 if (burnin < 0 || burnin >= maxStateCN) {
387 burnin = maxStateCN / 5;
388 System.out.println("WARNING: Burn-in larger than total number of states - using 20%");
389 }
390
391 tracesCN.setBurnIn(burnin);
392 tracesCS.setBurnIn(burnin);
393
394 // TODO: Filter traces to include only dNdS columns
395
396 CnCsPerSiteAnalysis analysis = new CnCsPerSiteAnalysis(tracesCN,tracesCS);
397
398 analysis.setCutoff(xo.getAttribute(CUTOFF, 0.05));
399 // analysis.setProportion(xo.getAttribute(PROPORTION, 0.95));
400 analysis.setSeparator(xo.getAttribute(SEPARATOR_STRING, "\t"));
401 analysis.setincludePValues(xo.getAttribute(INCLUDE_PVALUES, true));
402 analysis.setIncludeSignificantSymbol(xo.getAttribute(INCLUDE_SIGNIFICANT_SYMBOL, true));
403 analysis.setIncludeSiteClassification(xo.getAttribute(INCLUDE_SITE_CLASSIFICATION, true));
404 analysis.setIncludeSimulationOutcome(xo.getAttribute(INCLUDE_SIMULATION_OUTCOME, false));
405 if (analysis.getIncludeSimulationOutcome()){
406 String sites = (String)xo.getAttribute(SITE_SIMULATION, "empty");
407 if (sites.equals("empty")){
408 System.err.println("you want simulation evaluation but do not provide a site simulation string??");
409 } else {
410 String[] siteSimulation = parseVariableLengthStringArray(sites);
411 analysis.setSiteSimulation(siteSimulation);
412 }
413 }
414
415
416 return analysis;
417
418 } catch (FileNotFoundException fnfe) {
419 throw new XMLParseException("File '" + fileNameCN + "or" + fileNameCS + "' can not be opened for " + getParserName() + " element.");
420 } catch (java.io.IOException ioe) {
421 throw new XMLParseException(ioe.getMessage());
422 } catch (TraceException e) {
423 throw new XMLParseException(e.getMessage());
424 }
425 }
426
427 //************************************************************************
428 // AbstractXMLObjectParser implementation
429 //************************************************************************
430
431 public String getParserDescription() {
432 return "Performs a trace analysis of N and S counts.";
433 }
434
435 public Class getReturnType() {
436 return CnCsPerSiteAnalysis.class;
437 }
438
439 public XMLSyntaxRule[] getSyntaxRules() {
440 return rules;
441 }
442
443 private final XMLSyntaxRule[] rules = {
444 AttributeRule.newDoubleRule(CUTOFF, true),
445 AttributeRule.newIntegerRule(BURN_IN,true),
446 AttributeRule.newBooleanRule(INCLUDE_PVALUES, true),
447 AttributeRule.newBooleanRule(INCLUDE_SIGNIFICANT_SYMBOL, true),
448 AttributeRule.newBooleanRule(INCLUDE_SITE_CLASSIFICATION, true),
449 AttributeRule.newBooleanRule(INCLUDE_SIMULATION_OUTCOME, true),
450 AttributeRule.newStringRule(SITE_SIMULATION, true),
451 AttributeRule.newStringRule(SEPARATOR_STRING, true),
452 // new StringAttributeRule(FileHelpers.FILE_NAME,
453 // "The traceName of a BEAST log file (can not include trees, which should be logged separately"),
454 // new ElementRule(UNCONDITIONAL_S_COLUMN, new XMLSyntaxRule[]{
455 // new StringAttributeRule(Attribute.NAME, "The column name")}),
456 // new ElementRule(UNCONDITIONAL_N_COLUMN, new XMLSyntaxRule[]{
457 // new StringAttributeRule(Attribute.NAME, "The column name")}),
458 };
459 };
460
461 final private TraceList traceListN;
462 final private TraceList traceListS;
463 final private int numSites;
464 private OutputFormat format;
465
466
467 private int fieldWidth;
468 private int firstField;
469 private NumberFormatter numberFormatter;
470
471
472 }