Debian Codegraph @

src/dr/evomodel/trace/DnDsPerSiteAnalysis.java

raw symbols SCIP
1 /*
2 * DnDsPerSiteAnalysis.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.stats.DiscreteStatistics;
33 import dr.util.*;
34 import dr.xml.*;
35
36 import java.io.File;
37 import java.io.FileNotFoundException;
38 import java.util.*;
39
40 /**
41 * @author Philippe Lemey
42 * @author Marc A. Suchard
43 */
44 public class DnDsPerSiteAnalysis implements Citable {
45 public static final String DNDS_PER_SITE_ANALYSIS = "dNdSPerSiteAnalysis";
46 public static final String BURN_IN = "burnin";
47 public static final String CUTOFF = "cutoff";
48 public static final String PROPORTION = "proportion";
49 public static final String INCLUDE_SIGNIFICANT_SYMBOL = "includeSymbol";
50 public static final String INCLUDE_SIGNIFICANCE_LEVEL = "includeLevel";
51 public static final String INCLUDE_SITE_CLASSIFICATION = "includeClassification";
52 public static final String SIGNIFICANCE_TEST = "test";
53 public static final String SEPARATOR_STRING = "separator";
54 public static final String INCLUDE_SIMULATION_OUTCOME = "simulationOutcome";
55 public static final String INCLUDE_HPD = "includeHPD";
56 public static final String INCLUDE_CPD = "includeCPD";
57 public static final String SITE_SIMULATION = "siteSimulation";
58
59 public DnDsPerSiteAnalysis(TraceList traceList) {
60 this.traceList = traceList;
61 this.numSites = traceList.getTraceCount();
62 this.format = new OutputFormat();
63
64
65 fieldWidth = 14;
66 firstField = 10;
67 numberFormatter = new NumberFormatter(6);
68 numberFormatter.setPadding(true);
69 numberFormatter.setFieldWidth(fieldWidth);
70 }
71
72 public void setIncludeMean(boolean b) {
73 format.includeMean = b;
74 }
75
76 public void setIncludeHPD(boolean b) {
77 format.includeHPD = b;
78 }
79
80 public void setIncludeCPD(boolean b) {
81 format.includeCPD = b;
82 }
83
84 public void setIncludeSignificanceLevel(boolean b) {
85 format.includeSignificanceLevel = b;
86 }
87
88 public void setIncludeSignificantSymbol(boolean b) {
89 format.includeSignificantSymbol = b;
90 }
91
92 public void setIncludeSimulationOutcome(boolean b) {
93 format.includeSimulationOutcome = b;
94 }
95
96 public boolean getIncludeSimulationOutcome() {
97 return(format.includeSimulationOutcome);
98 }
99
100 public void setProportion(double d) {
101 format.proportion = d;
102 }
103
104 public void setSiteSimulation(String[] d) {
105 format.siteSimulation = d;
106 }
107
108 public void setIncludeSiteClassification(boolean b) {
109 format.includeSiteClassification = b;
110 }
111
112 public void setCutoff(double d) {
113 format.cutoff = d;
114 }
115
116 public void setSeparator(String s) {
117 format.separator = s;
118 }
119
120 public void setSignificanceTest(SignificanceTest t) {
121 format.test = t;
122 }
123
124 private String toStringSite(int index, OutputFormat format) {
125 StringBuilder sb = new StringBuilder();
126 traceList.analyseTrace(index);
127 TraceDistribution distribution = traceList.getDistributionStatistics(index);
128 sb.append(numberFormatter.formatToFieldWidth(Integer.toString(index + 1), firstField));
129
130 double[] hpd = new double[2];
131 double[] cpd = new double[2];
132
133 if (format.proportion == 0.95){
134 hpd[0] = distribution.getLowerHPD();
135 hpd[1] = distribution.getUpperHPD();
136 cpd[0] = distribution.getLowerCPD();
137 cpd[1] = distribution.getUpperCPD();
138 // this is weird, yes. But we used these 'HPD's/CPDs to obtain the ROC curves for different cut-offs
139 } else if (format.proportion >= 1.0) {
140 hpd[0] = cpd[0] = distribution.getMinimum() - (distribution.getMinimum()*(format.proportion - 1.0));
141 hpd[1] = cpd[1] = distribution.getMaximum() + (distribution.getMaximum()*(format.proportion - 1.0));
142 } else {
143 // distribution does not allow to specify proportion
144 hpd = getCustomHPDInterval(format.proportion,traceList.getValues(index));
145 double[] proportions = new double[]{((1.0-format.proportion)/2.0),(format.proportion+((1.0-format.proportion)/2.0))};
146 cpd = getCustomCPDInterval(proportions,traceList.getValues(index));
147
148 // System.out.println("HPD proportion is "+format.proportion);
149 }
150
151 if (format.includeMean) {
152 sb.append(format.separator);
153 sb.append(numberFormatter.format(distribution.getMean()));
154 }
155 if (format.includeHPD) {
156 sb.append(format.separator);
157 sb.append(numberFormatter.format(hpd[0]));
158 sb.append(format.separator);
159 sb.append(numberFormatter.format(hpd[1]));
160 }
161 if (format.includeCPD) {
162 sb.append(format.separator);
163 sb.append(numberFormatter.format(cpd[0]));
164 sb.append(format.separator);
165 sb.append(numberFormatter.format(cpd[1]));
166 }
167 if (format.includeSignificanceLevel || format.includeSignificantSymbol || format.includeSiteClassification || format.includeSimulationOutcome) {
168 boolean isSignificant = false;
169 String classification = "0";
170 String level;
171 if (format.test == SignificanceTest.NOT_EQUAL_HPD) {
172 if (hpd[0] < format.cutoff && hpd[1] < format.cutoff) {
173 level = numberFormatter.formatToFieldWidth(">"+format.proportion, fieldWidth);
174 isSignificant = true;
175 classification = "-";
176 } else if (hpd[0] > format.cutoff && hpd[1] > format.cutoff) {
177 level = numberFormatter.formatToFieldWidth(">"+format.proportion, fieldWidth);
178 isSignificant = true;
179 classification = "+";
180 } else {
181 level = numberFormatter.formatToFieldWidth("<="+format.proportion, fieldWidth);
182 }
183 } else if(format.test == SignificanceTest.NOT_EQUAL_CPD) {
184 if (cpd[0] < format.cutoff && cpd[1] < format.cutoff) {
185 level = numberFormatter.formatToFieldWidth(">"+format.proportion, fieldWidth);
186 isSignificant = true;
187 classification = "-";
188 } else if (cpd[0] > format.cutoff && cpd[1] > format.cutoff) {
189 level = numberFormatter.formatToFieldWidth(">"+format.proportion, fieldWidth);
190 isSignificant = true;
191 classification = "+";
192 } else {
193 level = numberFormatter.formatToFieldWidth("<="+format.proportion, fieldWidth);
194 }
195 } else {
196 List values = traceList.getValues(index);
197 double levelPosValue = 0.0;
198 double levelNegValue = 0.0;
199 int total = 0;
200 for (Object obj : values) {
201 double d = ((Number) obj).doubleValue();
202 // if ((format.test == SignificanceTest.LESS_THAN && d < format.cutoff) ||
203 // (format.test == SignificanceTest.GREATER_THAN && d > format.cutoff)) {
204 if (d < format.cutoff) {
205 if(format.test == SignificanceTest.LESS_THAN || format.test == SignificanceTest.LESS_OR_GREATER_THAN) {
206 levelNegValue++;
207 }
208 } else if (d > format.cutoff){
209 if (format.test == SignificanceTest.GREATER_THAN || format.test == SignificanceTest.LESS_OR_GREATER_THAN){
210 levelPosValue++;
211 }
212 }
213 total++;
214 }
215 levelPosValue /= total;
216 levelNegValue /= total;
217 if (levelPosValue > format.proportion) {
218 isSignificant = true;
219 classification = "+";
220 } else if (levelNegValue > format.proportion) {
221 isSignificant = true;
222 classification = "-";
223 }
224 if (levelPosValue > levelNegValue) {
225 level = numberFormatter.format(levelPosValue);
226 } else {
227 level = numberFormatter.format(levelNegValue);
228 }
229 }
230
231 if (format.includeSignificanceLevel) {
232 sb.append(format.separator);
233 sb.append(level);
234 }
235
236 if (format.includeSiteClassification) {
237 sb.append(format.separator);
238 sb.append(classification);
239 }
240
241
242 if (format.includeSignificantSymbol) {
243 sb.append(format.separator);
244 if (isSignificant) {
245 sb.append("*");
246 } else {
247 // Do nothing?
248 }
249 }
250
251 if (format.includeSimulationOutcome) {
252 sb.append(format.separator);
253 sb.append(format.siteSimulation[index]);
254 sb.append(format.separator);
255 if (format.siteSimulation[index].equals("+") || format.siteSimulation[index].equals("-")) {
256 if (classification.equals(format.siteSimulation[index])){
257 sb.append("TP"); // True Positive
258 } else {
259 sb.append("FN"); // True Negative
260 }
261 } else {
262 if (classification.equals(format.siteSimulation[index])){
263 sb.append("TN"); // True Negative
264 } else {
265 sb.append("FP"); // False Positive
266 }
267 }
268 }
269 }
270 sb.append("\n");
271 return sb.toString();
272 }
273
274 public String header(OutputFormat format) {
275 StringBuilder sb = new StringBuilder();
276 sb.append("# Some information here\n");
277 sb.append("# Please cite: " + Citable.Utils.getCitationString(this));
278
279
280 sb.append(numberFormatter.formatToFieldWidth("Site", firstField));
281
282 if (format.includeMean) {
283 sb.append(format.separator);
284 sb.append(numberFormatter.formatToFieldWidth("Mean", fieldWidth));
285 }
286
287 if (format.includeHPD) {
288 sb.append(format.separator);
289 sb.append(numberFormatter.formatToFieldWidth("HPD Low", fieldWidth));
290 sb.append(format.separator);
291 sb.append(numberFormatter.formatToFieldWidth("HPD Up", fieldWidth));
292 }
293
294 if (format.includeCPD) {
295 sb.append(format.separator);
296 sb.append(numberFormatter.formatToFieldWidth("CPD Low", fieldWidth));
297 sb.append(format.separator);
298 sb.append(numberFormatter.formatToFieldWidth("CPD Up", fieldWidth));
299 }
300
301 if (format.includeSignificanceLevel) {
302 sb.append(format.separator);
303 sb.append(numberFormatter.formatToFieldWidth("Level", fieldWidth));
304 }
305
306 if (format.includeSiteClassification) {
307 sb.append(format.separator);
308 sb.append(numberFormatter.formatToFieldWidth("Classification", fieldWidth));
309 }
310
311 if (format.includeSignificantSymbol) {
312 sb.append(format.separator);
313 sb.append(numberFormatter.formatToFieldWidth("Significant", fieldWidth));
314 }
315 if (format.includeSimulationOutcome) {
316 sb.append(format.separator);
317 sb.append(numberFormatter.formatToFieldWidth("Simulated", fieldWidth));
318 sb.append(format.separator);
319 sb.append(numberFormatter.formatToFieldWidth("Evaluation", fieldWidth));
320 }
321 sb.append("\n");
322 return sb.toString();
323 }
324
325 public String toString() {
326
327 StringBuilder sb = new StringBuilder();
328 sb.append(header(format));
329 for (int i = 0; i < numSites; ++i) {
330 sb.append(toStringSite(i, format));
331 }
332
333 return sb.toString();
334 }
335
336 @Override
337 public Citation.Category getCategory() {
338 return Citation.Category.COUNTING_PROCESSES;
339 }
340
341 @Override
342 public String getDescription() {
343 return "Renaissance counting";
344 }
345
346 @Override
347 public List<Citation> getCitations() {
348 return Collections.singletonList(CommonCitations.LEMEY_2012_RENAISSANCE);
349 }
350
351 private class OutputFormat {
352 boolean includeMean;
353 boolean includeHPD;
354 boolean includeCPD;
355 boolean includeSignificanceLevel;
356 boolean includeSignificantSymbol;
357 boolean includeSiteClassification;
358 boolean includeSimulationOutcome;
359 String[] siteSimulation;
360 double cutoff;
361 double proportion;
362 SignificanceTest test;
363 String separator;
364
365 OutputFormat() {
366 this(true, false, true, true, true, true, false, null, 1.0, 0.95, SignificanceTest.NOT_EQUAL_CPD, "\t");
367 }
368
369 OutputFormat(boolean includeMean,
370 boolean includeHPD,
371 boolean includeCPD,
372 boolean includeSignificanceLevel,
373 boolean includeSignificantSymbol,
374 boolean includeSiteClassification,
375 boolean includeSimulationOutcome,
376 String[] siteSimulation,
377 double cutoff,
378 double proportion,
379 SignificanceTest test,
380 String separator) {
381 this.includeMean = includeMean;
382 this.includeHPD = includeHPD;
383 this.includeCPD = includeCPD;
384 this.includeSignificanceLevel = includeSignificanceLevel;
385 this.includeSignificantSymbol = includeSignificantSymbol;
386 this.includeSiteClassification = includeSiteClassification;
387 this.includeSimulationOutcome = includeSimulationOutcome;
388 this.siteSimulation = siteSimulation;
389 this.cutoff = cutoff;
390 this.proportion = proportion;
391 this.test = test;
392 this.separator = separator;
393 }
394 }
395
396 public enum SignificanceTest {
397 GREATER_THAN("gt"), //>
398 LESS_THAN("lt"), //<
399 NOT_EQUAL_HPD("ne_HPD"), //!=
400 NOT_EQUAL_CPD("ne_CPD"), //!=
401 LESS_OR_GREATER_THAN("logt"); //<>
402
403 private SignificanceTest(String text) {
404 this.text = text;
405 }
406
407 public String getText() {
408 return text;
409 }
410
411 public static SignificanceTest parseFromString(String text) {
412 for (SignificanceTest test : SignificanceTest.values()) {
413 if (test.getText().compareToIgnoreCase(text) == 0)
414 return test;
415 }
416 return null;
417 }
418
419 private final String text;
420 }
421
422 private static double[] getCustomHPDInterval(double proportion, List list) {
423
424 double returnArray[] = new double[2];
425 int length = list.size();
426 int[] indices = new int[length];
427 Double[] resultObjArray = (Double[]) list.toArray( new Double[0] );
428 double[] result = toPrimitiveDoubleArray(resultObjArray);
429 HeapSort.sort(result, indices);
430 double minRange = Double.MAX_VALUE;
431 int hpdIndex = 0;
432
433 int diff = (int)Math.round(proportion * (double)length);
434
435 for (int i = 0; i <= (length - diff); i++) {
436 double minValue = result[indices[i]];
437 double maxValue = result[indices[i+diff-1]];
438 double range = Math.abs(maxValue - minValue);
439 if (range < minRange) {
440 minRange = range;
441 hpdIndex = i;
442 }
443 }
444 returnArray[0] = result[indices[hpdIndex]];
445 returnArray[1] = result[indices[hpdIndex+diff-1]];
446 return returnArray;
447 }
448
449 private static double[] getCustomCPDInterval(double[] proportions, List list) {
450
451 double returnArray[] = new double[2];
452 int length = list.size();
453 int[] indices = new int[length];
454 Double[] resultObjArray = (Double[]) list.toArray( new Double[0] );
455 double[] result = toPrimitiveDoubleArray(resultObjArray);
456 HeapSort.sort(result, indices);
457
458 returnArray[0] = DiscreteStatistics.quantile(proportions[0], result, indices);
459 returnArray[1] = DiscreteStatistics.quantile(proportions[1], result, indices);
460
461 return returnArray;
462 }
463
464 private static double[] toPrimitiveDoubleArray(Double[] array){
465 double[] returnArray = new double[array.length];
466 for(int i = 0; i < array.length; i++ ){
467 returnArray[i] = array[i].doubleValue();
468 }
469 return returnArray;
470 }
471
472 private static String[] parseVariableLengthStringArray(String inString) {
473
474 List<String> returnList = new ArrayList<String>();
475 StringTokenizer st = new StringTokenizer(inString, ",");
476 while (st.hasMoreTokens()) {
477 returnList.add(st.nextToken());
478 }
479
480 if (returnList.size() > 0) {
481 String[] stringArray = new String[returnList.size()];
482 stringArray = returnList.toArray(stringArray);
483 return stringArray;
484 }
485 return null;
486 }
487
488 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
489
490 public String getParserName() {
491 return DNDS_PER_SITE_ANALYSIS;
492 }
493
494 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
495
496 String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
497 try {
498
499 File file = new File(fileName);
500 String name = file.getName();
501 String parent = file.getParent();
502
503 if (!file.isAbsolute()) {
504 parent = System.getProperty("user.dir");
505 }
506
507 file = new File(parent, name);
508
509 fileName = file.getAbsolutePath();
510
511 LogFileTraces traces = new LogFileTraces(fileName, file);
512 traces.loadTraces();
513 long maxState = traces.getMaxState();
514
515 // leaving the burnin attribute off will result in 10% being used
516 long burnin = xo.getAttribute(BURN_IN, maxState / 10);
517 //TODO: implement custom burn-in
518
519 if (burnin < 0 || burnin >= maxState) {
520 burnin = maxState / 5;
521 System.out.println("WARNING: Burn-in larger than total number of states - using 20%");
522 }
523
524 traces.setBurnIn(burnin);
525
526 // TODO: Filter traces to include only dNdS columns
527
528 DnDsPerSiteAnalysis analysis = new DnDsPerSiteAnalysis(traces);
529
530 analysis.setSignificanceTest(
531 SignificanceTest.parseFromString(
532 xo.getAttribute(SIGNIFICANCE_TEST, SignificanceTest.NOT_EQUAL_CPD.getText())
533 )
534 );
535 analysis.setCutoff(xo.getAttribute(CUTOFF, 1.0));
536 analysis.setProportion(xo.getAttribute(PROPORTION, 0.95));
537 analysis.setSeparator(xo.getAttribute(SEPARATOR_STRING, "\t"));
538 analysis.setIncludeHPD(xo.getAttribute(INCLUDE_HPD, false));
539 analysis.setIncludeCPD(xo.getAttribute(INCLUDE_HPD, true));
540 analysis.setIncludeSignificanceLevel(xo.getAttribute(INCLUDE_SIGNIFICANCE_LEVEL, false));
541 analysis.setIncludeSignificantSymbol(xo.getAttribute(INCLUDE_SIGNIFICANT_SYMBOL, true));
542 analysis.setIncludeSiteClassification(xo.getAttribute(INCLUDE_SITE_CLASSIFICATION, true));
543 analysis.setIncludeSimulationOutcome(xo.getAttribute(INCLUDE_SIMULATION_OUTCOME, false));
544 if (analysis.getIncludeSimulationOutcome()){
545 String sites = (String)xo.getAttribute(SITE_SIMULATION, "empty");
546 if (sites.equals("empty")){
547 System.err.println("you want simulation evaluation but do not provide a site simulation string??");
548 } else {
549 String[] siteSimulation = parseVariableLengthStringArray(sites);
550 analysis.setSiteSimulation(siteSimulation);
551 }
552 }
553
554
555 return analysis;
556
557 } catch (FileNotFoundException fnfe) {
558 throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
559 } catch (java.io.IOException ioe) {
560 throw new XMLParseException(ioe.getMessage());
561 } catch (TraceException e) {
562 throw new XMLParseException(e.getMessage());
563 }
564 }
565
566 //************************************************************************
567 // AbstractXMLObjectParser implementation
568 //************************************************************************
569
570 public String getParserDescription() {
571 return "Performs a trace dN/dS analysis.";
572 }
573
574 public Class getReturnType() {
575 return DnDsPerSiteAnalysis.class;
576 }
577
578 public XMLSyntaxRule[] getSyntaxRules() {
579 return rules;
580 }
581
582 private final XMLSyntaxRule[] rules = {
583 AttributeRule.newDoubleRule(CUTOFF, true),
584 AttributeRule.newDoubleRule(PROPORTION, true),
585 AttributeRule.newIntegerRule(BURN_IN,true),
586 AttributeRule.newBooleanRule(INCLUDE_HPD, true),
587 AttributeRule.newBooleanRule(INCLUDE_CPD, true),
588 AttributeRule.newBooleanRule(INCLUDE_SIGNIFICANT_SYMBOL, true),
589 AttributeRule.newBooleanRule(INCLUDE_SIGNIFICANCE_LEVEL, true),
590 AttributeRule.newBooleanRule(INCLUDE_SITE_CLASSIFICATION, true),
591 AttributeRule.newBooleanRule(INCLUDE_SIMULATION_OUTCOME, true),
592 AttributeRule.newStringRule(SITE_SIMULATION, true),
593 AttributeRule.newStringRule(SIGNIFICANCE_TEST, true),
594 AttributeRule.newStringRule(SEPARATOR_STRING, true),
595 new StringAttributeRule(FileHelpers.FILE_NAME,
596 "The traceName of a BEAST log file (can not include trees, which should be logged separately"),
597 // new ElementRule(UNCONDITIONAL_S_COLUMN, new XMLSyntaxRule[]{
598 // new StringAttributeRule(Attribute.NAME, "The column name")}),
599 // new ElementRule(UNCONDITIONAL_N_COLUMN, new XMLSyntaxRule[]{
600 // new StringAttributeRule(Attribute.NAME, "The column name")}),
601 };
602 };
603
604 final private TraceList traceList;
605 final private int numSites;
606 private OutputFormat format;
607
608
609 private int fieldWidth;
610 private int firstField;
611 private NumberFormatter numberFormatter;
612
613
614 // private String separator = "\t";
615 // final private int numSamples;
616
617 // private double[][][] allSamples;
618 // final private static int NUM_VARIABLES = 4;
619 // final private static int COND_S = 0;
620 // final private static int UNCOND_S = 1;
621 // final private static int COND_N = 2;
622 // final private static int UNCOND_N = 3;
623 // final private static String[] names = {COND_SPERSITE_COLUMNS, UNCOND_SPERSITE_COLUMNS, COND_NPERSITE_COLUMNS, UNCOND_NPERSITE_COLUMNS};
624 // private double[][][] smoothSamples;
625 // private double[][][] smoothDnDsSamples;
626
627 private static final boolean DEBUG = true;
628
629 // private double[][] rawMeanStats;
630 // private double[][] smoothMeanStats;
631 // private double[][] smoothMeanDnDsStats;
632 // private double[][][] smoothHPDDnDsStats;
633
634 }