Debian Codegraph @

src/dr/app/tools/GetNSCountsFromTrees.java

raw symbols SCIP
1 package dr.app.tools;
2
3 import dr.app.beast.BeastVersion;
4 import dr.app.util.Arguments;
5 import dr.app.util.Utils;
6 import dr.evolution.io.Importer;
7 import dr.evolution.io.NexusImporter;
8 import dr.evolution.io.TreeImporter;
9 import dr.evolution.tree.NodeRef;
10 import dr.evolution.tree.Tree;
11 import dr.evolution.tree.TreeUtils;
12 import dr.inference.trace.TraceException;
13 import dr.util.Version;
14
15 import java.io.*;
16 import java.util.*;
17
18 /**
19 * Created by phil on 22/12/2016.
20 */
21 public class GetNSCountsFromTrees {
22
23 //TODO: allow to add parent and descendent node discrete state
24 private final static Version version = new BeastVersion();
25 public static final String BURNIN = "burnin";
26 public static final String totalcN = "N";
27 public static final String totalcS = "S";
28 public static final String totaluN = "b_u_N";
29 public static final String totaluS = "b_u_S";
30 public static final String historyN = "all_N";
31 public static final String historyS = "all_S";
32 public static final String SEP = "\t";
33 public static final String BRANCHINFO = "branchInfo";
34 public static final String[] falseTrue = {"false", "true"};
35 public static final String BRANCHSET = "branchSet";
36 // public static final String CLADETAXA = "cladeTaxa";
37 public static final String INCLUDECLADES = "includeClades";
38 public static final String CLADESTEM = "cladeStem";
39 public static final String EXCLUDECLADESTEM = "excludeCladeStem";
40 public static final String BACKBONETAXA = "backboneTaxa";
41 public static final String ZEROBRANCHES = "zeroBranches";
42 public static final String SUMMARY = "summary";
43 public static final String SITESUM = "siteSum";
44 public static final String CODONSITELIST = "codonSiteList";
45 public static final String MRSD = "mrsd";
46 public static final String EXCLUDECLADES = "excludeClades";
47
48 public GetNSCountsFromTrees(int burnin, String inputFileName, String outputFileName, boolean branchInfo,
49 BranchSet branchSet, List<Set> inclusionSets, boolean cladeStem, boolean zeroBranches, boolean summary,
50 int sites, double mrsd, List<Set> exclusionSets, boolean excludeCladeStems,
51 double[] siteList) throws IOException {
52
53 File inputFile = new File(inputFileName);
54 if (inputFile.isFile()){
55 System.out.println("Analysing tree file " + inputFileName +" with a burn-in of "+burnin+" trees...");
56 } else {
57 progressStream.println("cannot find "+inputFileName);
58 System.exit(0);
59 }
60
61 this.branchInfo = branchInfo;
62 this.zeroBranches = zeroBranches;
63 this.summary = summary;
64 this.mrsd = mrsd;
65 this.cladeStem = cladeStem;
66 this.excludeCladeStems = excludeCladeStems;
67
68 this.sites = sites;
69 if (siteList!=null){
70 this.sites = (siteList.length)*3;
71 progressStream.println("number of sites set based on site list provided");
72 }
73 // resultsStream = System.out;
74
75 if (outputFileName != null) {
76 try {
77 resultsStream = new PrintStream(new File(outputFileName));
78 } catch (IOException e) {
79 progressStream.println("Error opening file: " + outputFileName);
80 System.exit(-1);
81 }
82 } else {
83 resultsStream = new PrintStream(new File(inputFileName+".NSout.txt"));
84 }
85
86 analyze(inputFile, burnin, branchSet, inclusionSets, exclusionSets, siteList);
87
88 }
89
90 private void analyze(File inputFile, int burnin, BranchSet branchSet, List<Set> inclusionSets, List<Set> exclusionSets, double[] siteList){
91
92 if (summary) {
93 resultsStream.print("tree"+SEP+"cN"+SEP+"uN"+SEP+"cS"+SEP+"uS"+SEP+"cNrate"+SEP+"cSrate"+SEP+"dN/dS"+"\n");
94 } else {
95 resultsStream.print("tree"+SEP+"branch"+SEP+"N/S"+SEP+"site"+SEP+"height/date"+SEP+"fromState"+SEP+"toState");
96 if (branchInfo) {
97 resultsStream.print(SEP + "branchLength" + SEP + "branchCN/S" + SEP + "branchUN/S" + "\n");
98 } else {
99 resultsStream.print("\n");
100 }
101 }
102
103 int totalTrees = 10000;
104 int totalStars = 0;
105
106 System.out.println("Reading and analyzing trees (bar assumes 10,000 trees)...");
107 System.out.println("0 25 50 75 100");
108 System.out.println("|--------------|--------------|--------------|--------------|");
109
110 int stepSize = totalTrees / 60;
111 if (stepSize < 1) stepSize = 1;
112
113 int count = 0;
114 int treeUsed = 1;
115
116 try {
117 FileReader fileReader = new FileReader(inputFile);
118 TreeImporter importer = new NexusImporter(fileReader);
119
120 while (importer.hasTree()) {
121 Tree tree = importer.importNextTree();
122
123 if(count>=burnin) {
124 getNSCounts(tree, treeUsed, branchSet, inclusionSets, exclusionSets, siteList);
125 treeUsed ++;
126 }
127 count++;
128 if (totalTrees > 0 && totalTrees % stepSize == 0) {
129 System.out.print("*");
130 totalStars++;
131 if (totalStars % 61 == 0)
132 System.out.print("\n");
133 System.out.flush();
134 }
135 totalTrees++;
136 }
137 System.out.print("\n");
138
139 } catch (Importer.ImportException e) {
140 progressStream.println("Error Parsing Input Tree: " + e.getMessage());
141 } catch (IOException e) {
142 progressStream.println("Error Parsing Input Tree: " + e.getMessage());
143 }
144 }
145
146 private void getNSCounts(Tree tree, int treeUsed, BranchSet branchSet, List<Set> inclusionSets, List<Set> exclusionSets, double[] siteList){
147 int count = 0;
148 double cN = 0;
149 double uN = 0;
150 double cS = 0;
151 double uS = 0;
152 double length = 0;
153
154 for (int x = 0; x < tree.getNodeCount(); x++) {
155 NodeRef node = tree.getNode(x);
156 if (!tree.isRoot(node)){
157 count ++;
158
159 boolean proceed = false;
160 if (branchSet == BranchSet.ALL) {
161 proceed = true;
162 } else if (branchSet == BranchSet.EXT && tree.isExternal(node)) {
163 proceed = true;
164 } else if (branchSet == BranchSet.INT && !tree.isExternal(node)) {
165 proceed = true;
166 } else if (branchSet == BranchSet.BACKBONE) {
167 for (Set inclusionSet: inclusionSets){
168 if (onBackbone(tree, node, inclusionSet)){
169 proceed = true;
170 }
171 }
172 } else if (branchSet == BranchSet.CLADE) {
173 for (Set inclusionSet: inclusionSets){
174 if (inClade(tree, node, inclusionSet, cladeStem)){
175 proceed = true;
176 }
177 }
178 }
179
180 //if the node falls in one of the clades we are excluding, do not proceed.
181 if (proceed && exclusionSets.size()>0){
182 for(Set exclusionSet: exclusionSets){
183 if(inClade(tree, node, exclusionSet, excludeCladeStems)){
184 proceed = false;
185 break;
186 }
187 }
188 }
189
190 if (proceed){
191 double branchLength = tree.getBranchLength(node);
192 length += branchLength;
193 Object totalNObject = tree.getNodeAttribute(node, totalcN);
194 Object totalSObject = tree.getNodeAttribute(node, totalcS);
195 if (totalNObject!=null && totalSObject!=null) {
196 double totalN = (Double) totalNObject;
197 double totalS = (Double) totalSObject;
198 double totaluNObject = (Double) tree.getNodeAttribute(node, totaluN);
199 double totaluSObject = (Double) tree.getNodeAttribute(node, totaluS);
200 if(siteList==null){
201 cN += totalN;
202 cS += totalS;
203 }
204 uN += totaluNObject;
205 uS += totaluSObject;
206 if (totalN > 0) {
207 Object[] allNObject = (Object[]) tree.getNodeAttribute(node, historyN);
208 for (int a = 0; a < allNObject.length; a++) {
209 Object[] singleNObject = (Object[]) allNObject[a];
210 boolean proceedAgain = false;
211 if(siteList==null) {
212 proceedAgain = true;
213 } else {
214 if (inSiteList((Integer)singleNObject[0], siteList)) {
215 proceedAgain = true;
216 cN ++;
217 }
218 }
219 if(!summary && proceedAgain){
220 resultsStream.print(treeUsed + SEP + count + SEP + "N" + SEP);
221 resultsStream.print(singleNObject[0] + SEP);
222 if (mrsd > 0) {
223 resultsStream.print((mrsd - (Double) singleNObject[1]) + SEP);
224 } else {
225 resultsStream.print(singleNObject[1] + SEP);
226 }
227 resultsStream.print(singleNObject[2] + SEP + singleNObject[3] + SEP);
228 if (branchInfo) {
229 resultsStream.print(branchLength + SEP + totalN + SEP + totaluNObject + "\n");
230 } else {
231 resultsStream.print("\n");
232 }
233 }
234
235 }
236 }
237 if (totalS > 0) {
238 Object[] allSObject = (Object[]) tree.getNodeAttribute(node, historyS);
239 for (int a = 0; a < allSObject.length; a++) {
240 Object[] singleSObject = (Object[]) allSObject[a];
241 boolean proceedAgain = false;
242 if(siteList==null) {
243 proceedAgain = true;
244 } else {
245 if (inSiteList((Integer)singleSObject[0], siteList)) {
246 proceedAgain = true;
247 cS ++;
248 }
249 }
250 if(!summary && proceedAgain){
251 resultsStream.print(treeUsed + SEP + count + SEP + "S" + SEP);
252 resultsStream.print(singleSObject[0] + SEP);
253 if (mrsd > 0){
254 resultsStream.print((mrsd - (Double)singleSObject[1]) + SEP);
255 } else {
256 resultsStream.print(singleSObject[1] + SEP);
257 }
258 resultsStream.print(singleSObject[2] + SEP + singleSObject[3] + SEP);
259 if (branchInfo) {
260 resultsStream.print(branchLength + SEP + totalS + SEP + totaluSObject + "\n");
261 } else {
262 resultsStream.print("\n");
263 }
264 }
265 }
266 }
267
268 if ((totalN+totalS)==0){
269 if (zeroBranches) {
270 if (!summary){
271 resultsStream.print(treeUsed + SEP + count + SEP + "NA" + SEP);
272 resultsStream.print("NA" + SEP + "NA" + SEP + "NA" + SEP + "NA" + SEP);
273 if (branchInfo) {
274 resultsStream.print(branchLength + SEP + "NA" + SEP + "NA" + "\n");
275 } else {
276 resultsStream.print("\n");
277 }
278 }
279 } else {
280 //just to be consistent: if branches with zero N and S are ignored, they should also be ignored in the total branch length sum
281 length -= branchLength;
282 }
283 }
284 //tree,branch,S/N,position,oriState,destState,time,branchLength,totalBranchcN,totalcS,totaluN,totaluS,summaryTine
285 }
286 }
287 }
288 }
289 if (summary){
290 resultsStream.print(treeUsed + SEP + cN + SEP + uN + SEP + cS + SEP + uS
291 + SEP + cN/(length*sites) + SEP + cS/(length*sites) + SEP + (cN/uN)/(cS/uS)+"\n");
292 }
293 }
294
295
296 private boolean inSiteList(Integer site, double[] siteList){
297 boolean returnBoolean = false;
298 for (double siteInList : siteList){
299 if (site==siteInList){
300 returnBoolean = true;
301 break;
302 }
303 }
304 return returnBoolean;
305 }
306
307 private static Set getTargetSet(String x) {
308 Set targetSet = new HashSet();
309 try {
310 BufferedReader reader = new BufferedReader(new FileReader(x));
311 try {
312 String line = reader.readLine().trim();
313 while (line != null && !line.equals("")) {
314 targetSet.add(line);
315 line = reader.readLine();
316 if (line != null) line = line.trim();
317 }
318 }
319 catch (IOException io) {
320 progressStream.println("Error reading " + x);
321 }
322 }
323 catch (FileNotFoundException a) {
324 progressStream.println("Error finding " + x);
325 }
326 return targetSet;
327 }
328
329 private static boolean onBackbone(Tree tree, NodeRef node, Set targetSet) {
330
331 if (tree.isExternal(node)) return false;
332
333 Set leafSet = TreeUtils.getDescendantLeaves(tree, node);
334 int size = leafSet.size();
335
336 leafSet.retainAll(targetSet);
337
338 if (leafSet.size() > 0) {
339
340 // if all leaves below are in target then check just above.
341 if (leafSet.size() == size) {
342
343 Set superLeafSet = TreeUtils.getDescendantLeaves(tree, tree.getParent(node));
344 superLeafSet.removeAll(targetSet);
345
346 // the branch is on ancestral path if the super tree has some non-targets in it
347 return (superLeafSet.size() > 0);
348
349 } else return true;
350
351 } else return false;
352 }
353
354 private static boolean inClade(Tree tree, NodeRef node, Set targetSet, boolean includeStem) {
355
356 Set leafSet = TreeUtils.getDescendantLeaves(tree, node);
357
358 leafSet.removeAll(targetSet);
359
360 if (leafSet.size() == 0){
361
362 if (includeStem){
363 return true;
364 } else {
365 Set parentLeafSet = TreeUtils.getDescendantLeaves(tree, tree.getParent(node));
366 parentLeafSet.removeAll(targetSet);
367 if (parentLeafSet.size() == 0){
368 return true;
369 } else {
370 return false;
371 }
372 }
373 } else {
374 return false;
375 }
376 }
377
378 private boolean branchInfo;
379 private boolean zeroBranches;
380 private boolean summary;
381 private int sites;
382 private double mrsd;
383 private boolean cladeStem;
384 private boolean excludeCladeStems;
385 private static PrintStream progressStream = System.err;
386 private PrintStream resultsStream;
387
388 enum BranchSet {
389 ALL,
390 INT,
391 EXT,
392 BACKBONE,
393 CLADE
394 }
395
396 private static String[] parseVariableLengthStringArray(String inString) {
397
398 List<String> returnList = new ArrayList<String>();
399 StringTokenizer st = new StringTokenizer(inString, ",");
400 while (st.hasMoreTokens()) {
401 returnList.add(st.nextToken());
402 }
403
404 if (returnList.size() > 0) {
405 String[] stringArray = new String[returnList.size()];
406 stringArray = returnList.toArray(stringArray);
407 return stringArray;
408 }
409 return null;
410 }
411
412 public static double[] parseVariableLengthDoubleArray(String inString) {
413
414 List<Double> returnList = new ArrayList<Double>();
415 StringTokenizer st = new StringTokenizer(inString, ",");
416 while (st.hasMoreTokens()) {
417 returnList.add(Double.parseDouble(st.nextToken()));
418 }
419
420 if (returnList.size() > 0) {
421 double[] doubleArray = new double[returnList.size()];
422 for (int i = 0; i < doubleArray.length; i++)
423 doubleArray[i] = returnList.get(i);
424
425 return doubleArray;
426 }
427 return null;
428 }
429
430 public static void centreLine(String line, int pageWidth) {
431 int n = pageWidth - line.length();
432 int n1 = n / 2;
433 for (int i = 0; i < n1; i++) {
434 System.out.print(" ");
435 }
436 System.out.println(line);
437 }
438
439 public static void printUsage(Arguments arguments) {
440 //arguments.printUsage("loganalyser", "[-burnin <burnin>] [-short][-hpd] [-std] [<input-file-name> [<output-file-name>]]");
441 arguments.printUsage("GetNSCountsFromTrees", "[-burnin <burnin>][<input-file-name> [<output-file-name>]]");
442 progressStream.println();
443 progressStream.println(" Example: GetNSCountsFromTrees -burnin 10000 trees.log out.txt");
444 progressStream.println();
445
446 }
447
448 public static void printTitle() {
449 System.out.println();
450 centreLine("GetNSCountsFromTrees " + version.getVersionString() + ", " + version.getDateString(), 60);
451 centreLine("MCMC Output analysis", 60);
452 centreLine("by", 60);
453 centreLine("Philippe Lemey and Marc Suchard", 60);
454 System.out.println();
455 centreLine("Department of Immunology and Microbiology", 60);
456 centreLine("KU Leuven -- University of Leuven", 60);
457 centreLine("[email protected]", 60);
458 System.out.println();
459 centreLine("Department of Biomathematics", 60);
460 centreLine("University of Califormia, Los Angeles", 60);
461 centreLine("[email protected]", 60);
462 System.out.println();
463 System.out.println();
464 }
465
466 //Main method
467 public static void main(String[] args) throws IOException, TraceException {
468
469 printTitle();
470
471 Arguments arguments = new Arguments(
472 new Arguments.Option[]{
473 new Arguments.IntegerOption(BURNIN, "the number of states to be considered as 'burn-in' [default = 0]"),
474 new Arguments.StringOption(BRANCHINFO, falseTrue, false, "include a summary for the root [default=off]"),
475 new Arguments.StringOption(BRANCHSET, TimeSlicer.enumNamesToStringArray(BranchSet.values()), false,
476 "branch set [default = all]"),
477 // new Arguments.StringOption(CLADETAXA, "clade taxa file", "specifies a file with taxa that define the clade"),
478 new Arguments.StringOption(INCLUDECLADES, "clade exclusion files", "specifies files with taxa that define clades to be excluded"),
479 new Arguments.StringOption(CLADESTEM, falseTrue, false, "include clade stem [default=false]"),
480 new Arguments.StringOption(EXCLUDECLADESTEM, falseTrue, true, "include clade stem in the exclusion [default=true]"),
481 new Arguments.StringOption(BACKBONETAXA, "Backbone taxa file", "specifies a file with taxa that define the backbone"),
482 new Arguments.StringOption(ZEROBRANCHES, falseTrue, true, "include branches with 0 N and S subtitutions [default=included]"),
483 new Arguments.StringOption(SUMMARY, falseTrue, true, "provide a summary of the N and S counts per tree [default=detailed output]"),
484 new Arguments.RealOption(MRSD, "specifies the most recent sampling data in fractional years to rescale time [default=0]"),
485 new Arguments.StringOption(EXCLUDECLADES, "clade exclusion files", "specifies files with taxa that define clades to be excluded"),
486 new Arguments.IntegerOption(SITESUM, "the number of nucleotide sites to summarize rates in per site per time unit [default = 1]"),
487 new Arguments.StringOption(CODONSITELIST, "list of sites", "sites for which the summary is restricted to"),
488 new Arguments.Option("help", "option to print this message")
489 });
490
491 try {
492 arguments.parseArguments(args);
493 } catch (Arguments.ArgumentException ae) {
494 System.out.println(ae);
495 printUsage(arguments);
496 System.exit(1);
497 }
498
499 if (arguments.hasOption("help")) {
500 printUsage(arguments);
501 System.exit(0);
502 }
503
504 int burnin = -1;
505 if (arguments.hasOption(BURNIN)) {
506 burnin = arguments.getIntegerOption(BURNIN);
507 // System.err.println("Ignoring a burnin of " + burnin + " trees.");
508 }
509
510 boolean branchInfo = false;
511 String infoString = arguments.getStringOption(BRANCHINFO);
512 if (infoString != null && infoString.compareToIgnoreCase("true") == 0) {
513 branchInfo = true;
514 }
515
516 BranchSet set = BranchSet.ALL;
517 String branch = arguments.getStringOption(BRANCHSET);
518 List<Set> inclusionSets = new ArrayList();
519 if (branch != null) {
520 set = BranchSet.valueOf(branch.toUpperCase());
521 progressStream.println("Using the branch set: " + set.name());
522 }
523 if (set == set.BACKBONE) {
524 if (arguments.hasOption(BACKBONETAXA)) {
525 String[] fileList = parseVariableLengthStringArray(arguments.getStringOption(BACKBONETAXA));
526 for (String singleSet: fileList){
527 inclusionSets.add(getTargetSet(singleSet));
528 progressStream.println("getting target set for backbone inclusion: "+singleSet);
529 }
530 } else {
531 progressStream.println("you want to get summaries for (a) backbone(s), but no files with taxa to define it are provided??");
532 }
533 }
534 if (set == set.CLADE) {
535 // if (arguments.hasOption(CLADETAXA)) {
536 // taxaSet = getTargetSet(arguments.getStringOption(CLADETAXA));
537 // } else {
538 // progressStream.println("you want to get summaries for a clade, but have no taxa to define it??");
539 // }
540
541 if (arguments.hasOption(INCLUDECLADES)) {
542 String[] fileList = parseVariableLengthStringArray(arguments.getStringOption(INCLUDECLADES));
543 for (String singleSet: fileList){
544 inclusionSets.add(getTargetSet(singleSet));
545 progressStream.println("getting target set for clade inclusion: "+singleSet);
546 }
547 } else {
548 progressStream.println("you want to get summaries for one or more clades, but no files with taxa to define it are provided??");
549 }
550 }
551
552 boolean cladeStem = false;
553 String cladeStemString = arguments.getStringOption(CLADESTEM);
554 if (cladeStemString != null && cladeStemString.compareToIgnoreCase("true") == 0) {
555 cladeStem = true;
556 }
557
558 boolean excludeCladeStems = true;
559 String excludeCladeStemString = arguments.getStringOption(CLADESTEM);
560 if (excludeCladeStemString != null && excludeCladeStemString.compareToIgnoreCase("false") == 0) {
561 excludeCladeStems = false;
562 }
563
564 boolean zeroBranches = true;
565 String zeroBranchString = arguments.getStringOption(ZEROBRANCHES);
566 if (zeroBranchString != null && zeroBranchString.compareToIgnoreCase("false") == 0) {
567 zeroBranches = false;
568 }
569
570 boolean summary = false;
571 String summaryString = arguments.getStringOption(SUMMARY);
572 if (summaryString != null && summaryString.compareToIgnoreCase("true") == 0) {
573 summary = true;
574 }
575
576 int sites = 1;
577 if (arguments.hasOption(SITESUM)) {
578 sites = arguments.getIntegerOption(SITESUM);
579 }
580
581 double mrsd = 0;
582 if (arguments.hasOption(MRSD)) {
583 mrsd = arguments.getRealOption(MRSD);
584 }
585
586 List<Set> exclusionSets = new ArrayList();
587 if (arguments.hasOption(EXCLUDECLADES)) {
588 String[] fileList = parseVariableLengthStringArray(arguments.getStringOption(EXCLUDECLADES));
589 for (String singleSet: fileList){
590 exclusionSets.add(getTargetSet(singleSet));
591 progressStream.println("getting target set for clade exclusion: "+singleSet);
592 }
593 }
594
595 double[] siteList = null;
596 if (arguments.hasOption(CODONSITELIST)) {
597 siteList = parseVariableLengthDoubleArray(arguments.getStringOption(CODONSITELIST));
598 progressStream.println("site list provided: note that dN/dS will not be accurately estimated because the neutral expectation to get dN/dS (uN and uS) is for all sites along a branch.");
599 }
600
601 String inputFileName = null;
602 String outputFileName = null;
603
604 String[] args2 = arguments.getLeftoverArguments();
605
606 if (args2.length > 2) {
607 progressStream.println("Unknown option: " + args2[2]);
608 System.err.println();
609 printUsage(arguments);
610 System.exit(1);
611 }
612
613 if (args2.length > 0) {
614 inputFileName = args2[0];
615 }
616 if (args2.length > 1) {
617 outputFileName = args2[1];
618 }
619
620 if (inputFileName == null) {
621 // No input file name was given so throw up a dialog box...
622 inputFileName = Utils.getLoadFileName("GetNSCountsFromTrees " + version.getVersionString() + " - Select tree file to analyse");
623 }
624
625 if(burnin==-1) {
626 System.err.println("Enter number of trees to burn-in (integer): ");
627 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
628 burnin = Integer.parseInt(br.readLine());
629 }
630
631 new GetNSCountsFromTrees(burnin, inputFileName, outputFileName, branchInfo, set, inclusionSets, cladeStem, zeroBranches, summary, sites, mrsd, exclusionSets, excludeCladeStems, siteList);
632
633 System.exit(0);
634 }
635
636 }