Debian Codegraph @

src/dr/evomodel/antigenic/phyloclustering/misc/obsolete/TreeClusterGibbsOperator.java

raw symbols SCIP
1 package dr.evomodel.antigenic.phyloclustering.misc.obsolete;
2
3 import java.io.FileNotFoundException;
4 import java.io.FileReader;
5 import java.util.LinkedList;
6
7 import dr.evolution.tree.NodeRef;
8 import dr.evomodel.tree.TreeModel;
9 import dr.inference.model.MatrixParameter;
10 import dr.inference.model.Parameter;
11 import dr.inference.operators.GibbsOperator;
12 import dr.inference.operators.MCMCOperator;
13 import dr.inference.operators.SimpleMCMCOperator;
14 import dr.math.MathUtils;
15 import dr.xml.*;
16
17
18 /**
19 * A Gibbs operator for allocation of items to clusters under a distance dependent Chinese restaurant process.
20 *
21 * @author Charles Cheung
22 * @author Trevor Bedford
23 */
24 public class TreeClusterGibbsOperator extends SimpleMCMCOperator implements GibbsOperator{
25
26 //Parameter locationDrift; // no longer need to know
27 Parameter virusOffsetsParameter;
28 private double sigmaSq =1;
29 private int numdata = 0; //NEED TO UPDATE
30 //private double[] groupSize;
31
32 private MatrixParameter mu = null;
33 private Parameter clusterLabels = null;
34 private Parameter K = null;
35
36 private MatrixParameter virusLocations = null;
37
38 private int maxLabel = 0;
39 private int[] muLabels = null;
40
41 private int[] groupSize;
42 // public ClusterViruses clusterLikelihood = null;
43
44
45 private double numAcceptMoveMu = 0;
46 private double numProposeMoveMu = 0;
47
48 private double numAcceptMoveC = 0;
49 private double numProposeMoveC = 0;
50
51 private int isMoveMu = -1;
52
53
54 private double[] old_vLoc0 ;
55 private double[] old_vLoc1 ;
56
57 private Parameter clusterOffsetsParameter;
58 private AGLikelihoodTreeCluster clusterLikelihood = null;
59
60 private int groupSelectedChange = -1;
61 private int virusIndexChange = -1;
62 private double originalValueChange = -1;
63 private int dimSelectChange = -1;
64
65 private double[] mu0_offset;
66
67 private Parameter indicators = null;
68
69 private int binSize=20;
70
71
72 private Parameter excisionPoints;
73
74 private TreeModel treeModel;
75
76
77 // private int[] piIndicator = new int[numSites];
78
79
80 //public ClusterAlgorithmOperator(MatrixParameter virusLocations, MatrixParameter mu, Parameter clusterLabels, Parameter K, double weight, Parameter virusOffsetsParameter, Parameter locationDrift_in, Parameter clusterOffsetsParameter) {
81 public TreeClusterGibbsOperator(MatrixParameter virusLocations, MatrixParameter mu, Parameter clusterLabels, Parameter K, double weight, Parameter virusOffsetsParameter, Parameter clusterOffsetsParameter, Parameter indicatorsParameter, Parameter excisionPointsParameter, TreeModel treeModel_in, AGLikelihoodTreeCluster clusterLikelihood_in) {
82
83
84 System.out.println("Loading the constructor for ClusterGibbsOperator");
85
86 this.clusterLikelihood = clusterLikelihood_in;
87 this.treeModel= treeModel_in;
88 this.mu = mu;
89 this.K = K;
90 this.clusterLabels = clusterLabels;
91 // this.clusterLikelihood = clusterLikelihood;
92 this.virusLocations = virusLocations;
93 this.virusOffsetsParameter = virusOffsetsParameter;
94 // this.locationDrift = locationDrift_in; //no longer need
95 this.clusterOffsetsParameter = clusterOffsetsParameter;
96 this.indicators = indicatorsParameter;
97
98 this.excisionPoints = excisionPointsParameter;
99
100
101 numdata = virusOffsetsParameter.getSize();
102 System.out.println("numdata="+ numdata);
103
104
105 int K_int = (int) K.getParameterValue(0);
106
107
108 System.out.println("K_int=" + K_int);
109 groupSize = new int[binSize];
110 for(int i=0; i < binSize; i++){
111 groupSize[i] = 0;
112 }
113
114
115 for(int i=0; i < numdata; i++){
116 //System.out.println("i="+ i);
117 int index = (int) clusterLabels.getParameterValue(i);
118 groupSize[ index]++;
119 }
120
121 for(int i=0; i < numdata;i++){
122 if(maxLabel < (int) clusterLabels.getParameterValue(i)){
123 maxLabel = (int) clusterLabels.getParameterValue(i);
124 }
125 }
126
127 //NEED maxGROUP
128
129 //for(int i=0; i < K_int; i++){
130 //System.out.println("groupSize=" + groupSize[i]);
131 //}
132
133
134 muLabels = new int[binSize];
135
136 for(int i=0; i < maxLabel; i++){
137 int j=0;
138 if(groupSize[i] >0){
139 muLabels[j] = i;
140 j++;
141 }
142 }
143
144 //muLabels ...
145
146
147 setWeight(weight);
148
149 System.out.println("Finished loading the constructor for ClusterAlgorithmOperator");
150
151 }
152
153
154
155 /**
156 * change the parameter and return the log hastings ratio.
157 */
158 public final double doOperation() {
159
160
161 int numNodes = treeModel.getNodeCount();
162
163
164 double logHastingRatio = 0;
165 double chooseOperator = Math.random();
166
167 int K_int = (int) K.getParameterValue(0);
168
169
170 int selectedI = -1;
171
172
173 //System.out.println("AG likelihood cluster loaded");
174 //System.exit(0);
175
176 //Gibbs move:
177 double []logNumeratorProb = new double[numNodes];
178
179
180 int isOn = 0;
181 int I_selected = -1;
182
183 //obtain a random order of the "on" sites...
184
185 while(isOn == 0){
186 I_selected = (int) (Math.floor(Math.random()*binSize));
187 isOn = (int) excisionPoints.getParameterValue(I_selected);
188 //find an "on" excision point to move.
189 if(isOn==1){
190
191 // System.out.println("begin");
192
193 int originalSite = (int) indicators.getParameterValue(I_selected);
194 // System.out.println("original site is = " + originalSite);
195
196
197 //Determining the number of steps from the original site
198 int []numStepsFromOrigin = new int[numNodes];
199 for(int i=0; i < numNodes; i++){
200 numStepsFromOrigin[i] = 100000;
201 }
202
203 int curElementNumber =(int) indicators.getParameterValue(I_selected);
204 int rootElementNumber = curElementNumber;
205 //System.out.println("curElementNumber=" + curElementNumber);
206 NodeRef curElement = treeModel.getNode(curElementNumber);
207
208 LinkedList<NodeRef> visitlist = new LinkedList<NodeRef>();
209 LinkedList<NodeRef> fromlist = new LinkedList<NodeRef>();
210 LinkedList<Integer> nodeLevel = new LinkedList<Integer>();
211
212 LinkedList<Integer> possibilities = new LinkedList<Integer>();
213
214 NodeRef dummyNode = null;
215 visitlist.add(curElement);
216 fromlist.add(dummyNode);
217 nodeLevel.add(new Integer(0));
218
219 int maxNodeLevel = 1000;
220
221 //System.out.println("root node " + curElement.getNumber());
222 while(visitlist.size() > 0){
223
224 if(treeModel.getParent(curElement) != null){
225 //add parent
226 NodeRef node= treeModel.getParent(curElement);
227 if(fromlist.getFirst() != node){
228 if( nodeLevel.getFirst() < maxNodeLevel){
229 visitlist.add(node);
230 fromlist.add(curElement);
231 nodeLevel.add(new Integer(nodeLevel.getFirst()+1));
232 //System.out.println("node " + node.getNumber() + " added, parent of " + curElement.getNumber());
233 }
234 }
235 }
236
237
238 for(int childNum=0; childNum < treeModel.getChildCount(curElement); childNum++){
239 NodeRef node= treeModel.getChild(curElement,childNum);
240 if(fromlist.getFirst() != node){
241 if( nodeLevel.getFirst() < maxNodeLevel){
242 visitlist.add(node);
243 fromlist.add(curElement);
244 nodeLevel.add(new Integer(nodeLevel.getFirst()+1));
245 //System.out.println("node " + node.getNumber() + " added, child of " + curElement.getNumber());
246 }
247 }
248 }
249
250
251
252
253 //System.out.println("visited " + curElement.getNumber());
254 //test if I can add curElement.getNumber()
255 int site_test = curElement.getNumber();
256 int hasBeenAdded=0;
257 for(int i=0; i < binSize; i++){
258 if( indicators.getParameterValue(i) == site_test){
259 hasBeenAdded=1;
260 break;
261 }
262 }
263 if(hasBeenAdded==0 || curElement.getNumber() == rootElementNumber ){
264 //System.out.println("to possibilities: add " + site_test);
265 numStepsFromOrigin[site_test] = nodeLevel.getFirst();
266 possibilities.addLast(new Integer( site_test));
267 }
268 else{
269 //System.out.println("element " + curElement.getNumber() + " is already an excision point");
270 }
271
272 visitlist.pop();
273 fromlist.pop();
274 nodeLevel.pop();
275
276 if(visitlist.size() > 0){
277 curElement = visitlist.getFirst();
278 }
279
280
281 }
282
283
284
285 //Calculating the conditional probability
286 for(int curSite = 0; curSite < numNodes; curSite++){
287
288 //check if a site has been added
289 int hasBeenAdded=0;
290 for(int i=0; i < binSize; i++){
291 if( indicators.getParameterValue(i) == curSite){
292 hasBeenAdded=1;
293 break;
294 }
295 }
296 //site that has been added will be zeroed out.
297 if(hasBeenAdded==1){
298 double inf = Double.NEGATIVE_INFINITY;
299 logNumeratorProb[curSite] = inf;
300
301 }
302 else{
303 //calculate the numerator of the conditional probability
304
305 //select that node, change the Clusterlabels, and virus offsets, calculate loglikelihood from AGLikelihoodCluster and store
306 //perform Gibbs sampling
307 //change the cluster labels and virus offsets
308 int site_add = curSite;
309 //set to new sample
310 indicators.setParameterValue(I_selected, site_add);
311
312
313
314 //for each node that is not occupied,
315 //select that node, change the Clusterlabels, and virus offsets, calculate loglikelihood from AGLikelihoodCluster and store
316 //perform Gibbs sampling
317 //change the cluster labels and virus offsets
318
319
320 //swapped to the new on site
321 //nonZeroIndexes[I_off] = site_on;
322
323
324 //K IS CHANGED ACCORDINGLY
325 int K_count = 0; //K_int gets updated
326 for(int i=0; i < binSize; i++){
327 K_count += (int) excisionPoints.getParameterValue(i);
328 }
329 //System.out.println("K now becomes " + K_count);
330
331
332 //Remove the commenting out later.
333 K.setParameterValue(0, K_count); //update
334 K_int = K_count;
335
336 //use the tree to re-partition according to the change.
337 setClusterLabels(K_int);
338
339
340 //change the mu in the toBin and fromBIn
341 //borrow from getLogLikelihood:
342
343 double[] meanYear = new double[binSize];
344 double[] groupCount = new double[binSize];
345 for(int i=0; i < numdata; i++){
346 int label = (int) clusterLabels.getParameterValue(i);
347 double year = 0;
348 if (virusOffsetsParameter != null) {
349 // System.out.print("virus Offeset Parameter present"+ ": ");
350 // System.out.print( virusOffsetsParameter.getParameterValue(i) + " ");
351 // System.out.print(" drift= " + drift + " ");
352 year = virusOffsetsParameter.getParameterValue(i); //just want year[i]
353 //make sure that it is equivalent to double offset = year[virusIndex] - firstYear;
354 }
355 else{
356 System.out.println("virus Offeset Parameter NOT present. We expect one though. Something is wrong.");
357 }
358 meanYear[ label] = meanYear[ label] + year;
359
360 groupCount[ label ] = groupCount[ label ] +1;
361 }
362
363 for(int i=0; i < binSize; i++){
364 if(groupCount[i] > 0){
365 meanYear[i] = meanYear[i]/groupCount[i];
366 }
367 //System.out.println(meanYear[i]);
368 }
369
370
371 mu0_offset = new double[binSize];
372 //double[] mu1 = new double[maxLabel];
373
374
375 //System.out.println("maxLabel=" + maxLabel);
376 //now, change the mu..
377 for(int i=0; i < binSize; i++){
378 //System.out.println(meanYear[i]*beta);
379 mu0_offset[i] = meanYear[i];
380 //System.out.println("group " + i + "\t" + mu0_offset[i]);
381 }
382 // System.out.println("=====================");
383
384
385 //Set the vLoc to be the corresponding mu values , and clusterOffsetsParameter to be the corresponding offsets
386 //virus in the same cluster has the same position
387 for(int i=0; i < numdata; i++){
388 int label = (int) clusterLabels.getParameterValue(i);
389 Parameter vLoc = virusLocations.getParameter(i);
390 //setting the virus locs to be equal to the corresponding mu
391 double muValue = mu.getParameter(label).getParameterValue(0);
392 vLoc.setParameterValue(0, muValue);
393 double muValue2 = mu.getParameter(label).getParameterValue(1);
394 vLoc.setParameterValue(1, muValue2);
395 //System.out.println("vloc="+ muValue + "," + muValue2);
396 }
397
398 for(int i=0; i < numdata; i++){
399 int label = (int) clusterLabels.getParameterValue(i);
400 //if we want to apply the mean year virus cluster offset to the cluster
401 if(clusterOffsetsParameter != null){
402 //setting the clusterOffsets to be equal to the mean year of the virus cluster
403 // by doing this, the virus changes cluster AND updates the offset simultaneously
404 clusterOffsetsParameter.setParameterValue( i , mu0_offset[label]);
405 }
406 // System.out.println("mu0_offset[label]=" + mu0_offset[label]);
407 // System.out.println("clusterOffsets " + i +" now becomes =" + clusterOffsetsParameter.getParameterValue(i) );
408 }
409
410
411 logNumeratorProb[curSite] = clusterLikelihood.getLogLikelihood();
412 //System.out.println(clusterLikelihood.getLogLikelihood());
413
414
415 }
416
417 }//close for loop
418
419 selectedI = I_selected;
420
421
422
423 double maxLogProb = logNumeratorProb[0];
424 for(int i=0; i < numNodes; i++ ){
425 if(logNumeratorProb[i] > maxLogProb){
426 maxLogProb = logNumeratorProb[i];
427 }
428 }
429
430 //System.out.println(maxLogProb);
431
432
433 double sumLogDenominator = 0;
434
435 for(int i=0; i < numNodes; i++){
436 if(logNumeratorProb[i] != Double.NEGATIVE_INFINITY){
437 sumLogDenominator += Math.exp((logNumeratorProb[i]-maxLogProb));
438 }
439 }
440 sumLogDenominator = Math.log(sumLogDenominator) + maxLogProb;
441
442 double sumProb = 0;
443 double []condProb = new double[numNodes];
444 for(int i=0; i < numNodes; i++){
445 condProb[i] = Math.exp( logNumeratorProb[i] - sumLogDenominator );
446 //System.out.println("condProb of site " + i + " = " + condProb[i]);
447 sumProb +=condProb[i];
448 if(condProb[i] > 0.01){
449 // System.out.println("**site " + i + " with prob=" + condProb[i] + " steps from previous=" + numStepsFromOrigin[i]);
450
451 }
452 }
453
454 //System.out.println("sum up to " + sumProb);
455
456
457 //int site_add = MathUtils.randomChoicePDF(condProb); //seems to not be working properly
458 int site_add = MathUtils.randomChoicePDF(condProb); //seems to not be working properly
459
460 if(numStepsFromOrigin[site_add] >0){
461 System.out.println("Gibbs move: indicator " + I_selected +" from site " + originalSite + " to "+ site_add + " , chosen with prob =" + condProb[site_add] + " steps from previous placement=" + numStepsFromOrigin[site_add] );
462 }
463
464 // System.out.println("indicator " + I_selected +" from site " + originalSite + " to "+ site_add + " , chosen with prob =" + condProb[site_add] + " steps from previous placement=" + numStepsFromOrigin[site_add] );
465 indicators.setParameterValue(I_selected, site_add);
466
467
468 } //close if isOn.
469 }
470
471
472
473
474 // MathUtils.randomChoicePDF(pairwiseDivergenceCountPerSite[group1][group2])
475
476
477 // for(int curSite=0; curSite < numNodes; curSite++){
478 // System.out.println("log condProb of site " + curSite + " = " + logNumeratorProb[curSite] + " and scaled=" + (logNumeratorProb[curSite]-maxLogProb) );
479 // }
480
481
482 //normalize the score into probability distribution.
483
484 //(int) Math.floor( Math.random()*numNodes );
485 // int site_add = SAMPLE FROM THE DISTRIBUTION;
486 //set to new sample
487 // indicators.setParameterValue(I_selected, site_add);
488
489
490
491 //for each node that is not occupied,
492 //select that node, change the Clusterlabels, and virus offsets, calculate loglikelihood from AGLikelihoodCluster and store
493 //perform Gibbs sampling
494 //change the cluster labels and virus offsets
495
496
497
498 //====================================================================================================
499 //After finishing the proposal
500 //====================================================================================================
501
502
503
504 //swapped to the new on site
505 //nonZeroIndexes[I_off] = site_on;
506
507
508 //K IS CHANGED ACCORDINGLY
509 int K_count = 0; //K_int gets updated
510 for(int i=0; i < binSize; i++){
511 K_count += (int) excisionPoints.getParameterValue(i);
512 }
513 //System.out.println("K now becomes " + K_count);
514
515
516 //Remove the commenting out later.
517 K.setParameterValue(0, K_count); //update
518 K_int = K_count;
519
520 //use the tree to re-partition according to the change.
521 setClusterLabels(K_int);
522
523
524 //change the mu in the toBin and fromBIn
525 //borrow from getLogLikelihood:
526
527 double[] meanYear = new double[binSize];
528 double[] groupCount = new double[binSize];
529 for(int i=0; i < numdata; i++){
530 int label = (int) clusterLabels.getParameterValue(i);
531 double year = 0;
532 if (virusOffsetsParameter != null) {
533 // System.out.print("virus Offeset Parameter present"+ ": ");
534 // System.out.print( virusOffsetsParameter.getParameterValue(i) + " ");
535 // System.out.print(" drift= " + drift + " ");
536 year = virusOffsetsParameter.getParameterValue(i); //just want year[i]
537 //make sure that it is equivalent to double offset = year[virusIndex] - firstYear;
538 }
539 else{
540 System.out.println("virus Offeset Parameter NOT present. We expect one though. Something is wrong.");
541 }
542 meanYear[ label] = meanYear[ label] + year;
543
544 groupCount[ label ] = groupCount[ label ] +1;
545 }
546
547 for(int i=0; i < binSize; i++){
548 if(groupCount[i] > 0){
549 meanYear[i] = meanYear[i]/groupCount[i];
550 }
551 //System.out.println(meanYear[i]);
552 }
553
554
555 mu0_offset = new double[binSize];
556 //double[] mu1 = new double[maxLabel];
557
558
559 //System.out.println("maxLabel=" + maxLabel);
560 //now, change the mu..
561 for(int i=0; i < binSize; i++){
562 //System.out.println(meanYear[i]*beta);
563 mu0_offset[i] = meanYear[i];
564 //System.out.println("group " + i + "\t" + mu0_offset[i]);
565 }
566 // System.out.println("=====================");
567
568
569 //Set the vLoc to be the corresponding mu values , and clusterOffsetsParameter to be the corresponding offsets
570 //virus in the same cluster has the same position
571 for(int i=0; i < numdata; i++){
572 int label = (int) clusterLabels.getParameterValue(i);
573 Parameter vLoc = virusLocations.getParameter(i);
574 //setting the virus locs to be equal to the corresponding mu
575 double muValue = mu.getParameter(label).getParameterValue(0);
576 vLoc.setParameterValue(0, muValue);
577 double muValue2 = mu.getParameter(label).getParameterValue(1);
578 vLoc.setParameterValue(1, muValue2);
579 //System.out.println("vloc="+ muValue + "," + muValue2);
580 }
581
582 for(int i=0; i < numdata; i++){
583 int label = (int) clusterLabels.getParameterValue(i);
584 //if we want to apply the mean year virus cluster offset to the cluster
585 if(clusterOffsetsParameter != null){
586 //setting the clusterOffsets to be equal to the mean year of the virus cluster
587 // by doing this, the virus changes cluster AND updates the offset simultaneously
588 clusterOffsetsParameter.setParameterValue( i , mu0_offset[label]);
589 }
590 // System.out.println("mu0_offset[label]=" + mu0_offset[label]);
591 // System.out.println("clusterOffsets " + i +" now becomes =" + clusterOffsetsParameter.getParameterValue(i) );
592 }
593
594
595
596
597 // System.out.println("===The on nodes===");
598 // for(int i=0; i < binSize; i++){
599 // if((int) excisionPoints.getParameterValue(i) == 1){
600 // System.out.println("Cluster node " + i + " = " + (int) indicators.getParameterValue(i) + "\tstatus=" + (int) excisionPoints.getParameterValue(i));
601 // }
602 // }
603
604
605
606
607 //Hasting's Ratio is p(old |new)/ p(new|old)
608
609 //System.out.println("Done doing operation!");
610
611
612
613 //return(logHastingRatio); //log hasting ratio
614 return(logHastingRatio);
615
616 }
617
618
619 private void setClusterLabels(int K_int) {
620
621 int numNodes = treeModel.getNodeCount();
622 int[] cutNodes = new int[K_int];
623 int cutNum = 0;
624 String content = "";
625 for(int i=0; i < binSize; i++){
626 if( (int) excisionPoints.getParameterValue( i ) ==1 ){
627 cutNodes[cutNum] = (int) indicators.getParameterValue(i);
628 content += (int) indicators.getParameterValue(i) + ",";
629 cutNum++;
630 }
631
632 }
633 // System.out.println(content);
634
635 if(cutNum != K_int){
636 System.out.println("cutNum != K_int. we got a problem");
637 }
638
639 // for(int i=0; i < K_int; i++){
640 // System.out.println(cutNodes[i]);
641 // }
642
643 //int []membership = determine_membership(treeModel, cutNodes, K_int-1);
644 int []membership = determine_membership(treeModel, cutNodes, K_int);
645
646 double uniqueCode = 0;
647 for(int i=0; i < numNodes; i++){
648 uniqueCode += membership[i]*i;
649 }
650 // System.out.println(" sum = " + uniqueCode);
651
652 // System.out.println("number of nodes = " + treeModel.getNodeCount());
653 // for(int i=0; i < treeModel.getNodeCount(); i++){
654 // System.out.println(membership[i]);
655 // }
656
657
658 //System.out.println("Done");
659
660 // for(int i=0; i < numdata; i++){
661 // Parameter v = virusLocations.getParameter(i);
662 // String curName = v.getParameterName();
663 // System.out.println("i=" + i + " = " + curName);
664 // }
665
666 // for(int j=0; j < numdata; j++){
667 // System.out.println("j=" + j + " = " + treeModel.getTaxonId(j));
668 // }
669
670
671 // Parameter vv = virusLocations.getParameter(0);
672 // String curNamev = vv.getParameterName();
673
674 // System.out.println(curNamev + " and " +treeModel.getTaxonId(392) );
675 //System.out.println( curNamev.equals(treeModel.getTaxonId(392) ) );
676
677
678 //System.exit(0);
679
680 // System.out.println("numNodes=" + numNodes);
681 // System.exit(0);
682 //create dictionary:
683
684 //I suspect this is an expensive operation, so I don't want to do it many times,
685 //which is also unnecessary - MAY have to update whenever a different tree is used.
686 int []membershipToClusterLabelIndexes = new int[numdata];
687 for(int i=0; i < numdata; i++){
688 Parameter v = virusLocations.getParameter(i);
689 String curName = v.getParameterName();
690 // System.out.println(curName);
691 int isFound = 0;
692 for(int j=0; j < numNodes; j++){
693 String treeId = treeModel.getTaxonId(j);
694 if(curName.equals(treeId) ){
695 // System.out.println(" isFound at j=" + j);
696 membershipToClusterLabelIndexes[i] = j;
697 isFound=1;
698 break;
699 }
700
701 }
702 if(isFound ==0){
703 System.out.println("not found. Exit now.");
704 System.exit(0);
705 }
706 }
707
708
709 // System.exit(0);
710
711 // for(int i=0; i < numdata; i++){
712 // System.out.println(membershipToClusterLabelIndexes[i]);
713 // }
714 // System.exit(0);
715
716 for(int i=0; i < numdata; i++){
717 //The assumption that the first nodes being external node corresponding to the cluster labels IS FALSE
718 //so I have to search for the matching indexes
719 Parameter vloc = virusLocations.getParameter(i);
720
721
722 //must uncomment out because this sets the new partitioning ... now i am doing code testing.
723 clusterLabels.setParameterValue( i, membership[membershipToClusterLabelIndexes[i]]);
724 //System.out.println(vloc.getParameterName() + " i="+ i + " membership=" + (int) clusterLabels.getParameterValue(i));
725
726 // Parameter v = virusLocations.getParameter(i);
727 // System.out.println(v.getParameterName());
728 }
729
730
731
732 }
733
734
735
736 private static boolean isCutNode(int number, int cutNodes[], int numCut) {
737 if(numCut > 0){
738 for(int i=0; i < numCut; i++){
739 if(number == cutNodes[i]){
740 return true;
741 }
742 }
743 }
744 return false;
745 }
746
747
748
749 //traverse down the tree, top down, do calculation
750 static int[] determine_membership(TreeModel treeModel, int[] cutNodes, int numCuts){
751
752
753 //TEMPORARY SOLUTION
754 //load in the titer, corresponding to the taxon #.
755
756 TiterImporter titer = null ;
757
758 FileReader fileReader;
759 try {
760 fileReader = new FileReader("/Users/charles/Documents/research/antigenic/GenoPheno/data/taxon_y_titer.txt");
761 titer = new TiterImporter(fileReader);
762
763 } catch (FileNotFoundException e) {
764 // TODO Auto-generated catch block
765 e.printStackTrace();
766 }
767
768 NodeRef root = treeModel.getRoot();
769
770 int numClusters = 1;
771 LinkedList<NodeRef> list = new LinkedList<NodeRef>();
772 list.addFirst(root);
773
774 int[] membership = new int[treeModel.getNodeCount()];
775 for(int i=0; i < treeModel.getNodeCount(); i++){
776 membership[i] = -1;
777 }
778 membership[root.getNumber()] = 0; //root always given the first cluster
779
780 while(!list.isEmpty()){
781 //do things with the current object
782 NodeRef curElement = list.pop();
783 //String content = "node #" + curElement.getNumber() +", taxon=" + treeModel.getNodeTaxon(curElement) + " and parent is = " ;
784 String content = "node #" + curElement.getNumber() +", taxon= " ;
785 if(treeModel.getNodeTaxon(curElement)== null){
786 content += "internal node\t";
787 }
788 else{
789 content += treeModel.getNodeTaxon(curElement).getId() + "\t";
790 //content += treeModel.getTaxonIndex(treeModel.getNodeTaxon(curElement)) + "\t";
791 }
792
793 if(treeModel.getParent(curElement)== null){
794 //content += "no parent";
795 }
796 else{
797 //content += "parent node#=" + treeModel.getParent(curElement).getNumber();
798 }
799
800 //cluster assignment:
801 if(!treeModel.isRoot(curElement)){
802 if(isCutNode(curElement.getNumber(), cutNodes, numCuts)){
803 //if(isCutNode(curElement.getNumber())){
804 numClusters++ ;
805 membership[ curElement.getNumber() ] = numClusters - 1;
806 }
807 else{
808 //inherit from parent's cluster assignment
809 membership[curElement.getNumber()] = membership[treeModel.getParent(curElement).getNumber()];
810 }
811
812 }//is not Root
813 content += " cluster = " + membership[curElement.getNumber()] ;
814
815 // System.out.println(content);
816
817
818 for(int childNum=0; childNum < treeModel.getChildCount(curElement); childNum++){
819 list.addFirst(treeModel.getChild(curElement,childNum));
820 }
821 }
822
823 return(membership);
824 }
825
826
827
828
829
830 public void accept(double deviation) {
831 super.accept(deviation);
832
833 /*
834 if(isMoveMu==1){
835 numAcceptMoveMu++;
836 numProposeMoveMu++;
837 System.out.println("% accept move Mu = " + numAcceptMoveMu/(double)numProposeMoveMu);
838 }
839 else{
840 numAcceptMoveC++;
841 numProposeMoveC++;
842 System.out.println("% accept move C = " + numAcceptMoveC/(double)numProposeMoveC);
843 }
844 */
845
846 // if(virusIndexChange <5){
847 // System.out.println(" - Accepted!");
848 // }
849
850 }
851
852 public void reject(){
853 super.reject();
854
855
856 /*
857 //manually change mu back..
858 if(isMoveMu==1){
859 mu.getParameter(groupSelectedChange).setParameterValue(dimSelectChange, originalValueChange);
860 }
861 //manually change all the affected vLoc back...
862 for(int i=0; i < numdata; i++){
863 int label = (int) clusterLabels.getParameterValue(i);
864 Parameter vLoc = virusLocations.getParameter(i);
865 // double muValue = mu.getParameter(label).getParameterValue(0);
866 // vLoc.setParameterValue(0, muValue);
867 // double muValue2 = mu.getParameter(label).getParameterValue(1);
868 // vLoc.setParameterValue(1, muValue2);
869
870 clusterOffsetsParameter.setParameterValue( i , mu0_offset[label]);
871 }
872 */
873
874
875 /*
876 if(isMoveMu==1){
877 numProposeMoveMu++;
878 System.out.println("% accept move Mu = " + numAcceptMoveMu/(double)numProposeMoveMu);
879 }
880 else{
881 numProposeMoveC++;
882 System.out.println("% accept move C = " + numAcceptMoveC/(double)numProposeMoveC);
883 }
884 */
885 //if(virusIndexChange < 5){
886 System.out.println(" * Rejected!");
887 //}
888
889
890 /*
891 for(int i=0; i < numdata; i++){
892 Parameter vLoc = virusLocations.getParameter(i);
893
894 if( vLoc.getParameterValue(0) != old_vLoc0[i]){
895
896 System.out.println("virus " + i + " is different: " + vLoc.getParameterValue(0) + " and " + old_vLoc0[i]);
897 }
898
899 //System.out.println(old_vLoc0[i] + ", " + old_vLoc1[i]);
900 vLoc.setParameterValue(0, old_vLoc0[i]);
901 vLoc.setParameterValue(1, old_vLoc1[i]);
902
903 }
904 */
905 //System.exit(0);
906
907
908
909
910 }
911
912
913
914 public final static String TREE_CLUSTERGIBBS_OPERATOR = "TreeClusterGibbsOperator";
915
916
917 //MCMCOperator INTERFACE
918 public final String getOperatorName() {
919 return TREE_CLUSTERGIBBS_OPERATOR;
920 }
921
922 public final void optimize(double targetProb) {
923
924 throw new RuntimeException("This operator cannot be optimized!");
925 }
926
927 public boolean isOptimizing() {
928 return false;
929 }
930
931 public void setOptimizing(boolean opt) {
932 throw new RuntimeException("This operator cannot be optimized!");
933 }
934
935 public double getMinimumAcceptanceLevel() {
936 return 0.1;
937 }
938
939 public double getMaximumAcceptanceLevel() {
940 return 0.4;
941 }
942
943 public double getMinimumGoodAcceptanceLevel() {
944 return 0.20;
945 }
946
947 public double getMaximumGoodAcceptanceLevel() {
948 return 0.30;
949 }
950
951 public String getPerformanceSuggestion() {
952 if (Utils.getAcceptanceProbability(this) < getMinimumAcceptanceLevel()) {
953 return "";
954 } else if (Utils.getAcceptanceProbability(this) > getMaximumAcceptanceLevel()) {
955 return "";
956 } else {
957 return "";
958 }
959 }
960
961
962
963
964
965 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
966
967
968 public final static String VIRUSLOCATIONS = "virusLocations";
969 public final static String MU = "mu";
970 public final static String CLUSTERLABELS = "clusterLabels";
971 public final static String K = "k";
972 public final static String OFFSETS = "offsets";
973 // public final static String LOCATION_DRIFT = "locationDrift"; //no longer need
974
975 public final static String CLUSTER_OFFSETS = "clusterOffsetsParameter";
976
977 public final static String INDICATORS = "indicators";
978
979 public final static String EXCISION_POINTS = "excisionPoints";
980
981
982 public String getParserName() {
983 return TREE_CLUSTERGIBBS_OPERATOR;
984 }
985
986 /* (non-Javadoc)
987 * @see dr.xml.AbstractXMLObjectParser#parseXMLObject(dr.xml.XMLObject)
988 */
989 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
990
991 //System.out.println("Parser run. Exit now");
992 //System.exit(0);
993
994 double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT);
995
996
997 XMLObject cxo = xo.getChild(VIRUSLOCATIONS);
998 MatrixParameter virusLocations = (MatrixParameter) cxo.getChild(MatrixParameter.class);
999
1000
1001 cxo = xo.getChild(MU);
1002 MatrixParameter mu = (MatrixParameter) cxo.getChild(MatrixParameter.class);
1003
1004 cxo = xo.getChild(CLUSTERLABELS);
1005 Parameter clusterLabels = (Parameter) cxo.getChild(Parameter.class);
1006
1007 cxo = xo.getChild(K);
1008 Parameter k = (Parameter) cxo.getChild(Parameter.class);
1009
1010 cxo = xo.getChild(OFFSETS);
1011 Parameter offsets = (Parameter) cxo.getChild(Parameter.class);
1012
1013 // cxo = xo.getChild(LOCATION_DRIFT);
1014 // Parameter locationDrift = (Parameter) cxo.getChild(Parameter.class);
1015
1016 Parameter clusterOffsetsParameter = null;
1017 if (xo.hasChildNamed(CLUSTER_OFFSETS)) {
1018 clusterOffsetsParameter = (Parameter) xo.getElementFirstChild(CLUSTER_OFFSETS);
1019 }
1020
1021 cxo = xo.getChild(INDICATORS);
1022 Parameter indicators = (Parameter) cxo.getChild(Parameter.class);
1023
1024 cxo = xo.getChild(EXCISION_POINTS);
1025 Parameter excisionPoints = (Parameter) cxo.getChild(Parameter.class);
1026
1027 TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
1028
1029 AGLikelihoodTreeCluster agLikelihood = (AGLikelihoodTreeCluster) xo.getChild(AGLikelihoodTreeCluster.class);
1030
1031 //return new ClusterAlgorithmOperator(virusLocations, mu, clusterLabels, k, weight, offsets, locationDrift, clusterOffsetsParameter);
1032 return new TreeClusterGibbsOperator(virusLocations, mu, clusterLabels, k, weight, offsets, clusterOffsetsParameter, indicators, excisionPoints, treeModel, agLikelihood);
1033
1034 }
1035
1036 //************************************************************************
1037 // AbstractXMLObjectParser implementation
1038 //************************************************************************
1039
1040 public String getParserDescription() {
1041 return "An operator that picks a new allocation of an item to a cluster under the Dirichlet process.";
1042 }
1043
1044 public Class getReturnType() {
1045 return TreeClusterGibbsOperator.class;
1046 }
1047
1048
1049 public XMLSyntaxRule[] getSyntaxRules() {
1050 return rules;
1051 }
1052
1053 private final XMLSyntaxRule[] rules = {
1054 AttributeRule.newDoubleRule(MCMCOperator.WEIGHT),
1055
1056 new ElementRule(VIRUSLOCATIONS, Parameter.class),
1057 new ElementRule(MU, Parameter.class),
1058 new ElementRule(CLUSTERLABELS, Parameter.class),
1059 new ElementRule(K, Parameter.class),
1060 new ElementRule(OFFSETS, Parameter.class),
1061 // new ElementRule(LOCATION_DRIFT, Parameter.class), //no longer needed
1062 //
1063 new ElementRule(CLUSTER_OFFSETS, Parameter.class, "Parameter of cluster offsets of all virus"), // no longer REQUIRED
1064 new ElementRule(INDICATORS, Parameter.class),
1065 new ElementRule(EXCISION_POINTS, Parameter.class),
1066 new ElementRule(TreeModel.class),
1067
1068
1069 };
1070
1071 };
1072
1073
1074
1075 public int getStepCount() {
1076 return 1;
1077 }
1078
1079 }
1080
1081
1082
1083