Debian Codegraph @

src/dr/app/tools/SpeciesDelimitationAnalyser.java

raw symbols SCIP
1 /*
2 * SpeciesDelimitationAnalyser.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.app.tools;
27
28 import dr.app.beast.BeastVersion;
29 import dr.app.util.Arguments;
30 import dr.evolution.io.Importer;
31 import dr.evolution.io.NexusImporter;
32 import dr.evolution.tree.NodeRef;
33 import dr.evolution.tree.Tree;
34 import dr.evolution.util.TaxonList;
35 import dr.evomodel.alloppnet.speciation.BirthDeathCollapseModel;
36 import dr.util.Version;
37
38 import java.io.*;
39 import java.util.*;
40
41 /**
42 * @author Graham Jones
43 * Date: 01/09/2013
44 */
45 public class SpeciesDelimitationAnalyser {
46
47 private final static Version version = new BeastVersion();
48 private ArrayList<Cluster> clusters;
49 private TaxonList taxonList;
50
51 private int burnin;
52 double collapseheight;
53 private double similaritycutoff;
54 private String inputFileName;
55 private String outputFileName;
56
57 private class Cluster {
58 private int count;
59 private int [] partition;
60 private double totalsimilarity;
61 private boolean deleted;
62
63 public Cluster(TaxonList taxonList, Tree tree, double collapseheight) {
64 int nshort = 0;
65 count = 1;
66 partition = new int[taxonList.getTaxonCount()];
67 totalsimilarity = 1.0;
68 deleted = false;
69
70 int nnodes = tree.getNodeCount();
71 for (int n = 0; n < nnodes; n++) {
72 NodeRef nr = tree.getNode(n);
73 boolean collapse;
74 if (tree.isRoot(nr)) {
75 collapse = BirthDeathCollapseModel.belowCollapseHeight(tree.getNodeHeight(nr), collapseheight);
76 } else {
77 NodeRef anc = tree.getParent(nr);
78 collapse = (BirthDeathCollapseModel.belowCollapseHeight(tree.getNodeHeight(nr), collapseheight)
79 && !BirthDeathCollapseModel.belowCollapseHeight(tree.getNodeHeight(anc), collapseheight));
80 }
81 if (collapse) {
82 nshort++;
83 nodeToClade(taxonList, tree, nr, nshort);
84 }
85 }
86 }
87
88
89 double distance(Cluster sd) {
90 double d = 0.0;
91 for (int i = 0; i < partition.length; i++) {
92 for (int j = 0; j < i; j ++) {
93 boolean pair = partition[i] == partition[j];
94 boolean sdpair = sd.partition[i] == sd.partition[j];
95 if (pair != sdpair) {
96 d += 1.0;
97 }
98 }
99 }
100 return d / (partition.length * (partition.length-1.0) / 2.0);
101 }
102
103
104 double similarity(Cluster sd) {
105 return 1.0 - distance(sd);
106 }
107
108
109
110 private void nodeToClade(TaxonList taxonlist, Tree tree, NodeRef nr, int idx) {
111 if (tree.isExternal(nr)) {
112 String id = tree.getNodeTaxon(nr).getId();
113 int i = taxonIdToInt(taxonlist, id);
114 partition[i] = idx;
115 } else {
116 assert 2 == tree.getChildCount(nr);
117 nodeToClade(taxonlist, tree, tree.getChild(nr, 0), idx);
118 nodeToClade(taxonlist, tree, tree.getChild(nr, 1), idx);
119 }
120 }
121
122 int taxonIdToInt(TaxonList taxonList, String id) {
123 int j = -1;
124 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
125 String tid = taxonList.getTaxonId(i);
126 if (id.compareTo(tid) == 0) {
127 assert j < 0;
128 j = i;
129 }
130 }
131 assert j >= 0;
132 return j;
133 }
134 }
135
136
137 SpeciesDelimitationAnalyser(int burnin, double collapseheight, double similaritycutoff, String inputFileName, String outputFileName) {
138 this.burnin = burnin;
139 this.collapseheight = collapseheight;
140 this.similaritycutoff = similaritycutoff;
141 this.inputFileName = inputFileName;
142 this.outputFileName = outputFileName;
143 }
144
145 void readtrees() throws IOException {
146 clusters = new ArrayList<Cluster>(0);
147 int totalTrees;
148 FileReader fileReader = new FileReader(inputFileName);
149 NexusImporter importer = new NexusImporter(fileReader);
150 System.out.println("Reading trees...");
151 try {
152 taxonList = importer.parseTaxaBlock();
153 totalTrees = 0;
154 while (importer.hasTree()) {
155 Tree tree = importer.importNextTree();
156
157 if (totalTrees >= burnin) {
158 Cluster sd = new Cluster(taxonList, tree, collapseheight);
159 clusters.add(sd);
160 }
161
162 if (totalTrees > 0 && (totalTrees % 100 == 0)) {
163 System.out.print("*");
164 System.out.flush();
165 }
166 if (totalTrees > 0 && (totalTrees % 5000 == 0)) {
167 System.out.println(" " + totalTrees);
168 System.out.flush();
169 }
170 totalTrees++;
171 }
172 System.out.println("");
173 } catch (Importer.ImportException e) {
174 System.err.println("Error Parsing Input Tree: " + e.getMessage());
175 return;
176 }
177 fileReader.close();
178 if (totalTrees < 1) {
179 System.err.println("No trees");
180 return;
181 }
182 System.out.println("Total trees read: " + totalTrees);
183 }
184
185
186
187 void countclusterings() {
188 if (burnin > 0) {
189 System.out.println("Ignoring first " + burnin + " trees.");
190 }
191 System.out.println("Counting clusterings... ");
192 for (int i = 0; i < clusters.size(); i++) {
193 if (i > 0 && (i % 100 == 0)) {
194 System.out.print("*");
195 System.out.flush();
196 }
197 if (i > 0 && (i % 5000 == 0)) {
198 System.out.println(" " + i);
199 System.out.flush();
200 }
201
202 for (int j = i+1; j < clusters.size(); j++) {
203 if (clusters.get(j).count > 0) {
204 double simij = clusters.get(i).similarity(clusters.get(j));
205 if (simij == 1.0) {
206 clusters.get(i).count += 1;
207 clusters.get(j).count = 0;
208 clusters.get(j).deleted = true;
209 }
210 if (simij >= similaritycutoff || simij == 1.0) {
211 clusters.get(i).totalsimilarity += simij;
212 }
213 }
214 }
215 }
216 Collections.sort(clusters, CLUSTER_COMPARATOR);
217 }
218
219
220
221 void writeresults() throws IOException {
222 FileWriter fileWriter = new FileWriter(outputFileName);
223
224 fileWriter.write("count fraction similarity nclusters ");
225 for (int i = 0; i < taxonList.getTaxonCount(); i++) {
226 String tstr = taxonList.getTaxonId(i);
227 while (tstr.length() < 4) tstr += " ";
228 fileWriter.write(tstr + " ");
229 }
230 fileWriter.write("\n");
231 for (int i = 0; i < clusters.size(); i++) {
232 Cluster sd = clusters.get(i);
233 if (sd.count > 0) {
234 String countstr = "" + sd.count;
235 while (countstr.length() < 10) countstr += " ";
236 String fracstr = "" + (double)sd.count / (double) clusters.size();
237 while (fracstr.length() < 22) fracstr += " ";
238 String simstr = "" + sd.totalsimilarity;
239 while (simstr.length() < 22) simstr += " ";
240 int clustercount = 0;
241 for (int j = 0; j < sd.partition.length; j ++) {
242 if (sd.partition[j] > clustercount) {
243 clustercount = sd.partition[j];
244 }
245 }
246 String ccstr = "" + clustercount;
247 while (ccstr.length() < 10) ccstr += " ";
248 fileWriter.write(countstr + " " + fracstr + " " + simstr + " " + ccstr + " ");
249 for (int j = 0; j < sd.partition.length; j ++) {
250 String pjstr = "" + sd.partition[j];
251 while (pjstr.length() < 4) { pjstr += " "; }
252 fileWriter.write(pjstr + " ");
253 }
254 fileWriter.write("\n");
255 }
256 }
257 fileWriter.write("\n");
258 fileWriter.close();
259
260 }
261
262
263
264 public static void printTitle() {
265 System.out.println();
266 centreLine("SpeciesDelimitationAnalyser " + version.getVersionString() + ", " + version.getDateString(), 60);
267 centreLine("Finds clusterings of individuals into clusters", 60);
268 centreLine("(ie possible species) from MCMC tree samples", 60);
269 centreLine("by", 60);
270 centreLine("Graham Jones", 60);
271 centreLine("www.indriid.com", 60);
272 System.out.println();
273 System.out.println();
274 }
275
276
277
278 public static void centreLine(String line, int pageWidth) {
279 int n = pageWidth - line.length();
280 int n1 = n / 2;
281 for (int i = 0; i < n1; i++) {
282 System.out.print(" ");
283 }
284 System.out.println(line);
285 }
286
287
288 public static void printUsage(Arguments arguments) {
289
290 arguments.printUsage("SpeciesDelimitationAnalyser", "<input-file-name> <output-file-name>");
291 System.out.println();
292 System.out.println(" Example: SpeciesDelimitationAnalyser treesamples.txt out.txt");
293 System.out.println();
294 }
295
296
297 static final Comparator<Cluster> CLUSTER_COMPARATOR = new Comparator<Cluster>() {
298 public int compare(Cluster a, Cluster b) {
299 if (a.deleted != b.deleted) {
300 return a.deleted ? 1 : -1;
301 }
302 if (b.totalsimilarity != a.totalsimilarity) {
303 return (b.totalsimilarity > a.totalsimilarity) ? 1 : -1;
304 }
305 return 0;
306 }
307 };
308
309
310
311
312 public static void main(String[] args) throws java.io.IOException {
313
314 Locale.setDefault(Locale.US);
315
316 printTitle();
317
318 Arguments arguments = new Arguments(
319 new Arguments.Option[]{
320 new Arguments.IntegerOption("burnin", "the number of states to be considered as 'burn-in' [default = none]"),
321 new Arguments.RealOption("collapseheight", "the height below which nodes get collapsed [default = .001]"),
322 new Arguments.RealOption("simcutoff", "the value above which two clusters are regarded as similar enough to support one another's credibility [default = .9]"),
323 new Arguments.Option("help", "option to print this message")
324 });
325
326 try {
327 arguments.parseArguments(args);
328 } catch (Arguments.ArgumentException ae) {
329 System.out.println(ae);
330 printUsage(arguments);
331 System.exit(1);
332 }
333
334 if (arguments.hasOption("help")) {
335 printUsage(arguments);
336 System.exit(0);
337 }
338
339 int burnin = -1;
340 if (arguments.hasOption("burnin")) {
341 burnin = arguments.getIntegerOption("burnin");
342 }
343 System.out.println();
344
345 double collapseheight = 0.001;
346 if (arguments.hasOption("collapseheight")) {
347 collapseheight = arguments.getRealOption("collapseheight");
348 }
349
350 double similaritycutoff = 0.9;
351 if (arguments.hasOption("simcutoff")) {
352 similaritycutoff = arguments.getRealOption("simcutoff");
353 }
354
355 System.out.println("burnin " + burnin + " collapseheight " + collapseheight + " simcutoff "+ similaritycutoff);
356
357 String[] args2 = arguments.getLeftoverArguments();
358 if (args2.length > 2) {
359 System.err.println("Unknown option: " + args2[2]);
360 System.err.println();
361 printUsage(arguments);
362 System.exit(1);
363 }
364 if (args2.length < 2) {
365 System.err.println("Input filename and outputfilename required");
366 System.err.println();
367 printUsage(arguments);
368 System.exit(1);
369 }
370
371 String inputFileName = args2[0];
372 String outputFileName = args2[1];
373
374 SpeciesDelimitationAnalyser spDA =
375 new SpeciesDelimitationAnalyser(burnin, collapseheight, similaritycutoff, inputFileName, outputFileName);
376 spDA.readtrees();
377 spDA.countclusterings();
378 spDA.writeresults();
379
380 System.exit(0);
381
382 }
383 }