Debian Codegraph @

src/dr/evomodel/tree/HiddenLinkageModel.java

raw symbols SCIP
1 /*
2 * HiddenLinkageModel.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.tree;
27
28 import java.util.ArrayList;
29 import java.util.HashSet;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Set;
33
34 import dr.evolution.MetagenomeData;
35 import dr.evolution.alignment.Alignment;
36 import dr.evolution.alignment.PatternList;
37 import dr.evolution.datatype.DataType;
38 import dr.evolution.util.Taxon;
39 import dr.evolution.util.TaxonList;
40 import dr.oldevomodel.substmodel.SubstitutionModel;
41 import dr.oldevomodel.treelikelihood.GeneralLikelihoodCore;
42 import dr.oldevomodel.treelikelihood.LikelihoodCore;
43 import dr.oldevomodel.treelikelihood.NativeAminoAcidLikelihoodCore;
44 import dr.oldevomodel.treelikelihood.NativeNucleotideLikelihoodCore;
45 import dr.evomodel.tipstatesmodel.TipStatesModel;
46 import dr.inference.model.Model;
47 import dr.inference.model.Variable;
48 import dr.inference.model.Variable.ChangeType;
49 import dr.math.MathUtils;
50
51 /**
52 * A model of linkage among sets of metagenome sequence reads
53 * Reads are assumed to derive from a fixed number of organisms, where
54 * the identity of the organisms is unknown, and the assignment of reads
55 * to those organisms is also unknown.
56 * @author Aaron Darling (koadman)
57 *
58 */
59 public class HiddenLinkageModel extends TipStatesModel implements PatternList
60 {
61
62 int linkageGroupCount = 0;
63 ArrayList< HashSet<Taxon> > groups = null;
64 MetagenomeData data = null;
65 ArrayList<Taxon> alignmentTaxa;
66 double[][] tipPartials;
67 double[][] storedTipPartials;
68 boolean[] dirtyTipPartials;
69
70 LikelihoodCore core;
71 double blen = 0.001;
72 SubstitutionModel substitutionModel;
73
74 public HiddenLinkageModel(int linkageGroupCount, MetagenomeData data) {
75 super("HiddenLinkageModel", data.getReferenceTaxa(), data.getReadsTaxa());
76 this.linkageGroupCount = linkageGroupCount;
77 this.data = data;
78
79 // initial state: randomly assign reads to groups
80 groups = new ArrayList< HashSet<Taxon> >(linkageGroupCount);
81 for(int i=0; i<linkageGroupCount; i++)
82 groups.add(new HashSet<Taxon>());
83 TaxonList reads = data.getReadsTaxa();
84 for(int i=0; i<reads.getTaxonCount(); i++){
85 int g = MathUtils.nextInt(linkageGroupCount);
86 groups.get(g).add(reads.getTaxon(i));
87 }
88
89 // create an alignment taxa list with reference + hidden groups
90 alignmentTaxa = new ArrayList<Taxon>(data.getReferenceTaxa().asList());
91 for(int i=0; i<linkageGroupCount; i++)
92 alignmentTaxa.add(new Taxon("LinkageGroup_" + i));
93
94 int plen = data.getAlignment().getSiteCount() * data.getAlignment().getStateCount();
95 tipPartials = new double[alignmentTaxa.size()][plen];
96 storedTipPartials = new double[alignmentTaxa.size()][plen];
97 dirtyTipPartials = new boolean[alignmentTaxa.size()];
98
99 initCore();
100 setupMatrices();
101
102 // compute initial partials
103 for(int i=0; i<tipPartials.length; i++)
104 computeTipPartials(i);
105 }
106
107 double[] tipMatrix;
108 double[] internalMatrix;
109
110 @Override
111 public boolean areUnique() {
112 return false;
113 }
114
115 @Override
116 public boolean areUncertain() {
117 return false;
118 }
119
120 /*
121 * Initializes a likelihoodCore to calculate likelihoods for
122 * the tips
123 */
124 private void initCore(){
125 if(data.getAlignment().getDataType() instanceof dr.evolution.datatype.Nucleotides)
126 core = new NativeNucleotideLikelihoodCore();
127 if(data.getAlignment().getDataType() instanceof dr.evolution.datatype.AminoAcids)
128 core = new NativeAminoAcidLikelihoodCore();
129 if(data.getAlignment().getDataType() instanceof dr.evolution.datatype.Codons)
130 core = new GeneralLikelihoodCore(data.getAlignment().getStateCount());
131 // initialize the likelihood core
132 core.initialize(data.getReadsTaxa().getTaxonCount()*2, data.getAlignment().getSiteCount(), 1, false);
133 for(int i=0; i<data.getReadsTaxa().getTaxonCount(); i++){
134 int index = data.getAlignment().getTaxonIndex(data.getReadsTaxa().getTaxon(i));
135 int[] states = new int[data.getAlignment().getSiteCount()];
136 for(int j=0; j<states.length; j++)
137 states[j]=data.getAlignment().getState(index,j);
138 core.setNodeStates(i, states);
139 }
140 for(int i=0; i<data.getReadsTaxa().getTaxonCount(); i++)
141 core.createNodePartials(i+data.getReadsTaxa().getTaxonCount());
142 }
143
144 /*
145 * set up transition matrices for internal and external nodes
146 */
147 private void setupMatrices(){
148 tipMatrix=new double[data.getAlignment().getStateCount()*data.getAlignment().getStateCount()];
149 internalMatrix=new double[data.getAlignment().getStateCount()*data.getAlignment().getStateCount()];
150 double diag = 1.0-blen;
151 double offdiag = blen / (data.getAlignment().getStateCount() - 1);
152 double internalDiag = 0.99999999999999;
153 double internalOffDiag = (1.0-internalDiag) / (data.getAlignment().getStateCount() - 1);
154 for(int i=0; i<tipMatrix.length; i++)
155 {
156 tipMatrix[i]=offdiag;
157 internalMatrix[i]=internalOffDiag;
158 }
159 for(int i=0; i<data.getAlignment().getStateCount(); i++)
160 {
161 tipMatrix[i*data.getAlignment().getStateCount() + i] = diag;
162 internalMatrix[i*data.getAlignment().getStateCount() + i] = internalDiag;
163 }
164
165 for(int i=0; i<data.getReadsTaxa().getTaxonCount(); i++)
166 core.setNodeMatrix(i, 0, tipMatrix);
167 for(int i=0; i<data.getReadsTaxa().getTaxonCount(); i++)
168 core.setNodeMatrix(i+data.getReadsTaxa().getTaxonCount(), 0, internalMatrix);
169 }
170
171 public int getLinkageGroupCount() {
172 return linkageGroupCount;
173 }
174
175 public MetagenomeData getData() {
176 return data;
177 }
178
179
180 /**
181 * Returns the group ID to which a particular metagenomic read belongs
182 * @param t
183 * @return
184 */
185 public int getLinkageGroupId(Taxon t)
186 {
187 int i=0;
188 for(HashSet<Taxon> h : groups){
189 if(h.contains(t))
190 break;
191 i++;
192 }
193 return i;
194 }
195
196 private class Move {
197 public Move(Taxon read, int fromGroup, int toGroup){
198 this.read = read;
199 this.fromGroup = fromGroup;
200 this.toGroup = toGroup;
201 }
202 Taxon read;
203 int fromGroup;
204 int toGroup;
205 }
206 ArrayList<Move> movesMade = new ArrayList<Move>();
207
208 @Override
209 protected void acceptState() {
210 movesMade.clear();
211 for(int i=0; i<dirtyTipPartials.length; i++)
212 dirtyTipPartials[i]=false;
213 }
214
215 @Override
216 protected void handleModelChangedEvent(Model model, Object object, int index) {
217 // TODO Auto-generated method stub
218
219 }
220
221 protected void handleVariableChangedEvent(Variable variable, int index,
222 ChangeType type) {
223 // TODO Auto-generated method stub
224
225 }
226
227 protected void restoreState() {
228 // make all moves in reverse
229 for(int i=movesMade.size(); i>0; i--)
230 {
231 Move m = movesMade.get(i-1);
232 groups.get(m.toGroup).remove(m.read);
233 groups.get(m.fromGroup).add(m.read);
234 }
235 movesMade.clear();
236 for(int i=0; i<dirtyTipPartials.length; i++)
237 {
238 if(dirtyTipPartials[i]){
239 swapTipPartials(i);
240 dirtyTipPartials[i]=false;
241 }
242 }
243 }
244
245 protected void storeState() {
246 movesMade.clear();
247 for(int i=0; i<dirtyTipPartials.length; i++)
248 dirtyTipPartials[i]=false;
249 }
250
251 /**
252 * Get the members of the i'th linkage group
253 * @param i
254 * @return Members of the i'th group
255 */
256 public Set<Taxon> getGroup(int i){
257 return groups.get(i);
258 }
259 /**
260 * Moves a read from one linkage group to another linkage group
261 * @param read
262 * @param oldGroup
263 * @param newGroup
264 */
265 public void moveReadGroup(Taxon read, int oldGroup, int newGroup)
266 {
267 boolean found = groups.get(oldGroup).remove(read);
268 if(!found)
269 throw new RuntimeException("Error, could not find read " + read + " in linkage group " + oldGroup);
270 groups.get(newGroup).add(read);
271 movesMade.add(new Move(read, oldGroup, newGroup));
272 computeTipPartials(data.getReferenceTaxa().getTaxonCount() + oldGroup);
273 computeTipPartials(data.getReferenceTaxa().getTaxonCount() + newGroup);
274
275 // this.fireModelChanged();
276 this.fireModelChanged(alignmentTaxa.get(alignmentTaxa.size() - groups.size() + oldGroup));
277 this.fireModelChanged(alignmentTaxa.get(alignmentTaxa.size() - groups.size() + newGroup));
278 }
279
280 private void swapTipPartials(int nodeIndex){
281 double[] tmp = storedTipPartials[nodeIndex];
282 storedTipPartials[nodeIndex] = tipPartials[nodeIndex];
283 tipPartials[nodeIndex] = tmp;
284 }
285
286 private void computeTipPartials(int nodeIndex){
287 if(!dirtyTipPartials[nodeIndex]){
288 swapTipPartials(nodeIndex);
289 dirtyTipPartials[nodeIndex]=true;
290 }
291 double[] tipPartials = this.tipPartials[nodeIndex];
292
293 // if this is one of the reference organisms, then return the resolved partials
294 // if this is a linkage group, return partials that correspond to probabilities of each nucleotide.
295 Alignment aln = data.getAlignment();
296 int sc = aln.getStateCount();
297 for(int i=0; i<tipPartials.length; i++){
298 tipPartials[i]=0.0;
299 }
300 if(nodeIndex < data.getReferenceTaxa().getTaxonCount()){
301 int j=0;
302 for(int i=0; i<aln.getSiteCount(); i++){
303 int s = aln.getState(nodeIndex, i);
304 if(s>=sc){
305 for(int k=0; k<sc; k++)
306 tipPartials[j + k] = 1.0;
307 }else
308 tipPartials[j + s] = 1.0;
309 j += sc;
310 }
311 }else{
312 int gI = nodeIndex - data.getReferenceTaxa().getTaxonCount();
313 HashSet<Taxon> group = groups.get(gI);
314 int internalNum = data.getReadsTaxa().getTaxonCount();
315 Taxon firstTax=null;
316 boolean peeled = false;
317 for(Taxon tax : group){
318 if(firstTax==null)
319 {
320 firstTax = tax;
321 continue;
322 }
323 int c2 = data.getReadsTaxa().getTaxonIndex(tax);
324 if(!peeled){
325 int c1 = data.getReadsTaxa().getTaxonIndex(firstTax);
326 core.setNodePartialsForUpdate(internalNum);
327 core.calculatePartials(c1, c2, internalNum);
328 }else{
329 core.setNodePartialsForUpdate(internalNum);
330 core.calculatePartials(internalNum-1, c2, internalNum);
331 }
332 internalNum++;
333 peeled = true;
334 }
335 if(group.size()==0)
336 {
337 for(int i=0; i<tipPartials.length; i++)
338 tipPartials[i]=1.0;
339 }else if(!peeled)
340 getPartialsForGroupSizeOne(firstTax, tipPartials);
341 else
342 core.getPartials(internalNum-1, tipPartials);
343 }
344 }
345 private void getPartialsForGroupSizeOne(Taxon tax, double[] tipPartials)
346 {
347 Alignment aln = data.getAlignment();
348 int sc = aln.getStateCount();
349 int index = aln.getTaxonIndex(tax);
350 int j=0;
351 for(int i=0; i<aln.getSiteCount(); i++){
352 int s = aln.getState(index, i);
353 if(s>=sc){
354 for(int k=0; k<sc; k++)
355 tipPartials[j + k] = 1.0;
356 }else
357 System.arraycopy(internalMatrix, s*sc, tipPartials, j, sc);
358 j += sc;
359 }
360 }
361 /*
362 private void computeTipPartials(int nodeIndex){
363 if(!dirtyTipPartials[nodeIndex]){
364 swapTipPartials(nodeIndex);
365 dirtyTipPartials[nodeIndex]=true;
366 }
367 double[] tipPartials = this.tipPartials[nodeIndex];
368
369 // if this is one of the reference organisms, then return the resolved partials
370 // if this is a linkage group, return partials that correspond to probabilities of each nucleotide.
371 Alignment aln = data.getAlignment();
372 int sc = aln.getStateCount();
373 for(int i=0; i<tipPartials.length; i++){
374 tipPartials[i]=0.0;
375 }
376 if(nodeIndex < data.getReferenceTaxa().getTaxonCount()){
377 int j=0;
378 for(int i=0; i<aln.getSiteCount(); i++){
379 int s = aln.getState(nodeIndex, i);
380 if(s>=sc){
381 for(int k=0; k<sc; k++)
382 tipPartials[j + k] = 1.0;
383 }else
384 tipPartials[j + s] = 1.0;
385 j += sc;
386 }
387 }else{
388 // average the information for each sequence in the linkage group
389 int gI = nodeIndex - data.getReferenceTaxa().getTaxonCount();
390 HashSet<Taxon> group = groups.get(gI);
391 for( Taxon tax : group){
392 int sI = data.getAlignment().getTaxonIndex(tax);
393
394 int j=0;
395 for(int i=0; i<aln.getSiteCount(); i++){
396 int s = aln.getState(sI, i);
397 if(s<sc)
398 tipPartials[j + s] += 1.0;
399 j += sc;
400 }
401 }
402
403 // now normalize back to probability distributions
404 int j=0;
405 int l=tipPartials.length / sc;
406 for(int i=0; i<l; i++){
407 double max=0;
408 for(int k=0; k<sc; k++){
409 max = max > tipPartials[j+k] ? max : tipPartials[j+k];
410 }
411 if(max>0){
412 for(int k=0; k<sc; k++){
413 tipPartials[j+k]/=max;
414 }
415 }else{
416 // if no sequence had info, set it to unknown (1.0 for all values)
417 for(int k=0; k<sc; k++){
418 tipPartials[j+k]=1.0;
419 }
420 }
421 j += sc;
422 }
423 }
424 }
425 */
426 /**
427 * NOT YET IMPLEMENTED. Creates a new read linkage group.
428 * @return the new group id
429 */
430 public int newGroup(){
431 throw new RuntimeException("Not implemented!");
432 }
433 /**
434 * NOT YET IMPLEMENTED. Deletes a read linkage group. Must be empty.
435 */
436 public void deleteGroup(){
437 throw new RuntimeException("Not implemented!");
438 }
439
440 @Override
441 public Type getModelType() {
442 return Type.PARTIALS;
443 }
444
445 @Override
446 public void getTipStates(int nodeIndex, int[] tipStates) {
447 throw new IllegalArgumentException("This model emits only tip partials");
448 }
449
450 @Override
451 public void getTipPartials(int nodeIndex, double[] tipPartials) {
452 int n = nodeIdToMyTaxaMap[tree.getNode(nodeIndex).getNumber()];
453 System.arraycopy(this.tipPartials[n], 0, tipPartials, 0, tipPartials.length);
454 }
455
456 int[] nodeIdToMyTaxaMap;
457 protected void taxaChanged() {
458 nodeIdToMyTaxaMap = new int[tree.getNodeCount()];
459 for(int i=0; i<nodeIdToMyTaxaMap.length; i++){
460 for(int j=0; j<alignmentTaxa.size(); j++){
461 if(tree.getTaxon(i)==null)
462 continue;
463 if(tree.getTaxon(i)==null || alignmentTaxa.get(j) == null)
464 System.err.print("asdgasdg\n");
465 else if(tree.getTaxon(i).getId()==null || alignmentTaxa.get(j).getId() == null)
466 System.err.print("asdgasdg\n");
467 if(tree.getTaxon(i).getId().equalsIgnoreCase(alignmentTaxa.get(j).getId())){
468 nodeIdToMyTaxaMap[tree.getExternalNode(i).getNumber()] = j;
469 break;
470 }
471 }
472 }
473 }
474
475
476
477
478 //
479 // BEGIN PatternList Implementation
480 // This merely delegates to Alignment for most methods
481 //
482
483 public DataType getDataType() {
484 return data.getAlignment().getDataType();
485 }
486
487 public int[] getPattern(int patternIndex) {
488 return data.getAlignment().getPattern(patternIndex);
489 }
490
491 @Override
492 public double[][] getUncertainPattern(int patternIndex) {
493 return new double[0][];
494 }
495
496 public int getPatternCount() {
497 return data.getAlignment().getPatternCount();
498 }
499
500 public int getPatternLength() {
501 return data.getAlignment().getPatternLength();
502 }
503
504 public int getPatternState(int taxonIndex, int patternIndex) {
505 if(taxonIndex<data.getReferenceTaxa().getTaxonCount())
506 return data.getAlignment().getPatternState(taxonIndex, patternIndex);
507
508 return 0;
509 }
510
511 @Override
512 public double[] getUncertainPatternState(int taxonIndex, int patternIndex) {
513 return new double[0];
514 }
515
516 public double getPatternWeight(int patternIndex) {
517 return data.getAlignment().getPatternWeight(patternIndex);
518 }
519
520 public double[] getPatternWeights() {
521 return data.getAlignment().getPatternWeights();
522 }
523
524 public int getStateCount() {
525 return data.getAlignment().getStateCount();
526 }
527
528 public double[] getStateFrequencies() {
529 return data.getAlignment().getStateFrequencies();
530 }
531
532 public List<Taxon> asList() {
533 return alignmentTaxa;
534 }
535
536 public Taxon getTaxon(int taxonIndex) {
537 return alignmentTaxa.get(taxonIndex);
538 }
539
540 public Object getTaxonAttribute(int taxonIndex, String name) {
541 return alignmentTaxa.get(taxonIndex).getAttribute(name);
542 }
543
544 public int getTaxonCount() {
545 return alignmentTaxa.size();
546 }
547
548 public String getTaxonId(int taxonIndex) {
549 return alignmentTaxa.get(taxonIndex).getId();
550 }
551
552 public int getTaxonIndex(String id) {
553 for(int i=0; i<alignmentTaxa.size(); i++){
554 if(alignmentTaxa.get(i).getId().equals(id))
555 return i;
556 }
557 return -1;
558 }
559
560 public int getTaxonIndex(Taxon taxon) {
561 for(int i=0; i<alignmentTaxa.size(); i++){
562 if(alignmentTaxa.get(i).compareTo(taxon)==0)
563 return i;
564 }
565 return -1;
566 }
567
568 public Iterator<Taxon> iterator() {
569 return alignmentTaxa.iterator();
570 }
571 }