Debian Codegraph @

src/dr/evomodel/antigenic/phyloclustering/misc/simulateClusters.java

raw symbols SCIP
1 package dr.evomodel.antigenic.phyloclustering.misc;
2
3 import java.io.BufferedWriter;
4 import java.io.File;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.io.OutputStreamWriter;
8 import java.io.Writer;
9 import java.util.LinkedList;
10 import java.util.Random;
11
12 import dr.evolution.tree.NodeRef;
13 import dr.evomodel.antigenic.phyloclustering.TreeClusteringVirusesPrior;
14 import dr.evomodel.tree.TreeModel;
15 import dr.inference.model.MatrixParameter;
16 import dr.inference.model.Model;
17 import dr.inference.model.Parameter;
18 import dr.math.distributions.MultivariateNormalDistribution;
19 import dr.xml.AbstractXMLObjectParser;
20 import dr.xml.AttributeRule;
21 import dr.xml.ElementRule;
22 import dr.xml.XMLObject;
23 import dr.xml.XMLObjectParser;
24 import dr.xml.XMLParseException;
25 import dr.xml.XMLSyntaxRule;
26
27 public class simulateClusters {
28
29 public static final String CLASSNAME = "SimulateClustersAndHI";
30
31 private TreeModel treeModel;
32 private int[] clusterLabels;
33 // private Parameter clusterLabels;
34 private Parameter indicators;
35 private MatrixParameter virusLocations;
36 int []membershipToClusterLabelIndexes = null;
37 private Parameter virusOffsets;
38 private int []correspondingTreeIndexForVirus = null; //relates treeModels's indexing system to cluster label's indexing system of viruses. Gets assigned
39
40
41 private double[][] distCluster;
42
43 //maybe run BEAST to load in the phylogeny.. and then introduce the cut
44 //do the cutting
45 //and then exit.
46
47 //cut the tree
48 //simulate HI data
49
50
51 public simulateClusters(TreeModel treeModel_in, Parameter indicators_in ,int nClusters, int seraPerCluster, MatrixParameter vLoc_in,Parameter virusOffsets_in,
52 String HIFile, String distClusterFile, int seedNum, int minSize,
53 double meanHomologousTiter,
54 double unitPerTransition,
55 double measurementNoiseVar){
56
57 Random generator = new Random(seedNum);
58 //Random generator = new Random();
59
60
61 System.out.println("loading the constructor for SimulateCluster and HI");
62 TreeModel treeModel = treeModel_in;
63
64
65 this.treeModel = treeModel_in;
66 this.indicators = indicators_in;
67 this.virusLocations = vLoc_in;
68 this.virusOffsets = virusOffsets_in;
69
70
71 System.out.println("sera per cluster = " + seraPerCluster);
72 System.out.println("nClusters = " + nClusters);
73 System.out.println("minimum cluster size = " + minSize);
74 System.out.println("meanHomologousTiter = " + meanHomologousTiter);
75 System.out.println("unit per transition = " + unitPerTransition);
76 System.out.println("measurement noise variance = " + measurementNoiseVar);
77
78 System.out.println("seedNum = " + seedNum);
79
80 //initialize excision points
81 //indicators.setDimension(treeModel.getNodeCount());
82 for(int i=0; i < treeModel.getNodeCount(); i++){
83 indicators.setParameterValue(i, 0);
84 }
85
86
87
88
89 //need to know which are the viruses
90
91 int numdata = virusLocations.getColumnDimension();
92 int numNodes = treeModel.getNodeCount();
93
94
95 // correspondingTreeIndexForVirus = Tree_Clustering_Shared_Routines.setMembershipTreeToVirusIndexes(numdata, virusLocations, numNodes, treeModel);
96 setMembershipToClusterLabelIndexes();
97
98
99
100 distCluster = new double[nClusters][];
101 for(int i=0; i < nClusters; i++){
102 distCluster[i] = new double[nClusters];
103 }
104
105 int[] clusterSize = new int[1];
106 double[][] serumYear = new double[1][1];
107
108 //this.max_dim = max_dim_in;
109 //this.virusLocations = virusLocations_in;
110
111 indicators.setParameterValue( treeModel.getRoot().getNumber() ,1);
112 int numAddedClusters = 1;
113
114 while(numAddedClusters < nClusters){
115 //Clustering routine:
116 int I_selected;
117 do{
118 //I_selected = (int) (Math.floor(Math.random()*numNodes));
119 I_selected = (int) (Math.floor(generator.nextDouble()*numNodes));
120 }while( (int) indicators.getParameterValue(I_selected) == 1 );
121
122 indicators.setParameterValue(I_selected, 1);
123 numAddedClusters++;
124
125
126
127
128 //if each cluster has > 5 nodes, then this I_selected = 0
129
130 //want to count the number of nodes in each cluster
131
132 setClusterLabelsUsingIndicatorsAndCalculateDiff();
133
134 clusterSize = new int[numAddedClusters];
135 serumYear = new double[numAddedClusters][numdata];
136 for(int i=0; i < numdata; i++){
137 serumYear[clusterLabels[i]][clusterSize[clusterLabels[i]]] = virusOffsets.getParameterValue(i);
138 clusterSize[ clusterLabels[i]] ++;
139 //System.out.println(clusterLabels[i] );
140 }
141
142
143 int reachMinClusterSize = 1;
144 for(int i=0; i < numAddedClusters; i++){
145 if(clusterSize[i] < minSize){
146 reachMinClusterSize = 0;
147 }
148 }
149
150 if(reachMinClusterSize==1){
151 for(int i=0; i < numAddedClusters; i++){
152 System.out.print("cluster " + i + " size = " + clusterSize[i] + "\t");
153 for(int j=0; j < clusterSize[i]; j++){
154 System.out.print(serumYear[i][j]+",");
155 }
156 System.out.println("");
157 }
158 System.out.println("===========================================================");
159 }
160
161 if(reachMinClusterSize == 0){
162 indicators.setParameterValue(I_selected, 0);
163 numAddedClusters--;
164 }
165
166
167 }
168
169 System.out.println("Cluster labels: ");
170 for(int i=0; i < numdata; i++){
171 Parameter v = virusLocations.getParameter(i);
172 String curName = v.getParameterName();
173 System.out.println( curName + "\t" + clusterLabels[i] );
174 }
175
176
177 /*
178 try {
179 //Whatever the file path is.
180 File statText3 = new File("/Users/charles/Documents/researchData/clustering/simulations/H3N2_clusterAssignment.txt");
181 FileOutputStream is3 = new FileOutputStream(statText3);
182 OutputStreamWriter osw3 = new OutputStreamWriter(is3);
183 Writer w3 = new BufferedWriter(osw3);
184
185 for(int i=0; i < numdata; i++){
186 Parameter v = virusLocations.getParameter(i);
187 String curName = v.getParameterName();
188 w3.write( curName + "\t" + clusterLabels[i] +"\n");
189 }
190
191 w3.close();
192 } catch (IOException e3) {
193 System.err.println("Problem writing to the file");
194 }
195 */
196
197 System.out.println("==============================================================");
198
199 System.out.println("Indicators that are on:");
200 for(int i=0; i < numNodes; i++){
201 if((int)indicators.getParameterValue(i) ==1){
202 System.out.println(i);
203 }
204 }
205
206 /*
207 try {
208 //Whatever the file path is.
209 File statText2 = new File("/Users/charles/Documents/researchData/clustering/simulations/H3N2_HI_onIndicators.txt");
210 FileOutputStream is2 = new FileOutputStream(statText2);
211 OutputStreamWriter osw2 = new OutputStreamWriter(is2);
212 Writer w2 = new BufferedWriter(osw2);
213
214 for(int i=0; i < numNodes; i++){
215 if((int)indicators.getParameterValue(i) ==1){
216 w2.write(i+"\n");
217 }
218 }
219
220 w2.close();
221 } catch (IOException e2) {
222 System.err.println("Problem writing to the file");
223 }
224 */
225
226
227 System.out.println("===============================================================");
228
229 try {
230 System.out.println("distClusterFile = " + distClusterFile);
231 //Whatever the file path is.
232 File statText5 = new File(distClusterFile);
233 FileOutputStream is5 = new FileOutputStream(statText5);
234 OutputStreamWriter osw5 = new OutputStreamWriter(is5);
235 Writer w5 = new BufferedWriter(osw5);
236
237 for(int i=0; i < nClusters; i++){
238 for(int j=0; j < nClusters; j++){
239 System.out.print(distCluster[i][j] + " ");
240 w5.write(distCluster[i][j] + " ");
241 }
242 System.out.println("");
243 w5.write("\n");
244 }
245 w5.close();
246 } catch (IOException e5) {
247 System.err.println("Problem writing to the file");
248
249
250 }
251
252
253 System.out.println("===============================================================");
254
255 //NEED
256 //a way of telling how many cluster differences between 2 clusters..
257 //this should be like a table.
258
259 //When constructing clusters, also construct the distance table.
260 //just inherits from the parent + 1.
261 //distClutser[i,j] = #
262
263
264
265
266
267 try {
268 System.out.println("HIFile = " + HIFile);
269 //Whatever the file path is.
270 File statText = new File(HIFile);
271 FileOutputStream is = new FileOutputStream(statText);
272 OutputStreamWriter osw = new OutputStreamWriter(is);
273 Writer w = new BufferedWriter(osw);
274 w.write("virusIsolate\tvirusStrain\tvirusYear\tserumIsolate\tserumStrain\tserumYear\ttiter\tsource\n");
275
276
277 System.out.println("virusIsolate virusStrain virusYear serumIsolate serumStrain serumYear titer source");
278 for(int c=0; c< nClusters; c++){
279 for(int s=0; s<seraPerCluster; s++ ){
280
281 //sample serum year
282 //int whichSample = (int) (Math.floor(Math.random()*clusterSize[c]));
283 int whichSample = (int) (Math.floor(generator.nextDouble()*clusterSize[c]));
284 double curSerumYear = serumYear[c][whichSample];
285
286 for(int v=0; v< numdata; v++){
287 double[] meanTiter = new double[1];
288 meanTiter[0] = meanHomologousTiter - distCluster[c][clusterLabels[v]]*unitPerTransition;
289 double[][] prec = new double[1][1];
290 prec[0][0] = 1/measurementNoiseVar;
291
292 double[] values = MultivariateNormalDistribution.nextMultivariateNormalPrecision(meanTiter, prec);
293
294 Parameter virus = virusLocations.getParameter(v);
295 String curName = virus.getParameterName();
296 //System.out.print("C" + clusterLabels[v] + "\t" + curName +"\t" + virusOffsets.getParameterValue(v) +"\t" );
297 //System.out.print("C" + c +"\t" + "c" + c + "s" + (s+1) +"\t" + curSerumYear +"\t");
298 //System.out.println(Math.pow(2,values[0]) + "\tsimulation");
299
300 //if(Math.random() < 0.1){
301 //if(distCluster[c][clusterLabels[v]] <= 3){
302 w.write("C" + clusterLabels[v] + "\t" + curName +"\t" + virusOffsets.getParameterValue(v) +"\t" );
303 w.write("c" + c + "s" + (s+1) +"\t"+ "c" + c + "s" + (s+1) +"\t" + curSerumYear +"\t");
304 w.write(Math.pow(2,values[0]) + "\tsimulation\n");
305 // }
306 }
307 }
308 }
309
310 w.close();
311 } catch (IOException e) {
312 System.err.println("Problem writing to the file");
313
314
315 }
316
317
318
319
320 //Make XML
321 //Run
322
323 //System.exit(0);
324 }
325
326
327
328
329
330 private void setMembershipToClusterLabelIndexes(){
331
332 //I suspect this is an expensive operation, so I don't want to do it many times,
333 //which is also unnecessary - MAY have to update whenever a different tree is used.
334 int numdata = virusLocations.getColumnDimension();
335 int numNodes = treeModel.getNodeCount();
336 membershipToClusterLabelIndexes = new int[numdata];
337 clusterLabels = new int[numdata];
338 for(int i=0; i < numdata; i++){
339 Parameter v = virusLocations.getParameter(i);
340 String curName = v.getParameterName();
341 // System.out.println(curName);
342 int isFound = 0;
343 for(int j=0; j < numNodes; j++){
344 String treeId = treeModel.getTaxonId(j);
345 if(curName.equals(treeId) ){
346 // System.out.println(" isFound at j=" + j);
347 membershipToClusterLabelIndexes[i] = j;
348 isFound=1;
349 break;
350 }
351 }
352 if(isFound ==0){
353 System.out.println("not found. Exit now.");
354 System.exit(0);
355 }
356 }
357 }
358
359
360 private void setClusterLabelsUsingIndicatorsAndCalculateDiff(){
361
362 int []membership = determine_membership_v3(treeModel);
363 int numdata = virusLocations.getColumnDimension();
364 for(int i=0; i < numdata; i++){
365 clusterLabels[i] = membership[membershipToClusterLabelIndexes[i]] ;
366 }
367 }
368
369
370
371 //traverse down the tree, top down, do calculation
372 int[] determine_membership_v3(TreeModel treeModel){
373
374 NodeRef root = treeModel.getRoot();
375
376 int numClusters = 1;
377 LinkedList<NodeRef> list = new LinkedList<NodeRef>();
378 list.addFirst(root);
379
380 int[] membership = new int[treeModel.getNodeCount()];
381 for(int i=0; i < treeModel.getNodeCount(); i++){
382 membership[i] = -1;
383 }
384 membership[root.getNumber()] = 0; //root always given the first cluster
385
386 while(!list.isEmpty()){
387 //do things with the current object
388 NodeRef curElement = list.pop();
389 //String content = "node #" + curElement.getNumber() +", taxon=" + treeModel.getNodeTaxon(curElement) + " and parent is = " ;
390 String content = "node #" + curElement.getNumber() +", taxon= " ;
391 if(treeModel.getNodeTaxon(curElement)== null){
392 content += "internal node\t";
393 }
394 else{
395 content += treeModel.getNodeTaxon(curElement).getId() + "\t";
396 //content += treeModel.getTaxonIndex(treeModel.getNodeTaxon(curElement)) + "\t";
397 }
398
399 if(treeModel.getParent(curElement)== null){
400 //content += "no parent";
401 }
402 else{
403 //content += "parent node#=" + treeModel.getParent(curElement).getNumber();
404 }
405
406 //cluster assignment:
407 if(!treeModel.isRoot(curElement)){
408 if( (int) indicators.getParameterValue(curElement.getNumber() ) == 1) {
409 numClusters++ ;
410 membership[ curElement.getNumber() ] = numClusters - 1;
411
412 int parentClusterLabel = membership[treeModel.getParent(curElement).getNumber()] ; //parent cluster label
413 //assign distCluster
414 for(int i=0; i < (numClusters-1); i++){
415 distCluster[numClusters -1][i] = distCluster[ parentClusterLabel][i] +1;
416 distCluster[i][numClusters -1] = distCluster[i][ parentClusterLabel] +1;
417
418 }
419 }
420 else{
421 //inherit from parent's cluster assignment
422 membership[curElement.getNumber()] = membership[treeModel.getParent(curElement).getNumber()];
423 }
424 }//is not Root
425 content += " cluster = " + membership[curElement.getNumber()] ;
426
427 // System.out.println(content);
428
429
430 for(int childNum=0; childNum < treeModel.getChildCount(curElement); childNum++){
431 list.addFirst(treeModel.getChild(curElement,childNum));
432 }
433 }
434
435 return(membership);
436 }
437
438
439
440
441
442
443
444 //traverse down the tree, top down, do calculation
445 int[] determine_from_membership_v2(TreeModel treeModel){
446 //note: I set MAX_DIM as the most I would print, but in order to avoid bug, I
447 //declare the number of nodes as the most active nodes I can have.
448 int[] fromMembership = new int[treeModel.getNodeCount()];
449 for(int i=0; i < treeModel.getNodeCount(); i++){
450 fromMembership[i ] = -1;
451 }
452
453 NodeRef root = treeModel.getRoot();
454
455 int numClusters = 1;
456 LinkedList<NodeRef> list = new LinkedList<NodeRef>();
457 list.addFirst(root);
458
459 int[] membership = new int[treeModel.getNodeCount()];
460 for(int i=0; i < treeModel.getNodeCount(); i++){
461 membership[i] = -1;
462 }
463 membership[root.getNumber()] = 0; //root always given the first cluster
464
465 while(!list.isEmpty()){
466 //do things with the current object
467 NodeRef curElement = list.pop();
468 //String content = "node #" + curElement.getNumber() +", taxon=" + treeModel.getNodeTaxon(curElement) + " and parent is = " ;
469 String content = "node #" + curElement.getNumber() +", taxon= " ;
470 if(treeModel.getNodeTaxon(curElement)== null){
471 content += "internal node\t";
472 }
473 else{
474 content += treeModel.getNodeTaxon(curElement).getId() + "\t";
475 //content += treeModel.getTaxonIndex(treeModel.getNodeTaxon(curElement)) + "\t";
476 }
477
478 if(treeModel.getParent(curElement)== null){
479 //content += "no parent";
480 }
481 else{
482 //content += "parent node#=" + treeModel.getParent(curElement).getNumber();
483 }
484
485 //cluster assignment:
486 if(!treeModel.isRoot(curElement)){
487 if( (int) indicators.getParameterValue(curElement.getNumber() ) == 1) {
488 // System.out.print("indicator # " + curElement.getNumber() + " ");
489 numClusters++ ;
490 membership[ curElement.getNumber() ] = numClusters - 1;
491 fromMembership[numClusters -1] = membership[ treeModel.getParent(curElement).getNumber()];
492 // System.out.println(" membership " + (numClusters-1) + " assigned from " + membership[ treeModel.getParent(curElement).getNumber()] );
493 }
494 else{
495 //inherit from parent's cluster assignment
496 membership[curElement.getNumber()] = membership[treeModel.getParent(curElement).getNumber()];
497 }
498
499 }//is not Root
500 content += " cluster = " + membership[curElement.getNumber()] ;
501
502 // System.out.println(content);
503
504
505 for(int childNum=0; childNum < treeModel.getChildCount(curElement); childNum++){
506 list.addFirst(treeModel.getChild(curElement,childNum));
507 }
508 }
509
510 return(fromMembership);
511 }
512
513
514
515
516
517
518
519
520
521 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
522
523 public final static String EXCISIONPOINTS = "excisionPoints";
524 public final static String CLUSTERLABELS = "clusterLabels";
525 public final static String CLUSTERLABELSTREENODE = "clusterLabelsTreeNode";
526
527 public final static String MU = "mu";
528
529 public final static String OFFSETS = "offsets";
530 public final static String VIRUS_LOCATIONS = "virusLocations";
531 public final static String VIRUS_LOCATIONSTREENODE = "virusLocationsTreeNodes";
532
533 public final static String INDICATORS = "indicators";
534
535 public final static String VIRUS_OFFSETS = "virusOffsets";
536 boolean integrate = false;
537
538
539 // public final static String MUVARIANCE = "muVariance";
540 public final static String MUPRECISION = "muPrecision";
541 public final static String PROBACTIVENODE = "probActiveNode";
542
543 public final static String INITIALNUMCLUSTERS = "numClusters";
544 public final static String NUMSERA = "numSeraPerCluster";
545
546 public final static String MUMEAN = "muMean";
547
548 public final static String FILE_NAME = "HIFile";
549 public final static String FILE_NAME2 = "distClusterFile";
550
551 public final static String SEEDNUM = "seed";
552 public final static String MINSIZECLUSTER = "minClusterSize";
553
554
555 public final static String MEANHOMOLOGOUSTITER = "meanHomologousLog2Titer";
556 public final static String UNITPERTRANSITION = "log2TiterDiffPerTransition";
557 public final static String MEASUREMENTNOISEVAR = "measurementNoiseVariance";
558
559 public String getParserName() {
560 return CLASSNAME;
561 }
562
563 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
564
565
566 int initialK = 10;
567 if (xo.hasAttribute(INITIALNUMCLUSTERS)) {
568 initialK = xo.getIntegerAttribute(INITIALNUMCLUSTERS);
569 }
570
571 int numSera = 10;
572 if (xo.hasAttribute(NUMSERA)) {
573 numSera = xo.getIntegerAttribute(NUMSERA);
574 }
575
576 int seedNum = (int) Math.floor(Math.random()*100000);
577 if (xo.hasAttribute(SEEDNUM)) {
578 seedNum = xo.getIntegerAttribute(SEEDNUM);
579 }
580
581 int minSizeCluster = 5;
582 if (xo.hasAttribute(MINSIZECLUSTER)) {
583 minSizeCluster = xo.getIntegerAttribute(MINSIZECLUSTER);
584 }
585
586
587 double meanHomologousTiter = 10; //log2
588 if(xo.hasAttribute(MEANHOMOLOGOUSTITER)){
589 meanHomologousTiter = xo.getDoubleAttribute(MEANHOMOLOGOUSTITER);
590 }
591 double unitPerTransition = 2;
592 if(xo.hasAttribute(UNITPERTRANSITION)){
593 unitPerTransition = xo.getDoubleAttribute(UNITPERTRANSITION);
594 }
595 double measurementNoiseVar = 1;
596 if(xo.hasAttribute(MEASUREMENTNOISEVAR)){
597 measurementNoiseVar = xo.getDoubleAttribute(MEASUREMENTNOISEVAR);
598 }
599
600 TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
601 XMLObject cxo = xo.getChild(INDICATORS);
602 Parameter indicators = (Parameter) cxo.getChild(Parameter.class);
603 cxo=xo.getChild(VIRUS_LOCATIONS);
604 MatrixParameter virusLocations =(MatrixParameter) cxo.getChild(MatrixParameter.class);
605
606 cxo=xo.getChild(VIRUS_OFFSETS);
607 Parameter virusOffsets =(Parameter) cxo.getChild(Parameter.class);
608
609 String fileName = xo.getStringAttribute(FILE_NAME);
610 String fileName2 = xo.getStringAttribute(FILE_NAME2);
611
612
613
614 return new simulateClusters(treeModel, indicators, initialK, numSera, virusLocations, virusOffsets, fileName, fileName2, seedNum, minSizeCluster,
615 meanHomologousTiter, unitPerTransition, measurementNoiseVar);
616 }
617
618 private final XMLSyntaxRule[] rules = {
619 AttributeRule.newStringRule(FILE_NAME, false, "The name of the file containing the assay table"),
620 AttributeRule.newStringRule(FILE_NAME2, false, "The name of the file containing the assay table"),
621 AttributeRule.newIntegerRule(INITIALNUMCLUSTERS, true, "the initial number of clusters"),
622 AttributeRule.newIntegerRule(SEEDNUM, true, "the initial number of clusters"),
623 AttributeRule.newIntegerRule(NUMSERA, true, "number of sera to simulate"),
624 AttributeRule.newIntegerRule(MINSIZECLUSTER, true, "The minimum cluster size of a virus"),
625 AttributeRule.newDoubleRule(MEANHOMOLOGOUSTITER, true, "the expected log2 titer of a homologous virus"),
626 AttributeRule.newDoubleRule(UNITPERTRANSITION, true, "the expected decrease in log2 titer value per major transition"),
627 AttributeRule.newDoubleRule(MEASUREMENTNOISEVAR, true, "the variance of the measurement noise in the log2 titer value"),
628 new ElementRule(TreeModel.class),
629 new ElementRule(INDICATORS, Parameter.class),
630 new ElementRule(VIRUS_LOCATIONS, MatrixParameter.class),
631 new ElementRule(VIRUS_OFFSETS, Parameter.class),
632 };
633
634 //************************************************************************
635 // AbstractXMLObjectParser implementation
636 //************************************************************************
637
638 public String getParserDescription() {
639 return "tree clustering viruses";
640 }
641
642 public Class getReturnType() {
643 return TreeClusteringVirusesPrior.class;
644 }
645
646 public XMLSyntaxRule[] getSyntaxRules() {
647 return rules;
648 }
649
650
651
652
653 };
654
655 String Atribute = null;
656
657 public Model getModel() {
658 // TODO Auto-generated method stub
659 return null;
660 }
661
662
663
664
665
666 public double getLogLikelihood() {
667 // TODO Auto-generated method stub
668 return 0;
669 }
670
671
672
673
674
675 public void makeDirty() {
676 // TODO Auto-generated method stub
677
678 }
679
680
681
682
683
684 }