Debian Codegraph @

src/dr/inference/operators/AdaptableVarianceMultivariateNormalOperator.java

raw symbols SCIP
1 /*
2 * AdaptableVarianceMultivariateNormalOperator.java
3 *
4 * Copyright (c) 2002-2018 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.inference.operators;
27
28 import java.util.ArrayList;
29 import java.util.List;
30
31 import cern.colt.matrix.impl.DenseDoubleMatrix2D;
32 import cern.colt.matrix.linalg.SingularValueDecomposition;
33 import dr.inference.model.CompoundParameter;
34 import dr.inference.model.MatrixParameter;
35 import dr.inference.model.Parameter;
36 import dr.math.MathUtils;
37 import dr.math.matrixAlgebra.CholeskyDecomposition;
38 import dr.math.matrixAlgebra.IllegalDimension;
39 import dr.math.matrixAlgebra.SymmetricMatrix;
40 import dr.util.Transform;
41 import dr.xml.AbstractXMLObjectParser;
42 import dr.xml.AttributeRule;
43 import dr.xml.ElementRule;
44 import dr.xml.XMLObject;
45 import dr.xml.XMLObjectParser;
46 import dr.xml.XMLParseException;
47 import dr.xml.XMLSyntaxRule;
48
49 /**
50 * @author Guy Baele
51 * @author Marc A. Suchard
52 */
53 public class AdaptableVarianceMultivariateNormalOperator extends AbstractAdaptableOperator {
54
55 public static final String AVMVN_OPERATOR = "adaptableVarianceMultivariateNormalOperator";
56 public static final String SCALE_FACTOR = "scaleFactor";
57 public static final String BETA = "beta";
58 public static final String INITIAL = "initial";
59 public static final String BURNIN = "burnin";
60 public static final String UPDATE_EVERY = "updateEvery";
61 public static final String FORM_XTX = "formXtXInverse";
62 public static final String COEFFICIENT = "coefficient";
63 public static final String SKIP_RANK_CHECK = "skipRankCheck";
64
65 public static final String TRANSFORM = "transform";
66 public static final String TYPE = "type";
67
68 public static final boolean DEBUG = false;
69 public static final boolean PRINT_FULL_MATRIX = false;
70
71 private double scaleFactor;
72 private double beta;
73 private int iterations, updates, initial, burnin, every;
74 private final Parameter parameter;
75 private final Transform[] transformations;
76 private final int[] transformationSizes;
77 private final double[] transformationSums;
78 private final int dim;
79 // private final double constantFactor;
80 private double[] oldMeans, newMeans;
81
82 final double[][] matrix;
83 private double[][] empirical;
84 private double[][] cholesky;
85
86 // temporary storage, allocated once.
87 private double[] epsilon;
88 private double[][] proposal;
89
90 public AdaptableVarianceMultivariateNormalOperator(Parameter parameter, Transform[] transformations, int[] transformationSizes, double[] transformationSums, double scaleFactor, double[][] inMatrix,
91 double weight, double beta, int initial, int burnin, int every, AdaptationMode mode, boolean isVarianceMatrix, boolean skipRankCheck) {
92
93 super(mode);
94 this.scaleFactor = scaleFactor;
95 this.parameter = parameter;
96 this.transformations = transformations;
97 this.transformationSizes = transformationSizes;
98 this.transformationSums = transformationSums;
99 this.beta = beta;
100 this.iterations = 0;
101 this.updates = 0;
102 setWeight(weight);
103 dim = parameter.getDimension();
104 // constantFactor = Math.pow(2.38, 2) / ((double) dim); // not necessary because scaleFactor is auto-tuned
105 this.initial = initial;
106 this.burnin = burnin;
107 this.every = every;
108 this.empirical = new double[dim][dim];
109 this.oldMeans = new double[dim];
110 this.newMeans = new double[dim];
111
112 this.epsilon = new double[dim];
113 this.proposal = new double[dim][dim];
114
115 if (!skipRankCheck) {
116 SingularValueDecomposition svd = new SingularValueDecomposition(new DenseDoubleMatrix2D(inMatrix));
117 if (inMatrix[0].length != svd.rank()) {
118 throw new RuntimeException("Variance matrix in AdaptableVarianceMultivariateNormalOperator is not of full rank");
119 }
120 }
121
122 if (isVarianceMatrix) {
123 matrix = inMatrix;
124 } else {
125 matrix = formXtXInverse(inMatrix);
126 }
127
128 /*System.err.println("matrix initialization: ");
129 for (int i = 0; i < matrix.length; i++) {
130 for (int j = 0; j < matrix.length; j++) {
131 System.err.print(matrix[i][j] + " ");
132 }
133 System.err.println();
134 }*/
135
136 try {
137 cholesky = (new CholeskyDecomposition(matrix)).getL();
138 } catch (IllegalDimension illegalDimension) {
139 throw new RuntimeException("Unable to decompose matrix in AdaptableVarianceMultivariateNormalOperator");
140 }
141 }
142
143 public AdaptableVarianceMultivariateNormalOperator(Parameter parameter, Transform[] transformations, int[] transformationSizes, double[] transformationSums, double scaleFactor,
144 MatrixParameter varMatrix, double weight, double beta, int initial, int burnin, int every, AdaptationMode mode, boolean isVariance, boolean skipRankCheck) {
145 this(parameter, transformations, transformationSizes, transformationSums, scaleFactor, varMatrix.getParameterAsMatrix(), weight, beta, initial, burnin, every, mode, isVariance, skipRankCheck);
146 }
147
148 private double[][] formXtXInverse(double[][] X) {
149 int N = X.length;
150 int P = X[0].length;
151
152 double[][] matrix = new double[P][P];
153 for (int i = 0; i < P; i++) {
154 for (int j = 0; j < P; j++) {
155 int total = 0;
156 for (int k = 0; k < N; k++) {
157 total += X[k][i] * X[k][j];
158 }
159 matrix[i][j] = total;
160 }
161 }
162
163 // Take inverse
164 matrix = new SymmetricMatrix(matrix).inverse().toComponents();
165 return matrix;
166 }
167
168 //act as if population mean is known
169 private double calculateCovariance(int number, double currentMatrixEntry, double[] values, int firstIndex, int secondIndex) {
170
171 // number will always be > 1 here
172 /*double result = currentMatrixEntry * (number - 1);
173 result += (values[firstIndex] * values[secondIndex]);
174 result += ((number - 1) * oldMeans[firstIndex] * oldMeans[secondIndex] - number * newMeans[firstIndex] * newMeans[secondIndex]);
175 result /= ((double) number);*/
176
177 double result = currentMatrixEntry * (number - 2);
178 result += (values[firstIndex] * values[secondIndex]);
179 result += ((number - 1) * oldMeans[firstIndex] * oldMeans[secondIndex] - number * newMeans[firstIndex] * newMeans[secondIndex]);
180 result /= ((double)(number - 1));
181
182 return result;
183
184 }
185
186 public double doOperation() {
187
188 iterations++;
189
190 if (DEBUG) {
191 System.err.println("\nAVMVN Iteration: " + iterations);
192 System.err.println("Using AdaptableVarianceMultivariateNormalOperator: " + iterations + " for " + parameter.getParameterName());
193 System.err.println("Old parameter values:");
194 for (int i = 0; i < dim; i++) {
195 System.err.println(parameter.getParameterValue(i));
196 }
197 }
198
199 double[] x = parameter.getParameterValues();
200
201 //transform to the appropriate scale
202 double[] transformedX = new double[dim];
203 /*for (int i = 0; i < dim; i++) {
204 transformedX[i] = transformations[i].transform(x[i]);
205 }*/
206 //iterate over transformation sizes rather than number of parameters
207 //as a transformation might impact multiple parameters
208 int currentIndex = 0;
209 for (int i = 0; i < transformationSizes.length; i++) {
210 if (DEBUG) {
211 System.err.println("currentIndex = " + currentIndex);
212 System.err.println("transformationSizes[i] = " + transformationSizes[i]);
213 }
214 if (transformationSizes[i] > 1) {
215 System.arraycopy(transformations[i].transform(x, currentIndex, currentIndex + transformationSizes[i] - 1),0,transformedX,currentIndex,transformationSizes[i]);
216 } else {
217 transformedX[currentIndex] = transformations[i].transform(x[currentIndex]);
218 if (DEBUG) {
219 System.err.println("x[" + currentIndex + "] = " + x[currentIndex] + " -> " + transformedX[currentIndex]);
220 }
221 }
222 currentIndex += transformationSizes[i];
223 }
224
225 if (DEBUG) {
226 System.err.println("Old transformed parameter values:");
227 for (int i = 0; i < dim; i++) {
228 System.err.println(transformedX[i]);
229 }
230 }
231
232 //store MH-ratio in logq
233 double logJacobian = 0.0;
234
235 //change this: make a rule for when iterations == burnin
236 if (iterations > 1 && iterations > burnin) {
237
238 if (DEBUG) {
239 System.err.println(" AVMVN iterations > burnin");
240 }
241
242 if (iterations > (burnin+1)) {
243
244 if (iterations % every == 0) {
245
246 updates++;
247
248 if (DEBUG) {
249 System.err.println("updates = " + updates);
250 }
251
252 //first recalculate the means using recursion
253 for (int i = 0; i < dim; i++) {
254 newMeans[i] = ((oldMeans[i] * (updates - 1)) + transformedX[i]) / updates;
255 }
256
257 if (updates > 1) {
258 //here we can simply use the double[][] matrix
259 for (int i = 0; i < dim; i++) {
260 for (int j = i; j < dim; j++) {
261 empirical[i][j] = calculateCovariance(updates, empirical[i][j], transformedX, i, j);
262 empirical[j][i] = empirical[i][j];
263 }
264 }
265 }
266
267 if (DEBUG) {
268 System.err.println("Old means:");
269 for (int i = 0; i < dim; i++) {
270 System.err.println(oldMeans[i]);
271 }
272 System.err.println("New means:");
273 for (int i = 0; i < dim; i++) {
274 System.err.println(newMeans[i]);
275 }
276 System.err.println("Empirical covariance matrix:");
277 for (int i = 0; i < dim; i++) {
278 for (int j = 0; j < dim; j++) {
279 System.err.print(empirical[i][j] + " ");
280 }
281 System.err.println();
282 }
283 }
284
285 }
286
287 /*if (iterations == 17) {
288 System.exit(0);
289 }*/
290
291 } else if (iterations == (burnin+1)) {
292
293 //updates++;
294
295 //i.e. iterations == burnin+1, i.e. first sample for C_t
296 //this will not be reached when burnin is set to 0
297 for (int i = 0; i < dim; i++) {
298 //oldMeans[i] = transformedX[i];
299 //newMeans[i] = transformedX[i];
300 oldMeans[i] = 0.0;
301 newMeans[i] = 0.0;
302 }
303
304 for (int i = 0; i < dim; i++) {
305 for (int j = 0; j < dim; j++) {
306 empirical[i][j] = 0.0;
307 }
308 }
309
310 }
311
312 } else if (iterations == 1) {
313
314 if (DEBUG) {
315 System.err.println("\niterations == 1");
316 }
317 //System.err.println("Iteration: " + iterations);
318
319 //iterations == 1
320 for (int i = 0; i < dim; i++) {
321 //oldMeans[i] = transformedX[i];
322 //newMeans[i] = transformedX[i];
323 oldMeans[i] = 0.0;
324 newMeans[i] = 0.0;
325 }
326
327 for (int i = 0; i < dim; i++) {
328 for (int j = 0; j < dim; j++) {
329 empirical[i][j] = 0.0;
330 proposal[i][j] = matrix[i][j];
331 }
332 }
333
334 }
335
336 for (int i = 0; i < dim; i++) {
337 epsilon[i] = scaleFactor * MathUtils.nextGaussian();
338 }
339
340 if (iterations > initial) {
341
342 if (DEBUG) {
343 System.err.println(" iterations > initial");
344 }
345
346 if (iterations % every == 0) {
347 // TODO: For speed, it may not be necessary to update decomposition each and every iteration
348 //double start = System.nanoTime();
349
350 // double[][] proposal = new double[dim][dim];
351 for (int i = 0; i < dim; i++) {
352 for (int j = i; j < dim; j++) { // symmetric matrix
353 proposal[j][i] = proposal[i][j] = (1 - beta) * // constantFactor * /* auto-tuning using scaleFactor */
354 empirical[i][j] + beta * matrix[i][j];
355 }
356 }
357
358 // not necessary for first test phase, but will need to be performed when covariance matrix is being updated
359 try {
360 cholesky = (new CholeskyDecomposition(proposal)).getL();
361 } catch (IllegalDimension illegalDimension) {
362 throw new RuntimeException("Unable to decompose matrix in AdaptableVarianceMultivariateNormalOperator");
363 }
364
365 //double end = System.nanoTime();
366 //double baseResult = end - start;
367 //System.err.println("Cholesky decomposition took: " + baseResult);
368 }
369
370 }
371
372 if (DEBUG) {
373 System.err.println(" Drawing new values");
374 }
375
376 /*for (int i = 0; i < dim; i++) {
377 for (int j = i; j < dim; j++) {
378 transformedX[i] += cholesky[j][i] * epsilon[j];
379 // caution: decomposition returns lower triangular
380 }
381 if (MULTI) {
382 parameter.setParameterValueQuietly(i, transformations[i].inverse(transformedX[i]));
383 } else {
384 if (transformationSizes[i] > 1) {
385 throw new RuntimeException("Transformations on more than 1 parameter value should be set quietly");
386 } else {
387 parameter.setParameterValue(i, transformations[i].inverse(transformedX[i]));
388 }
389 }
390 //this should be correct
391 //logJacobian += transformations[i].getLogJacobian(parameter.getParameterValue(i)) - transformations[i].getLogJacobian(x[i]);
392 logJacobian += transformations[i].getLogJacobian(x[i]) - transformations[i].getLogJacobian(parameter.getParameterValue(i));
393 }*/
394
395 for (int i = 0; i < dim; i++) {
396 for (int j = i; j < dim; j++) {
397 transformedX[i] += cholesky[j][i] * epsilon[j];
398 // caution: decomposition returns lower triangular
399 }
400 }
401
402 if (DEBUG) {
403 System.err.println("\nTransformed X values:");
404 for (int i = 0; i < dim; i++) {
405 System.err.println(transformedX[i]);
406 }
407 System.err.println();
408 }
409
410 //iterate over transformation sizes rather than number of parameters
411 //as a transformation might impact multiple parameters
412 currentIndex = 0;
413 for (int i = 0; i < transformationSizes.length; i++) {
414 if (DEBUG) {
415 System.err.println("currentIndex = " + currentIndex);
416 System.err.println("transformationSizes[i] = " + transformationSizes[i]);
417 }
418 if (MULTI) {
419 if (transformationSizes[i] > 1) {
420 double[] temp = transformations[i].inverse(transformedX, currentIndex, currentIndex + transformationSizes[i] - 1, transformationSums[i]);
421 for (int k = 0; k < temp.length; k++) {
422 parameter.setParameterValueQuietly(currentIndex + k, temp[k]);
423 }
424 logJacobian += transformations[i].getLogJacobian(x, currentIndex, currentIndex + transformationSizes[i] - 1) - transformations[i].getLogJacobian(temp, 0, transformationSizes[i] - 1);
425 } else {
426 parameter.setParameterValueQuietly(currentIndex, transformations[i].inverse(transformedX[currentIndex]));
427 logJacobian += transformations[i].getLogJacobian(x[currentIndex]) - transformations[i].getLogJacobian(parameter.getParameterValue(currentIndex));
428 }
429 if (DEBUG) {
430 System.err.println("Current logJacobian = " + logJacobian);
431 }
432 } else {
433 if (transformationSizes[i] > 1) {
434 //TODO: figure out if this is really a problem ...
435 throw new RuntimeException("Transformations on more than 1 parameter value should be set quietly");
436 } else {
437 parameter.setParameterValue(currentIndex, transformations[i].inverse(transformedX[currentIndex]));
438 logJacobian += transformations[i].getLogJacobian(x[currentIndex]) - transformations[i].getLogJacobian(parameter.getParameterValue(currentIndex));
439 }
440 if (DEBUG) {
441 System.err.println("Current logJacobian = " + logJacobian);
442 }
443 }
444 currentIndex += transformationSizes[i];
445 }
446
447 if (DEBUG) {
448 System.err.println("Proposed parameter values:");
449 for (int i = 0; i < dim; i++) {
450 System.err.println(x[i] + " -> " + parameter.getValue(i));
451 }
452 System.err.println("LogJacobian: " + logJacobian);
453 }
454
455 if (MULTI) {
456 parameter.fireParameterChangedEvent(); // Signal once.
457 }
458
459 if (iterations % every == 0) {
460 if (DEBUG) {
461 System.err.println(" Copying means");
462 }
463 //copy new means to old means for next update iteration
464 //System.arraycopy(newMeans, 0, oldMeans, 0, dim);
465 double[] tmp = oldMeans;
466 oldMeans = newMeans;
467 newMeans = tmp; // faster to swap pointers
468 }
469
470 //System.err.println("scale factor: " + scaleFactor);
471 /*System.err.println("New parameter values:");
472 for (int i = 0; i < dim; i++) {
473 System.err.println(parameter.getParameterValue(i));
474 }*/
475 //System.err.println("log(Jacobian): " + logJacobian);
476
477 //return 0.0;
478 return logJacobian;
479
480 }
481
482 public String toString() {
483 return AVMVN_OPERATOR + "(" + parameter.getParameterName() + ")";
484 }
485
486 public static final boolean MULTI = true;
487
488 //Methods needed when using TwoPhaseOperator(Parser)
489 public Parameter getParameter() {
490 return this.parameter;
491 }
492
493 public void provideSamples(ArrayList<ArrayList<Double>> parameterSamples) {
494 if (DEBUG) {
495 System.err.println("AVMVN operator parameter length: " + parameter.getDimension());
496 System.err.println("provideSamples argument length: " + parameterSamples.size());
497 }
498 if (parameter.getDimension() != parameterSamples.size()) {
499 throw new RuntimeException("Dimension mismatch in AVMVN Operator: inconsistent parameter dimensions");
500 } else {
501 int lowestNumberOfSamples = parameterSamples.get(0).size();
502 for (int i = 0; i < parameterSamples.size(); i++) {
503 if (parameterSamples.get(i).size() < lowestNumberOfSamples) {
504 lowestNumberOfSamples = parameterSamples.get(i).size();
505 }
506 }
507 if (DEBUG) {
508 System.err.println("lowest number of samples: " + lowestNumberOfSamples);
509 }
510 //set number of iterations of AVMVN operator
511 this.iterations = lowestNumberOfSamples;
512 this.updates = lowestNumberOfSamples;
513 this.beta = 0.0;
514 //set means based on provided samples, but take into account transformation(s)
515 for (int i = 0; i < parameterSamples.size(); i++) {
516 for (int j = 0; j < lowestNumberOfSamples; j++) {
517 newMeans[i] += transformations[i].transform(parameterSamples.get(i).get(j));
518 //parameterSamples.get(i).get(j);
519 }
520 newMeans[i] /= (double)lowestNumberOfSamples;
521 }
522 if (DEBUG) {
523 System.err.println();
524 for (int i = 0; i < parameterSamples.size(); i++) {
525 System.err.println("Mean " + i + ": " + newMeans[i]);
526 }
527 }
528 //set covariance matrix based on provided samples, but take into account transformation(s)
529 for (int i = 0; i < dim; i++) {
530 for (int j = i; j < dim; j++) {
531 for (int k = 0; k < lowestNumberOfSamples; k++) {
532 empirical[i][j] += transformations[i].transform(parameterSamples.get(i).get(k))*transformations[i].transform(parameterSamples.get(j).get(k));
533 }
534 empirical[i][j] /= (double)lowestNumberOfSamples;
535 empirical[i][j] -= newMeans[i]*newMeans[j];
536 empirical[j][i] = empirical[i][j];
537 }
538 }
539 if (DEBUG) {
540 System.err.println();
541 for (int i = 0; i < dim; i++) {
542 for (int j = 0; j < dim; j++) {
543 System.err.print(empirical[i][j] + " ");
544 }
545 System.err.println();
546 }
547 }
548 }
549 }
550
551 //MCMCOperator INTERFACE
552 public final String getOperatorName() {
553 String output = "adaptableVarianceMultivariateNormal(" + parameter.getParameterName() + ")";
554 if (PRINT_FULL_MATRIX) {
555 output += "\nMeans:\n";
556 for (int i = 0; i < dim; i++) {
557 output += newMeans[i] + " ";
558 }
559 output += "\nVariance-covariance matrix:\n";
560 for (int i = 0; i < dim; i++) {
561 for (int j = 0; j < dim; j++) {
562 output += empirical[i][j] + " ";
563 }
564 output += "\n";
565 }
566 }
567 return output;
568 }
569
570 public double getAdaptableParameter() {
571 return Math.log(scaleFactor);
572 }
573
574 public void setAdaptableParameter(double value) {
575 scaleFactor = Math.exp(value);
576 }
577
578 public double getRawParameter() {
579 return scaleFactor;
580 }
581
582 public double getScaleFactor() {
583 return scaleFactor;
584 }
585
586 public String getAdaptableParameterName() {
587 return "scaleFactor";
588 }
589
590 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
591
592 public String getParserName() {
593 return AVMVN_OPERATOR;
594 }
595
596 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
597
598 if (DEBUG) {
599 System.err.println("\nParsing AdaptableVarianceMultivariateNormalOperator.");
600 }
601
602 AdaptationMode mode = AdaptationMode.parseMode(xo);
603
604 double weight = xo.getDoubleAttribute(WEIGHT);
605 double beta = xo.getDoubleAttribute(BETA);
606 int initial = xo.getIntegerAttribute(INITIAL);
607 double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR);
608 double coefficient = xo.getDoubleAttribute(COEFFICIENT);
609
610 int burnin = 0;
611 int every = 1;
612 if (xo.hasAttribute(BURNIN)) {
613 burnin = xo.getIntegerAttribute(BURNIN);
614 }
615 if (burnin > initial || burnin < 0) {
616 throw new XMLParseException("Burn-in must be smaller than the initial period.");
617 }
618
619 if (xo.hasAttribute(UPDATE_EVERY)) {
620 every = xo.getIntegerAttribute(UPDATE_EVERY);
621 }
622
623 if (every <= 0) {
624 throw new XMLParseException("Covariance matrix needs to be updated at least every single iteration.");
625 }
626
627 if (scaleFactor <= 0.0) {
628 throw new XMLParseException("ScaleFactor must be greater than zero.");
629 }
630
631 boolean formXtXInverse = xo.getAttribute(FORM_XTX, false);
632
633 Transform.ParsedTransform pt = (Transform.ParsedTransform) xo.getChild(Transform.ParsedTransform.class);
634 boolean oldXML;
635 if (pt == null) {
636 throw new XMLParseException("No valid transformations have been provided in the XML file.");
637 }
638 oldXML = pt.parameters == null;
639
640 Parameter parameter;
641 Transform[] transformations;
642 int[] transformationSizes;
643 double[] transformationSums;
644
645 int transformationSizeCounter = 0;
646
647 if (!oldXML) {
648 // if there are no ParsedTransform elements then use the new parser syntax
649 if (DEBUG) {
650 System.err.println("New parser");
651 }
652
653 CompoundParameter allParameters = new CompoundParameter("allParameters");
654
655 List<Transform> transformList = new ArrayList<Transform>();
656 List<Integer> transformCountList = new ArrayList<Integer>();
657 List<Double> transformSumList = new ArrayList<Double>();
658
659 for (Object co : xo.getChildren()) {
660 if (co instanceof Parameter) {
661 // parameters in the body of the object are assumed to have no transform
662 transformList.add(Transform.NONE);
663 Parameter param = (Parameter) co;
664 allParameters.addParameter(param);
665 transformCountList.add(param.getDimension());
666 transformSumList.add(0.0);
667 } else if (co instanceof Transform.ParsedTransform) {
668 Transform.ParsedTransform parsedTransform = (Transform.ParsedTransform)co;
669
670 transformList.add(parsedTransform.transform);
671
672 int dim = 0;
673 for (Parameter param : parsedTransform.parameters) {
674 allParameters.addParameter(param);
675 dim += param.getDimension();
676 }
677 transformCountList.add(dim);
678 transformSumList.add(parsedTransform.fixedSum);
679 } else {
680 throw new XMLParseException("Unknown element in " + AVMVN_OPERATOR);
681 }
682 }
683
684 parameter = allParameters;
685 transformations = new Transform[parameter.getDimension()];
686 transformationSizes = new int[parameter.getDimension()];
687 transformationSums = new double[parameter.getDimension()];
688
689 /*transformations = transformList.toArray(transformations);
690 for (int i = 0; i < transformCountList.size(); i++) {
691 transformationSizes[i] = transformCountList.get(i);
692 }*/
693 if (DEBUG) {
694 for (int i = 0; i < transformList.size(); i++) {
695 System.err.println(i + " " + transformList.get(i));
696 }
697 for (int i = 0; i < transformCountList.size(); i++) {
698 System.err.println(i + " " + transformCountList.get(i));
699 }
700 }
701 int index = 0;
702 for (int i = 0; i < transformCountList.size(); i++) {
703 if (!transformList.get(i).getTransformName().equals(Transform.LOG_CONSTRAINED_SUM.getTransformName())) {
704 for (int j = 0; j < transformCountList.get(i); j++) {
705 transformations[index] = transformList.get(i);
706 transformationSizes[index] = 1;
707 transformationSums[index] = transformSumList.get(i);
708 index++;
709 transformationSizeCounter++;
710 }
711 } else {
712 //log constrained sum transformation
713 transformations[index] = transformList.get(i);
714 transformationSizes[index] = transformCountList.get(i);
715 transformationSums[index] = transformSumList.get(i);
716 index++;
717 transformationSizeCounter++;
718 }
719 }
720
721 } else {
722
723 if (DEBUG) {
724 System.err.println("Old parser");
725 }
726 // assume old parser syntax for backwards compatibility
727 parameter = (Parameter)xo.getChild(Parameter.class);
728
729 transformations = new Transform[parameter.getDimension()];
730 transformationSizes = new int[parameter.getDimension()];
731 transformationSums = new double[parameter.getDimension()];
732
733 for (int i = 0; i < xo.getChildCount(); i++) {
734 Object child = xo.getChild(i);
735 if (child instanceof Transform.ParsedTransform) {
736 Transform.ParsedTransform thisObject = (Transform.ParsedTransform) child;
737
738 if (DEBUG) {
739 System.err.println(thisObject.transform.getTransformName());
740 }
741
742 if (thisObject.transform.getTransformName().equals(Transform.LOG_CONSTRAINED_SUM.getTransformName())) {
743 transformations[transformationSizeCounter] = thisObject.transform;
744 transformationSizes[transformationSizeCounter] = thisObject.end - thisObject.start;
745 //transformationSums[transformationSizeCounter] = thisObject.fixedSum;
746 transformationSums[transformationSizeCounter] = thisObject.end - thisObject.start;
747 if (DEBUG) {
748 System.err.println("Transformation size (logConstrainedSum) = " + transformationSizes[transformationSizeCounter]);
749 }
750 transformationSizeCounter++;
751 } else {
752 for (int j = thisObject.start; j < thisObject.end; ++j) {
753 transformations[transformationSizeCounter] = thisObject.transform;
754 transformationSizes[transformationSizeCounter] = 1;
755 transformationSums[transformationSizeCounter] = thisObject.fixedSum;
756 if (DEBUG) {
757 System.err.println("Transformation size = " + transformationSizes[transformationSizeCounter]);
758 }
759 transformationSizeCounter++;
760 }
761 }
762 }
763 }
764 }
765
766 //determine array length for transformationSizes = transformationSizeCounter - 1;
767 if (DEBUG) {
768 System.err.println("\nCleaning up transformation and size arrays");
769 System.err.println("transformationSizeCounter = " + transformationSizeCounter);
770 }
771 int temp[] = new int[transformationSizeCounter];
772 Transform tempTransform[] = new Transform[transformationSizeCounter];
773 double[] tempSum = new double[transformationSizeCounter];
774 for (int i = 0; i < temp.length; i++) {
775 temp[i] = transformationSizes[i];
776 tempTransform[i] = transformations[i];
777 tempSum[i] = transformationSums[i];
778 if (transformationSizes[i] == 0 || temp[i] == 0) {
779 throw new XMLParseException("Transformation size 0 encountered");
780 }
781 }
782 transformationSizes = temp;
783 transformations = tempTransform;
784 transformationSums = tempSum;
785
786 //varMatrix needs to be initialized
787 int dim = parameter.getDimension();
788 if (DEBUG) {
789 System.err.println("Dimension: " + dim);
790 }
791
792 if (initial <= 2 * dim) {
793 initial = 2 * dim;
794 }
795
796 Parameter[] init = new Parameter[dim];
797 for (int i = 0; i < dim; i++) {
798 init[i] = new Parameter.Default(dim, 0.0);
799 }
800 for (int i = 0; i < dim; i++) {
801 init[i].setParameterValue(i, Math.pow(coefficient, 2) / ((double) dim));
802 }
803 MatrixParameter varMatrix = new MatrixParameter(null, init);
804
805 if (DEBUG) {
806 System.err.println("\nChecking transformation array contents");
807 for (int i = 0; i < transformations.length; i++) {
808 System.err.println(transformations[i].getTransformName());
809 }
810 System.err.println("\nChecking size array contents");
811 for (int i = 0; i < transformationSizes.length; i++) {
812 System.err.print(transformationSizes[i] + " ");
813 }
814 System.err.println("\nChecking transformation sum contents");
815 for (int i = 0; i < transformationSums.length; i++) {
816 System.err.print(transformationSums[i] + " ");
817 }
818 System.err.println();
819 }
820
821 // Make sure varMatrix is square and dim(varMatrix) = dim(parameter)
822
823 if (!formXtXInverse) {
824 if (varMatrix.getColumnDimension() != varMatrix.getRowDimension())
825 throw new XMLParseException("The variance matrix is not square");
826 }
827
828 if (varMatrix.getColumnDimension() != parameter.getDimension())
829 throw new XMLParseException("The parameter and variance matrix have differing dimensions");
830
831 /*java.util.logging.Logger.getLogger("dr.inference").info("\nCreating the adaptable variance multivariate normal operator:" +
832 "\n beta = " + beta + "\n initial = " + initial + "\n burnin = " + burnin + "\n every = " + every +
833 "\n If you use this operator, please cite: " +
834 " Guy Baele, Philippe Lemey, Marc A. Suchard. 2016. In preparation.");*/
835
836 boolean skipRankCheck = xo.getAttribute(SKIP_RANK_CHECK, false);
837
838 return new AdaptableVarianceMultivariateNormalOperator(parameter, transformations, transformationSizes, transformationSums, scaleFactor, varMatrix, weight, beta, initial, burnin, every,
839 mode, !formXtXInverse, skipRankCheck);
840 }
841
842 //************************************************************************
843 // AbstractXMLObjectParser implementation
844 //************************************************************************
845
846 public String getParserDescription() {
847 return "This element returns an adaptable variance multivariate normal operator on a given parameter.";
848 }
849
850 public Class getReturnType() {
851 return MCMCOperator.class;
852 }
853
854 public XMLSyntaxRule[] getSyntaxRules() {
855 return rules;
856 }
857
858 private final XMLSyntaxRule[] rules = {
859 AttributeRule.newDoubleRule(SCALE_FACTOR),
860 AttributeRule.newDoubleRule(WEIGHT),
861 AttributeRule.newDoubleRule(BETA),
862 AttributeRule.newDoubleRule(COEFFICIENT),
863 AttributeRule.newIntegerRule(INITIAL),
864 AttributeRule.newIntegerRule(BURNIN, true),
865 AttributeRule.newIntegerRule(UPDATE_EVERY, true),
866 AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true),
867 AttributeRule.newBooleanRule(FORM_XTX, true),
868 AttributeRule.newBooleanRule(SKIP_RANK_CHECK, true),
869 new ElementRule(Parameter.class, 0, Integer.MAX_VALUE),
870 new ElementRule(Transform.ParsedTransform.class, 0, Integer.MAX_VALUE)
871 };
872
873 };
874 }