Debian Codegraph @

src/dr/app/beagle/tools/Partition.java

raw symbols SCIP
1 /*
2 * Partition.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.beagle.tools;
27
28 import java.util.LinkedHashMap;
29 import java.util.Map;
30
31 import dr.evomodel.treedatalikelihood.BufferIndexHelper;
32 import org.apache.commons.math.random.MersenneTwister;
33
34 import beagle.Beagle;
35 import beagle.BeagleFactory;
36 import dr.evomodel.branchmodel.BranchModel;
37 import dr.evomodel.siteratemodel.GammaSiteRateModel;
38 import dr.evomodel.substmodel.FrequencyModel;
39 import dr.evomodel.treelikelihood.SubstitutionModelDelegate;
40 import dr.app.bss.Utils;
41 import dr.evolution.datatype.Codons;
42 import dr.evolution.datatype.DataType;
43 import dr.evolution.sequence.Sequence;
44 import dr.evolution.tree.NodeRef;
45 import dr.evolution.util.Taxon;
46 import dr.evomodel.branchratemodel.BranchRateModel;
47 import dr.evomodel.tree.TreeModel;
48 import dr.math.MathUtils;
49
50 /**
51 * @author Filip Bielejec
52 * @version $Id$
53 */
54 public class Partition {
55
56 private static final boolean DEBUG = false;
57
58 // Constructor fields
59 public int from;
60 public int to;
61 public int every;
62 private BranchModel branchModel;
63 private TreeModel treeModel;
64 private GammaSiteRateModel siteRateModel;
65 private BranchRateModel branchRateModel;
66 private FrequencyModel freqModel;
67
68 // Buffer helpers
69 private BufferIndexHelper partialBufferHelper;
70 private BufferIndexHelper scaleBufferHelper;
71 private BufferIndexHelper matrixBufferHelper;
72
73 // Beagle stuff
74 private Beagle beagle;
75 private SubstitutionModelDelegate substitutionModelDelegate;
76
77 // int fields
78 private Integer partitionNumber;
79 private int partitionSiteCount;
80 private int nodeCount;
81 private int tipCount;
82 private int internalNodeCount;
83 private int stateCount;
84 private int compactPartialsCount;
85 private int patternCount;
86 private int siteRateCategoryCount;
87
88 // Sequence fields
89 private LinkedHashMap<Taxon, int[]> alignmentMap;
90 // private LinkedHashMap<NodeRef, int[]> sequencesMap = new LinkedHashMap<NodeRef, int[]>();
91 private DataType dataType;
92 private boolean hasRootSequence = false;
93 private Sequence rootSequence = null;
94 private boolean outputAncestralSequences = false;
95
96 // Random number generation
97 private MersenneTwister random;
98
99 // Annotating trees
100 // private boolean annotateTree = true;
101
102 public Partition(TreeModel treeModel, //
103 BranchModel branchModel, //
104 GammaSiteRateModel siteModel, //
105 BranchRateModel branchRateModel, //
106 FrequencyModel freqModel, //
107 int from, //
108 int to, //
109 int every, //
110 DataType dType
111 ) {
112
113 this.treeModel = treeModel;
114 this.siteRateModel = siteModel;
115 this.freqModel = freqModel;
116 this.branchModel = branchModel;
117 this.branchRateModel = branchRateModel;
118
119 this.from = from;
120 this.to = to;
121 this.every = every;
122
123 if(dType == null) {
124 dataType = freqModel.getDataType();
125 }else{
126 dataType = dType;
127 }
128 partitionSiteCount = getPartitionSiteCount();
129
130 setBufferHelpers();
131 setSubstitutionModelDelegate();
132 loadBeagleInstance();
133
134 alignmentMap = new LinkedHashMap<Taxon, int[]>();
135 random = new MersenneTwister(MathUtils.nextLong());
136
137 }// END: Constructor
138
139 public Partition(TreeModel treeModel, //
140 BranchModel branchModel, //
141 GammaSiteRateModel siteModel, //
142 BranchRateModel branchRateModel, //
143 FrequencyModel freqModel, //
144 int from, //
145 int to, //
146 int every //
147 ){
148 this(treeModel, branchModel, siteModel, branchRateModel, freqModel, from, to, every, null);
149 }
150
151 private void setSubstitutionModelDelegate() {
152 substitutionModelDelegate = new SubstitutionModelDelegate(treeModel,
153 branchModel);
154 }// END: setSubstitutionModelDelegate
155
156 private void setBufferHelpers() {
157
158 nodeCount = treeModel.getNodeCount();
159 matrixBufferHelper = new BufferIndexHelper(nodeCount, 0);
160
161 tipCount = treeModel.getExternalNodeCount();
162 internalNodeCount = treeModel.getInternalNodeCount();
163
164 partialBufferHelper = new BufferIndexHelper(nodeCount, tipCount);
165 scaleBufferHelper = new BufferIndexHelper(internalNodeCount + 1, 0);
166
167 }// END: setBufferHelpers
168
169 public void loadBeagleInstance() {
170
171 compactPartialsCount = tipCount;
172 stateCount = dataType.getStateCount();
173 patternCount = partitionSiteCount;
174 siteRateCategoryCount = siteRateModel.getCategoryCount();
175
176 int[] resourceList = new int[] { 0 };
177 long preferenceFlags = 0;
178 long requirementFlags = 0;
179
180 beagle = BeagleFactory.loadBeagleInstance(tipCount, //
181 partialBufferHelper.getBufferCount(), //
182 compactPartialsCount, //
183 stateCount, //
184 patternCount, //
185 substitutionModelDelegate.getEigenBufferCount(), //
186 substitutionModelDelegate.getMatrixBufferCount(), //
187 siteRateCategoryCount, //
188 scaleBufferHelper.getBufferCount(), //
189 resourceList, //
190 preferenceFlags, //
191 requirementFlags);
192
193 }// END: loadBeagleInstance
194
195 public void simulatePartition() {
196
197 try {
198
199 NodeRef root = treeModel.getRoot();
200
201 // gamma category rates
202 double[] categoryRates = siteRateModel.getCategoryRates();
203 beagle.setCategoryRates(categoryRates);
204
205 // probabilities for gamma category rates
206 double[] categoryProbs = siteRateModel.getCategoryProportions();
207 // beagle.setCategoryWeights(0, categoryProbs);
208
209 // Utils.printArray(categoryRates);
210 // Utils.printArray(categoryProbs);
211
212 int[] category = new int[partitionSiteCount];
213 for (int i = 0; i < partitionSiteCount; i++) {
214
215 category[i] = randomChoicePDF(categoryProbs, partitionNumber,
216 "categories");
217
218 }
219
220 // category = new int[] {1, 0, 0, 0, 0, 1, 0, 1, 0, 0 };
221
222 if(DEBUG){
223 System.out.println("category for each site:");
224 Utils.printArray(category);
225 }//END: DEBUG
226
227 int[] parentSequence = new int[partitionSiteCount];
228
229 // set ancestral sequence for partition if it exists
230 if (hasRootSequence) {
231
232 if (rootSequence.getLength() == partitionSiteCount) {
233
234 parentSequence = sequence2intArray(rootSequence);
235
236 } else if (dataType instanceof Codons && rootSequence.getLength() == 3 * partitionSiteCount) {
237
238 parentSequence = sequence2intArray(rootSequence);
239
240 } else {
241
242 throw new RuntimeException("Ancestral sequence length of "
243 + rootSequence.getLength()
244 + " does not match partition site count of "
245 + partitionSiteCount + ".");
246
247 }
248
249 } else {
250
251 double[] frequencies = freqModel.getFrequencies();
252 for (int i = 0; i < partitionSiteCount; i++) {
253
254 parentSequence[i] = randomChoicePDF(frequencies,
255 partitionNumber, "root");
256
257 }
258
259 }// END:ancestralSequence check
260
261 if (DEBUG) {
262 synchronized (this) {
263 System.out.println();
264 System.out.println("root Sequence:");
265 Utils.printArray(parentSequence);
266 }
267 }//END: DEBUG
268
269 substitutionModelDelegate.updateSubstitutionModels(beagle);
270
271 traverse(root, parentSequence, category);
272
273 if (DEBUG) {
274 synchronized (this) {
275 System.out.println("Simulated alignment:");
276 printSequences();
277 }
278 }//END: DEBUG
279
280 beagle.finalize();
281
282 } catch (Exception e) {
283 e.printStackTrace();
284 } catch (Throwable e) {
285 System.err.println("BeagleException: " + e.getMessage());
286 System.exit(-1);
287 }
288
289 }// END: simulatePartition
290
291 private void traverse(NodeRef node, //
292 int[] parentSequence, //
293 int[] category //
294 ) {
295
296 if (DEBUG) {
297 synchronized (this) {
298 System.out.println();
299 System.out.println("I'm at: " + node.toString());
300 System.out.println();
301 }
302 }//END: DEBUG
303
304 for (int iChild = 0; iChild < treeModel.getChildCount(node); iChild++) {
305
306 NodeRef child = treeModel.getChild(node, iChild);
307 int[] partitionSequence = new int[partitionSiteCount];
308 double[] cProb = new double[stateCount];
309
310 double[][] probabilities = getTransitionProbabilities(child);
311
312 if (DEBUG) {
313 synchronized (this) {
314 System.out.println("Going to child " + iChild + ": " + child.toString());
315 System.out.println("Child finite transition probs matrix:");
316 Utils.print2DArray(probabilities, stateCount);
317 System.out.println();
318 }
319 }// END: DEBUG
320
321 for (int i = 0; i < partitionSiteCount; i++) {
322
323 if (DEBUG) {
324 System.out.println("length of copy: " + stateCount);
325 System.out.println("source length: " + probabilities[category[i]].length);
326 System.out.println("destination length: " + cProb.length);
327 }
328
329 System.arraycopy(probabilities[category[i]], parentSequence[i] * stateCount, cProb, 0, stateCount);
330
331 if (DEBUG) {
332 synchronized (this) {
333 System.out.println("site:" + i);
334 System.out.println("site probs:");
335 Utils.printArray(cProb);
336 }
337 }// END: DEBUG
338
339 partitionSequence[i] = randomChoicePDF(cProb, partitionNumber,
340 "seq");
341
342 }// END: i loop
343
344 if (DEBUG) {
345 synchronized (this) {
346 // partitionSequence = new int[]{1, 3, 2, 3, 0, 1, 0, 1, 0, 2, 2, 0, 1, 3, 3, 3, 0, 1, 2, 1, 3, 1, 1, 1, 1, 3, 0, 0, 3, 2, 3, 2, 3, 2, 1, 2, 1, 3, 2, 3, 3, 0, 2, 2, 3, 2, 3, 2, 3, 1, 2, 0, 2, 1, 3, 2, 3, 1, 1, 1, 1, 0, 2, 3, 1, 0, 2, 1, 2, 1, 3, 0, 0, 0, 0, 0, 2, 0, 2, 3, 1, 0, 1, 3, 0, 2, 1, 2, 1, 3, 0, 0, 3, 2, 2, 0, 1, 0, 0, 3 };
347 System.out.println("Simulated sequence:");
348 Utils.printArray(partitionSequence);
349 }
350 }// END: if DEBUG
351
352 // if(annotateTree) {
353 //
354 // sequencesMap.put(child, partitionSequence);
355 //
356 // }
357
358 if (treeModel.getChildCount(child) == 0) {
359
360 Taxon taxon = treeModel.getNodeTaxon(child);
361 alignmentMap.put(taxon, partitionSequence);
362
363 if (DEBUG) {
364 synchronized (this) {
365 System.out.println("Simulated sequence (translated):");
366 System.out.println(Utils.intArray2Sequence(taxon, partitionSequence, BeagleSequenceSimulator.gapFlag, dataType).getSequenceString());
367 }
368 }// END: DEBUG
369
370 } else {
371
372 if(outputAncestralSequences) {
373
374 alignmentMap.put(new Taxon("internalNodeHeight" + treeModel.getNodeHeight(child)), partitionSequence);
375
376 }
377
378 } // END: tip node check
379
380 traverse(treeModel.getChild(node, iChild), partitionSequence,
381 category);
382
383 }// END: child nodes loop
384
385 }// END: traverse
386
387 private double[][] getTransitionProbabilities(NodeRef node //
388 ) {
389
390 double[][] probabilities = new double[siteRateCategoryCount][stateCount
391 * stateCount];
392
393 int nodeNum = node.getNumber();
394 matrixBufferHelper.flipOffset(nodeNum);
395 int branchIndex = nodeNum;
396
397 double branchRate = branchRateModel.getBranchRate(treeModel, node);
398
399 double branchLength = treeModel.getBranchLength(node);
400 double branchTime = branchLength * branchRate;// * siteRate;
401
402 if (DEBUG) {
403 synchronized (this) {
404 System.out.println("Branch length: " + branchLength
405 + " branch rate: " + branchRate + " branch time: "
406 + branchTime);// + " site rate: " + siteRate);
407 }
408 }// END: DEBUG
409
410 int count = 1;
411 substitutionModelDelegate.updateTransitionMatrices(beagle,
412 new int[] { branchIndex }, new double[] { branchTime }, count);
413
414 double transitionMatrix[] = new double[siteRateCategoryCount
415 * stateCount * stateCount];
416
417 beagle.getTransitionMatrix(branchIndex, //
418 transitionMatrix //
419 );
420
421 for (int siteRateCat = 0; siteRateCat < siteRateCategoryCount; siteRateCat++) {
422
423 System.arraycopy(transitionMatrix, siteRateCat * stateCount * stateCount,
424 probabilities[siteRateCat], 0, stateCount * stateCount);
425
426 }// END: i loop
427
428 return probabilities;
429 }// END: getTransitionProbabilities
430
431 // ///////////////////////////
432 // ---START: EXPERIMENTAL---//
433 // ///////////////////////////
434
435 // void traverse(NodeRef node, //
436 // int [] parentSequence, //
437 // int [] category //
438 // ) {
439 //
440 // for (int iChild = 0; iChild < treeModel.getChildCount(node); iChild++) {
441 //
442 // NodeRef child = treeModel.getChild(node, iChild);
443 //
444 // for (int i = 0; i < categoryCount; i++) {
445 // getTransitionProbabilities(child, i, probabilities[i]);
446 // }
447 //
448 //// if(DEBUG){
449 //// Utils.print2DArray(probabilities);
450 //// }
451 //
452 // int [] seq = new int[partitionSiteCount];
453 // double [] cProb = new double[stateCount];
454 //
455 // for (int i = 0; i < partitionSiteCount; i++) {
456 // System.arraycopy(probabilities[category[i]], parentSequence[i] * stateCount, cProb, 0, stateCount);
457 // seq[i] = MathUtils.randomChoicePDF(cProb);
458 // }
459 //
460 // if (treeModel.getChildCount(child) == 0) {
461 // Taxon taxon = treeModel.getNodeTaxon(child);
462 // sequenceList.put(taxon, seq);
463 // }
464 //
465 // traverse(treeModel.getChild(node, iChild), seq, category);
466 //
467 // }//END: child loop
468 // } // traverse
469 //
470 // void getTransitionProbabilities(
471 //NodeRef node, int rateCategory, double[] probs) {
472 //
473 // NodeRef parent = treeModel.getParent(node);
474 //
475 // double branchRate = branchRateModel.getBranchRate(treeModel, node);
476 //
477 // // Get the operational time of the branch
478 // double branchTime = branchRate * (treeModel.getNodeHeight(parent) - treeModel.getNodeHeight(node));
479 //
480 // if (branchTime < 0.0) {
481 // throw new RuntimeException("Negative branch length: " + branchTime);
482 // }
483 //
484 // double branchLength = siteModel.getRateForCategory(rateCategory) * branchTime;
485 //
486 // siteModel.getSubstitutionModel().getTransitionProbabilities(branchLength, probs);
487 // } // getTransitionProbabilities
488
489 // /////////////////////////
490 // ---END: EXPERIMENTAL---//
491 // /////////////////////////
492
493 private int[] sequence2intArray(Sequence sequence) {
494
495 int array[] = new int[partitionSiteCount];
496
497 if (dataType instanceof Codons) {
498
499 int k = 0;
500 for (int i = 0; i < partitionSiteCount; i++) {
501 array[i] = ((Codons) dataType).getState(sequence.getChar(k),
502 sequence.getChar(k + 1), sequence.getChar(k + 2));
503 k += 3;
504 }// END: replications loop
505
506 } else {
507
508 for (int i = 0; i < partitionSiteCount; i++) {
509 array[i] = dataType.getState(sequence.getChar(i));
510 }// END: replications loop
511
512 }// END: dataType check
513
514 return array;
515 }// END: sequence2intArray
516
517 private int randomChoicePDF(double[] pdf, int partitionNumber, String error) {
518
519 int samplePos = -Integer.MAX_VALUE;
520 double cumProb = 0.0;
521 double u = random.nextDouble();
522
523 for (int i = 0; i < pdf.length; i++) {
524
525 cumProb += pdf[i];
526
527 if (u < cumProb) {
528 samplePos = i;
529 break;
530 }
531 }
532
533 return samplePos;
534 }// END: randomChoicePDF
535
536 // /////////////
537 // --SETTERS--//
538 // /////////////
539
540 public void setPartitionNumber(Integer partitionNumber) {
541 this.partitionNumber = partitionNumber;
542 }
543
544 public void setRootSequence(Sequence rootSequence) {
545 this.rootSequence = rootSequence;
546 this.hasRootSequence = true;
547 }// END: setAncestralSequence
548
549 public void setOutputAncestralSequences(boolean outputAncestralSequences) {
550 this.outputAncestralSequences = outputAncestralSequences;
551 }
552
553 // /////////////
554 // --GETTERS--//
555 // /////////////
556
557 // public boolean isOutputAncestralSequences() {
558 // return outputAncestralSequences;
559 // }
560
561 public TreeModel getTreeModel() {
562 return treeModel;
563 }
564
565 public int getPartitionSiteCount() {
566 return ((to - from) / every) + 1;
567 }// END: getPartitionSiteCount
568
569 public BranchModel getBranchModel() {
570 return this.branchModel;
571 }// END: getBranchModelic
572
573 public FrequencyModel getFreqModel() {
574 return freqModel;
575 }// END: getFreqModel
576
577 public Integer getPartitionNumber() {
578 return partitionNumber;
579 }// END: getPartitionNumber
580
581 public DataType getDataType() {
582 return dataType;
583 }// END: getDataType
584
585 public Map<Taxon, int[]> getTaxonSequencesMap() {
586 return alignmentMap;
587 }// END: getSequenceList
588
589 // public LinkedHashMap<NodeRef, int[]> getSequenceMap() {
590 // return sequencesMap;
591 // }
592
593 public Sequence getRootSequence() {
594 return rootSequence;
595 }
596
597 // ///////////////
598 // --DEBUGGING--//
599 // ///////////////
600
601 public void printSequences() {
602 System.out.println("partition " + partitionNumber);
603 Utils.printMap(alignmentMap);
604 }// END: printSequences
605
606 }// END: class