Debian Codegraph @

src/dr/evomodel/antigenic/phyloclustering/TreeClusteringVirusesPrior.java

raw symbols SCIP
1 package dr.evomodel.antigenic.phyloclustering;
2
3 import java.io.BufferedReader;
4 import java.io.FileNotFoundException;
5 import java.io.FileReader;
6 import java.io.IOException;
7 import java.util.Iterator;
8 import java.util.LinkedList;
9
10 import dr.evolution.datatype.Nucleotides;
11 import dr.evolution.tree.NodeRef;
12 import dr.evomodel.antigenic.phyloclustering.misc.obsolete.TiterImporter;
13 import dr.evomodel.tree.TreeModel;
14 import dr.inference.model.AbstractModelLikelihood;
15 import dr.inference.model.MatrixParameter;
16 import dr.inference.model.Model;
17 import dr.inference.model.Parameter;
18 import dr.inference.model.Variable;
19 import dr.math.MathUtils;
20 import dr.xml.AbstractXMLObjectParser;
21 import dr.xml.AttributeRule;
22 import dr.xml.ElementRule;
23 import dr.xml.XMLObject;
24 import dr.xml.XMLObjectParser;
25 import dr.xml.XMLParseException;
26 import dr.xml.XMLSyntaxRule;
27
28 /**
29 * @author Charles Cheung
30 * @author Trevor Bedford
31 */
32
33
34 public class TreeClusteringVirusesPrior extends AbstractModelLikelihood {
35
36
37 public static final String TREE_CLUSTER_VIRUSES = "treeClusterViruses";
38
39 private Parameter muPrecision;
40 private Parameter p_on;
41 private double initialK;
42
43 private int startBase;
44 private int endBase;
45 private int numSites;
46
47 //Variables
48 private Parameter indicators;
49 private Parameter probSites;
50 private MatrixParameter mu; //mu - means
51 private Parameter clusterLabels; //C
52 private Parameter clusterLabelsTreeNode;
53 private MatrixParameter virusLocations = null;
54 private MatrixParameter virusLocationsTreeNode = null;
55
56 private Parameter muMean = null; //obsolete - to be removed
57 boolean hasDrift;
58 TreeModel treeModel;
59
60 int numdata;
61 int []membershipToClusterLabelIndexes = null;
62 private double mostRecentTransformedValue = 0; //keep a copy of the most recent version of transformFactor, to keep track of whether the transformFactor has changed
63 private boolean treeChanged = false; //a flag that becomes true when treeModel changes
64
65
66 private String[] mutationString;
67 private LinkedList<Integer>[] mutationList ;
68 private LinkedList<Integer>[] causalList ;
69 private int[] causalCount;
70 private int[] nonCausalCount;
71
72 private Parameter siteIndicators;
73 private String gp_prior;
74 private double prob00=0.95;
75 private double prob11=0.5;
76
77
78 public LinkedList<Integer>[] getMutationList(){
79 return(mutationList);
80 }
81 public LinkedList<Integer>[] getCausalList(){
82 return(causalList);
83 }
84
85 public TreeClusteringVirusesPrior (TreeModel treeModel_in,
86 Parameter indicators_in,
87 Parameter clusterLabels_in,
88 Parameter clusterLabelsTreeNode_in,
89 MatrixParameter mu_in,
90 Boolean hasDrift,
91 MatrixParameter virusLocations_in,
92 MatrixParameter virusLocationsTreeNode_in,
93 Parameter muPrecision,
94 Parameter p_onValue ,
95 double initialK_in,
96 Parameter muMean,
97 Parameter probSites_in,
98 Parameter siteIndicators_in,
99 int startBase_in,
100 int endBase_in,
101 String gp_prior_in,
102 double prob00_in,
103 double prob11_in,
104 double initial_probSiteValue
105 ){
106
107 super(TREE_CLUSTER_VIRUSES);
108 System.out.println("loading the constructor for TreeClusterViruses");
109
110 if(probSites_in == null){
111 System.out.println("Antigenic Clustering only");
112 }
113 else{
114 System.out.println("Antigenic Genotype to Phenotype model");
115 }
116
117 this.treeModel= treeModel_in;
118
119 if(probSites_in != null){
120 this.startBase = startBase_in;
121 this.endBase = endBase_in;
122 this.gp_prior = gp_prior_in;
123
124 System.out.println("gp prior = " + gp_prior);
125 if(gp_prior.compareTo("generic") == 0 ||gp_prior.compareTo("saturated") == 0||
126 gp_prior.compareTo("shrinkage") == 0||gp_prior.compareTo("correlated") == 0){
127 }
128 else{
129 System.out.println("Prior is incorrectly specified - choose from [generic/saturated/shrinkage/correlated]");
130 System.exit(0);
131 }
132
133 treeMutations(); //this routine also calculates the number of sites and checks for error
134 this.probSites = probSites_in;
135 this.siteIndicators = siteIndicators_in;
136 this.prob00 = prob00_in;
137 this.prob11 = prob11_in;
138
139 }
140 //this.K = K_in; //to be deleted
141 this.indicators = indicators_in;
142
143 this.clusterLabels = clusterLabels_in;
144 this.clusterLabelsTreeNode = clusterLabelsTreeNode_in;
145 this.mu = mu_in;
146
147 this.hasDrift=hasDrift;
148 this.virusLocations = virusLocations_in;
149 this.virusLocationsTreeNode = virusLocationsTreeNode_in;
150
151 this.muPrecision = muPrecision;
152 this.p_on = p_onValue; // this is shared by the clustering-only and also the saturated prior in genotype to phenotype
153 this.initialK = initialK_in;
154 this.muMean = muMean;
155
156 System.out.println("sigmaSq = " + 1/muPrecision.getParameterValue(0));
157 System.out.println("p_on = " + p_onValue.getParameterValue(0));
158
159 //numdata = offsets.getSize();
160 int numNodes = treeModel.getNodeCount();
161 numdata = virusLocations_in.getColumnDimension();
162 //initialize clusterLabels
163 clusterLabels.setDimension(numdata);
164 for (int i = 0; i < numdata; i++) {
165 clusterLabels.setParameterValue(i, 0);
166 }
167 addVariable(clusterLabels);
168
169 //initialize excision points
170 indicators.setDimension(treeModel.getNodeCount());
171 for(int i=0; i < treeModel.getNodeCount(); i++){
172 indicators.setParameterValue(i, 0);
173 }
174
175
176
177 //initialize with the specified number of initial clusters.
178 indicators.setParameterValue( treeModel.getRoot().getNumber() , 1 );
179 for(int k=0; k< (initialK -1); k++){
180 //sample another one.
181 int sampleNew = 1;
182 while(sampleNew ==1){
183 int rSiteIndex = (int) (Math.floor(Math.random()*numNodes));
184 if( (int) indicators.getParameterValue(rSiteIndex) == 0){
185 //clustering only
186 if(probSites_in == null){
187 //success sampling
188 indicators.setParameterValue(rSiteIndex, 1);
189 sampleNew = 0;
190 }
191 //genotype to phenotype
192 else{
193 //added condition to avoid getting 0 probability:
194 if(mutationList[rSiteIndex] != null){
195 //success sampling
196 indicators.setParameterValue(rSiteIndex, 1);
197 sampleNew = 0;
198 }
199 }//else
200 }
201 }
202
203 }
204
205 addVariable(indicators);
206
207 //genotype to phenotype
208 if(probSites_in != null){
209 //int numSites = 330; //HARDCODED RIGHT NOW
210 if(gp_prior.compareTo("generic") == 0 ){
211 probSites.setDimension(1);
212 probSites.setParameterValue(0, initial_probSiteValue);
213 }
214 else{
215 probSites.setDimension(numSites); //initialize dimension of probSites
216 //initialize the probability of each site
217 //double initial_p = 0.05;
218 for(int k=0; k < numSites; k++){
219 //probSites.setParameterValue(k, initial_p);
220 probSites.setParameterValue(k, initial_probSiteValue );
221 }
222 }
223 addVariable(probSites);
224
225
226 //MAYBE ONLY INITIALIZE IT IF IT USES THE SHRINKAGE OR correlated PRIOR?
227 siteIndicators.setDimension(numSites);
228 for(int k=0; k < numSites; k++){
229 siteIndicators.setParameterValue(k, 1);
230 }
231 addVariable(siteIndicators);
232 }
233
234
235 clusterLabelsTreeNode.setDimension(treeModel.getNodeCount());
236 addVariable(clusterLabelsTreeNode);
237
238 //initialize mu
239 mu.setColumnDimension(2);
240 mu.setRowDimension( treeModel.getNodeCount() ); //have a fixed number, although in reality, only K of them are active
241
242 for(int i=0; i < (treeModel.getNodeCount() ); i++){
243 double zero=0;
244 mu.getParameter(i).setValue(0, zero);
245 mu.getParameter(i).setValue(1, zero);
246 }
247
248 //adding the pre-clustering step.
249 // preClustering();
250
251 addVariable(virusLocations);
252
253 virusLocationsTreeNode.setColumnDimension(2); //mds dimension is 2
254 virusLocationsTreeNode.setRowDimension(numNodes);
255 addVariable(virusLocationsTreeNode);
256
257 addModel(treeModel);
258 addVariable(mu);
259
260 addVariable(muPrecision);
261 addVariable(p_on);
262
263 numdata = virusLocations.getColumnDimension();
264
265 //loadInitialMuLocations();
266 //loadIndicators();
267
268 //int []membershipToClusterLabelIndexes = new int[numdata];
269 //setMembershipToClusterLabelIndexes(); //run once in case the tree changes.
270 //setClusterLabelsParameter();
271
272 //loadIndicators();
273 //System.out.println("Finished loading the constructor for TreeClusteringVirusesPrior");
274
275 //genotype to phenotype
276 if(probSites_in != null){
277 sampleCausativeStates();
278
279 /*
280 for(int i=0; i< treeModel.getNodeCount(); i++){
281 System.out.print( (int)indicators.getParameterValue(i) + "\t");
282 System.out.print("node i=" + i +":\t");
283 if(mutationList[i] != null){
284 Iterator itr = mutationList[i].iterator();
285 Iterator itr2 = causalList[i].iterator();
286 while(itr.hasNext()){
287 int curMutation = ((Integer) itr.next()).intValue();
288 int curCausalState = ((Integer) itr2.next()).intValue();
289 System.out.print(curMutation + "(" + curCausalState +")" + " ");
290 }
291 }
292 System.out.println("");
293
294 }
295 */
296
297 }//genotype to phenotype
298
299 //System.out.println("exit");
300 //System.exit(0);
301
302
303 }
304
305
306
307 private void treeMutations() {
308
309 int numNodes = treeModel.getNodeCount();
310 // Get sequences
311 String[] sequence = new String[numNodes];
312
313 // Universal
314 String GENETIC_CODE_TABLES ="KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF";
315 int numCodons = -1; //needs to set it, when it looks at the sequence
316
317 for(int curIndex = 0; curIndex < numNodes; curIndex ++){
318 String ns = (String) treeModel.getNodeAttribute( treeModel.getNode(curIndex), "states");
319
320 if(endBase == -1){
321 endBase = ns.length() -1;
322 }
323
324
325 if( (endBase - startBase) % 3 != 0){
326 System.out.println("Nucleotide sequence needs to be triplet to convert to codon - check your startbase and endbase");
327 System.exit(0);
328 }
329 if(endBase > (ns.length()-1 ) ){
330 System.out.println("the last base cannot be greater than the length of the nucleotide. Exit now.");
331 System.exit(0);
332 }
333 if(startBase > (ns.length()-1 ) ){
334 System.out.println("the start base cannot be greater than the length of the nucleotide. Exit now.");
335 System.exit(0);
336 }
337 if(startBase > endBase){
338 System.out.println("Start base cannot be greater than the end base");
339 System.exit(0);
340 }
341
342 numSites = (endBase - startBase)/3;
343 numCodons = numSites;
344
345 //System.out.println("startbase = " + startBase);
346 //System.out.println("endbase = " + endBase);
347 //System.out.println("numSites = " + numSites);
348
349 ns = ns.substring(startBase, endBase );
350 //ns = ns.substring(3+27, ns.length() - 1);
351 //System.out.println(ns);
352 //System.exit(0);
353
354 //numCodons = ns.length()/3; // or do I care about only 330?
355
356 //System.out.println(numCodons);
357 String codonSequence = "";
358 for(int codon=0; codon< numCodons; codon++){
359
360 int nuc1 = Nucleotides.NUCLEOTIDE_STATES[ns.charAt(codon*3)];
361 int nuc2 = Nucleotides.NUCLEOTIDE_STATES[ns.charAt(codon*3+1)];
362 int nuc3 = Nucleotides.NUCLEOTIDE_STATES[ns.charAt(codon*3+2)];
363
364 int canonicalState = (nuc1 * 16) + (nuc2 * 4) + nuc3;
365
366 codonSequence = codonSequence + GENETIC_CODE_TABLES.charAt(canonicalState);
367 }
368 //System.out.println(codonSequence);
369 sequence[curIndex] = codonSequence;
370
371 }
372
373 mutationList = new LinkedList[ numNodes];
374 mutationString = new String[treeModel.getNodeCount()];
375
376 NodeRef cNode = treeModel.getRoot();
377 LinkedList<NodeRef> visitlist = new LinkedList<NodeRef>();
378
379 visitlist.add(cNode);
380
381 int countProcessed=0;
382 while(visitlist.size() > 0){
383 countProcessed++;
384 //assign value to the current node...
385 if(treeModel.getParent(cNode) == null){ //this means it is a root node
386 //visiting the root
387 //System.out.println(cNode.getNumber() + ":\t" + "root");
388 }
389 else{
390 //visiting
391 //System.out.print(cNode.getNumber() + ":\t");
392
393 //String listMutations = "\"";
394 mutationString[cNode.getNumber()] = "\"";
395 String nodeState = sequence[cNode.getNumber()];
396 String parentState = sequence[treeModel.getParent(cNode).getNumber()];
397
398 int count = 0;
399 for(int i=0; i < numCodons; i++){
400 if(nodeState.charAt(i) != parentState.charAt(i)){
401 count++;
402 if(count>1){
403 //System.out.print(",");
404 mutationString[cNode.getNumber()] = mutationString[cNode.getNumber()] + ",";
405 }
406 //System.out.print(i+1);
407 mutationString[cNode.getNumber()] = mutationString[cNode.getNumber()] + (i+1); //i+1 so mutation starts from 1 - 330
408
409 // Make sure the list is initialized before adding to it
410 if (mutationList[cNode.getNumber()] == null) {
411 mutationList[cNode.getNumber()] = new LinkedList<Integer>();
412 }
413 mutationList[cNode.getNumber()].add((i+1));
414
415 }
416
417 //store in linked list
418 }
419 //System.out.println("");
420 mutationString[cNode.getNumber()] = mutationString[cNode.getNumber()] + "\"";
421 }
422
423 //System.out.println(cNode.getNumber() + "\t" + treeModel.getNodeAttribute(cNode, "states") );
424
425
426 //add all the children to the queue
427 for(int childNum=0; childNum < treeModel.getChildCount(cNode); childNum++){
428 NodeRef node= treeModel.getChild(cNode,childNum);
429 visitlist.add(node);
430 }
431
432
433 visitlist.pop(); //now that we have finished visiting this node, pops it out of the queue
434
435 if(visitlist.size() > 0){
436 cNode = visitlist.getFirst(); //set the new first node in the queue to visit
437 }
438
439
440 }
441
442
443 }
444
445
446
447 //new version, with probSites determining the indicators
448 public double getLogLikelihood() {
449
450 double N_nodes = (double) treeModel.getNodeCount();
451
452 int K_value = 0; //K_int gets updated
453 for(int i=0; i < indicators.getDimension(); i++){
454 K_value += (int) indicators.getParameterValue(i);
455 }
456 //System.out.println("K_value" + K_value);
457
458 double logL = 0;
459
460 double muVariance = 1/ muPrecision.getParameterValue(0);
461 double p_onValue = p_on.getParameterValue(0);
462
463 //sync with the current value of p_on
464 //for(int k=0; k < treeModel.getNodeCount(); k++){
465 //probSites.setParameterValue(k, initial_p);
466 // probSites.setParameterValue(k, p_on.getParameterValue(0) );
467 //}
468
469
470 double muMeanParameter = muMean.getParameterValue(0);
471 //System.out.println("muMeanParameter = " + muMeanParameter);
472
473 for(int i=0; i < ( N_nodes ) ; i++){
474
475 double mu_i0 = mu.getParameter(i).getParameterValue(0);
476 double mu_i1 = mu.getParameter(i).getParameterValue(1);
477
478 //if( (int) indicators.getParameterValue(i) == 1){ //Commented out because I am not using P(mu_i = 0 | I_i = 0) = 1
479 logL -= 0.5*( (mu_i0 - muMeanParameter )*(mu_i0 - muMeanParameter ) + ( mu_i1 )*( mu_i1 ) )/muVariance;
480 //}
481 //System.out.println(logL);
482 }
483
484
485 //clustering
486 if(probSites == null){
487 logL -= (K_value ) * ( Math.log(2) + Math.log(Math.PI)+ Math.log(muVariance) );
488 }
489 //genotype to phenotype
490 else{
491 logL -= (N_nodes ) * ( Math.log(2) + Math.log(Math.PI)+ Math.log(muVariance) );
492
493 //4 priors:
494 //generic: assumes that each $\pi_j = \pi$, where $\pi \sim Beta(\alpha,\beta)$. The posterior $\pi$ is estimated from the MCMC run.
495 //Saturated prior: allows each $\pi_j$ to be different. $\pi_j$ is assumed to follow the hierarchical $Beta(\alpha, \beta)$ distribution, where $\alpha$ and $\beta$ are fixed according to plausible prior belief. The $Beta$ distribution is chosen because it is conjugate to the categorical distribution, so Gibbs sampling can be accomplished for $\pi$ (See details in the Implementation).
496 //Shrinkage Prior: models the belief about epitope and non-epitope sites. Here, we define a latent vector of binary indicators for amino acid positions $\delta = (\delta_1, \dots, \delta_L)$, where $\delta_k= 1$ if position $j$ is an epitope site and 0 otherwise.
497 //correlated prior: models the correlation among amino acid positions being epitopes or not (Figure \ref{correlationPrior}). This prior is motivated by the knowledge that groups of epitope sites tend to occur at adjacent positions.
498
499 double priorContribution = 0;
500 if(gp_prior.compareTo("correlated") == 0 ){
501 priorContribution = correlatedPriorComputation();
502 }
503 else if(gp_prior.compareTo("shrinkage") == 0 ){
504 priorContribution = shrinkagePriorComputation();
505 }
506 else if(gp_prior.compareTo("generic") == 0 ){
507 priorContribution = genericPriorComputation();
508 }
509 //saturated
510 else if(gp_prior.compareTo("saturated") == 0 ){
511 priorContribution = saturatedPriorComputation();
512 }
513 else{
514 System.out.println("Prior unknown. quit now");
515 System.exit(0);
516 }
517
518 logL += priorContribution;
519 //System.out.println(logL);
520 // System.exit(0);
521 if(logL != Double.NEGATIVE_INFINITY){
522 sampleCausativeStates();
523 }
524
525 } //end of genotype to phenotype
526 return(logL);
527 }
528
529
530 private double saturatedPriorComputation() {
531 double contribution = 0;
532 double N_nodes = (double) treeModel.getNodeCount();
533
534 double []probMutationSite = new double[numSites];
535 for(int i=0; i < numSites; i++){
536 probMutationSite[i] = probSites.getParameterValue(i);
537 }
538
539 //OMIT THE ROOT NODE BECAUSE THERE IS NO MUTATION ANYWAY
540 //(N_nodes - 1)
541 for(int i=0; i < (N_nodes-1) ; i ++){
542 double prob_Node_i_On = 1;
543 double prob_allMutationsOff = 1;
544 if(mutationList[i] != null){
545 Iterator itr = mutationList[i].iterator();
546 while(itr.hasNext()){
547 int curMutation = ((Integer) itr.next()).intValue();
548 prob_allMutationsOff = prob_allMutationsOff * (1 - probMutationSite[curMutation -1] ); //offset of 1
549 }
550 }
551
552 prob_Node_i_On = 1 - prob_allMutationsOff;
553 if( (int) indicators.getParameterValue(i) == 1){
554 contribution += Math.log(prob_Node_i_On);
555 }
556 else{
557 contribution += Math.log(1-prob_Node_i_On);
558 }
559 }
560 return(contribution);
561 }
562 private double genericPriorComputation() {
563 double contribution = 0;
564 double N_nodes = (double) treeModel.getNodeCount();
565
566 double probMutationSite = probSites.getParameterValue(0); // a single value.. not a vector
567
568 //OMIT THE ROOT NODE BECAUSE THERE IS NO MUTATION ANYWAY
569 //(N_nodes - 1)
570 for(int i=0; i < (N_nodes-1) ; i ++){
571 double prob_Node_i_On = 1;
572 double prob_allMutationsOff = 1;
573 if(mutationList[i] != null){
574 Iterator itr = mutationList[i].iterator();
575 while(itr.hasNext()){
576 int curMutation = ((Integer) itr.next()).intValue();
577 prob_allMutationsOff = prob_allMutationsOff * (1 - probMutationSite ); //offset of 1
578 }
579 }
580
581 prob_Node_i_On = 1 - prob_allMutationsOff;
582 if( (int) indicators.getParameterValue(i) == 1){
583 contribution += Math.log(prob_Node_i_On);
584 }
585 else{
586 contribution += Math.log(1-prob_Node_i_On);
587 }
588 }
589 return(contribution);
590 }
591
592 private double shrinkagePriorComputation() {
593 double contribution = 0;
594 double N_nodes = (double) treeModel.getNodeCount();
595
596 double []probMutationSite = new double[numSites];
597 for(int i=0; i < numSites; i++){
598 probMutationSite[i] = probSites.getParameterValue(i) * siteIndicators.getParameterValue(i) ; //with the null-ing out the probSites with siteIndicators
599 }
600
601 //OMIT THE ROOT NODE BECAUSE THERE IS NO MUTATION ANYWAY
602 //(N_nodes - 1)
603 for(int i=0; i < (N_nodes-1) ; i ++){
604 double prob_Node_i_On = 1;
605 double prob_allMutationsOff = 1;
606 if(mutationList[i] != null){
607 Iterator itr = mutationList[i].iterator();
608 while(itr.hasNext()){
609 int curMutation = ((Integer) itr.next()).intValue();
610 prob_allMutationsOff = prob_allMutationsOff * (1 - probMutationSite[curMutation -1] ); //offset of 1
611 }
612 }
613
614 prob_Node_i_On = 1 - prob_allMutationsOff;
615 if( (int) indicators.getParameterValue(i) == 1){
616 contribution += Math.log(prob_Node_i_On);
617 }
618 else{
619 contribution += Math.log(1-prob_Node_i_On);
620 }
621 }
622
623
624
625 int numSignificantSites = 0;
626 for(int i=0; i < numSites; i++){
627 if( (int) siteIndicators.getParameterValue(i) ==1){
628 numSignificantSites++;
629 }
630 }
631 int numNonSignificantSites = numSites - numSignificantSites;
632 //contribution += (numSignificantSites*Math.log( 0.45 ) + numNonSignificantSites*Math.log( 0.55 ) );
633 //contribution += (numSignificantSites*Math.log(0.2) + numNonSignificantSites*Math.log(0.8));
634 contribution += numSignificantSites*Math.log(p_on.getParameterValue(0)) + numNonSignificantSites*Math.log(1-p_on.getParameterValue(0));
635 //System.out.println("#sig= " + numSignificantSites + " #nonsig=" + numNonSignificantSites);
636
637
638 return(contribution);
639 }
640 private double correlatedPriorComputation() {
641 double contribution = 0;
642 double N_nodes = (double) treeModel.getNodeCount();
643
644 // p^k (1-p)^(numNodes - k)
645 //logL += K_value*Math.log( p_onValue ) + (N_nodes - K_value)*Math.log( 1- p_onValue);
646 //int numSites = 330; //now have a private variable
647 double []probMutationSite = new double[numSites];
648 for(int i=0; i < numSites; i++){
649 //probMutationSite[i] = probSites.getParameterValue(i);
650 probMutationSite[i] = probSites.getParameterValue(i) * siteIndicators.getParameterValue(i) ; //with the null-ing out the probSites with siteIndicators
651 }
652
653 //OMIT THE ROOT NODE BECAUSE THERE IS NO MUTATION ANYWAY
654 //(N_nodes - 1)
655 for(int i=0; i < (N_nodes-1) ; i ++){
656 double prob_Node_i_On = 1;
657 double prob_allMutationsOff = 1;
658 // for( each mutation in the node i){
659 // prob_allMutationsOff = prob_allMutationsOff * (1 - probSites.getParameterValue(curMutation_node_i));
660 // }
661 if(mutationList[i] != null){
662 Iterator itr = mutationList[i].iterator();
663 while(itr.hasNext()){
664 int curMutation = ((Integer) itr.next()).intValue();
665 prob_allMutationsOff = prob_allMutationsOff * (1 - probMutationSite[curMutation -1] ); //offset of 1
666 }
667 }
668
669
670
671 prob_Node_i_On = 1 - prob_allMutationsOff;
672 if( (int) indicators.getParameterValue(i) == 1){
673 contribution += Math.log(prob_Node_i_On);
674 }
675 else{
676 contribution += Math.log(1-prob_Node_i_On);
677 }
678 //System.out.println(logL);
679 //System.out.println("node=" + i + " prob=" + prob_Node_i_On);
680 }
681
682
683
684 // int numSignificantSites = 0;
685 // for(int i=0; i < numSites; i++){
686 // if( (int) siteIndicators.getParameterValue(i) ==1){
687 // numSignificantSites++;
688 // }
689 // }
690 // int numNonSignificantSites = numSites - numSignificantSites;
691 // logL += (numSignificantSites*Math.log( 0.45 )
692 // + numNonSignificantSites*Math.log( 0.55 ) );
693
694 //System.out.println("#sig= " + numSignificantSites + " #nonsig=" + numNonSignificantSites);
695
696 //logL += (numSignificantSites*Math.log(0.2) + numNonSignificantSites*Math.log(0.8));
697
698
699
700 //transition matrix:
701
702 // p(0->0) = 0.9, p(0->1) = 0.2
703 // p(1->0) = 0.6 p(1->1) = 0.4
704
705 contribution += Math.log(0.5); //initial
706 int numSignificantSites = 0;
707 int num_00=0;
708 int num_01=0;
709 int num_10=0;
710 int num_11=0;
711 for(int i=1; i < numSites; i++){
712 if( (int) siteIndicators.getParameterValue(i-1) ==0){
713 if( (int) siteIndicators.getParameterValue(i) ==0){
714 num_00++;
715 }
716 else{
717 num_01++;
718 }
719 }
720 else{
721 if( (int) siteIndicators.getParameterValue(i) ==0){
722 num_10++;
723 }
724 else{
725 num_11++;
726 }
727 }
728 }
729
730 double alpha = prob00; //0 stay as 0
731 double beta = prob11; // 1 stay as 1
732 // 0 1
733 //0 0.9 0.1
734 //1 0.5 0.5
735
736 contribution += ( num_00*Math.log( alpha ) + num_01*Math.log( 1-alpha )
737 +num_10*Math.log( 1-beta ) + num_11*Math.log(beta ) );
738
739 return(contribution);
740 }
741 public int[] getCausalCount(){
742 return(causalCount);
743 }
744
745 public int[] getNonCausalCount(){
746 return(nonCausalCount);
747 }
748
749 public LinkedList<Integer>[] getMutationsPerNode(){
750 return(mutationList);
751 }
752
753 public LinkedList<Integer>[] getCausativeStatesPerNode(){
754 return(causalList);
755 }
756
757
758 //the thing is, if the log likelihood is negative inifinity, this shouldn't be called
759 // because that means a siteInidicator gets flipped off... so then none of the mutation on the node is on..
760 //this should produce a 0 likelihood.
761 //so, no point of realizing the causal state if it is going to be rejected
762
763 //as a matter of fact, I think causal state should only be updated upon an acceptance move
764 public void sampleCausativeStates(){
765
766
767 causalCount = new int[numSites]; //HARD CODED
768 nonCausalCount = new int[numSites]; //HARD CODED
769 for(int i=0; i < numSites; i++){
770 causalCount[i] = 0;
771 nonCausalCount[i] = 0;
772 }
773
774 int N_nodes = (int) treeModel.getNodeCount();
775
776 //resample the whole set of causal states
777 causalList = new LinkedList[ N_nodes];
778
779 for(int curNode=0; curNode < (N_nodes-1) ; curNode ++){
780 double prob_Node_i_On = 1;
781 double prob_allMutationsOff = 1;
782 // for( each mutation in the node i){
783 // prob_allMutationsOff = prob_allMutationsOff * (1 - probSites.getParameterValue(curMutation_node_i));
784 // }
785
786 if((int) indicators.getParameterValue(curNode) == 0 ){
787 if(mutationList[curNode] != null){
788 causalList[curNode] = new LinkedList<Integer>();
789 Iterator itr = mutationList[curNode].iterator();
790 while(itr.hasNext()){
791 int curMutation = ((Integer) itr.next()).intValue();
792 causalList[curNode].add(new Integer(0));
793 nonCausalCount[curMutation -1]++;
794 }
795 }
796 }
797 else{ //if indicator is 1... then need to sample to get the causal indicator (the mutation(s) that give(s) causal state =1
798 if(mutationList[curNode] != null){
799
800 //System.out.println("cur node is " + curNode);
801
802 //count the number of mutations that has nonzero probabilities
803 //Iterator itr_it = mutationList[curNode].iterator();
804 //int count = 0;
805 //while(itr_it.hasNext()){
806 // int curMutation = ((Integer) itr_it.next()).intValue();
807 // if(probSites.getParameterValue(curMutation -1) * siteIndicators.getParameterValue(curMutation -1) >0){
808 // count++;
809 // }
810 //}
811 //int numMutations = count;
812 int numMutations = mutationList[curNode].size();
813
814 causalList[curNode] = new LinkedList<Integer>();
815 double[] probM = new double[numMutations];
816 Iterator itr = mutationList[curNode].iterator();
817 int count = 0;
818 while(itr.hasNext()){
819 int curMutation = ((Integer) itr.next()).intValue();
820 //prob_allMutationsOff = prob_allMutationsOff * (1 - probSites.getParameterValue(curMutation));
821 //probM[count]= probSites.getParameterValue(curMutation -1);
822 //if(probSites.getParameterValue(curMutation -1) * siteIndicators.getParameterValue(curMutation -1) >0){
823 if(gp_prior.compareTo("generic") == 0 ){
824 probM[count]= probSites.getParameterValue(0);
825 }
826 else if(gp_prior.compareTo("saturated") == 0 ){
827 probM[count]= probSites.getParameterValue(curMutation -1) ;
828 }
829 else if(gp_prior.compareTo("correlated") == 0 ||gp_prior.compareTo("shrinkage") == 0 ){
830 probM[count]= probSites.getParameterValue(curMutation -1) * siteIndicators.getParameterValue(curMutation -1);
831 }
832 count++;
833 //}
834 }
835
836
837 //System.out.println("numMutations = " + numMutations);
838 //generate all possibilities - the binary tuples (I think I actually don't have to realize it..)
839 //int numMutations = 3; //num mutations
840 double[] probPossibilities = new double[ (int) Math.pow(2,numMutations)];
841 //double[] probM = {0.05, 0.1, 0.2};
842
843 for(int kk=0; kk < Math.pow(2, numMutations); kk++){
844 int input = kk;
845
846 int[] bits = new int[numMutations];
847 for (int i = (numMutations-1); i >= 0; i--) {
848 bits[i] = ( (input & (1 << i)) != 0 ) ? 1 : 0;;
849 }
850 probPossibilities[kk] = 1;
851 for(int curM=0; curM < numMutations; curM++){
852 if(bits[curM] == 1){
853 probPossibilities[kk] = probPossibilities[kk] * probM[curM];
854 }
855 else{
856 probPossibilities[kk] = probPossibilities[kk] * (1- probM[curM]);
857 }
858 }
859 }
860 probPossibilities[0] = 0; //zero out the 0,0,0
861
862 //sample from the possibilities.. and then reconstruct back the binary tuple
863 int choice = MathUtils.randomChoicePDF(probPossibilities);
864 //System.out.println("choice is " + choice);
865
866 int[] bits = new int[numMutations];
867 for (int i = (numMutations-1); i >= 0; i--) {
868 bits[i] = ( (choice & (1 << i)) != 0 ) ? 1 : 0;;
869 causalList[curNode].add(new Integer(bits[i]));
870
871 if(bits[i] ==1){
872 causalCount[mutationList[curNode].get(i).intValue() -1 ]++;
873 }
874 else{
875 nonCausalCount[mutationList[curNode].get(i).intValue()-1]++;
876 }
877 }
878 //System.out.print(choice + " = " + Arrays.toString(bits) + "\t");
879
880
881
882
883 //System.exit(0);
884
885
886 }
887 }
888 }
889
890 /*
891 for(int i=0; i < 330; i++){
892 System.out.println(i + "\t" + causalCount[i] + " " + nonCausalCount[i]);
893 }
894 System.out.println("=====================");
895 */
896 }
897
898
899
900 /*
901 public double getLogLikelihood() {
902
903 double N_nodes = (double) treeModel.getNodeCount();
904
905 int K_value = 0; //K_int gets updated
906 for(int i=0; i < indicators.getDimension(); i++){
907 K_value += (int) indicators.getParameterValue(i);
908 }
909 //System.out.println("K_value" + K_value);
910
911 double logL = 0;
912
913 double muVariance = 1/ muPrecision.getParameterValue(0);
914 double p_onValue = p_on.getParameterValue(0);
915 double muMeanParameter = muMean.getParameterValue(0);
916 //System.out.println("muMeanParameter = " + muMeanParameter);
917 //logL -= (K_value ) * ( Math.log(2) + Math.log(Math.PI)+ Math.log(muVariance) );
918 logL -= (N_nodes ) * ( Math.log(2) + Math.log(Math.PI)+ Math.log(muVariance) );
919
920 for(int i=0; i < ( N_nodes ) ; i++){
921
922 double mu_i0 = mu.getParameter(i).getParameterValue(0);
923 double mu_i1 = mu.getParameter(i).getParameterValue(1);
924
925 //if( (int) indicators.getParameterValue(i) == 1){ //Commented out because I am not using P(mu_i = 0 | I_i = 0) = 1
926 logL -= 0.5*( (mu_i0 - muMeanParameter )*(mu_i0 - muMeanParameter ) + ( mu_i1 )*( mu_i1 ) )/muVariance;
927 //}
928 //System.out.println(logL);
929 }
930
931 // p^k (1-p)^(numNodes - k)
932 logL += K_value*Math.log( p_onValue ) + (N_nodes - K_value)*Math.log( 1- p_onValue);
933 return(logL);
934 }
935 */
936
937
938
939 private void loadIndicators() {
940
941 FileReader fileReader2;
942 try {
943 //fileReader2 = new FileReader("/Users/charles/Documents/research/antigenic/GenoPheno/Gabriela/results/initialCondition/H3N2.serumLocs.log");
944 //fileReader2 = new FileReader("/Users/charles/Documents/researchData/clustering/output/test25/run64/H3N2_mds.breakpoints.log");
945 // fileReader2 = new FileReader("/Users/charles/Documents/researchData/clustering/output/test25/run79/H3N2_mds.indicators.log");
946 fileReader2 = new FileReader("/Users/charles/Documents/researchData/clustering/output/test26/run20-test/H3N2_mds.indicatorsStat-120000.log");
947
948 BufferedReader bReader2 = new BufferedReader( fileReader2);
949
950 String line = null;
951
952 //skip to the last line
953 String testLine;
954 while ((testLine = bReader2.readLine()) != null){
955 line = testLine;
956 }
957
958 // System.out.println(line);
959
960 String datavalue[] = line.split("\t");
961
962
963 // System.out.println(serumLocationsParameter.getParameterCount());
964 for (int i = 0; i < treeModel.getNodeCount(); i++) {
965
966 indicators.setParameterValue(i, Double.parseDouble(datavalue[i+1]));
967 // System.out.println(datavalue[i*2+1]);
968 // System.out.println("indicator=" + indicators.getParameterValue(i));
969
970 }
971 bReader2.close();
972
973 } catch (FileNotFoundException e) {
974 // TODO Auto-generated catch block
975 e.printStackTrace();
976 } catch (IOException e) {
977 // TODO Auto-generated catch block
978 e.printStackTrace();
979 }
980
981
982
983 }
984
985
986
987
988
989 private void loadInitialMuLocations() {
990
991 FileReader fileReader2;
992 try {
993 //fileReader2 = new FileReader("/Users/charles/Documents/research/antigenic/GenoPheno/Gabriela/results/initialCondition/H3N2.serumLocs.log");
994 //fileReader2 = new FileReader("/Users/charles/Documents/researchData/clustering/output/test25/run64/H3N2_mds.mu.log");
995 fileReader2 = new FileReader("/Users/charles/Documents/researchData/clustering/output/test25/run79/H3N2_mds.mu.log");
996
997 BufferedReader bReader2 = new BufferedReader( fileReader2);
998
999 String line = null;
1000
1001 //skip to the last line
1002 String testLine;
1003 while ((testLine = bReader2.readLine()) != null){
1004 line = testLine;
1005 }
1006
1007 // System.out.println(line);
1008
1009 String datavalue[] = line.split("\t");
1010
1011
1012 // System.out.println(serumLocationsParameter.getParameterCount());
1013 for (int i = 0; i < mu.getParameterCount(); i++) {
1014
1015 double dim1 = Double.parseDouble(datavalue[i*2+1]);
1016 double dim2 = Double.parseDouble(datavalue[i*2+2]);
1017 mu.getParameter(i).setParameterValue(0, dim1);
1018 mu.getParameter(i).setParameterValue(1, dim2);
1019 // System.out.println(datavalue[i*2+1]);
1020 // System.out.println("mu=" + mu.getParameter(i).getParameterValue(0) +"," + mu.getParameter(i).getParameterValue(1));
1021
1022 }
1023 bReader2.close();
1024
1025 } catch (FileNotFoundException e) {
1026 e.printStackTrace();
1027 } catch (IOException e) {
1028 e.printStackTrace();
1029 }
1030
1031
1032
1033 }
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043 private void setMembershipToClusterLabelIndexes(){
1044 int numNodes = treeModel.getNodeCount();
1045
1046 //I suspect this is an expensive operation, so I don't want to do it many times,
1047 //which is also unnecessary - MAY have to update whenever a different tree is used.
1048 membershipToClusterLabelIndexes = new int[numdata];
1049 for(int i=0; i < numdata; i++){
1050 Parameter v = virusLocations.getParameter(i);
1051 String curName = v.getParameterName();
1052 // System.out.println(curName);
1053 int isFound = 0;
1054 for(int j=0; j < numNodes; j++){
1055 String treeId = treeModel.getTaxonId(j);
1056 if(curName.equals(treeId) ){
1057 // System.out.println(" isFound at j=" + j);
1058 membershipToClusterLabelIndexes[i] = j;
1059 isFound=1;
1060 break;
1061 }
1062 }
1063 if(isFound ==0){
1064 System.out.println("not found. Exit now.");
1065 System.exit(0);
1066 }
1067 }
1068 }
1069
1070
1071
1072 private void setClusterLabelsParameter() {
1073 int K_int = 0;
1074 for(int i=0; i < treeModel.getNodeCount(); i++){
1075 if( (int) indicators.getParameterValue( i ) ==1 ){
1076 K_int++;
1077 }
1078 }
1079
1080 int numNodes = treeModel.getNodeCount();
1081 int[] cutNodes = new int[K_int];
1082 int cutNum = 0;
1083 String content = "";
1084 for(int i=0; i < numNodes; i++){
1085 if( (int) indicators.getParameterValue( i ) ==1 ){
1086 cutNodes[cutNum] = i;
1087 content += i + ",";
1088 cutNum++;
1089 }
1090 }
1091
1092 int []membership = determine_membership(treeModel, cutNodes, K_int);
1093
1094 for(int i=0; i < numdata; i++){
1095 clusterLabels.setParameterValue( i, membership[membershipToClusterLabelIndexes[i]]); //The assumption that the first nodes being external node corresponding to the cluster labels IS FALSE, so I have to search for the matching indexes
1096 //Parameter vloc = virusLocations.getParameter(i);
1097 //System.out.println(vloc.getParameterName() + " i="+ i + " membership=" + (int) clusterLabels.getParameterValue(i));
1098 }
1099
1100 }
1101
1102
1103 //traverse down the tree, top down, do calculation
1104 static int[] determine_membership(TreeModel treeModel, int[] cutNodes, int numCuts){
1105
1106
1107 //TEMPORARY SOLUTION
1108 //load in the titer, corresponding to the taxon #.
1109
1110 TiterImporter titer = null ;
1111
1112 FileReader fileReader;
1113 try {
1114 fileReader = new FileReader("/Users/charles/Documents/research/antigenic/GenoPheno/data/taxon_y_titer.txt");
1115 titer = new TiterImporter(fileReader);
1116
1117 } catch (FileNotFoundException e) {
1118 // TODO Auto-generated catch block
1119 e.printStackTrace();
1120 }
1121
1122 NodeRef root = treeModel.getRoot();
1123
1124 int numClusters = 1;
1125 LinkedList<NodeRef> list = new LinkedList<NodeRef>();
1126 list.addFirst(root);
1127
1128 int[] membership = new int[treeModel.getNodeCount()];
1129 for(int i=0; i < treeModel.getNodeCount(); i++){
1130 membership[i] = -1;
1131 }
1132 membership[root.getNumber()] = 0; //root always given the first cluster
1133
1134 while(!list.isEmpty()){
1135 //do things with the current object
1136 NodeRef curElement = list.pop();
1137 //String content = "node #" + curElement.getNumber() +", taxon=" + treeModel.getNodeTaxon(curElement) + " and parent is = " ;
1138 String content = "node #" + curElement.getNumber() +", taxon= " ;
1139 if(treeModel.getNodeTaxon(curElement)== null){
1140 content += "internal node\t";
1141 }
1142 else{
1143 content += treeModel.getNodeTaxon(curElement).getId() + "\t";
1144 //content += treeModel.getTaxonIndex(treeModel.getNodeTaxon(curElement)) + "\t";
1145 }
1146
1147 if(treeModel.getParent(curElement)== null){
1148 //content += "no parent";
1149 }
1150 else{
1151 //content += "parent node#=" + treeModel.getParent(curElement).getNumber();
1152 }
1153
1154 //cluster assignment:
1155 if(!treeModel.isRoot(curElement)){
1156 if(isCutNode(curElement.getNumber(), cutNodes, numCuts)){
1157 //if(isCutNode(curElement.getNumber())){
1158 numClusters++ ;
1159 membership[ curElement.getNumber() ] = numClusters - 1;
1160 }
1161 else{
1162 //inherit from parent's cluster assignment
1163 membership[curElement.getNumber()] = membership[treeModel.getParent(curElement).getNumber()];
1164 }
1165
1166 }//is not Root
1167 content += " cluster = " + membership[curElement.getNumber()] ;
1168
1169 // System.out.println(content);
1170
1171
1172 for(int childNum=0; childNum < treeModel.getChildCount(curElement); childNum++){
1173 list.addFirst(treeModel.getChild(curElement,childNum));
1174 }
1175 }
1176
1177 return(membership);
1178 }
1179
1180
1181 private static boolean isCutNode(int number, int cutNodes[], int numCut) {
1182 if(numCut > 0){
1183 for(int i=0; i < numCut; i++){
1184 if(number == cutNodes[i]){
1185 return true;
1186 }
1187 }
1188 }
1189 return false;
1190 }
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203 //=====================================================================================================================
1204
1205
1206 public int factorial(int n) {
1207 int fact = 1; // this will be the result
1208 for (int i = 1; i <= n; i++) {
1209 fact *= i;
1210 }
1211 return fact;
1212 }
1213
1214
1215 public Model getModel() {
1216 return this;
1217 }
1218
1219 public void makeDirty() {
1220 }
1221
1222 public void acceptState() {
1223 // DO NOTHING
1224 }
1225
1226 public void restoreState() {
1227 // DO NOTHING
1228 }
1229
1230 public void storeState() {
1231 // DO NOTHING
1232 }
1233
1234
1235
1236 protected void handleModelChangedEvent(Model model, Object object, int index) {
1237 if(model == treeModel){
1238 //System.out.println("==========Tree model changes!!!!!!!!=====");
1239 treeChanged = true;
1240 }
1241 else{
1242 }
1243 }
1244
1245 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
1246 }
1247
1248
1249
1250
1251
1252 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
1253
1254 public final static String EXCISIONPOINTS = "excisionPoints";
1255 public final static String CLUSTERLABELS = "clusterLabels";
1256 public final static String CLUSTERLABELSTREENODE = "clusterLabelsTreeNode";
1257
1258 public final static String MU = "mu";
1259
1260 public final static String OFFSETS = "offsets";
1261 public final static String VIRUS_LOCATIONS = "virusLocations";
1262 public final static String VIRUS_LOCATIONSTREENODE = "virusLocationsTreeNodes";
1263
1264 public final static String INDICATORS = "indicators";
1265 public final static String PROBSITES = "probSites";
1266 public final static String SITEINDICATORS = "siteIndicators";
1267
1268
1269 boolean integrate = false;
1270
1271
1272 // public final static String MUVARIANCE = "muVariance";
1273 public final static String MUPRECISION = "muPrecision";
1274 public final static String PROBACTIVENODE = "probActiveNode";
1275
1276 public final static String INITIALNUMCLUSTERS = "initialK";
1277 public final static String MUMEAN = "muMean";
1278
1279 public final static String STARTBASE = "startNucleotide";
1280 public final static String ENDBASE = "endNucleotide";
1281
1282 public final static String PROB00 = "prob00";
1283 public final static String PROB11 = "prob11";
1284
1285
1286
1287 public final static String INITIAL_PROBSITE_VALUE = "initialProbSite";
1288
1289 public final static String GP_PRIOR_OPTION = "gp_prior";
1290
1291 public String getParserName() {
1292 return TREE_CLUSTER_VIRUSES;
1293 }
1294
1295 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
1296
1297
1298 double initialK = 10;
1299 if (xo.hasAttribute(INITIALNUMCLUSTERS)) {
1300 initialK = xo.getDoubleAttribute(INITIALNUMCLUSTERS);
1301 }
1302
1303 double prob00 = 0.95;
1304 if (xo.hasAttribute(PROB00)) {
1305 prob00 = xo.getDoubleAttribute(PROB00);
1306 }
1307 double prob11 = 0.5;
1308 if (xo.hasAttribute(PROB11)) {
1309 prob11 = xo.getDoubleAttribute(PROB11);
1310 }
1311
1312 double initial_probSiteValue = 0.05;
1313 if (xo.hasAttribute(INITIAL_PROBSITE_VALUE)) {
1314 initial_probSiteValue = xo.getDoubleAttribute(INITIAL_PROBSITE_VALUE);
1315 }
1316
1317
1318
1319
1320
1321
1322 int startBase = 0;
1323 if (xo.hasAttribute(STARTBASE)) {
1324 startBase = xo.getIntegerAttribute(STARTBASE) - 1; //minus 1 because index begins at 0
1325 }
1326
1327 int endBase = -1;
1328 if (xo.hasAttribute(ENDBASE)) {
1329 endBase = xo.getIntegerAttribute(ENDBASE) -1 ; //minus 1 because index begins at 0
1330 }
1331
1332 String gp_prior = "";
1333 if (xo.hasAttribute(GP_PRIOR_OPTION)) {
1334 gp_prior = xo.getStringAttribute(GP_PRIOR_OPTION) ; //minus 1 because index begins at 0
1335 }
1336
1337
1338 TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
1339
1340 XMLObject cxo = xo.getChild(CLUSTERLABELS);
1341 Parameter clusterLabels = (Parameter) cxo.getChild(Parameter.class);
1342
1343 cxo = xo.getChild(CLUSTERLABELSTREENODE);
1344 Parameter clusterLabelsTreeNode = (Parameter) cxo.getChild(Parameter.class);
1345
1346
1347 cxo = xo.getChild(MU);
1348 MatrixParameter mu = (MatrixParameter) cxo.getChild(MatrixParameter.class);
1349
1350 cxo=xo.getChild(VIRUS_LOCATIONS);
1351 MatrixParameter virusLocations =(MatrixParameter) cxo.getChild(MatrixParameter.class);
1352
1353 cxo = xo.getChild(VIRUS_LOCATIONSTREENODE);
1354 MatrixParameter virusLocationsTreeNode =(MatrixParameter) cxo.getChild(MatrixParameter.class);
1355
1356 cxo = xo.getChild(INDICATORS);
1357 Parameter indicators = (Parameter) cxo.getChild(Parameter.class);
1358
1359 cxo = xo.getChild(SITEINDICATORS);
1360 Parameter siteIndicators = null;
1361 if(cxo != null){
1362 siteIndicators = (Parameter) cxo.getChild(Parameter.class);
1363 }
1364
1365 cxo = xo.getChild(PROBSITES);
1366 Parameter probSites = null;
1367 if(cxo != null){
1368 probSites = (Parameter) cxo.getChild(Parameter.class);
1369 }
1370
1371 cxo = xo.getChild(MUPRECISION);
1372 Parameter muPrecision = (Parameter) cxo.getChild(Parameter.class);
1373
1374 cxo = xo.getChild(PROBACTIVENODE);
1375 Parameter probActiveNode = (Parameter) cxo.getChild(Parameter.class);
1376
1377 boolean hasDrift = false;
1378
1379 cxo = xo.getChild(MUMEAN);
1380 Parameter muMean = (Parameter) cxo.getChild(Parameter.class);
1381
1382 return new TreeClusteringVirusesPrior(treeModel, indicators, clusterLabels, clusterLabelsTreeNode, mu, hasDrift, virusLocations, virusLocationsTreeNode, muPrecision, probActiveNode, initialK, muMean, probSites, siteIndicators,
1383 startBase, endBase, gp_prior, prob00, prob11, initial_probSiteValue);
1384 }
1385
1386 //************************************************************************
1387 // AbstractXMLObjectParser implementation
1388 //************************************************************************
1389
1390 public String getParserDescription() {
1391 return "tree clustering viruses";
1392 }
1393
1394 public Class getReturnType() {
1395 return TreeClusteringVirusesPrior.class;
1396 }
1397
1398 public XMLSyntaxRule[] getSyntaxRules() {
1399 return rules;
1400 }
1401
1402
1403 private final XMLSyntaxRule[] rules = {
1404 //AttributeRule.newDoubleRule(MUVARIANCE, true, "the variance of mu"),
1405 //AttributeRule.newDoubleRule(PROBACTIVENODE, true, "the prior probability of turning on a node"),
1406 AttributeRule.newDoubleRule(INITIALNUMCLUSTERS, true, "the initial number of clusters"),
1407 AttributeRule.newDoubleRule(STARTBASE, true, "the start base in the sequence to consider in the genotype to phenotype model"),
1408 AttributeRule.newIntegerRule(ENDBASE, true, "the end base in the sequence to consider in the genotype to phenotype model"),
1409 AttributeRule.newIntegerRule(STARTBASE, true, "the start base in the sequence to consider in the genotype to phenotype model"),
1410 AttributeRule.newDoubleRule(PROB00, true, "correlated prior - the probability of staying at state 0 for adjacent siteIndicator"),
1411 AttributeRule.newDoubleRule(PROB11, true, "correlated prior - the probability of staying at state 1 for adjacent siteIndicator"),
1412 AttributeRule.newStringRule(GP_PRIOR_OPTION, true, "specifying the prior for probSites (and siteIndicators)"),
1413 AttributeRule.newDoubleRule(INITIAL_PROBSITE_VALUE, true, "the initial value of the probSite"),
1414
1415 new ElementRule(EXCISIONPOINTS, Parameter.class),
1416 new ElementRule(CLUSTERLABELS, Parameter.class),
1417 new ElementRule(CLUSTERLABELSTREENODE, Parameter.class),
1418 new ElementRule(VIRUS_LOCATIONSTREENODE, MatrixParameter.class),
1419 new ElementRule(MU, MatrixParameter.class),
1420 // new ElementRule(OFFSETS, Parameter.class),
1421 new ElementRule(VIRUS_LOCATIONS, MatrixParameter.class),
1422 new ElementRule(INDICATORS, Parameter.class),
1423 //make it so that it isn't required
1424 new ElementRule(SITEINDICATORS, Parameter.class, "the indicator of a site having probability greater than 0 of being associated with antigenic transition", true),
1425 new ElementRule(PROBSITES, Parameter.class, "the probability that mutation on a site is associated with antigenic transition", true),
1426 new ElementRule(TreeModel.class),
1427 new ElementRule(MUPRECISION, Parameter.class),
1428 new ElementRule(PROBACTIVENODE, Parameter.class),
1429 new ElementRule(MUMEAN, Parameter.class)
1430 };
1431
1432 };
1433
1434 String Atribute = null;
1435
1436
1437 public int getNumSites() {
1438 return numSites;
1439 }
1440 public int getStartBase() {
1441 return startBase;
1442 }
1443 public int getEndBase() {
1444 // TODO Auto-generated method stub
1445 return endBase;
1446 }
1447
1448 }
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461 //load initial serum location - load the last line
1462 //OBSOLETE WITH THE NEW indicators
1463 /*
1464 private void loadBreakpoints() {
1465
1466 FileReader fileReader2;
1467 try {
1468
1469 //fileReader2 = new FileReader("/Users/charles/Documents/researchData/clustering/output/test23/run4/H3N2_mds.breakPoints.log");
1470
1471 fileReader2 = new FileReader("/Users/charles/Documents/researchData/clustering/output/test25/run5/H3N2_mds.breakpoints.log");
1472 BufferedReader bReader2 = new BufferedReader( fileReader2);
1473
1474 String line = null;
1475
1476 //skip to the last line
1477 String testLine;
1478 while ((testLine = bReader2.readLine()) != null){
1479 line = testLine;
1480 }
1481
1482 System.out.println(line);
1483
1484 String datavalue[] = line.split("\t");
1485
1486
1487 // System.out.println(serumLocationsParameter.getParameterCount());
1488 for (int i = 0; i < treeModel.getNodeCount(); i++) {
1489
1490 breakPoints.setParameterValue(i, Double.parseDouble(datavalue[i+1]));
1491 // System.out.println(datavalue[i*2+1]);
1492 System.out.println("indicators=" + breakPoints.getParameterValue(i));
1493
1494 }
1495 bReader2.close();
1496
1497 } catch (FileNotFoundException e) {
1498 // TODO Auto-generated catch block
1499 e.printStackTrace();
1500 } catch (IOException e) {
1501 // TODO Auto-generated catch block
1502 e.printStackTrace();
1503 }
1504
1505
1506
1507 }
1508
1509 */
1510
1511
1512 //OBSOLETE WITH INDICATORS..
1513 //load initial serum location - load the last line
1514 /*
1515 private void loadStatus() {
1516
1517 FileReader fileReader2;
1518 try {
1519 //fileReader2 = new FileReader("/Users/charles/Documents/research/antigenic/GenoPheno/Gabriela/results/initialCondition/H3N2.serumLocs.log");
1520 fileReader2 = new FileReader("/Users/charles/Documents/researchData/clustering/output/test23/run4/H3N2_mds.status.log");
1521
1522 BufferedReader bReader2 = new BufferedReader( fileReader2);
1523
1524 String line = null;
1525
1526 //skip to the last line
1527 String testLine;
1528 while ((testLine = bReader2.readLine()) != null){
1529 line = testLine;
1530 }
1531
1532 System.out.println(line);
1533
1534 String datavalue[] = line.split("\t");
1535
1536
1537 // System.out.println(serumLocationsParameter.getParameterCount());
1538 for (int i = 0; i < binSize; i++) {
1539
1540 indicators.setParameterValue(i, Double.parseDouble(datavalue[i+1]));
1541 // System.out.println(datavalue[i*2+1]);
1542 System.out.println("excisionPoints=" + indicators.getParameterValue(i));
1543
1544 }
1545 bReader2.close();
1546
1547 } catch (FileNotFoundException e) {
1548 // TODO Auto-generated catch block
1549 e.printStackTrace();
1550 } catch (IOException e) {
1551 // TODO Auto-generated catch block
1552 e.printStackTrace();
1553 }
1554
1555
1556
1557 }
1558 */
1559
1560
1561
1562 /*
1563
1564
1565
1566
1567
1568
1569
1570
1571 private void preClustering() {
1572
1573
1574 int numNodes = treeModel.getNodeCount(); //need to re-evaluate
1575
1576 int []isOccupied = new int[numNodes];
1577 //initial bag:
1578 //int numNonZeroIndicators = 0;
1579 //nonZeroIndexes = new int[numNodes]; //another variable for quick access of the indexes that are turned on - only the first numNonZeroIndicators are meaningful
1580
1581 //assumption: numOn << than the numNodes
1582 for(int k=0; k< treeModel.getNodeCount(); k++){
1583 //sample another one.
1584 int sampleNew = 1;
1585 while(sampleNew ==1){
1586 int rSiteIndex = (int) Math.floor( Math.random()*numNodes );
1587 if(isOccupied[rSiteIndex] == 0){
1588 //success sampling
1589 //System.out.println("rSiteIndex "+ rSiteIndex);
1590 indicators.setParameterValue( rSiteIndex, 1);
1591 isOccupied[rSiteIndex] = 1;
1592 //nonZeroIndexes[numNonZeroIndicators] = rSiteIndex;
1593 //numNonZeroIndicators++; // be filled to be equal to the numOn
1594 sampleNew = 0;
1595 }
1596 }
1597 }
1598
1599
1600 int K_int = (int) K.getParameterValue(0);
1601 for(int k=0; k< (K_int-1); k++){
1602 //sample another one.
1603 int sampleNew = 1;
1604 while(sampleNew ==1){
1605 int rSiteIndex = (int) Math.floor( Math.random()*numNodes );
1606 if(indicators.getParameterValue(rSiteIndex) == 0){
1607 //success sampling
1608 indicators.setParameterValue(rSiteIndex , 1);
1609 //nonZeroIndexes[numNonZeroIndicators] = rSiteIndex;
1610 //numNonZeroIndicators++; // be filled to be equal to the numOn
1611 sampleNew = 0;
1612 }
1613
1614 }
1615 }
1616
1617 //for(int i=0; i < binSize; i++){
1618 // System.out.println("excision point = " + excisionPoints.getParameterValue(i));
1619 //}
1620
1621 //for(int i=0; i < numNonZeroIndicators; i++){
1622 //System.out.println(nonZeroIndexes[i]);
1623 //}
1624
1625
1626 // NodeRef node = treeModel.getRoot();
1627
1628 // if(treeModel.isExternal(node)){
1629 // System.out.println("External node");
1630 // }
1631 // else{
1632 // System.out.println("Internal node");
1633 // }
1634
1635
1636 int[] cutNodes = new int[K_int];
1637 int cutNum = 0;
1638 for(int i=0; i < numNodes; i++){
1639 if( (int) indicators.getParameterValue( i ) ==1 ){
1640 cutNodes[cutNum] = i;
1641 cutNum++;
1642 }
1643
1644 }
1645
1646 // for(int i=0; i < K_int; i++){
1647 // System.out.println(cutNodes[i]);
1648 // }
1649
1650 int []membership = determine_membership(treeModel, cutNodes, K_int-1);
1651
1652 // System.out.println("number of nodes = " + treeModel.getNodeCount());
1653 // for(int i=0; i < treeModel.getNodeCount(); i++){
1654 // System.out.println(membership[i]);
1655 // }
1656
1657
1658 //System.out.println("Done");
1659
1660 // for(int i=0; i < numdata; i++){
1661 // Parameter v = virusLocations.getParameter(i);
1662 // String curName = v.getParameterName();
1663 // System.out.println("i=" + i + " = " + curName);
1664 // }
1665
1666 // for(int j=0; j < numdata; j++){
1667 // System.out.println("j=" + j + " = " + treeModel.getTaxonId(j));
1668 // }
1669
1670
1671 // Parameter vv = virusLocations.getParameter(0);
1672 // String curNamev = vv.getParameterName();
1673
1674 // System.out.println(curNamev + " and " +treeModel.getTaxonId(392) );
1675 //System.out.println( curNamev.equals(treeModel.getTaxonId(392) ) );
1676
1677
1678 //System.exit(0);
1679
1680 // System.out.println("numNodes=" + numNodes);
1681 // System.exit(0);
1682 //create dictionary:
1683
1684 //I suspect this is an expensive operation, so I don't want to do it many times,
1685 //which is also unnecessary
1686 int []membershipToClusterLabelIndexes = new int[numdata];
1687 for(int i=0; i < numdata; i++){
1688 Parameter v = virusLocations.getParameter(i);
1689 String curName = v.getParameterName();
1690 // System.out.println(curName);
1691 int isFound = 0;
1692 for(int j=0; j < numNodes; j++){
1693 String treeId = treeModel.getTaxonId(j);
1694 if(curName.equals(treeId) ){
1695 // System.out.println(" isFound at j=" + j);
1696 membershipToClusterLabelIndexes[i] = j;
1697 isFound=1;
1698 break;
1699 }
1700
1701 }
1702 if(isFound ==0){
1703 System.out.println("not found. Exit now.");
1704 System.exit(0);
1705 }
1706 }
1707
1708
1709 // System.exit(0);
1710
1711 // for(int i=0; i < numdata; i++){
1712 // System.out.println(membershipToClusterLabelIndexes[i]);
1713 // }
1714 // System.exit(0);
1715
1716 for(int i=0; i < numdata; i++){
1717 //The assumption that the first nodes being external node corresponding to the cluster labels IS FALSE
1718 //so I have to search for the matching indexes
1719 Parameter vloc = virusLocations.getParameter(i);
1720
1721 clusterLabels.setParameterValue( i, membership[membershipToClusterLabelIndexes[i]]);
1722 // System.out.println(vloc.getParameterName() + " i="+ i + " membership=" + (int) clusterLabels.getParameterValue(i));
1723
1724 // Parameter v = virusLocations.getParameter(i);
1725 // System.out.println(v.getParameterName());
1726 }
1727
1728
1729 // System.out.println("Exit now");
1730 // System.exit(0);
1731
1732
1733 int numViruses = offsets.getSize();
1734 System.out.println("# offsets = " + offsets.getSize());
1735 //for(int i=0; i < offsets.getSize(); i++){
1736 //System.out.println(offsets.getParameterValue(i));
1737 //}
1738
1739
1740 //Need a routine to convert the membership back to clusterlabels for external nodes..
1741
1742
1743 int maxLabel=0;
1744 for(int i=0;i< numdata; i++){
1745 if(maxLabel < (int) clusterLabels.getParameterValue(i)){
1746 maxLabel = (int) clusterLabels.getParameterValue(i);
1747 }
1748 }
1749
1750
1751 //now, change the mu..
1752 for(int i=0; i <= maxLabel; i++){
1753 //System.out.println(meanYear[i]*beta);
1754 //mu.getParameter(i).setParameterValue(0, meanYear[i]*beta);//now separate out mu from virusLocation
1755 mu.getParameter(i).setParameterValue(0, 0);
1756 mu.getParameter(i).setParameterValue(1, 0);
1757 }
1758
1759
1760 //System.exit(0);
1761
1762 */