Debian Codegraph @

src/dr/evomodel/trace/OldDnDsPerSiteAnalysis.java

raw symbols SCIP
1 /*
2 * OldDnDsPerSiteAnalysis.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.TraceException;
30 import dr.inferencexml.trace.MarginalLikelihoodAnalysisParser;
31 import dr.math.EmpiricalBayesPoissonSmoother;
32 import dr.stats.DiscreteStatistics;
33 import dr.util.Attribute;
34 import dr.util.FileHelpers;
35 import dr.util.HeapSort;
36 import dr.xml.*;
37
38 import java.io.File;
39 import java.io.FileNotFoundException;
40 import java.io.IOException;
41 import java.util.List;
42
43 /**
44 * @author Philippe Lemey
45 * @author Marc A. Suchard
46 */
47 public class OldDnDsPerSiteAnalysis {
48 public static final String DNDS_PERSITE_ANALYSIS = "olddNdSPerSiteAnalysis";
49 public static final String COND_SPERSITE_COLUMNS = "conditionalSperSite";
50 public static final String UNCOND_SPERSITE_COLUMNS = "unconditionalSperSite";
51 public static final String COND_NPERSITE_COLUMNS = "conditionalNperSite";
52 public static final String UNCOND_NPERSITE_COLUMNS = "unconditionalNperSite";
53 //public static final String ALIGNMENT = "alignment";
54
55 OldDnDsPerSiteAnalysis(double[][] sampleSperSite, double[][] unconditionalS,
56 double[][] sampleNperSite, double[][] unconditionalN) {
57
58 numSites = sampleNperSite.length;
59 numSamples = sampleNperSite[0].length;
60
61 allSamples = new double[NUM_VARIABLES][numSites][numSamples];
62 allSamples[COND_S] = sampleSperSite;
63 allSamples[UNCOND_S] = unconditionalS;
64 allSamples[COND_N] = sampleNperSite;
65 allSamples[UNCOND_N] = unconditionalN;
66
67 if (DEBUG) {
68 System.err.println("sumSites = " + numSites);
69 System.err.println("numSamples = " + numSamples);
70 }
71
72 // TODO Assert that all arrays have the same dimensions, else throw exception
73
74 smoothSamples = performSmoothing(allSamples);
75 // collect 'dN'(=N/U_N)', 'dS', 'dN/dS'
76 smoothDnDsSamples = getDnDsSamples(smoothSamples);
77
78 rawMeanStats = computeMeanStats(allSamples);
79 smoothMeanStats = computeMeanStats(smoothSamples);
80 smoothMeanDnDsStats = computeMeanStats(smoothDnDsSamples);
81 smoothHPDDnDsStats = computeHPDStats(smoothDnDsSamples);
82
83 }
84
85 // public double[][] getdSPerSiteSample() {
86 // if (!dNAnddSPerSiteSampleCollected) {
87 // collectDnAndDsPerSite();
88 // }
89 // return dSPerSiteSample;
90 // }
91 //
92 // public double[][] getdNPerSiteSample() {
93 // if (!dNAnddSPerSiteSampleCollected) {
94 // collectDnAndDsPerSite();
95 // }
96 // return dNPerSiteSample;
97 // }
98 //
99 // public double[][] getdNdSRatioPerSiteSample() {
100 // if (!dNAnddSPerSiteSampleCollected) {
101 // collectDnAndDsPerSite();
102 // }
103 // return dNdSRatioPerSiteSample;
104 // }
105 //
106 // public double[][] getEBdNdSratioPerSiteSample() {
107 // if (!dNAnddSPerSiteSampleCollected) {
108 // collectDnAndDsPerSite();
109 // }
110 // return EBdNdSratioPerSiteSample;
111 // }
112
113 private double[][][] getDnDsSamples(double[][][] smoothedSamples) {
114 double[][][] dNdSArray = new double[3][][];
115 //get smooth(S)/smooth(u_S)
116 dNdSArray[0] = get2DArrayRatio(smoothedSamples[0],smoothedSamples[1]);
117 //get smooth(N)/smooth(u_N)
118 dNdSArray[1] = get2DArrayRatio(smoothedSamples[2],smoothedSamples[3]);
119 //get (smooth(N)/smooth(u_N))/(smooth(S)/smooth(u_S))
120 dNdSArray[2] = get2DArrayRatio(dNdSArray[1],dNdSArray[0]);
121 return dNdSArray;
122 }
123
124 private double[][] get2DArrayRatio (double[][] numerator, double[][] denominator) {
125 double[][] returnArray = new double[numerator.length][numerator[0].length];
126 for(int site = 0; site < numerator.length; site ++) {
127 returnArray[site] = get1DArrayRatio(numerator[site],denominator[site]);
128 }
129 return returnArray;
130 }
131
132 private double[] get1DArrayRatio (double[] numerator, double[] denominator) {
133 double[] returnArray = new double[numerator.length];
134 for(int sample = 0; sample < numerator.length; sample ++) {
135 returnArray[sample] = numerator[sample]/denominator[sample];
136 }
137 return returnArray;
138 }
139
140 private double[][] transpose(double[][] in) {
141 double[][] out = new double[in[0].length][in.length];
142 for (int r = 0; r < in.length; r++) {
143 for (int c = 0; c < in[0].length; c++) {
144 out[c][r] = in[r][c];
145 }
146 }
147 return out;
148 }
149
150 private double computeDnDs(double[][][] allSamples, int site, int sample) {
151 return (allSamples[COND_N][site][sample] / allSamples[COND_S][site][sample]) /
152 (allSamples[UNCOND_N][site][sample] / allSamples[UNCOND_S][site][sample]);
153 }
154
155 private double[][][] performSmoothing(double[][][] allSamples) {
156 double[][][] smoothedArray = new double[allSamples.length][][];
157 double[][][] transpose = new double[allSamples.length][][];
158 for (int i = 0; i < allSamples.length; i++) {
159 transpose[i] = transpose(allSamples[i]); // transpose means: [allSamples][site]
160 for (int sample = 0; sample < numSamples; ++sample) {
161 transpose[i][sample] = EmpiricalBayesPoissonSmoother.smooth(transpose[i][sample]);
162 }
163 smoothedArray[i] = transpose(transpose[i]);
164 }
165 return smoothedArray;
166
167 }
168
169 private double computeRatio(double[][][] allSamples, int site, int sample, int numerator, int denominator) {
170 return allSamples[numerator][site][sample] / allSamples[denominator][site][sample];
171 }
172
173 private double[][] computeMeanStats(double[][][] allSamples) {
174 double[][] statistics = new double[allSamples.length][allSamples[0].length];
175 for (int variable = 0; variable < allSamples.length; ++variable) {
176 statistics[variable] = mean(allSamples[variable]);
177 }
178 return statistics;
179 }
180
181 private double[][][] computeHPDStats(double[][][] allSamples) {
182 // we collect mean and 95% HPD boundaries
183 double[][][] statistics = new double[allSamples.length][allSamples[0].length][2];
184 for (int variable = 0; variable < allSamples.length; variable++) {
185 statistics[variable] = getArrayHPDintervals(allSamples[variable]);
186 }
187 return statistics;
188 }
189
190 // private void collectDnAndDsPerSite() {
191 //
192 // // If output arrays not yet constructed, then allocate memory once
193 // if (dSPerSiteSample == null) {
194 // dSPerSiteSample = new double[numSites][numSamples];
195 // dNPerSiteSample = new double[numSites][numSamples];
196 // dNdSRatioPerSiteSample = new double[numSites][numSamples];
197 // EBdNdSratioPerSiteSample = new double[numSites][numSamples];
198 // }
199 //
200 // // Compute statistics on unsmoothed values
201 // for (int site = 0; site < numSites; ++site) {
202 // for (int sample = 0; sample < numSamples; ++sample) {
203 // dSPerSiteSample[site][sample] = computeRatio(allSamples, site, sample, COND_S, UNCOND_S);
204 // dNPerSiteSample[site][sample] = computeRatio(allSamples, site, sample, COND_N, UNCOND_N);
205 // dNdSRatioPerSiteSample[site][sample] = computeDnDs(allSamples, site, sample);
206 // }
207 // }
208 //
209 // if (DEBUG) {
210 // System.err.println("allSamples = " + new Vector(allSamples[0][0]));
211 //// System.exit(-1);
212 // System.err.println("dS = " + new Vector(dSPerSiteSample[0]));
213 // }
214 //
215 // performSmoothing(allSamples);
216 //
217 // // Compute test statistics on smoothed values
218 // for (int site = 0; site < numSites; ++site) {
219 // for (int sample = 0; sample < numSamples; ++sample) {
220 // dNdSRatioPerSiteSample[site][sample] = computeDnDs(allSamples, site, sample);
221 // }
222 // }
223 //
224 // dNAnddSPerSiteSampleCollected = true;
225 // }
226
227
228 // public static double[] smooth(double[] in) {
229 // final int length = in.length;
230 // double[] out = new double[length];
231 // double[] gammaStats = getNegBin(in);
232 // for (int i = 0; i < length; i++) {
233 // out[i] = (in[i] + gammaStats[0]) / (1 + 1 / gammaStats[1]);
234 // }
235 // return out;
236 // }
237 //
238 // private static double[] getNegBin(double[] array) {
239 //// double[] returnArray = new double[2];
240 // double mean = DiscreteStatistics.mean(array);
241 // double variance = DiscreteStatistics.variance(array, mean);
242 // double returnArray0 = (1 - (mean / variance));
243 // double returnArray1 = (mean * ((1 - returnArray0) / returnArray0));
244 // return new double[]{returnArray1, (returnArray0 / (1 - returnArray0))};
245 // }
246 public String output() {
247 StringBuffer sb = new StringBuffer();
248 sb.append("site\tcS\tuS\tcN\tuN\tsmooth(cS)\tsmooth(uS)\tsmooth(cN)\tsmooth(uN)" +
249 "\tsmooth(cS/uS)\tsmooth(cN/uN)\tsmooth((cN/uN)/(cS/uS))\t[hpd]\n");
250 for (int site = 0; site < numSites; site++) {
251 sb.append(site + 1 + "\t" +
252 rawMeanStats[0][site] + "\t" + rawMeanStats[1][site] + "\t" + rawMeanStats[2][site] + "\t" + rawMeanStats[3][site] + "\t" +
253 smoothMeanStats[0][site] + "\t" + smoothMeanStats[1][site] + "\t" + smoothMeanStats[2][site] + "\t" + smoothMeanStats[3][site] + "\t" +
254 smoothMeanDnDsStats[0][site] + "\t" + smoothMeanDnDsStats[1][site] + "\t" + smoothMeanDnDsStats[2][site] + "\t" +
255 "["+smoothHPDDnDsStats[2][site][0] + "," + smoothHPDDnDsStats[2][site][1] + "]");
256 if (smoothHPDDnDsStats[2][site][0] > 1 || smoothHPDDnDsStats[2][site][1] < 1) {
257 sb.append("\t*");
258 }
259 sb.append("\n");
260 }
261 return sb.toString();
262 }
263
264 private static double[][] getArrayHPDintervals(double[][] array) {
265 double[][] returnArray = new double[array.length][2];
266 for (int row = 0; row < array.length; row++) {
267 int counter = 0;
268 for (int col = 0; col < array[0].length; col++) {
269 if (!(((Double) array[row][col]).isNaN())) {
270 counter += 1;
271 }
272 }
273
274 if (counter > 0) {
275 double[] rowNoNaNArray = new double[counter];
276 int index = 0;
277 for (int col = 0; col < array[0].length; col++) {
278 if (!(((Double) array[row][col]).isNaN())) {
279 rowNoNaNArray[index] = array[row][col];
280 index += 1;
281 }
282 }
283 int[] indices = new int[counter];
284 HeapSort.sort(rowNoNaNArray, indices);
285 double hpdBinInterval[] = getHPDInterval(0.95, rowNoNaNArray, indices);
286
287 returnArray[row][0] = hpdBinInterval[0];
288 returnArray[row][1] = hpdBinInterval[1];
289 } else {
290 returnArray[row][0] = Double.NaN;
291 returnArray[row][1] = Double.NaN;
292 }
293
294 }
295
296 return returnArray;
297 }
298
299 private static double[] getHPDInterval(double proportion, double[] array, int[] indices) {
300
301 double returnArray[] = new double[2];
302 double minRange = Double.MAX_VALUE;
303 int hpdIndex = 0;
304
305 int diff = (int) Math.round(proportion * (double) array.length);
306 for (int i = 0; i <= (array.length - diff); i++) {
307 double minValue = array[indices[i]];
308 double maxValue = array[indices[i + diff - 1]];
309 double range = Math.abs(maxValue - minValue);
310 if (range < minRange) {
311 minRange = range;
312 hpdIndex = i;
313 }
314 }
315 returnArray[0] = array[indices[hpdIndex]];
316 returnArray[1] = array[indices[hpdIndex + diff - 1]];
317 return returnArray;
318 }
319
320 private static double[] mean(double[][] x) {
321 double[] returnArray = new double[x.length];
322 //System.out.println("lala");
323 for (int i = 0; i < x.length; i++) {
324 returnArray[i] = DiscreteStatistics.mean(x[i]);
325 //System.out.println((i+1)+"\t"+DiscreteStatistics.mean(x[i]));
326 //System.out.println(DiscreteStatistics.mean(x[i]));
327 }
328 return returnArray;
329 }
330
331 // private static void print2DArray(double[][] array, String name) {
332 // try {
333 // PrintWriter outFile = new PrintWriter(new FileWriter(name), true);
334 //
335 // for (int i = 0; i < array.length; i++) {
336 // for (int j = 0; j < array[0].length; j++) {
337 // outFile.print(array[i][j]+"\t");
338 // }
339 // outFile.println("");
340 // }
341 // outFile.close();
342 //
343 // } catch(IOException io) {
344 // System.err.print("Error writing to file: " + name);
345 // }
346 // }
347
348 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
349
350 public String getParserName() {
351 return DNDS_PERSITE_ANALYSIS;
352 }
353
354 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
355
356 String fileName = xo.getStringAttribute(FileHelpers.FILE_NAME);
357 try {
358
359 File file = new File(fileName);
360 String name = file.getName();
361 String parent = file.getParent();
362
363 if (!file.isAbsolute()) {
364 parent = System.getProperty("user.dir");
365 }
366
367 file = new File(parent, name);
368
369 fileName = file.getAbsolutePath();
370
371 LogFileTraces traces = new LogFileTraces(fileName, file);
372 traces.loadTraces();
373 long maxState = traces.getMaxState();
374
375 // leaving the burnin attribute off will result in 10% being used
376 long burnin = xo.getAttribute(MarginalLikelihoodAnalysisParser.BURN_IN, maxState / 10);
377 //TODO: implement custom burn-in
378
379 if (burnin < 0 || burnin >= maxState) {
380 burnin = maxState / 5;
381 System.out.println("WARNING: Burn-in larger than total number of states - using to 20%");
382 }
383
384 traces.setBurnIn(burnin);
385
386 double samples[][][] = new double[NUM_VARIABLES][][];
387
388 for (int variable = 0; variable < NUM_VARIABLES; ++variable) {
389 XMLObject cxo = xo.getChild(names[variable]);
390 String columnName = cxo.getStringAttribute(Attribute.NAME);
391 int traceStartIndex = -1;
392 int traceEndIndex = -1;
393 boolean traceIndexFound = false;
394
395 for (int i = 0; i < traces.getTraceCount(); i++) {
396 String traceName = traces.getTraceName(i);
397 if (traceName.trim().contains(columnName)) {
398 traceEndIndex = i;
399 if (!traceIndexFound) {
400 traceStartIndex = i;
401 traceIndexFound = true;
402 }
403 }
404 }
405 if (traceStartIndex == -1) {
406 throw new XMLParseException(columnName + " columns can not be found for " + getParserName() + " element.");
407 }
408 int numberOfSites = 1 + (traceEndIndex - traceStartIndex);
409
410 double[][] countPerSite = new double[numberOfSites][];
411 for (int a = 0; a < numberOfSites; a++) {
412 List<Double> values = (List)traces.getValues((a + traceStartIndex));
413 countPerSite[a] = new double[values.size()];
414 for (int i = 0; i < values.size(); i++) {
415 countPerSite[a][i] = values.get(i);
416 }
417 }
418
419 samples[variable] = countPerSite;
420
421 }
422
423 OldDnDsPerSiteAnalysis analysis = new OldDnDsPerSiteAnalysis(samples[COND_S], samples[UNCOND_S],
424 samples[COND_N], samples[UNCOND_N]);
425
426 System.out.println(analysis.output());
427 //TODO: save to file
428
429 return analysis;
430
431 } catch (FileNotFoundException fnfe) {
432 throw new XMLParseException("File '" + fileName + "' can not be opened for " + getParserName() + " element.");
433 } catch (IOException ioe) {
434 throw new XMLParseException(ioe.getMessage());
435 } catch (TraceException e) {
436 throw new XMLParseException(e.getMessage());
437 }
438 }
439
440 //************************************************************************
441 // AbstractXMLObjectParser implementation
442 //************************************************************************
443
444 public String getParserDescription() {
445 return "Performs a trace dN dS analysis.";
446 }
447
448 public Class getReturnType() {
449 return OldDnDsPerSiteAnalysis.class;
450 }
451
452 public XMLSyntaxRule[] getSyntaxRules() {
453 return rules;
454 }
455
456 private final XMLSyntaxRule[] rules = {
457 new StringAttributeRule(FileHelpers.FILE_NAME,
458 "The traceName of a BEAST log file (can not include trees, which should be logged separately"),
459 // new ElementRule(UNCONDITIONAL_S_COLUMN, new XMLSyntaxRule[]{
460 // new StringAttributeRule(Attribute.NAME, "The column name")}),
461 // new ElementRule(UNCONDITIONAL_N_COLUMN, new XMLSyntaxRule[]{
462 // new StringAttributeRule(Attribute.NAME, "The column name")}),
463 };
464 };
465
466 final private int numSites;
467 final private int numSamples;
468
469 private double[][][] allSamples;
470 final private static int NUM_VARIABLES = 4;
471 final private static int COND_S = 0;
472 final private static int UNCOND_S = 1;
473 final private static int COND_N = 2;
474 final private static int UNCOND_N = 3;
475 final private static String[] names = {COND_SPERSITE_COLUMNS, UNCOND_SPERSITE_COLUMNS, COND_NPERSITE_COLUMNS, UNCOND_NPERSITE_COLUMNS};
476 private double[][][] smoothSamples;
477 private double[][][] smoothDnDsSamples;
478
479 private static final boolean DEBUG = true;
480
481 private double[][] rawMeanStats;
482 private double[][] smoothMeanStats;
483 private double[][] smoothMeanDnDsStats;
484 private double[][][] smoothHPDDnDsStats;
485
486 }