Debian Codegraph @

src/dr/inference/multidimensionalscaling/mm/MultiDimensionalScalingMM.java

raw symbols SCIP
1 /*
2 * MultiDimensionalScalingMM.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.inference.multidimensionalscaling.mm;
27
28 import dr.inference.multidimensionalscaling.MultiDimensionalScalingLikelihood;
29 import dr.inference.model.MatrixParameterInterface;
30 import dr.inference.operators.EllipticalSliceOperator;
31 import dr.math.distributions.GaussianProcessRandomGenerator;
32 import dr.xml.*;
33
34 /**
35 * Created by msuchard on 12/15/15.
36 */
37 public class MultiDimensionalScalingMM extends MMAlgorithm {
38
39 private final MultiDimensionalScalingLikelihood likelihood;
40 private final GaussianProcessRandomGenerator gp;
41
42 private final int P; // Embedding dimension
43 private final int Q; // Data dimension
44
45 private double[] XtX = null;
46 private double[] D = null;
47 private double[] distance = null;
48
49 final private double tolerance;
50
51 public MultiDimensionalScalingLikelihood getLikelihood() { return likelihood; }
52
53 public GaussianProcessRandomGenerator getGaussianProcess() { return gp; }
54
55 public double getTolerance() { return tolerance; }
56
57 public MultiDimensionalScalingMM(MultiDimensionalScalingLikelihood likelihood,
58 GaussianProcessRandomGenerator gp,
59 double tolerance) {
60 super();
61
62 this.likelihood = likelihood;
63 this.gp = gp;
64
65 this.P = likelihood.getMdsDimension();
66 this.Q = likelihood.getLocationCount();
67
68 this.tolerance = tolerance;
69 }
70
71 public void run() {
72 run(100000);
73 }
74
75 public void run(final int maxIterations) {
76
77 if (maxIterations == 0) return;
78
79 if (gp != null) {
80 double[][] precision = gp.getPrecisionMatrix();
81 setPrecision(precision);
82 }
83
84 // System.err.println("");
85
86 // System.err.println("weight: " + 1.0 / likelihood.getMDSPrecision());
87 weightTree = 1.0 / likelihood.getMDSPrecision();
88
89 double[] start = likelihood.getMatrixParameter().getParameterValues();
90
91 System.err.println("Start: " + printArray(start));
92 double penaltyStart = printLogObjective();
93
94 // EllipticalSliceOperator.transformPoint(mode, true, true, P);
95 // setParameterValues(likelihood.getMatrixParameter(), mode);
96 // printLogObjective();
97
98 double[] mode = null;
99
100 try {
101 mode = findMode(likelihood.getMatrixParameter().getParameterValues(),
102 tolerance, maxIterations);
103
104 } catch (NotConvergedException e) {
105 e.printStackTrace();
106 }
107
108 // System.err.println("Final: " + printArray(mode));
109
110 setParameterValues(likelihood.getMatrixParameter(), mode);
111 double penaltyEnd = printLogObjective();
112
113 System.err.println("Move: " + penaltyStart + " -> " + penaltyEnd + " : " + (penaltyEnd - penaltyStart));
114 //
115 // if (penaltyStart - penaltyEnd > 1E-1) {
116
117 // if (penaltyEnd < penaltyStart) {
118 // throw new RuntimeException("MM moved up-hill\n\tStart: " + penaltyStart + "\n\tEnd : " + penaltyEnd);
119 // System.err.println("Revert: MM moved up-hill?");
120 // setParameterValues(likelihood.getMatrixParameter(), start);
121 // double penaltyRevert = printLogObjective();
122 // System.err.println("End: " + penaltyEnd);
123 // System.err.println("revert : " + penaltyRevert);
124 // throw new RuntimeException("out");
125 //
126 // }
127
128 // EllipticalSliceOperator.transformPoint(mode, true, true, P);
129 //
130 // System.err.println("Final: " + printArray(mode));
131 //
132 // setParameterValues(likelihood.getMatrixParameter(), mode);
133 // printLogObjective();
134
135 // throw new RuntimeException("done");
136 }
137
138 private double printLogObjective() {
139 double logLike = likelihood.getLogLikelihood();
140 double logPenalty = gp.getLikelihood().getLogLikelihood();
141 double total = logLike;
142 if (weightTree != 0.0) {
143 total += logPenalty;
144 }
145 System.err.println("obj: " + total + " = " + logLike + " + " + logPenalty);
146 // return logPenalty;
147 return total;
148 }
149
150 private void setParameterValues(MatrixParameterInterface mat, double[] values) {
151
152 // for (int i = 0; i < values.length; ++i) {
153 // mat.setValue(i, values[i]);
154 // }
155 mat.setAllParameterValuesQuietly(values, 0);
156 mat.setParameterValueNotifyChangedAll(0, 0, values[0]); // Fire changed
157 // for (int i = 0; i < mat.getUniqueParameterCount(); ++i) {
158 // mat.getUniqueParameter(0).fireParameterChangedEvent();
159 // }
160 // mat.getUniqueParameter(0);
161 }
162
163 private double[] getDistanceMatrix() {
164 return likelihood.getObservations();
165 }
166
167 private void setPrecision(double[][] matrix) {
168
169 if (!ignoreGP) {
170
171 final int QP = matrix.length;
172 if (QP != this.Q * this.P) throw new IllegalArgumentException("Invalid dimensions");
173
174 precision = matrix;
175 // precision = new double[QP * QP];
176 // precisionSign = new int[QP * QP];
177
178 precisionStatistics = new double[QP];
179
180 for (int ik = 0; ik < QP; ++ik) {
181 double sum = 0.0;
182 for (int jl = 0; jl < QP; ++jl) {
183 // double value = weightTree * matrix[ik][jl];
184 if (ik != jl) {
185 sum += Math.abs(precision[ik][jl]);
186 }
187 // precisionSign[ik * QP + jl] = (value > 0.0) ? 1 : -1;
188 // precision[ik * QP + jl] = Math.abs(value);
189 }
190 precisionStatistics[ik] = sum;
191 }
192
193 }
194
195 }
196
197 protected void mmUpdate(final double[] current, double[] next) {
198
199 if (XtX == null) {
200 XtX = new double[Q * Q];
201 }
202
203 if (D == null) {
204 D = new double[Q * Q];
205 for (int i = 0; i < Q; ++i) {
206 D[i * Q + i] = 1.0; // To protect against divide-by-zero
207 }
208 }
209
210 if (distance == null) {
211 distance = getDistanceMatrix();
212 }
213
214 // Compute XtX
215 for (int i = 0; i < Q; ++i) {
216 for (int j = i; j < Q; ++j) {
217 double innerProduct = 0.0;
218 for (int k = 0; k < P; ++k) {
219 innerProduct += current[i * P + k] * current[j * P + k];
220 }
221 XtX[j * Q + i] = XtX[i * Q + j] = innerProduct;
222 }
223 }
224
225 // Compute D
226 for (int i = 0; i < Q; ++i) {
227 for (int j = i + 1; j < Q; ++j) { // TODO XtX is not a necessary intermediate
228 double norm2 = XtX[i * Q + i] + XtX[j * Q + j] - 2 * XtX[i * Q + j];
229 double norm = norm2 > 0.0 ? Math.sqrt(norm2) : 0.0;
230 D[j * Q + i] = D[i * Q + j] = Math.max(norm, 1E-10);
231
232 if (Double.isNaN(D[i * Q + j])) {
233 System.err.println("D NaN");
234 System.err.println(XtX[i * Q + i]);
235 System.err.println(XtX[j * Q + j]);
236 System.err.println(2 * XtX[i * Q + j]);
237 System.err.println(norm2);
238 System.err.println(norm);
239 System.exit(-1);
240 }
241 }
242 }
243
244 // Compute update
245 for (int i = 0; i < Q; ++i) { // TODO Embarrassingly parallel
246 for (int k = 0; k < P; ++k) { // TODO Embarrassingly parallel
247
248 final int ik = i * P + k;
249 // final int QP = Q * P;
250
251 double numerator = 0.0;
252 for (int j = 0; j < Q; ++j) {
253 double inc = 0.0;
254 if (i != j) {
255 // int add = (i != j) ? 1 : 0;
256 // double inc = add * distance[i * Q + j] * (current[i * P + k] - current[j * P + k]) / D[i * Q + j]
257 // + (current[i * P + k] + current[j * P + k]);
258 inc += distance[i * Q + j] * (current[i * P + k] - current[j * P + k]) / D[i * Q + j]
259 + (current[i * P + k] + current[j * P + k]);
260 }
261 // inc = 0.0; // TODO Remove!
262
263 if (Double.isNaN(inc)) {
264 System.err.println("Bomb at " + i + " " + k + " " + j);
265 System.err.println("Distance = " + distance[i * Q + j]);
266 System.err.println("Ci = " + current[i * P + k]);
267 System.err.println("Cj = " + current[j * P + k]);
268 System.err.println("D = " + D[i * Q + j]);
269 System.exit(-1);
270 }
271
272 if (precision != null) {
273 for (int l = 0; l < P; ++l) {
274 final int jl = j * P + l;
275 final double prec = precision[ik][jl];
276 final int sign = (prec > 0.0) ? 1 : -1;
277 inc += weightTree * Math.abs(prec) * (current[i * P + k] - sign * current[j * P + l]);
278 }
279 }
280
281 numerator += inc;
282 }
283 double denominator = 2 * (Q - 1);
284
285 // denominator = 0.0; // TODO Remove
286
287 if (precision != null) {
288 denominator += weightTree * (2 * precision[ik][ik] + precisionStatistics[ik]);
289 }
290
291 next[i * P + k] = numerator / denominator;
292 }
293 }
294
295 // Force translation, rotation, reflection symmetry
296 EllipticalSliceOperator.transformPoint(next, true, true, P);
297 }
298
299 // **************************************************************
300 // XMLObjectParser
301 // **************************************************************
302
303 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
304
305 public static final String MDS_STARTING_VALUES = "mdsModeFinder";
306 public static final String TOLERANCE = "tolerance";
307
308 public String getParserName() {
309 return MDS_STARTING_VALUES;
310 }
311
312 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
313
314 MultiDimensionalScalingLikelihood likelihood =
315 (MultiDimensionalScalingLikelihood) xo.getChild(MultiDimensionalScalingLikelihood.class);
316
317 GaussianProcessRandomGenerator gp =
318 (GaussianProcessRandomGenerator) xo.getChild(GaussianProcessRandomGenerator.class);
319
320 double tolerance = xo.getAttribute(TOLERANCE, 1E-3);
321
322 MultiDimensionalScalingMM mm = new MultiDimensionalScalingMM(likelihood, gp, tolerance);
323 mm.run();
324 return mm;
325 }
326
327 //************************************************************************
328 // AbstractXMLObjectParser implementation
329 //************************************************************************
330
331 public String getParserDescription() {
332 return "Provides a mode finder for a MDS model on a tree";
333 }
334
335 public XMLSyntaxRule[] getSyntaxRules() {
336 return rules;
337 }
338
339 private final XMLSyntaxRule[] rules = {
340 new ElementRule(MultiDimensionalScalingLikelihood.class),
341 new ElementRule(GaussianProcessRandomGenerator.class, true),
342 AttributeRule.newDoubleRule(TOLERANCE, true),
343 };
344
345 public Class getReturnType() {
346 return MMAlgorithm.class;
347 }
348 };
349
350 private double[][] precision = null;
351
352 private double[] precisionStatistics = null;
353 // private int[] precisionSign = null;
354
355 private boolean ignoreGP = false;
356
357 private double weightTree; // TODO Formally compute
358 }