Debian Codegraph @

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

raw symbols SCIP
1 package dr.evomodel.antigenic.phyloclustering.misc.obsolete;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.LinkedList;
6 import java.util.List;
7 import java.util.Set;
8
9 import dr.evolution.tree.NodeRef;
10 //import dr.evomodel.antigenic.driver.OrderDouble;
11
12 import dr.evomodel.tree.TreeModel;
13 import dr.inference.model.AbstractModelLikelihood;
14 import dr.inference.model.CompoundParameter;
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.xml.AbstractXMLObjectParser;
20 import dr.xml.ElementRule;
21 import dr.xml.XMLObject;
22 import dr.xml.XMLObjectParser;
23 import dr.xml.XMLParseException;
24 import dr.xml.XMLSyntaxRule;
25
26 /**
27 * @author Charles Cheung
28 * @author Trevor Bedford
29 */
30
31 //Some suggestion to speed up the code from Charles Cheung
32 //(please scroll through to places marked by to see the places of changes //---------- suggestion from cykc----------------
33
34
35 public class ClusterViruses extends AbstractModelLikelihood {
36
37 //---------- suggestion from cykc----------------
38 private double mostRecentTransformedValue = 0; //keep a copy of the most recent version of transformFactor, to keep track of whether the transformFactor has changed
39 //private boolean ShouldUpdateDepMatrix = true; // this way of flagging for change is not used anymore
40 private boolean treeChanged = false; //a flag that becomes true when treeModel changes
41 //---------- End of suggestion from cykc----------------
42
43 public static final String CLUSTER_VIRUSES = "ClusterViruses";
44
45
46
47
48 //==============================================================================================================================
49 //variables
50
51
52 double lambda = 10;
53 double sigmaSq = 9;
54 // double sigmaSq = 100; //when offset is off
55
56
57 //K - number of parameters
58 Parameter K; // for now, there is no move to change K
59
60 //E|K - excision points
61 Parameter excisionPoints;
62
63 //C
64 Parameter clusterLabels;
65
66 //mu - means
67 MatrixParameter mu;
68
69
70 double[] muLabels;
71
72
73 MatrixParameter virusLocations = null;
74
75
76
77
78 // Parameter virusOffsetsParameter; //need to read it from AntigenicLIkelihood (the year ) // use offsets instead
79
80 //need to stop the virus from
81
82
83
84
85
86
87 public ClusterViruses (TreeModel treeModel_in,
88 Parameter K_in,
89 Parameter excisionPoints_in,
90 Parameter clusterLabels_in,
91 MatrixParameter mu_in,
92 Boolean hasDrift,
93 // Parameter locationDrift_in,
94 Parameter offsets_in,
95 MatrixParameter virusLocations_in){
96
97 super(CLUSTER_VIRUSES);
98
99 this.treeModel= treeModel_in;
100 this.K = K_in;
101 this.excisionPoints = excisionPoints_in;
102 this.clusterLabels = clusterLabels_in;
103 this.mu = mu_in;
104
105 this.hasDrift=hasDrift;
106 // this.locationDrift=locationDrift_in;
107 this.offsets=offsets_in;
108 //this.hasDrift=false;
109 this.virusLocations = virusLocations_in;
110 numdata = offsets.getSize();
111
112 System.out.println("numdata = " + numdata);
113
114 //initialize clusterLabels
115 clusterLabels.setDimension(numdata);
116 for (int i = 0; i < numdata; i++) {
117 clusterLabels.setParameterValue(i, 0);
118 }
119 addVariable(clusterLabels);
120
121
122
123 //initialize mu
124 mu.setColumnDimension(2);
125 //mu.setRowDimension(numdata); //in reality, only K of them are used
126 int K_int = (int) K.getParameterValue(0);
127 mu.setRowDimension(K_int); //in reality, only K of them are used
128 //System.out.println((int) K.getParameterValue(0));
129 //System.exit(0);
130
131 for(int i=0; i < K_int; i++){
132 //can I set initial condition to be like this? and then let the algorithm set it properly later?
133 double zero=0;
134 mu.getParameter(i).setValue(0, zero);
135 mu.getParameter(i).setValue(1, zero);
136 }
137
138 //adding the pre-clustering step.
139 preClustering();
140
141 /*
142 this.abc.setColumnDimension(2); //set dimension equal to 2
143 abc.setRowDimension(strains.size());
144 for (int i = 0; i < strains.size(); i++) {
145 abc.getParameter(i).setId(strains.get(i));
146 }
147 */
148
149
150 addVariable(virusLocations);
151 addModel(treeModel);
152 //addVariable(locationDrift);
153 addVariable(offsets);
154 addVariable(K);
155 addVariable(excisionPoints);
156 addVariable(mu);
157 System.out.println("Finished loading the constructor for ClusterViruses");
158
159 }
160
161
162
163 private void preClustering() {
164
165 int numViruses = offsets.getSize();
166 System.out.println("# offsets = " + offsets.getSize());
167 //for(int i=0; i < offsets.getSize(); i++){
168 //System.out.println(offsets.getParameterValue(i));
169 //}
170
171
172 List<OrderDouble> list = new ArrayList<OrderDouble>();
173 for(int i=0; i < numViruses; i++){
174 list.add(new OrderDouble(i, offsets.getParameterValue(i))); //offset of 1
175 }
176 Collections.sort(list, new OrderDouble());
177
178 int initialEqualBinSize = numViruses/(int)(K.getParameterValue(0) -1);
179 System.out.println("initial bin size = " + initialEqualBinSize);
180 System.out.println("Initial cluster assignment:");
181 // System.out.println("virus index\tOffset\tCluster label");
182 for(int i=0; i < numViruses; i++){
183 // System.out.println(list.get(i).getIndex() + "\t" + list.get(i).getValue() +"\t"+ i/ initialEqualBinSize );
184
185 int label = i/initialEqualBinSize;
186 clusterLabels.setParameterValue(list.get(i).getIndex() , label);
187 }
188
189
190
191
192 /*
193 //borrow from getLogLikelihood:
194 int K_int = (int) K.getParameterValue(0);
195
196 double[] meanYear = new double[K_int];
197 double[] groupCount = new double[K_int];
198 for(int i=0; i < numdata; i++){
199 int label = (int) clusterLabels.getParameterValue(i);
200 double year = 0;
201 if (offsets != null) {
202 // System.out.print("virus Offeset Parameter present"+ ": ");
203 // System.out.print( virusOffsetsParameter.getParameterValue(i) + " ");
204 // System.out.print(" drift= " + drift + " ");
205 year = offsets.getParameterValue(i); //just want year[i]
206 //make sure that it is equivalent to double offset = year[virusIndex] - firstYear;
207 }
208 else{
209 System.out.println("virus Offeset Parameter NOT present. We expect one though. Something is wrong.");
210 }
211 meanYear[ label] += year;
212
213 groupCount[ label ] = groupCount[ label ] +1;
214 }
215 */
216 int maxLabel=0;
217 for(int i=0;i< numdata; i++){
218 if(maxLabel < (int) clusterLabels.getParameterValue(i)){
219 maxLabel = (int) clusterLabels.getParameterValue(i);
220 }
221 }
222
223
224 /*
225 for(int i=0; i <= maxLabel; i++){
226 meanYear[i] = meanYear[i]/groupCount[i];
227 //System.out.println(meanYear[i]);
228 }
229 */
230
231 //double beta = locationDrift.getParameterValue(0);
232
233
234 //now, change the mu..
235 for(int i=0; i <= maxLabel; i++){
236 //System.out.println(meanYear[i]*beta);
237 //mu.getParameter(i).setParameterValue(0, meanYear[i]*beta);//now separate out mu from virusLocation
238 mu.getParameter(i).setParameterValue(0, 0);
239 mu.getParameter(i).setParameterValue(1, 0);
240 }
241
242 //now change the clusterOffsets
243 //... is it necessary?
244
245 //System.exit(0);
246 }
247
248
249
250 public double getLogLikelihood() {
251
252 //System.out.println("getLogLikelihood of ClusterViruses");
253
254 double logL = 0;
255
256
257 int maxLabel=0;
258 for(int i=0;i< numdata; i++){
259 if(maxLabel < (int) clusterLabels.getParameterValue(i)){
260 maxLabel = (int) clusterLabels.getParameterValue(i);
261 }
262 }
263
264 //P(K=k)
265 int K_int = (int) K.getParameterValue(0);
266 //logL += Math.log(K.getParameterValue(0)) - lambda*K.getParameterValue(0) - Math.log( (double) factorial(K_int));
267 logL += -lambda + K.getParameterValue(0)*Math.log(lambda) - Math.log( (double) factorial(K_int));
268
269
270 // p(C | K= k)
271 logL -= numdata * Math.log(K.getParameterValue(0));
272
273 //p(mu_j | C, years) ~ N( theta , sigma^2)
274 //logL -= Math.log(2*Math.PI);
275 //logL -= 0.5*Math.log( sigmaSq*sigmaSq);
276
277
278 logL -= K.getParameterValue(0) * ( Math.log(2) + Math.log(Math.PI)+ 0.5*Math.log(sigmaSq) + 0.5*Math.log(sigmaSq) );
279
280 //double[] meanYear = new double[K_int];
281 double[] groupCount = new double[K_int];
282 for(int i=0; i < numdata; i++){
283 int label = (int) clusterLabels.getParameterValue(i);
284 groupCount[ label ] = groupCount[ label ] +1;
285 }
286
287 //for(int i=0; i <= maxLabel; i++){
288 //meanYear[i] = meanYear[i]/groupCount[i];
289 //System.out.println(meanYear[i]);
290 //}
291
292
293 for(int i=0; i <= maxLabel; i++){
294 double mu_i0 = mu.getParameter(i).getParameterValue(0);
295 double mu_i1 = mu.getParameter(i).getParameterValue(1);
296
297 //double beta = locationDrift.getParameterValue(0);
298 if( groupCount[i] >0){
299 //System.out.println("meanYear = " + meanYear[i]);
300 //logL -= 0.5*( (mu_i0 - beta*meanYear[i] )*(mu_i0 - beta*meanYear[i] ) + ( mu_i1 -0)*( mu_i1 - 0) )/sigmaSq;
301 logL -= 0.5*( (mu_i0 )*(mu_i0 ) + ( mu_i1 )*( mu_i1 ) )/sigmaSq;
302 }
303 }
304
305 //System.out.println(logL);
306
307 // System.out.println("logL=" + logL);
308 //System.out.println("done getLogLikelihood of ClusterViruses");
309
310 //System.out.println("logL=" + logL);
311
312
313 //double logL = 0; // for testing purpose only
314 return(logL);
315 /*
316 // if treeModel changes, compute the depMatrix from scratch
317 // if only the transformFactor change, go back to the latest copy of the untransformed deptMatrix,
318 //and transform it, so it doesn't have to go through the treeModel to get the distance.
319 if(treeChanged==true){
320 // setDepMatrix(); //the super slow step
321 if(treeChanged ==true){
322 treeChanged = false;
323 }
324
325 }
326
327
328 double logL = 0.0;
329 for (int j=0 ; j<logLikelihoodsVector.length;j++){
330 logLikelihoodsVector[j]=getLogLikGroup(j);
331
332 logL +=logLikelihoodsVector[j];
333
334 }
335
336 for (int j=0 ; j<links.getDimension();j++){
337 if(links.getParameterValue(j)==j){
338 logL += Math.log(alpha.getParameterValue(0));
339 }
340 else{logL += Math.log(depMatrix[j][(int) links.getParameterValue(j)]);
341
342 }
343
344 double sumDist=0.0;
345 for (int i=0;i<numdata;i++){
346 if(i!=j){sumDist += depMatrix[i][j];
347 }
348 }
349
350 logL-= Math.log(alpha.getParameterValue(0)+sumDist);
351 }
352
353
354 return logL;
355 */
356 }
357
358
359
360 //=====================================================================================================================
361
362
363 public int factorial(int n) {
364 int fact = 1; // this will be the result
365 for (int i = 1; i <= n; i++) {
366 fact *= i;
367 }
368 return fact;
369 }
370
371
372
373
374
375 public Model getModel() {
376 return this;
377 }
378
379
380
381
382
383
384 public void makeDirty() {
385 }
386
387 public void acceptState() {
388 // DO NOTHING
389 }
390
391 public void restoreState() {
392 // DO NOTHING
393 }
394
395 public void storeState() {
396 // DO NOTHING
397 }
398
399
400
401 protected void handleModelChangedEvent(Model model, Object object, int index) {
402 //---------- suggestion from cykc----------------
403 // I am making an assumption that whenever treeModel changes, the changes get caught here.
404 if(model == treeModel){
405 //System.out.println("==========Tree model changes!!!!!!!!=====");
406 treeChanged = true;
407 }
408 else{
409 }
410 //---------- End of suggestion from cykc----------------
411 }
412
413
414 //---------- suggestion from cykc----------------
415 //I tried to catch the transformedFactor changes through this routine, but it seems that it doesn't catch all,
416 //so I abandoned this routine and now use 'mostRecentTransformedValue' to directly test if transformedValue has changed.
417 //This ShouldUpdateDepMatrix never gets used and is now an obsolete variable.
418
419 //I am noticing that handleVariableChangedEvent doesn't always catch when transformFactor changes.
420 //I am observing that sometimes transformFactor can change more than once within a single MCMC sample - I don't know why,
421 //if getLogLikelihood() gets called after the transformFactor changes but ShouldUpdateDepMatrix flag doesn't catch it,
422 //then the getLogLikelihood() will not be calculated correctly.
423 //Hence, this way of catching when transformFactor changes now becomes obsolete
424 //
425 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
426 /*
427 if (variable == transformFactor) {
428 //System.out.println("TransformFactor gets updated and is caught here!!");
429 ShouldUpdateDepMatrix = true;
430
431 } else {
432 //has to change at another sample instead of setting it to false right after
433 //updating the matrix because the transformFactor value
434 //can update twice within a sample, so setDepMatrix has to update twice
435 if(ShouldUpdateDepMatrix == true){
436 //System.out.println("ShouldUpdateDepMatrix changes from true to false");
437 ShouldUpdateDepMatrix = false;
438 }
439 }
440 */
441 }
442 //---------- End of suggestion from cykc----------------
443
444 Set<NodeRef> allTips;
445 CompoundParameter traitParameter;
446 Parameter alpha;
447 Parameter clusterPrec ;
448 Parameter priorPrec ;
449 Parameter priorMean ;
450 Parameter assignments;
451 Parameter links;
452 Parameter means2;
453 Parameter means1;
454 Parameter locationDrift;
455 Parameter offsets;
456 boolean hasDrift;
457
458 TreeModel treeModel;
459 String traitName;
460 double[][] data;
461 double[][] depMatrix;
462 double[][] logDepMatrix;
463 double[][] cur_untransformedMatrix; //---------- suggestion from cykc----------------
464
465 double[] logLikelihoodsVector;
466 int numdata;
467 Parameter transformFactor;
468 double k0;
469 double v0;
470 double[][] T0Inv;
471 double[] m;
472 double logDetT0;
473
474 LinkedList<Integer>[] assignmentsLL;
475 int seqLength;
476
477 public int getSeqLength() {
478 return seqLength;
479 }
480
481 char[][] seqData;
482
483
484
485
486 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
487
488
489 public final static String TREEMODEL = "treeModel";
490 public final static String K = "k";
491 public final static String EXCISIONPOINTS = "excisionPoints";
492 public final static String CLUSTERLABELS = "clusterLabels";
493 public final static String MU = "mu";
494 //public final static String HASDRIFT = ??
495 // public final static String LOCATION_DRIFT = "locationDrift";
496 public final static String OFFSETS = "offsets";
497 public final static String VIRUS_LOCATIONS = "virusLocations";
498
499 boolean integrate = false;
500
501
502 public String getParserName() {
503 return CLUSTER_VIRUSES;
504 }
505
506 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
507
508 TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
509 //String traitName = (String) xo.getAttribute(TRAIT_NAME);
510
511 XMLObject cxo = xo.getChild(K);
512 Parameter k = (Parameter) cxo.getChild(Parameter.class);
513
514
515 cxo = xo.getChild(EXCISIONPOINTS);
516 Parameter excisionPoints = (Parameter) cxo.getChild(Parameter.class);
517
518 cxo = xo.getChild(CLUSTERLABELS);
519 Parameter clusterLabels = (Parameter) cxo.getChild(Parameter.class);
520
521 cxo = xo.getChild(MU);
522 MatrixParameter mu = (MatrixParameter) cxo.getChild(MatrixParameter.class);
523
524 //alternative way to load in the MatrixParameter?
525 // MatrixParameter serumLocationsParameter = null;
526 // if (xo.hasChildNamed(SERUM_LOCATIONS)) {
527 // serumLocationsParameter = (MatrixParameter) xo.getElementFirstChild(SERUM_LOCATIONS);
528 //}
529
530
531
532 // cxo=xo.getChild(LOCATION_DRIFT) ;
533 // Parameter locationDrift= (Parameter) cxo.getChild(Parameter.class);
534
535 cxo=xo.getChild(OFFSETS);
536 Parameter offsets =(Parameter) cxo.getChild(Parameter.class);
537
538 cxo=xo.getChild(VIRUS_LOCATIONS);
539 MatrixParameter virusLocations =(MatrixParameter) cxo.getChild(MatrixParameter.class);
540
541 boolean hasDrift = false;
542 if (offsets.getDimension()>1){
543 hasDrift=true;
544 }
545
546
547 // TreeTraitParserUtilities utilities = new TreeTraitParserUtilities();
548 // String traitName = TreeTraitParserUtilities.DEFAULT_TRAIT_NAME;
549
550
551 // TreeTraitParserUtilities.TraitsAndMissingIndices returnValue =
552 // utilities.parseTraitsFromTaxonAttributes(xo, traitName, treeModel, integrate);
553 // // traitName = returnValue.traitName;
554 // CompoundParameter traitParameter = returnValue.traitParameter;
555
556
557 //return new ClusterViruses (treeModel,traitParameter , K, excisionPoints, clusterLabels, mu, hasDrift);
558 // return new ClusterViruses(treeModel, k, excisionPoints, clusterLabels, mu, hasDrift, locationDrift, offsets, virusLocations);
559 return new ClusterViruses(treeModel, k, excisionPoints, clusterLabels, mu, hasDrift, offsets, virusLocations);
560
561
562 }
563
564 //************************************************************************
565 // AbstractXMLObjectParser implementation
566 //************************************************************************
567
568 public String getParserDescription() {
569 return "clustering viruses";
570 }
571
572 public Class getReturnType() {
573 return ClusterViruses.class;
574 }
575
576 public XMLSyntaxRule[] getSyntaxRules() {
577 return rules;
578 }
579
580
581 private final XMLSyntaxRule[] rules = {
582 // new StringAttributeRule(TreeTraitParserUtilities.TRAIT_NAME, "The name of the trait for which a likelihood should be calculated"),
583 // new ElementRule(TREEMODEL, Parameter.class),
584 new ElementRule(K, Parameter.class),
585 new ElementRule(EXCISIONPOINTS, Parameter.class),
586 new ElementRule(CLUSTERLABELS, Parameter.class),
587 new ElementRule(MU, MatrixParameter.class),
588 // new ElementRule(LOCATION_DRIFT, Parameter.class),
589 new ElementRule(OFFSETS, Parameter.class),
590 new ElementRule(VIRUS_LOCATIONS, MatrixParameter.class)
591 };
592
593 };
594
595
596
597
598
599 String Atribute = null;
600
601
602 }
603
604