Debian Codegraph @

src/dr/inference/operators/LoadingsGibbsOperator.java

raw symbols SCIP
1 /*
2 * LoadingsGibbsOperator.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.operators;
27
28 import dr.inference.distribution.DistributionLikelihood;
29 import dr.inference.distribution.IndependentNormalDistributionModel;
30 import dr.inference.distribution.LatentFactorModelInterface;
31 import dr.inference.model.LatentFactorModel;
32 import dr.inference.model.MatrixParameterInterface;
33 import dr.inference.model.Parameter;
34 import dr.math.MathUtils;
35 import dr.math.distributions.MultivariateNormalDistribution;
36 import dr.math.distributions.NormalDistribution;
37 import dr.math.matrixAlgebra.*;
38
39 import java.util.ArrayList;
40 import java.util.List;
41 import java.util.ListIterator;
42 import java.util.concurrent.Callable;
43 import java.util.concurrent.ExecutorService;
44 import java.util.concurrent.Executors;
45
46 /**
47 * Created with IntelliJ IDEA.
48 * User: max
49 * Date: 5/23/14
50 * Time: 2:23 PM
51 * To change this template use File | Settings | File Templates.
52 */
53 public class LoadingsGibbsOperator extends SimpleMCMCOperator implements PathDependentOperator, GibbsOperator {
54 NormalDistribution prior;
55 IndependentNormalDistributionModel prior3;
56 NormalDistribution workingPrior;
57 LatentFactorModelInterface LFM;
58 ArrayList<double[][]> precisionArray;
59 ArrayList<double[]> meanMidArray;
60 ArrayList<double[]> meanArray;
61 boolean randomScan;
62 double pathParameter=1.0;
63 final Parameter missingIndicator;
64 final MatrixParameterInterface loadings;
65 final boolean upperTriangle;
66
67 double priorPrecision;
68 double priorMeanPrecision;
69 double priorPrecisionWorking;
70 double priorMeanPrecisionWorking;
71
72 public LoadingsGibbsOperator(LatentFactorModelInterface LFM, DistributionLikelihood prior, IndependentNormalDistributionModel prior3, MatrixParameterInterface loadings,
73 double weight, boolean randomScan, DistributionLikelihood workingPrior, boolean multiThreaded, int numThreads,
74 boolean upperTriangle) {
75 setWeight(weight);
76 this.upperTriangle = upperTriangle;
77 if (prior != null){
78 this.prior = (NormalDistribution) prior.getDistribution();}
79 else
80 this.prior3 = (prior3);
81 if (workingPrior != null) {
82 this.workingPrior = (NormalDistribution) workingPrior.getDistribution();
83 }
84 if(loadings != null){
85 this.loadings = loadings;
86 }
87 else
88 this.loadings = LFM.getLoadings();
89 this.LFM = LFM;
90 precisionArray = new ArrayList<double[][]>();
91 double[][] temp;
92 this.randomScan = randomScan;
93
94
95 meanArray = new ArrayList<double[]>();
96 meanMidArray = new ArrayList<double[]>();
97 double[] tempMean;
98 if (!randomScan) {
99 for (int i = 0; i < LFM.getFactorDimension(); i++) {
100 temp = new double[i + 1][i + 1];
101 precisionArray.add(temp);
102 }
103 for (int i = 0; i < LFM.getFactorDimension(); i++) {
104 tempMean = new double[i + 1];
105 meanArray.add(tempMean);
106 }
107
108 for (int i = 0; i < LFM.getFactorDimension(); i++) {
109 tempMean = new double[i + 1];
110 meanMidArray.add(tempMean);
111 }
112 } else {
113 for (int i = 0; i < LFM.getFactorDimension(); i++) {
114 temp = new double[LFM.getFactorDimension() - i][LFM.getFactorDimension() - i];
115 precisionArray.add(temp);
116 }
117 for (int i = 0; i < LFM.getFactorDimension(); i++) {
118 tempMean = new double[LFM.getFactorDimension() - i];
119 meanArray.add(tempMean);
120 }
121
122 for (int i = 0; i < LFM.getFactorDimension(); i++) {
123 tempMean = new double[LFM.getFactorDimension() - i];
124 meanMidArray.add(tempMean);
125 }
126 }
127
128 // vectorProductAnswer=new MatrixParameter[LFM.getLoadings().getRowDimension()];
129 // for (int i = 0; i <vectorProductAnswer.length ; i++) {
130 // vectorProductAnswer[i]=new MatrixParameter(null);
131 // vectorProductAnswer[i].setDimensions(i+1, 1);
132 // }
133
134 // priorMeanVector=new MatrixParameter[LFM.getLoadings().getRowDimension()];
135 // for (int i = 0; i <priorMeanVector.length ; i++) {
136 // priorMeanVector[i]=new MatrixParameter(null, i+1, 1, this.prior.getMean()/(this.prior.getSD()*this.prior.getSD()));
137 //
138 //
139 // }
140 if(prior != null) {
141 priorPrecision = 1 / (this.prior.getSD() * this.prior.getSD());
142 priorMeanPrecision = this.prior.getMean() * priorPrecision;
143 }
144
145 if (workingPrior == null) {
146 priorMeanPrecisionWorking = priorMeanPrecision;
147 priorPrecisionWorking = priorPrecision;
148 } else {
149 priorPrecisionWorking = 1 / (this.workingPrior.getSD() * this.workingPrior.getSD());
150 priorMeanPrecisionWorking = this.workingPrior.getMean() * priorPrecisionWorking;
151 }
152
153 if (multiThreaded) {
154 for (int i = 0; i < loadings.getRowDimension(); i++) {
155 if (i < LFM.getFactorDimension() && upperTriangle)
156 drawCallers.add(new DrawCaller(i, new double[i + 1][i + 1], new double[i + 1], new double[i + 1]));
157 else
158 drawCallers.add(new DrawCaller(i, new double[LFM.getFactorDimension()][LFM.getFactorDimension()], new double[LFM.getFactorDimension()], new double[LFM.getFactorDimension()]));
159 }
160 int threads = numThreads;
161
162 // Integer.parseInt(System.getProperty("thread.count"));
163 pool = Executors.newFixedThreadPool(threads);
164 }
165 else{
166 pool = null;
167 }
168 missingIndicator = LFM.getMissingIndicator();
169 }
170
171
172 private void getPrecisionOfTruncated(MatrixParameterInterface full, int newRowDimension, int row, double[][] answer) {
173
174 // MatrixParameter answer=new MatrixParameter(null);
175 // answer.setDimensions(this.getRowDimension(), Right.getRowDimension());
176 // System.out.println(answer.getRowDimension());
177 // System.out.println(answer.getColumnDimension());
178
179 int p = full.getColumnDimension();
180 for (int i = 0; i < newRowDimension; i++) {
181 for (int j = i; j < newRowDimension; j++) {
182 double sum = 0;
183 for (int k = 0; k < p; k++){
184 if(missingIndicator == null || missingIndicator.getParameterValue(k * LFM.getScaledData().getRowDimension() + row) != 1)
185 sum += full.getParameterValue(i, k) * full.getParameterValue(j, k);
186 }
187 answer[i][j] = sum * LFM.getColumnPrecision().getParameterValue(row, row);
188 if (i == j) {
189 if(prior3 != null){
190 if(prior3.getVariance() != null){
191 if(!upperTriangle)
192 priorPrecision = 1 / prior3.getVariance().getParameterValue(i * loadings.getRowDimension() + row);
193 else
194 priorPrecision = 1 / prior3.getVariance().getParameterValue(i * loadings.getRowDimension() + row);
195 }
196 else{
197 priorPrecision = prior3.getPrecision().getParameterValue(i * loadings.getRowDimension() + row);
198 }
199 if (workingPrior == null) {
200 priorMeanPrecisionWorking = priorMeanPrecision;
201 priorPrecisionWorking = priorPrecision;
202 }
203 }
204 answer[i][j] = answer[i][j] * pathParameter + getAdjustedPriorPrecision();
205 } else {
206 answer[i][j] *= pathParameter;
207 answer[j][i] = answer[i][j];
208 }
209 }
210 }
211 }
212
213
214 private void getTruncatedMean(int newRowDimension, int dataColumn, double[][] variance, double[] midMean, double[] mean, MatrixParameterInterface factors) {
215
216 // MatrixParameter answer=new MatrixParameter(null);
217 // answer.setDimensions(this.getRowDimension(), Right.getRowDimension());
218 // System.out.println(answer.getRowDimension());
219 // System.out.println(answer.getColumnDimension());
220 MatrixParameterInterface data = LFM.getScaledData();
221 MatrixParameterInterface Left = factors;
222 int p = data.getColumnDimension();
223 for (int i = 0; i < newRowDimension; i++) {
224 double sum = 0;
225 for (int k = 0; k < p; k++)
226 {
227 if(missingIndicator == null || missingIndicator.getParameterValue(k * LFM.getScaledData().getRowDimension() + dataColumn) != 1)
228 sum += Left.getParameterValue(i, k) * data.getParameterValue(dataColumn, k);
229 }
230 sum = sum * LFM.getColumnPrecision().getParameterValue(dataColumn, dataColumn);
231 if(prior3 != null){
232 if(prior3.getVariance() != null){
233 priorMeanPrecision = 1 / prior3.getVariance().getParameterValue(i * loadings.getRowDimension() + dataColumn)
234 * prior3.getMean().getParameterValue(i * loadings.getRowDimension() + dataColumn);
235 }
236
237 }
238 sum += priorMeanPrecision;
239 midMean[i] = sum;
240 }
241 for (int i = 0; i < newRowDimension; i++) {
242 double sum = 0;
243 for (int k = 0; k < newRowDimension; k++)
244 sum += variance[i][k] * midMean[k];
245 mean[i] = sum;
246 }
247
248 }
249
250 private void getPrecision(int i, double[][] answer, MatrixParameterInterface factors) {
251 int size = LFM.getFactorDimension();
252 if (i < size && upperTriangle) {
253 getPrecisionOfTruncated(factors, i + 1, i, answer);
254 } else {
255 getPrecisionOfTruncated(factors, size, i, answer);
256 }
257 }
258
259 private void getMean(int i, double[][] variance, double[] midMean, double[] mean, MatrixParameterInterface factors) {
260 // Matrix factors=null;
261 int size = LFM.getFactorDimension();
262 // double[] scaledDataColumn=LFM.getScaledData().getRowValues(i);
263 // Vector dataColumn=null;
264 // Vector priorVector=null;
265 // Vector temp=null;
266 // Matrix data=new Matrix(LFM.getScaledData().getParameterAsMatrix());
267 if (i < size && upperTriangle) {
268 getTruncatedMean(i + 1, i, variance, midMean, mean, factors);
269 // dataColumn=new Vector(data.toComponents()[i]);
270 // try {
271 // answer=precision.inverse().product(new Matrix(priorMeanVector[i].add(vectorProductAnswer[i]).getParameterAsMatrix()));
272 // } catch (IllegalDimension illegalDimension) {
273 // illegalDimension.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
274 // }
275 } else {
276 getTruncatedMean(size, i, variance, midMean, mean, factors);
277 // dataColumn=new Vector(data.toComponents()[i]);
278 // try {
279 // answer=precision.inverse().product(new Matrix(priorMeanVector[size-1].add(vectorProductAnswer[size-1]).getParameterAsMatrix()));
280 // } catch (IllegalDimension illegalDimension) {
281 // illegalDimension.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
282 // }
283 }
284 for (int j = 0; j < mean.length ; j++) {//TODO implement for generic prior
285 mean[j] *= pathParameter;
286 }
287
288 }
289
290 private void copy(int i, double[] random) {
291 MatrixParameterInterface changing = loadings;
292 for (int j = 0; j < random.length; j++) {
293 changing.setParameterValueQuietly(i, j, random[j]);
294 }
295 }
296
297 private void drawI(int i, double[][] precision, double[] midMean, double[] mean, MatrixParameterInterface factors) {
298 double[] draws = null;
299 double[][] variance;
300 double[][] cholesky = null;
301 getPrecision(i, precision, factors);
302 variance = (new SymmetricMatrix(precision)).inverse().toComponents();
303
304 try {
305 cholesky = new CholeskyDecomposition(variance).getL();
306 } catch (IllegalDimension illegalDimension) {
307 illegalDimension.printStackTrace();
308 }
309
310 getMean(i, variance, midMean, mean, factors);
311
312 draws = MultivariateNormalDistribution.nextMultivariateNormalCholesky(mean, cholesky);
313 // if(i<draws.length)
314 //
315 // {
316 // while (draws[i] < 0) {
317 // draws = MultivariateNormalDistribution.nextMultivariateNormalCholesky(mean, cholesky);
318 // }
319 // }
320 if (i < draws.length) {
321 //if (draws[i] > 0) { TODO implement as option
322 copy(i, draws);
323 //}
324 } else {
325 copy(i, draws);
326 }
327
328 if (DEBUG) {
329 System.err.println("draw: " + new Vector(draws));
330 }
331
332 // copy(i, draws);
333
334 }
335
336
337 public int getStepCount() {
338 return 0; //To change body of implemented methods use File | Settings | File Templates.
339 }
340
341 @Override
342 public String getOperatorName() {
343 return "loadingsGibbsOperator"; //To change body of implemented methods use File | Settings | File Templates.
344 }
345
346 private static boolean DEBUG = false;
347
348 @Override
349 public double doOperation() {
350 MatrixParameterInterface factors = LFM.getFactors();
351
352 if (DEBUG) {
353 System.err.println("Start doOp");
354 }
355
356 int size = loadings.getRowDimension();
357 if(LFM.getFactorDimension() != precisionArray.listIterator().next().length){
358
359 if (DEBUG) {
360 System.err.println("!= length");
361 }
362
363 precisionArray.clear();
364 meanArray.clear();
365 meanMidArray.clear();
366 double[] tempMean;
367 double[][] temp;
368 if (!randomScan) {
369 for (int i = 0; i < LFM.getFactorDimension(); i++) {
370 temp = new double[i + 1][i + 1];
371 precisionArray.add(temp);
372 }
373 for (int i = 0; i < LFM.getFactorDimension(); i++) {
374 tempMean = new double[i + 1];
375 meanArray.add(tempMean);
376 }
377
378 for (int i = 0; i < LFM.getFactorDimension(); i++) {
379 tempMean = new double[i + 1];
380 meanMidArray.add(tempMean);
381 }
382 } else {
383 for (int i = 0; i < LFM.getFactorDimension(); i++) {
384 temp = new double[LFM.getFactorDimension() - i][LFM.getFactorDimension() - i];
385 precisionArray.add(temp);
386 }
387 for (int i = 0; i < LFM.getFactorDimension(); i++) {
388 tempMean = new double[LFM.getFactorDimension() - i];
389 meanArray.add(tempMean);
390 }
391
392 for (int i = 0; i < LFM.getFactorDimension(); i++) {
393 tempMean = new double[LFM.getFactorDimension() - i];
394 meanMidArray.add(tempMean);
395 }
396 }
397 }
398
399 if(pool != null){
400
401 if (DEBUG) {
402 System.err.println("!= poll");
403 }
404
405 try {
406 pool.invokeAll(drawCallers);
407 loadings.fireParameterChangedEvent();
408 } catch (InterruptedException e) {
409 e.printStackTrace();
410 }
411 }
412
413 else {
414
415 if (DEBUG) {
416 System.err.println("inner");
417 }
418
419 if (!randomScan) {
420 ListIterator<double[][]> currentPrecision = precisionArray.listIterator();
421 ListIterator<double[]> currentMidMean = meanMidArray.listIterator();
422 ListIterator<double[]> currentMean = meanArray.listIterator();
423 double[][] precision = new double[loadings.getColumnDimension()][loadings.getColumnDimension()];
424 double[] midMean = new double[loadings.getColumnDimension()];
425 double[] mean = new double[loadings.getColumnDimension()];
426 for (int i = 0; i < size; i++) {
427 if(i < LFM.getFactorDimension() && upperTriangle)
428 {precision = currentPrecision.next();
429 midMean = currentMidMean.next();
430 mean = currentMean.next();
431 }
432
433 drawI(i, precision, midMean, mean, factors);
434 }
435 loadings.fireParameterChangedEvent();
436 } else {
437 int i = MathUtils.nextInt(loadings.getRowDimension());
438 ListIterator<double[][]> currentPrecision;
439 ListIterator<double[]> currentMidMean;
440 ListIterator<double[]> currentMean;
441 double[][] precision;
442 double[] midMean;
443 double[] mean;
444 if (i < LFM.getFactorDimension() && upperTriangle) {
445 currentPrecision = precisionArray.listIterator(LFM.getFactorDimension() - i - 1);
446 precision = currentPrecision.next();
447 currentMidMean = meanMidArray.listIterator(LFM.getFactorDimension() - i - 1);
448 midMean = currentMidMean.next();
449 currentMean = meanArray.listIterator(LFM.getFactorDimension() - i - 1);
450 mean = currentMean.next();
451 } else if (LFM.getFactorDimension() == i){
452 currentPrecision = precisionArray.listIterator();
453 precision = currentPrecision.next();
454 currentMidMean = meanMidArray.listIterator();
455 midMean = currentMidMean.next();
456 currentMean = meanArray.listIterator();
457 mean = currentMean.next();
458 }
459 else{
460 precision = new double[loadings.getColumnDimension()][loadings.getColumnDimension()];
461 midMean = new double[loadings.getColumnDimension()];
462 mean = new double[loadings.getColumnDimension()];
463 }
464 drawI(i, precision, midMean, mean, factors);
465 loadings.fireParameterChangedEvent(i, null);
466 // LFM.getLoadings().fireParameterChangedEvent();
467 }
468
469 }
470
471 if (DEBUG) {
472 for (double[] m : meanArray) {
473 System.err.println(new Vector(m));
474 }
475
476 for (double[] m : meanMidArray) {
477 System.err.println(new Vector(m));
478 }
479
480 for (double[][] p : precisionArray) {
481 System.err.println(new Matrix(p));
482 }
483 // System.err.println(new Matrix(precisionArray));
484 }
485
486 if (DEBUG) {
487 System.err.println("End doOp");
488 }
489
490 return 0;
491 }
492
493 public void setPathParameter(double beta){
494 pathParameter=beta;
495 }
496
497 public double getAdjustedPriorPrecision() {
498 return priorPrecision * pathParameter + (1 - pathParameter) * priorPrecisionWorking;
499 }
500
501
502 class DrawCaller implements Callable<Double> {
503
504 int i;
505 double[][] precision;
506 double[] midMean;
507 double[] mean;
508
509 public DrawCaller(int i, double[][] precision, double[] midMean, double [] mean) {
510 this.i = i;
511 this.precision = precision;
512 this.midMean = midMean;
513 this.mean = mean;
514 }
515
516
517 private final boolean DEBUG_PARALLEL_EVALUATION = false;
518 public Double call() throws Exception {
519 if (DEBUG_PARALLEL_EVALUATION) {
520 System.err.print("Invoking thread #" + i + " for " + ": ");
521 }
522 MatrixParameterInterface factors = LFM.getFactors();
523 drawI(i, precision, midMean, mean, factors);
524 return null;
525 }
526
527 }
528
529 private final List<Callable<Double>> drawCallers = new ArrayList<Callable<Double>>();
530
531 private final ExecutorService pool;
532 }