Debian Codegraph @

src/dr/evomodel/continuous/InhibitionAssayLikelihood.java

raw symbols SCIP
1 /*
2 * InhibitionAssayLikelihood.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.evomodel.continuous;
27
28 import dr.evolution.tree.NodeRef;
29 import dr.evolution.tree.Tree;
30 import dr.evomodel.tree.TreeModel;
31 import dr.inference.loggers.LogColumn;
32 import dr.inference.loggers.NumberColumn;
33 import dr.inference.model.*;
34 import dr.xml.*;
35 import org.w3c.dom.Document;
36 import org.w3c.dom.Element;
37
38 import java.util.ArrayList;
39 import java.util.HashMap;
40 import java.util.List;
41 import java.util.logging.Logger;
42
43 /**
44 * @author Marc Suchard
45 * @author Jack O'Brien
46 */
47
48
49 public class InhibitionAssayLikelihood extends AbstractModelLikelihood /*implements NodeAttributeProvider*/ {
50
51 public static final String TRAIT_LIKELIHOOD = "inhibitionLikelihood";
52 public static final String TRAIT_NAME = "traitName";
53 public static final String ROOT_PRIOR = "rootPrior";
54 public static final String MODEL = "diffusionModel";
55 public static final String TREE = "tree";
56 public static final String TRAIT_PARAMETER = "traitParameter";
57 public static final String SET_TRAIT = "setOutcomes";
58 public static final String MISSING = "missingIndicator";
59 public static final String CACHE_BRANCHES = "cacheBranches";
60 public static final String IN_REAL_TIME = "inRealTime";
61 public static final String PRECISION = "precision";
62
63 public InhibitionAssayLikelihood(TreeModel treeModel,
64
65 // List<Integer> missingIndices,
66 MatrixParameter dataParameter,
67 Parameter precision) {
68
69 super(TRAIT_LIKELIHOOD);
70 this.treeModel = treeModel;
71 this.dataParameter = dataParameter;
72
73 addModel(treeModel);
74
75 addVariable(dataParameter);
76 addVariable(precision);
77
78 N = treeModel.getExternalNodeCount();
79
80 StringBuffer sb = new StringBuffer("Creating inhibition assay model:\n");
81 sb.append("\tPlease cite O'Brien and Suchard (in preparation) if you publish results using this model.");
82
83 Logger.getLogger("dr.evomodel").info(sb.toString());
84
85 }
86
87 // **************************************************************
88 // ModelListener IMPLEMENTATION
89 // **************************************************************
90
91 protected void handleModelChangedEvent(Model model, Object object, int index) {
92
93 likelihoodKnown = false;
94
95 }
96
97
98 private double getBranchMean(TreeModel tree, NodeRef node) {
99
100 if (tree.isRoot(node)) {
101 return tree.getNodeTrait(node, "mean");
102 } else {
103 double rate;
104 if (isClusterChangeOnBranchAbove(tree, node)) {
105 rate = tree.getNodeTrait(node, "mean");
106
107 } else {
108 rate = getBranchMean(tree, tree.getParent(node));
109 }
110 return rate;
111 }
112 }
113
114 public final boolean isClusterChangeOnBranchAbove(TreeModel tree, NodeRef node) {
115 return tree.getNodeTrait(node, "indicator") == 1;
116 }
117
118
119 public final boolean areNodesInSameCluster(TreeModel tree, NodeRef node1, NodeRef node2) {
120 return clusterStart(tree, node1) == clusterStart(tree, node2);
121 }
122
123 public final NodeRef clusterStart(TreeModel tree, NodeRef node) {
124 if (tree.isRoot(node) || isClusterChangeOnBranchAbove(tree, node))
125 return node;
126 return clusterStart(tree, tree.getParent(node));
127 }
128
129 // **************************************************************
130 // VariableListener IMPLEMENTATION
131 // **************************************************************
132
133 protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
134
135 likelihoodKnown = false;
136 }
137
138 // **************************************************************
139 // Model IMPLEMENTATION
140 // **************************************************************
141
142 /**
143 * Stores the precalculated state: in this case the intervals
144 */
145 protected void storeState() {
146 storedLikelihoodKnown = likelihoodKnown;
147 storedLogLikelihood = logLikelihood;
148 storedTreeLength = treeLength;
149 }
150
151 /**
152 * Restores the precalculated state: that is the intervals of the tree.
153 */
154 protected void restoreState() {
155 likelihoodKnown = storedLikelihoodKnown;
156 logLikelihood = storedLogLikelihood;
157 treeLength = storedTreeLength;
158 }
159
160 protected void acceptState() {
161 } // nothing to do
162
163 public TreeModel getTreeModel() {
164 return treeModel;
165 }
166
167 // public MultivariateDiffusionModel getDiffusionModel() {
168 // return diffusionModel;
169 // }
170 //
171 // public boolean getInSubstitutionTime() {
172 // return inSubstitutionTime;
173 // }
174
175 // **************************************************************
176 // Likelihood IMPLEMENTATION
177 // **************************************************************
178
179 public Model getModel() {
180 return this;
181 }
182
183 public String toString() {
184 return getClass().getName() + "(" + getLogLikelihood() + ")";
185
186 }
187
188 public final double getLogLikelihood() {
189 if (!likelihoodKnown) {
190 logLikelihood = calculateLogLikelihood();
191 likelihoodKnown = true;
192 }
193 return logLikelihood;
194 }
195
196 public void makeDirty() {
197 likelihoodKnown = false;
198 }
199
200 /**
201 * Calculate the log likelihood of the current state.
202 *
203 * @return the log likelihood.
204 */
205 public double calculateLogLikelihood() {
206
207 logLikelihood = 0;
208
209 // for(int i=0; i<treeModel.getNodeCount(); i++) {
210 // treeModel.setNodeTrait(treeModel.getNode(i),"indicator",0.0);
211 // }
212 //
213 // treeModel.setNodeTrait(treeModel.getInternalNode(2),"indicator",1.0);
214 //
215 //
216 // treeModel.setNodeTrait(treeModel.getRoot(),"mean",2.0);
217 //
218 //
219 // for(int i=0; i<treeModel.getExternalNodeCount(); i++) {
220 // System.err.println("mean for tip "+i+" = "+getBranchMean(treeModel,treeModel.getExternalNode(i)));
221 // }
222
223
224 double[] mean = new double[N];
225
226 for (int i = 0; i < N; i++)
227 mean[i] = getBranchMean(treeModel, treeModel.getExternalNode(i));
228
229 final double[][] data = dataParameter.getParameterAsMatrix();
230 final boolean[][] commonCluster = determineCommonClusters();
231
232 for (int i = 0; i < N; i++) {
233 for (int j = i; j < N; j++) {
234 if (i != j) {
235 if (commonCluster[i][j]) {
236 // todo do something to logLikelihood
237 } else {
238 // todo do something else to logLikelihood
239 }
240 }
241 }
242 }
243
244
245 return logLikelihood;
246 }
247
248
249 private boolean[][] determineCommonClusters() {
250
251 boolean[][] commonCluster = new boolean[N][N];
252 for (int i = 0; i < N; i++) {
253 for (int j = i; j < N; j++) {
254 if (i != j) {
255 NodeRef nodeI = treeModel.getExternalNode(i);
256 NodeRef nodeJ = treeModel.getExternalNode(j);
257 if (areNodesInSameCluster(treeModel, nodeI, nodeJ)) {
258 commonCluster[i][j] = commonCluster[j][i] = true;
259 } else {
260 commonCluster[i][j] = commonCluster[j][i] = false;
261 }
262 }
263 }
264 }
265
266 return commonCluster;
267
268 }
269
270 public double getMaxLogLikelihood() {
271 return maxLogLikelihood;
272 }
273
274
275 public int[] getRestrictedGrowthFunction() {
276 boolean[][] commonCluster = determineCommonClusters();
277 int totalClusters = 1;
278 int[] map = new int[N];
279 map[0] = 0; // first taxon is always in first cluster
280
281 for (int i = 1; i < N; i++) { // iterate over all remaining taxa
282 boolean notFound = true;
283 for (int j = 0; notFound && j < i; j++) {
284 if (commonCluster[i][j]) {
285 notFound = false;
286 map[i] = map[j]; // i and j are in the same cluster
287 }
288 }
289 if (notFound) { // i is in a new cluster
290 map[i] = totalClusters;
291 totalClusters++;
292 }
293 }
294 return map;
295 }
296
297 public String getClusterString() { // returns the restricted growth representation of the clusters
298
299 int[] map = getRestrictedGrowthFunction();
300
301 StringBuffer sb = new StringBuffer("{");
302 sb.append(map[0]);
303 for (int i = 1; i < N; i++)
304 sb.append("," + map[i]);
305 sb.append("}");
306
307 return sb.toString();
308 }
309
310 // **************************************************************
311 // Loggable IMPLEMENTATION
312 // **************************************************************
313
314 /**
315 * @return the log columns.
316 */
317 public LogColumn[] getColumns() {
318 return new LogColumn[]{
319 new LikelihoodColumn(getId()),
320 // new NumberClustersColumn(getId()),
321 new ClustersColumn(getId())
322 };
323 }
324
325 private String[] attributeLabel = null;
326
327 public String[] getNodeAttributeLabel() {
328 if (attributeLabel == null) {
329 double[] trait = treeModel.getMultivariateNodeTrait(treeModel.getRoot(), "trait");
330 attributeLabel = new String[trait.length];
331 if (trait.length == 1)
332 attributeLabel[0] = traitName;
333 else {
334 for (int i = 1; i <= trait.length; i++)
335 attributeLabel[i - 1] = traitName + i;
336 }
337 }
338 return attributeLabel;
339 }
340
341 public String[] getAttributeForNode(Tree tree, NodeRef node) {
342 double trait[] = treeModel.getMultivariateNodeTrait(node, "trait");
343 // StringBuffer sb = new StringBuffer();
344 // sb.append("{");
345 // for(int i=0; i<trait.length-1; i++) {
346 // sb.append(trait[i]);
347 // sb.append(",");
348 // }
349 // sb.append(trait[trait.length-1]);
350 // sb.append("}");
351 String[] value = new String[trait.length];
352 for (int i = 0; i < trait.length; i++)
353 value[i] = Double.toString(trait[i]);
354
355 // return new String[] {sb.toString()}; //To change body of implemented methods use File | Settings | File Templates.
356 return value;
357 }
358
359 private class LikelihoodColumn extends NumberColumn {
360
361 public LikelihoodColumn(String label) {
362 super(label);
363 }
364
365 public double getDoubleValue() {
366 return getLogLikelihood();
367 }
368 }
369
370 // private class NumberClustersColumn extends NumberColumn {
371 //
372 // public NumberClustersColumn(String label) {
373 // super(label);
374 // }
375 //
376 // public double getDoubleValue() {
377 // int total = 1;
378 //
379 // return total;
380 // }
381 // }
382
383 private class ClustersColumn extends LogColumn.Abstract {
384
385 public ClustersColumn(String label) {
386 super(label);
387 }
388
389 protected String getFormattedValue() {
390 return getClusterString();
391 }
392 }
393
394 // **************************************************************
395 // XMLElement IMPLEMENTATION
396 // **************************************************************
397
398 public Element createElement(Document d) {
399 throw new RuntimeException("Not implemented yet!");
400 }
401
402 // **************************************************************
403 // XMLObjectParser
404 // **************************************************************
405
406 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
407
408 public String getParserName() {
409 return TRAIT_LIKELIHOOD;
410 }
411
412 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
413
414 // System.err.println("did i get here?");
415
416 // MultivariateDiffusionModel diffusionModel = (MultivariateDiffusionModel) xo.getChild(MultivariateDiffusionModel.class);
417 TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
418 // CompoundParameter traitParameter = (CompoundParameter) xo.getSocketChild(TRAIT_PARAMETER);
419
420 MatrixParameter data = (MatrixParameter) xo.getChild(MatrixParameter.class);
421
422 XMLObject cxo = xo.getChild(PRECISION);
423
424 Parameter precision = (Parameter) cxo.getChild(Parameter.class);
425
426 int numTips = treeModel.getExternalNodeCount();
427 if (numTips != data.getColumnDimension() || numTips != data.getRowDimension())
428 throw new XMLParseException("Dimensions of matrix '" + data.getId() + "' do not match the number of taxa in '" + treeModel.getId() + "'");
429
430 // boolean cacheBranches = false;
431 // if (xo.hasAttribute(CACHE_BRANCHES))
432 // cacheBranches = xo.getBooleanAttribute(CACHE_BRANCHES);
433 //
434 // boolean inSubstitutionTime = false;
435 // if (xo.hasAttribute(IN_REAL_TIME))
436 // inSubstitutionTime = !xo.getBooleanAttribute(IN_REAL_TIME);
437 //
438 List<Integer> missingIndices = null;
439 // String traitName = "trait";
440
441 // if (xo.hasAttribute(TRAIT_NAME)) {
442 //
443 // traitName = xo.getStringAttribute(TRAIT_NAME);
444 //
445 // // Fill in attributeValues
446 // int taxonCount = treeModel.getTaxonCount();
447 // for (int i = 0; i < taxonCount; i++) {
448 // String taxonName = treeModel.getTaxonId(i);
449 // System.err.println("taxon "+i+" = "+taxonName);
450 // String paramName = taxonName + ".trait";
451 // Parameter traitParam = getTraitParameterByName(traitParameter, paramName);
452 // if (traitParam == null)
453 // throw new RuntimeException("Missing trait parameters at tree tips");
454 // String object = (String) treeModel.getTaxonAttribute(i, traitName);
455 // if (object == null)
456 // throw new RuntimeException("Trait \"" + traitName + "\" not found for taxa \"" + taxonName + "\"");
457 // else {
458 // StringTokenizer st = new StringTokenizer(object);
459 // int count = st.countTokens();
460 // if (count != traitParam.getDimension())
461 // throw new RuntimeException("Trait length must match trait parameter dimension");
462 // for (int j = 0; j < count; j++) {
463 // String oneValue = st.nextToken();
464 // double value = Double.NaN;
465 // if (oneValue.compareTo("NA") == 0) {
466 // // Missing values not yet handled.
467 // } else {
468 // try {
469 // value = (new Double(oneValue)).doubleValue();
470 // } catch (NumberFormatException e) {
471 // throw new RuntimeException(e.getMessage());
472 // }
473 // }
474 // traitParam.setParameterValue(j, value);
475 // }
476 // }
477 // }
478
479 // // Find missing values
480 // double[] allValues = traitParameter.getParameterValues();
481 // missingIndices = new ArrayList<Integer>();
482 // for (int i = 0; i < allValues.length; i++) {
483 // if ((new Double(allValues[i])).isNaN()) {
484 // traitParameter.setParameterValue(i, 0);
485 // missingIndices.add(i);
486 // }
487 // }
488 //
489 // if (xo.hasSocket(MISSING)) {
490 // XMLObject cxo = (XMLObject) xo.getChild(MISSING);
491 // Parameter missingParameter = new Parameter.Default(allValues.length, 0.0);
492 // for (int i : missingIndices) {
493 // missingParameter.setParameterValue(i, 1.0);
494 // }
495 // missingParameter.addBounds(new Parameter.DefaultBounds(1.0, 0.0, allValues.length));
496 ///* CompoundParameter missingParameter = new CompoundParameter(MISSING);
497 // System.err.println("TRAIT: "+traitParameter.toString());
498 // System.err.println("CNT: "+traitParameter.getNumberOfParameters());
499 // for(int i : missingIndices) {
500 // Parameter thisParameter = traitParameter.getIndicatorParameter(i);
501 // missingParameter.addVariable(thisParameter);
502 // }*/
503 // replaceParameter(cxo, missingParameter);
504 // }
505
506 // }
507 return new InhibitionAssayLikelihood(treeModel, data, precision);
508 }
509
510
511 private Parameter getTraitParameterByName(CompoundParameter traits, String name) {
512 // Parameter found = null;
513 // System.err.println("LOOKING FOR: "+name);
514 for (int i = 0; i < traits.getParameterCount(); i++) {
515 Parameter found = traits.getParameter(i);
516 // System.err.println("COMPARE TO: "+found.getStatisticName());
517 if (found.getStatisticName().compareTo(name) == 0)
518 return found;
519 }
520 return null;
521 }
522
523 //************************************************************************
524 // AbstractXMLObjectParser implementation
525 //************************************************************************
526
527 public String getParserDescription() {
528 return "Provides the likelihood of a continuous trait evolving on a tree by a " +
529 "given diffusion model.";
530 }
531
532 public XMLSyntaxRule[] getSyntaxRules() {
533 return rules;
534 }
535
536 private final XMLSyntaxRule[] rules = {
537 // new StringAttributeRule(TRAIT_NAME, "The name of the trait for which a likelihood should be calculated"),
538 // AttributeRule.newBooleanRule(IN_REAL_TIME, true),
539 // new ElementRule(MultivariateDiffusionModel.class),
540 new ElementRule(TreeModel.class),
541 new ElementRule(MatrixParameter.class),
542 // new ElementRule("precision", Parameter)
543 // new ElementRule(Parameter.class)
544
545
546 new ElementRule(PRECISION,
547 new XMLSyntaxRule[]{
548 new ElementRule(Parameter.class)})
549
550
551 };
552
553
554 public Class getReturnType() {
555 return AbstractMultivariateTraitLikelihood.class;
556 }
557
558 // public void replaceParameter(XMLObject xo, Parameter newParam) throws XMLParseException {
559 //
560 // for (int i = 0; i < xo.getChildCount(); i++) {
561 //
562 // if (xo.getChild(i) instanceof Parameter) {
563 //
564 // XMLObject rxo = null;
565 // Object obj = xo.getRawChild(i);
566 //
567 // if (obj instanceof Reference) {
568 // rxo = ((Reference) obj).getReferenceObject();
569 // } else if (obj instanceof XMLObject) {
570 // rxo = (XMLObject) obj;
571 // } else {
572 // throw new XMLParseException("object reference not available");
573 // }
574 //
575 // if (rxo.getChildCount() > 0) {
576 // throw new XMLParseException("No child elements allowed in parameter element.");
577 // }
578 //
579 // if (rxo.hasAttribute(XMLParser.IDREF)) {
580 // throw new XMLParseException("References to " + xo.getName() + " parameters are not allowed in treeModel.");
581 // }
582 //
583 // if (rxo.hasAttribute(ParameterParser.VALUE)) {
584 // throw new XMLParseException("Parameters in " + xo.getName() + " have values set automatically.");
585 // }
586 //
587 // if (rxo.hasAttribute(ParameterParser.UPPER)) {
588 // throw new XMLParseException("Parameters in " + xo.getName() + " have bounds set automatically.");
589 // }
590 //
591 // if (rxo.hasAttribute(ParameterParser.LOWER)) {
592 // throw new XMLParseException("Parameters in " + xo.getName() + " have bounds set automatically.");
593 // }
594 //
595 // if (rxo.hasAttribute(XMLParser.ID)) {
596 //
597 // newParam.setId(rxo.getStringAttribute(XMLParser.ID));
598 // }
599 //
600 // rxo.setNativeObject(newParam);
601 //
602 // return;
603 // }
604 // }
605 // }
606 };
607
608 private TreeModel treeModel = null;
609 private MatrixParameter dataParameter = null;
610 private final Parameter precision = null;
611
612 private final int N;
613
614
615 MultivariateDiffusionModel diffusionModel = null;
616 String traitName = null;
617 // private boolean jeffreysPrior = false;
618 CompoundParameter traitParameter;
619 List<Integer> missingIndices;
620
621 ArrayList dataList = new ArrayList();
622
623 private double logLikelihood;
624 private final double maxLogLikelihood = Double.NEGATIVE_INFINITY;
625 private double storedLogLikelihood;
626 private boolean likelihoodKnown = false;
627 private boolean storedLikelihoodKnown = false;
628
629 // private double[] cachedLikelihoods = null;
630 private final HashMap<NodeRef, Double> cachedLikelihoods = null;
631
632 private double treeLength;
633 private double storedTreeLength;
634
635 private boolean inSubstitutionTime;
636 }
637