Debian Codegraph @

src/dr/evomodel/continuous/OrderedLatentLiabilityLikelihood.java

raw symbols SCIP
1 /*
2 * OrderedLatentLiabilityLikelihood.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.alignment.PatternList;
29 import dr.evolution.tree.NodeRef;
30 import dr.evomodel.tree.TreeModel;
31 import dr.inference.model.*;
32 import dr.math.distributions.Distribution;
33 import dr.util.Citable;
34 import dr.util.Citation;
35 import dr.util.CommonCitations;
36 import dr.xml.*;
37
38 import java.util.ArrayList;
39 import java.util.List;
40 import java.util.logging.Logger;
41
42
43 /**
44 * A class to model multivariate ordered data as realizations from a latent (liability) multivariate Brownian diffusion
45 *
46 * @author Gabrila Cybis
47 * @author Marc A. Suchard
48 * @author Joe Felsenstein
49 * @version $Id$
50 */
51
52 public class OrderedLatentLiabilityLikelihood extends AbstractModelLikelihood implements LatentTruncation, Citable, SoftThresholdLikelihood {
53
54 public final static String ORDERED_LATENT_LIABILITY_LIKELIHOOD = "orderedLatentLiabilityLikelihood";
55
56 public OrderedLatentLiabilityLikelihood(TreeModel treeModel, PatternList patternList, CompoundParameter tipTraitParameter, CompoundParameter thresholdParameter, Parameter numClasses, boolean isUnordered) {
57 super(ORDERED_LATENT_LIABILITY_LIKELIHOOD);
58 this.treeModel = treeModel;
59 this.patternList = patternList;
60 this.tipTraitParameter = tipTraitParameter;
61 this.thresholdParameter = thresholdParameter;
62 this.numClasses = numClasses;
63 this.isUnordered = isUnordered;
64 this.NAcode = setNAcode();
65
66 addVariable(tipTraitParameter);
67 addVariable(thresholdParameter);
68
69 setTipDataValuesForAllNodes();
70
71 StringBuilder sb = new StringBuilder();
72 sb.append("Constructing a latent liability likelihood model:\n");
73 sb.append("\tBinary patterns: ").append(patternList.getId()).append("\n");
74 sb.append("\tPlease cite:\n").append(Citable.Utils.getCitationString(this));
75 Logger.getLogger("dr.evomodel.continous").info(sb.toString());
76 }
77
78 public CompoundParameter getTipTraitParameter() {
79 return tipTraitParameter;
80 }
81
82 public PatternList getPatternList() {
83 return patternList;
84 }
85
86 private void setTipDataValuesForAllNodes() {
87 if (tipData == null) {
88 tipData = new int[treeModel.getExternalNodeCount()][patternList.getPatternCount()];
89 }
90 for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
91 NodeRef node = treeModel.getExternalNode(i);
92 String id = treeModel.getTaxonId(i);
93 int index = patternList.getTaxonIndex(id);
94 setTipDataValuesForNode(node, index);
95
96 if (DEBUG) {
97 System.err.println("\t For node: " + i + " with ID " + id + " you get taxon " + index + " with ID " + patternList.getTaxonId(index));
98 }
99 }
100
101 if (DEBUG) {
102 Bounds<Double> bounds = tipTraitParameter.getBounds();
103 for (int i = 0; i < tipTraitParameter.getDimension(); ++i) {
104 double value = tipTraitParameter.getParameterValue(i);
105 if (value <= bounds.getLowerLimit(i) || value >= bounds.getUpperLimit(i)) {
106 System.err.println("tipTrait error: " + i);
107 System.exit(-1);
108 }
109 }
110
111 System.err.println("Setup bounds correctly");
112 }
113 }
114
115 private void setTipDataValuesForNode(NodeRef node, int index) {
116 // Set tip data values
117 final int Nindex = node.getNumber();
118 final int dim = tipTraitParameter.getParameter(0).getDimension();
119
120 // TODO - This class appears to work for only binary data; how does it handle ordered-multistate data?
121
122 // boolean isBinary = patternList.getDataType() == TwoStates.INSTANCE;
123
124 double[] upperBounds = new double[dim];
125 double[] lowerBounds = new double[dim];
126
127 for (int datum = 0; datum < patternList.getPatternCount(); ++datum) {
128 tipData[Nindex][datum] = (int) patternList.getPattern(datum)[index];
129
130 switch(tipData[Nindex][datum]) {
131 case 0:
132 upperBounds[datum] = 0;
133 lowerBounds[datum] = Double.NEGATIVE_INFINITY;
134 break;
135 case 1:
136 upperBounds[datum] = Double.POSITIVE_INFINITY;
137 lowerBounds[datum] = 0;
138 break;
139 default:
140 upperBounds[datum] = Double.POSITIVE_INFINITY;
141 lowerBounds[datum] = Double.NEGATIVE_INFINITY;
142 break;
143 }
144 }
145
146 tipTraitParameter.getParameter(Nindex).addBounds(new Parameter.DefaultBounds(upperBounds,lowerBounds));
147 }
148
149 @Override
150 protected void handleModelChangedEvent(Model model, Object object, int index) {
151 }
152
153 @Override
154 protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
155 likelihoodKnown = false;
156 }
157
158 @Override
159 protected void storeState() {
160 storedLogLikelihood = logLikelihood;
161 }
162
163 @Override
164 protected void restoreState() {
165 logLikelihood = storedLogLikelihood;
166 likelihoodKnown = true;
167 }
168
169 @Override
170 protected void acceptState() {
171 // do nothing
172 }
173
174 public void makeDirty() {
175 likelihoodKnown = false;
176 }
177
178 public Model getModel() {
179 return this;
180 }
181
182 public double getLogLikelihood() {
183 if (!likelihoodKnown) {
184 logLikelihood = computeLogLikelihood();
185 likelihoodKnown = true;
186
187 }
188 return logLikelihood;
189 }
190
191 @Override
192 public void setPathParameter(double beta) {
193 pathParameter = beta;
194 }
195
196 @Override
197 public double getLikelihoodCorrection() {
198 boolean valid = true;
199 for (int tip = 0; tip < tipData.length && valid; ++tip) {
200 valid = validTraitForTip(tip);
201
202 }
203 if (valid) {
204 return 0;
205 } else {
206 return -1 / (1 - pathParameter);
207 }
208 }
209
210 public String toString() {
211 return getClass().getName() + "(" + getLogLikelihood() + ")";
212 }
213
214 protected double computeLogLikelihood() {
215 boolean valid = true;
216
217 for (int tip = 0; tip < tipData.length && valid; ++tip) {
218 valid = validTraitForTip(tip);
219 }
220
221 if (valid) {
222 return 0.0;
223 } else {
224 if (pathParameter == 1) {
225 return Double.NEGATIVE_INFINITY;
226 } else {
227 return Math.log(1 - pathParameter);
228 }
229 }
230 }
231
232 public int[] getData(int tip) {
233 return tipData[tip];
234 }
235
236
237
238 public boolean validTraitForTip(int tip) {
239 boolean valid = true;
240 Parameter oneTipTraitParameter = tipTraitParameter.getParameter(tip);
241 int[] data = tipData[tip];
242
243 if (!isUnordered) {
244
245 int threshNum = 0;
246
247 for (int index = 0; index < data.length && valid; ++index) {
248
249 int datum = data[index];
250 double trait = oneTipTraitParameter.getParameterValue(index);
251 int dim = (int) numClasses.getParameterValue(index);
252
253 if (dim == 1.0) {
254 valid = true;
255 } else if (dim == 2.0) {
256 if (trait == 0) {
257 valid = true;
258 } else if (datum > 1) {
259 valid = true;
260 } else {
261 boolean positive = trait > 0.0;
262 if (positive) {
263 valid = (datum == 1.0);
264 } else {
265 valid = (datum == 0.0);
266 }
267 }
268 } else {
269 if (datum == 0) {
270 valid = trait <= 0.0;
271 } else if (datum == 1) {
272 valid = (trait >= 0 &&
273 trait <= thresholdParameter.getParameter(threshNum).getParameterValue(0));
274 } else if (datum == (dim - 1)) {
275 valid = trait >= thresholdParameter.getParameter(threshNum).getParameterValue(dim - 3);
276 } else if (datum > (dim - 1)) {
277 valid = true;
278 } else {
279 valid = (trait >= thresholdParameter.getParameter(threshNum).getParameterValue(datum - 2) &&
280 trait <= thresholdParameter.getParameter(threshNum).getParameterValue(datum - 1));
281 }
282
283 threshNum++;
284 }
285 }
286 } else {
287 int LLpointer = 0;
288
289 for (int index = 0; index < data.length && valid; ++index) {
290
291 int datum = data[index];
292 int dim = (int) numClasses.getParameterValue(index);
293
294
295
296 if(datum==NAcode){
297 valid = true;
298
299 if(dim==1) {
300 LLpointer++;
301 }else{
302 LLpointer+= dim-1;
303 }
304
305 }else{
306
307
308 if (dim == 1.0) {
309 valid = true;
310 LLpointer++;
311 } else if (dim == 2.0) {
312
313 double trait = oneTipTraitParameter.getParameterValue(LLpointer);
314
315
316 if (trait == 0) {
317 valid = true;
318 } else {
319
320
321 boolean positive = trait > 0.0;
322 if (positive) {
323 valid = (datum == 1.0);
324 } else {
325 valid = (datum == 0.0);
326 }
327 }
328 LLpointer++;
329 } else {
330 double[] trait = new double[dim];
331 trait[0] = 0.0;
332 for (int l = 1; l < dim; l++) {
333 trait[l] = oneTipTraitParameter.getParameterValue(LLpointer + l - 1);
334 }
335
336 valid = isMax(trait, datum);
337
338 LLpointer += dim - 1;
339 }
340
341
342 } }
343 }
344
345 return valid;
346 }
347
348 private boolean isMax(double[] trait, int datum) {
349
350 boolean isMax = true;
351
352
353 for (int j = 0; j < trait.length && isMax; j++) {
354 isMax = (trait[datum] >= trait[j]);
355 }
356
357
358 return isMax;
359 }
360
361
362 private int setNAcode(){
363 int dim = numClasses.getDimension();
364 int max=0;
365 for (int i=0; i<dim; i++){
366 int num = (int) numClasses.getParameterValue(i);
367 if (num>max){
368 max=num;
369 }
370
371 }
372 return max;
373 }
374
375
376 public double getNormalizationConstant(Distribution working) {
377 return normalizationDelegate.getNormalizationConstant(working); // delegate to abstract Delegate
378 }
379
380 private final LatentTruncation.Delegate normalizationDelegate = new Delegate() {
381
382 protected double computeNormalizationConstant(Distribution working) {
383 double constant = 0.0;
384 // TODO
385 return constant;
386 }
387 };
388
389 public Boolean getOrdering() {
390 return isUnordered;
391 }
392 // **************************************************************
393 // XMLObjectParser
394 // **************************************************************
395
396 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
397
398 public final static String TIP_TRAIT = "tipTrait";
399 public final static String THRESHOLD_PARAMETER = "threshold";
400 public final static String NUM_CLASSES = "numClasses";
401 public static final String IS_UNORDERED = "isUnordered";
402 public final static String N_DATA = "NData";
403 public final static String N_TRAITS = "NTraits";
404
405
406 public String getParserName() {
407 return ORDERED_LATENT_LIABILITY_LIKELIHOOD;
408 }
409
410 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
411
412 TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class);
413 int numTaxa = treeModel.getTaxonCount();
414
415 CompoundParameter tipTraitParameter = (CompoundParameter) xo.getElementFirstChild(TIP_TRAIT);
416
417 int numData;
418 int dimTrait;
419 if (xo.hasAttribute(N_DATA) && xo.hasAttribute(N_TRAITS)) {
420 String numDataTemp = (String) xo.getAttribute(N_DATA);
421 String dimTraitTemp = (String) xo.getAttribute(N_TRAITS);
422 numData = Integer.parseInt(numDataTemp);
423 dimTrait = Integer.parseInt(dimTraitTemp);
424 } else {
425 AbstractMultivariateTraitLikelihood traitLikelihood = (AbstractMultivariateTraitLikelihood)
426 xo.getChild(AbstractMultivariateTraitLikelihood.class);
427 if (traitLikelihood != null) {
428 numData = traitLikelihood.getNumData();
429 dimTrait = traitLikelihood.getDimTrait();
430 } else {
431 numData = 1;
432 if (tipTraitParameter.getParameterCount() != numTaxa) {
433 throw new XMLParseException("Tip trait parameter is wrong dimension");
434 }
435 dimTrait = tipTraitParameter.getDimension() / numTaxa;
436 }
437 }
438
439 PatternList patternList = (PatternList) xo.getChild(PatternList.class);
440
441 CompoundParameter thresholdParameter = (CompoundParameter) xo.getElementFirstChild(THRESHOLD_PARAMETER);
442 Parameter numClasses = (Parameter) xo.getElementFirstChild(NUM_CLASSES);
443 boolean isUnorderd = xo.getAttribute(IS_UNORDERED, false);
444
445 if (tipTraitParameter.getDimension() != numTaxa * numData * dimTrait) {
446 throw new XMLParseException("Tip trait parameter is wrong dimension in latent liability model");
447 }
448
449 if (!isUnorderd) {
450
451 if (patternList.getPatternCount() != numData * dimTrait) {
452 throw new XMLParseException("Data are wrong dimension in latent liability model. "
453 + "Pattern count = " + patternList.getPatternCount() + ", while per-taxon parameter dimension = "
454 + (numData * dimTrait));
455 }
456 }
457
458 return new OrderedLatentLiabilityLikelihood(treeModel, patternList, tipTraitParameter, thresholdParameter, numClasses, isUnorderd);
459 }
460
461 //************************************************************************
462 // AbstractXMLObjectParser implementation
463 //************************************************************************
464
465 public String getParserDescription() {
466 return "Provides the likelihood of a latent liability model on multivariate ordered trait data";
467 }
468
469 public XMLSyntaxRule[] getSyntaxRules() {
470 return rules;
471 }
472
473 private final XMLSyntaxRule[] rules = {
474 new XORRule(
475 new ElementRule(AbstractMultivariateTraitLikelihood.class, true),
476 new AndRule(AttributeRule.newIntegerRule(N_DATA),
477 AttributeRule.newIntegerRule(N_TRAITS))
478 ),
479 new ElementRule(TIP_TRAIT, CompoundParameter.class, "The parameter of tip locations from the tree"),
480 new ElementRule(THRESHOLD_PARAMETER, CompoundParameter.class, "The parameter with nonzero thershold values"),
481 new ElementRule(NUM_CLASSES, Parameter.class, "Number of multinomial classes in each dimention"),
482 new ElementRule(PatternList.class, "The binary/multinomial tip data"),
483 new ElementRule(TreeModel.class, "The tree model"),
484 AttributeRule.newBooleanRule(IS_UNORDERED, true),
485 };
486
487 public Class getReturnType() {
488 return OrderedLatentLiabilityLikelihood.class;
489 }
490 };
491
492 @Override
493 public Citation.Category getCategory() {
494 return Citation.Category.TRAIT_MODELS;
495 }
496
497 @Override
498 public String getDescription() {
499 return "Latent Liability model";
500 }
501
502 @Override
503 public List<Citation> getCitations() {
504 List<Citation> citations = new ArrayList<Citation>();
505 citations.add(CommonCitations.CYBIS_2015_ASSESSING);
506 return citations;
507 }
508
509 public TreeModel treeModel;
510 private PatternList patternList;
511 public CompoundParameter tipTraitParameter;
512 private CompoundParameter thresholdParameter;
513 public Parameter numClasses;
514 private Parameter containsMissing;
515 private int NAcode;
516
517 private boolean isUnordered = false;
518 private int[][] tipData;
519
520
521 private boolean likelihoodKnown = false;
522 private double logLikelihood;
523 private double storedLogLikelihood;
524
525 private static final boolean DEBUG = false;
526
527 private double pathParameter = 1;
528
529 public Parameter getThreshold() {
530 return thresholdParameter;
531 }
532 }