Debian Codegraph @

src/dr/math/distributions/MultivariatePolyaDistributionLikelihood.java

raw symbols SCIP
1 /*
2 * MultivariatePolyaDistributionLikelihood.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.math.distributions;
27
28 import dr.inference.loggers.LogColumn;
29 import dr.inference.loggers.NumberColumn;
30 import dr.inference.model.*;
31 import dr.math.GammaFunction;
32 import dr.xml.*;
33
34 import java.util.Arrays;
35 import java.util.HashSet;
36 import java.util.Set;
37
38 /**
39 * Package: MultivariatePolyaDistributionLikelihood
40 * Description:
41 * this class provides a model for over-dispersed multinomial counts. The model follows Dirichlet-Multinomial distribution with
42 * multinomial parameters integrated out analytically. This model is also known as Multivariate Polya distribution.
43 * Standard parametrization involves k intensities a_i's. This implementation uses the standard parametrization internally, but allows
44 * for re-parametrization as frequencies (k-1 df) and dispersion parameters, where a = sum_i=1^k a_i is dispersion and f_i = a_i/a
45 * <p/>
46 * Created by
47 *
48 * @author Alexander V. Alekseyenko ([email protected])
49 * Date: Sep 23, 2010
50 * Time: 12:25:14 PM
51 */
52 public class MultivariatePolyaDistributionLikelihood extends AbstractModel implements Likelihood {
53
54 protected Parameter frequencies;
55 protected Parameter dispersion;
56 protected Parameter alphas;
57 protected boolean usingAlphas;
58 protected boolean isAlphasKnown;
59 protected MatrixParameter data;
60 protected double fixedNorm;
61 protected double variableNorm;
62 protected double storedFixedNorm;
63 protected double storedVariableNorm;
64 protected double logLikelihood;
65 protected double storedLogLikelihood;
66 protected boolean isLogLikelihoodKnown;
67 protected boolean isFixedNormKnown;
68 protected boolean isVariableNormKnown;
69 protected double rowSums[];
70
71
72 public MultivariatePolyaDistributionLikelihood(String modelID, MatrixParameter data, Parameter frequencies, Parameter dispersion) {
73 super(modelID);
74 this.frequencies = frequencies;
75 this.dispersion = dispersion;
76 this.alphas = new Parameter.Default(frequencies.getDimension());
77 computeAlphas();
78 this.data = data;
79 isFixedNormKnown = false;
80 isVariableNormKnown = false;
81 addVariable(this.frequencies);
82 addVariable(this.dispersion);
83 addVariable(this.data);
84 if (this.alphas.getDimension() != data.getColumnDimension()) {
85 System.err.println("Dimensions of the frequency vector and number of columns do not match!");
86 }
87 }
88
89 public MultivariatePolyaDistributionLikelihood(String modelID, MatrixParameter data, Parameter alphas) {
90 super(modelID);
91 this.alphas = alphas;
92 isAlphasKnown = true;
93 usingAlphas = true;
94
95 this.frequencies = new Parameter.Default(alphas.getDimension());
96 this.dispersion = new Parameter.Default(1);
97 this.data = data;
98 isFixedNormKnown = false;
99 isVariableNormKnown = false;
100 addVariable(this.alphas);
101 addVariable(this.data);
102 if (this.alphas.getDimension() != data.getColumnDimension()) {
103 System.err.println("Dimensions of the frequency vector and number of columns do not match!");
104 }
105 }
106
107 /* Compute alphas from frequencies and dispersion
108 */
109 protected void computeAlphas(){
110 double disp=dispersion.getParameterValue(0);
111 double[] freqs = frequencies.getParameterValues();
112
113 for(int i=0; i<alphas.getDimension(); ++i){
114 alphas.setParameterValueQuietly(i, disp*freqs[i]);
115 }
116 alphas.setParameterValueNotifyChangedAll(0, alphas.getParameterValue(0));
117 isAlphasKnown = true;
118 }
119
120 public MultivariatePolyaDistributionLikelihood(String modelID) {
121 super(modelID);
122 }
123
124 public double calculateLogLikelihood() {
125 // R code for this function:
126 // //assuming X[,1] is row totals, lfactX is log factorial of X //
127 // logLikes = sapply(1:n, function(i) lfactX[subset,1][i] - sum(lfactX[subset,][i,2:p1]) +
128 // lgamma(sum(alpha)) - lgamma(X[subset,1][i] + sum(alpha)) + sum(lgamma(X[subset,2:p1][i,] + alpha)) - sum(lgamma(alpha)));
129 // sum(logLikes)
130 if(!isAlphasKnown) computeAlphas();
131 if (!isFixedNormKnown) {
132 computeFixedNorm();
133 }
134 if (!isVariableNormKnown) {
135 computeVariableNorm();
136 }
137 double logP = fixedNorm + variableNorm;
138
139 double disp = 0;
140 double[] a = alphas.getParameterValues();
141 for(int i = 0; i< alphas.getDimension(); ++i){
142 disp = disp + a[i];
143 }
144
145
146 for (int i = 0; i < data.getRowDimension(); ++i) {
147 for (int j = 0; j < data.getColumnDimension(); ++j) {
148 logP += GammaFunction.lnGamma(data.getParameterValue(i, j) + a[j]);
149 }
150 logP -= GammaFunction.lnGamma(rowSums[i] + disp);
151 }
152 return logP;
153 }
154
155 protected void computeFixedNorm() {
156 rowSums = new double[data.getRowDimension()];
157 for (int i = 0; i < data.getRowDimension(); ++i) {
158 rowSums[i] = 0;
159 for (int j = 0; j < data.getColumnDimension(); ++j) {
160 rowSums[i] += data.getParameterValue(i, j);
161 }
162 }
163
164 fixedNorm = 0;
165 for (int i = 0; i < data.getRowDimension(); ++i) {
166 for (int j = 0; j < data.getColumnDimension(); ++j) {
167 fixedNorm -= GammaFunction.lnGamma(data.getParameterValue(i, j) + 1);
168 }
169 fixedNorm += GammaFunction.lnGamma(rowSums[i] + 1);
170 }
171
172 isFixedNormKnown = true;
173 }
174
175 protected void computeVariableNorm() {
176 double disp = 0;
177 double[] a = alphas.getParameterValues();
178 for(int i = 0; i< alphas.getDimension(); ++i){
179 disp = disp + a[i];
180 }
181 variableNorm = GammaFunction.lnGamma(disp);
182
183 for (int i = 0; i < alphas.getDimension(); ++i) {
184 variableNorm -= GammaFunction.lnGamma(a[i]);
185 }
186 variableNorm *= data.getRowDimension();
187 }
188
189 protected void handleModelChangedEvent(Model model, Object object, int index) {
190 }
191
192 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
193 if (variable.getVariableName().equals(frequencies.getVariableName()) || variable.getVariableName().equals(dispersion.getVariableName())) {
194 isAlphasKnown = false;
195 isVariableNormKnown = false;
196 } else if (variable.getVariableName().equals(data.getVariableName())) {
197 isFixedNormKnown = false;
198 }
199 else if(variable.getVariableName().equals(alphas.getVariableName())){
200 isVariableNormKnown = false;
201 }
202 }
203
204 protected void storeState() {
205 storedVariableNorm = variableNorm;
206 storedFixedNorm = fixedNorm;
207 storedLogLikelihood = logLikelihood;
208 }
209
210 protected void restoreState() {
211 variableNorm = storedVariableNorm;
212 fixedNorm = storedFixedNorm;
213 logLikelihood = storedLogLikelihood;
214 if(!usingAlphas) computeAlphas();
215 }
216
217 protected void acceptState() {
218 }
219
220 public Model getModel() {
221 return this;
222 }
223
224 public double getLogLikelihood() {
225 if (!isLogLikelihoodKnown) {
226 logLikelihood = calculateLogLikelihood();
227 }
228 return logLikelihood;
229 }
230
231 public void makeDirty() {
232 isLogLikelihoodKnown = false;
233 isVariableNormKnown = false;
234 isFixedNormKnown = false;
235 }
236
237 public String prettyName() {
238 return "Multivariate Polya Distribution Likelihood";
239 }
240
241 public boolean evaluateEarly() {
242 return false;
243 }
244
245 @Override
246 public Set<Likelihood> getLikelihoodSet() {
247 return new HashSet<Likelihood>(Arrays.asList(this));
248 }
249
250 public void setUsed() {
251 }
252
253
254 public LogColumn[] getColumns() {
255 return new LogColumn[]{
256 new NumberColumn(this.getId()) {
257 public double getDoubleValue() {
258 return getLogLikelihood();
259 }
260 }
261 };
262 }
263
264 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
265
266 public String getParserName() {
267 return MVPLIKE;
268 }
269
270 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
271 MatrixParameter data;
272 Parameter dispersion;
273 Parameter frequencies;
274 Parameter rates;
275
276 if (xo.hasChildNamed(DATA)) {
277 data = (MatrixParameter) xo.getChild(DATA).getChild(MatrixParameter.class);
278 } else {
279 throw new XMLParseException("Missing data element!");
280 }
281
282 if (xo.hasChildNamed(RATES)) {
283 rates = (Parameter) xo.getChild(RATES).getChild(Parameter.class);
284 if (rates.getDimension() != data.getColumnDimension()) {
285 throw new XMLParseException("The number of data columns must match the dimension of " + RATES
286 + " parameter (" + data.getColumnDimension() + " != " + rates.getDimension() + "!");
287 }
288 }
289 else if (xo.hasChildNamed(FREQ)) {
290 frequencies = (Parameter) xo.getChild(FREQ).getChild(Parameter.class);
291 if (xo.hasChildNamed(DISPERSION)) {
292 dispersion = (Parameter) xo.getChild(DISPERSION).getChild(Parameter.class);
293 } else {
294 throw new XMLParseException(DISPERSION + " element has to be specified when using " + FREQ
295 +" parametrization");
296 }
297 if (dispersion.getDimension() != 1) {
298 throw new XMLParseException("Dispersion parameter must be of dimmension exactly 1!");
299 }
300
301 if (frequencies.getDimension() != data.getColumnDimension()) {
302 throw new XMLParseException("The number of data columns must match the dimension of "+ FREQ
303 + " parameter (" + data.getColumnDimension() + " != " + frequencies.getDimension() + "!");
304 }
305 return new MultivariatePolyaDistributionLikelihood(MVPLIKE, data, frequencies, dispersion);
306
307 } else {
308 throw new XMLParseException("Either " + FREQ + " or " + RATES + "element has to be specified!");
309 }
310
311
312 return new MultivariatePolyaDistributionLikelihood(MVPLIKE, data, rates);
313 }
314
315 //************************************************************************
316 // AbstractXMLObjectParser implementation
317 //************************************************************************
318
319 public String getParserDescription() {
320 return "A matrix parameter constructed from its component parameters.";
321 }
322
323 public XMLSyntaxRule[] getSyntaxRules() {
324 return rules;
325 }
326
327 private final XMLSyntaxRule[] rules = {
328 new ElementRule(DATA, new XMLSyntaxRule[]{new ElementRule(MatrixParameter.class)}, false),
329 new XORRule(new ElementRule(RATES, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, false),
330 new ElementRule(FREQ, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, false)),
331 new ElementRule(DISPERSION, new XMLSyntaxRule[]{new ElementRule(Parameter.class)}, true),
332 };
333
334 public Class getReturnType() {
335 return MatrixParameter.class;
336 }
337 };
338 public static final String MVPLIKE = "mvPolyaLikelihood";
339 public static final String DATA = "data";
340 public static final String DISPERSION = "dispersion";
341 public static final String FREQ = "frequencies";
342 public static final String RATES = "alpha";
343 }