Debian Codegraph @

src/dr/inference/model/CompoundLikelihood.java

raw symbols SCIP
1 /*
2 * CompoundLikelihood.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.model;
27
28 import dr.util.Keywordable;
29 import dr.util.NumberFormatter;
30 import dr.xml.Reportable;
31
32 import java.util.*;
33 import java.util.concurrent.*;
34
35 /**
36 * A likelihood function which is simply the product of a set of likelihood functions.
37 *
38 * @author Alexei Drummond
39 * @author Andrew Rambaut
40 * @version $Id: CompoundLikelihood.java,v 1.19 2005/05/25 09:14:36 rambaut Exp $
41 */
42 public class CompoundLikelihood implements Likelihood, Reportable, Keywordable {
43
44 public final static boolean UNROLL_COMPOUND = true;
45
46 public final static boolean EVALUATION_TIMERS = true;
47 public final long[] evaluationTimes;
48 public final int[] evaluationCounts;
49
50 public CompoundLikelihood(int threads, Collection<Likelihood> likelihoods) {
51
52 int i = 0;
53 for (Likelihood l : likelihoods) {
54 addLikelihood(l, i, true);
55 i++;
56 }
57
58 if (threads < 0 && this.likelihoods.size() > 1) {
59 // asking for an automatic threadpool size and there is more than one likelihood to compute
60 threadCount = this.likelihoods.size(); // create a threadpool the size of the number of likelihoods
61 // threadCount = -1; // use cached thread pool
62 } else if (threads > 0) {
63 threadCount = threads; // use a thread pool of a specified size
64 } else {
65 // no thread pool requested or only one likelihood
66 threadCount = 0;
67 }
68
69 if (threadCount > 0) {
70 pool = Executors.newFixedThreadPool(threadCount);
71 } else if (threadCount < 0) {
72 // create a cached thread pool which should create one thread per likelihood...
73 pool = Executors.newCachedThreadPool();
74 } else {
75 // don't use a threadpool (i.e., compute serially)
76 pool = null;
77 }
78
79 if (EVALUATION_TIMERS) {
80 evaluationTimes = new long[this.likelihoods.size()];
81 evaluationCounts = new int[this.likelihoods.size()];
82 } else {
83 evaluationTimes = null;
84 evaluationCounts = null;
85 }
86 }
87
88 public CompoundLikelihood(Collection<Likelihood> likelihoods) {
89
90 pool = null;
91 threadCount = 0;
92
93 int i = 0;
94 for (Likelihood l : likelihoods) {
95 addLikelihood(l, i, false);
96 i++;
97 }
98
99 if (EVALUATION_TIMERS) {
100 evaluationTimes = new long[this.likelihoods.size()];
101 evaluationCounts = new int[this.likelihoods.size()];
102 } else {
103 evaluationTimes = null;
104 evaluationCounts = null;
105 }
106 }
107
108 // public CompoundLikelihood(BeagleBranchLikelihoods bbl) {
109 //
110 // pool = null;
111 // threadCount = 0;
112 // evaluationTimes = null;
113 // evaluationCounts = null;
114 //
115 // }
116
117 protected void addLikelihood(Likelihood likelihood, int index, boolean addToPool) {
118
119 // unroll any compound likelihoods
120 if (UNROLL_COMPOUND && addToPool && likelihood instanceof CompoundLikelihood) {
121
122 for (Likelihood l : ((CompoundLikelihood)likelihood).getLikelihoods()) {
123 addLikelihood(l, index, addToPool);
124 }
125
126 } else {
127
128 if (!likelihoods.contains(likelihood)) {
129
130 likelihoods.add(likelihood);
131 if (likelihood.getModel() != null) {
132 compoundModel.addModel(likelihood.getModel());
133 }
134
135 if (likelihood.evaluateEarly()) {
136
137 earlyLikelihoods.add(likelihood);
138
139 } else {
140
141 // late likelihood list is used to evaluate them if the thread pool is not being used...
142 lateLikelihoods.add(likelihood);
143
144 if (addToPool) {
145 likelihoodCallers.add(new LikelihoodCaller(likelihood, index));
146 }
147 }
148
149 } else {
150 throw new IllegalArgumentException("Attempted to add the same likelihood multiple times to CompoundLikelihood.");
151 } // END: contains check
152
153 }//END: if unroll check
154
155 }//END: addLikelihood
156
157 public Set<Likelihood> getLikelihoodSet() {
158 Set<Likelihood> set = new HashSet<Likelihood>();
159 for (Likelihood l : likelihoods) {
160 set.add(l);
161 set.addAll(l.getLikelihoodSet());
162 }
163 return set;
164 }
165
166 public int getLikelihoodCount() {
167 return likelihoods.size();
168 }
169
170 public final Likelihood getLikelihood(int i) {
171 return likelihoods.get(i);
172 }
173
174 public List<Likelihood> getLikelihoods() {
175 return likelihoods;
176 }
177
178 public List<Callable<Double>> getLikelihoodCallers() {
179 return likelihoodCallers;
180 }
181
182 // **************************************************************
183 // Likelihood IMPLEMENTATION
184 // **************************************************************
185
186 public Model getModel() {
187 return compoundModel;
188 }
189
190 // // todo: remove in release
191 // static int DEBUG = 0;
192
193 public double getLogLikelihood() {
194
195 double logLikelihood = evaluateLikelihoods(earlyLikelihoods);
196
197 if( logLikelihood == Double.NEGATIVE_INFINITY ) {
198 return Double.NEGATIVE_INFINITY;
199 }
200
201 if (pool == null) {
202 // Single threaded
203 logLikelihood += evaluateLikelihoods(lateLikelihoods);
204 } else {
205
206 try {
207 List<Future<Double>> results = pool.invokeAll(likelihoodCallers);
208
209 for (Future<Double> result : results) {
210 double logL = result.get();
211 logLikelihood += logL;
212 }
213
214 } catch (InterruptedException e) {
215 e.printStackTrace();
216 } catch (ExecutionException e) {
217 e.printStackTrace();
218 }
219 }
220
221 // if( DEBUG > 0 ) {
222 // int t = DEBUG; DEBUG = 0;
223 // System.err.println(getId() + ": " + getDiagnosis(0) + " = " + logLikelihood);
224 // DEBUG = t;
225 // }
226
227 if (DEBUG_PARALLEL_EVALUATION) {
228 System.err.println("");
229 }
230 return logLikelihood;
231 }
232
233 private double evaluateLikelihoods(ArrayList<Likelihood> likelihoods) {
234 double logLikelihood = 0.0;
235 int i = 0;
236 for (Likelihood likelihood : likelihoods) {
237 if (EVALUATION_TIMERS) {
238 // this code is only compiled if EVALUATION_TIMERS is true
239 long time = System.nanoTime();
240 double l = likelihood.getLogLikelihood();
241 evaluationTimes[i] += System.nanoTime() - time;
242 evaluationCounts[i] ++;
243
244 if( l == Double.NEGATIVE_INFINITY )
245 return Double.NEGATIVE_INFINITY;
246
247 logLikelihood += l;
248
249 i++;
250 } else {
251 final double l = likelihood.getLogLikelihood();
252 // if the likelihood is zero then short cut the rest of the likelihoods
253 // This means that expensive likelihoods such as TreeLikelihoods should
254 // be put after cheap ones such as BooleanLikelihoods
255 if( l == Double.NEGATIVE_INFINITY )
256 return Double.NEGATIVE_INFINITY;
257 logLikelihood += l;
258 }
259 }
260
261 return logLikelihood;
262 }
263
264 public void makeDirty() {
265 for( Likelihood likelihood : likelihoods ) {
266 likelihood.makeDirty();
267 }
268 }
269
270 public boolean evaluateEarly() {
271 return false;
272 }
273
274 public String getDiagnosis() {
275 return getDiagnosis(0);
276 }
277
278 public String getDiagnosis(int indent) {
279 String message = "";
280 boolean first = true;
281
282 final NumberFormatter nf = new NumberFormatter(6);
283
284 for( Likelihood lik : likelihoods ) {
285
286 if( !first ) {
287 message += ", ";
288 } else {
289 first = false;
290 }
291
292 if (indent >= 0) {
293 message += "\n";
294 for (int i = 0; i < indent; i++) {
295 message += " ";
296 }
297 }
298 message += lik.prettyName() + "=";
299
300 if( lik instanceof CompoundLikelihood ) {
301 final String d = ((CompoundLikelihood) lik).getDiagnosis(indent < 0 ? -1 : indent + 2);
302 if( d != null && d.length() > 0 ) {
303 message += "(" + d;
304
305 if (indent >= 0) {
306 message += "\n";
307 for (int i = 0; i < indent; i++) {
308 message += " ";
309 }
310 }
311 message += ")";
312 }
313 } else {
314
315 final double logLikelihood = lik.getLogLikelihood();
316 if( logLikelihood == Double.NEGATIVE_INFINITY ) {
317 message += "-Inf";
318 } else if( Double.isNaN(logLikelihood) ) {
319 message += "NaN";
320 } else if( logLikelihood == Double.POSITIVE_INFINITY ) {
321 message += "+Inf";
322 } else {
323 message += nf.formatDecimal(logLikelihood, 4);
324 }
325 }
326 }
327 message += "\n";
328 for (int i = 0; i < indent; i++) {
329 message += " ";
330 }
331 message += "Total = " + this.getLogLikelihood();
332
333 return message;
334 }
335
336 public String toString() {
337 return getId();
338 // really bad for debugging
339 //return Double.toString(getLogLikelihood());
340 }
341
342 public String prettyName() {
343 return Abstract.getPrettyName(this);
344 }
345
346 public boolean isUsed() {
347 return used;
348 }
349
350 public void setUsed() {
351 used = true;
352 for (Likelihood l : likelihoods) {
353 l.setUsed();
354 }
355 }
356
357 public int getThreadCount() {
358 return threadCount;
359 }
360
361 public long[] getEvaluationTimes() {
362 return evaluationTimes;
363 }
364
365 public int[] getEvaluationCounts() {
366 return evaluationCounts;
367 }
368
369 public void resetEvaluationTimes() {
370 for (int i = 0; i < evaluationTimes.length; i++) {
371 evaluationTimes[i] = 0;
372 evaluationCounts[i] = 0;
373 }
374 }
375
376
377 // **************************************************************
378 // Loggable IMPLEMENTATION
379 // **************************************************************
380
381 /**
382 * @return the log columns.
383 */
384 public dr.inference.loggers.LogColumn[] getColumns() {
385 return new dr.inference.loggers.LogColumn[]{
386 new LikelihoodColumn(getId() == null ? "likelihood" : getId())
387 };
388 }
389
390 @Override
391 public void addKeyword(String keyword) {
392 throw new UnsupportedOperationException("Can't add keywords here");
393 }
394
395 @Override
396 public List<String> getKeywords() {
397 List<String> keywords = new ArrayList<String>();
398 for (Likelihood likelihood : likelihoods) {
399 if (likelihood instanceof Keywordable) {
400 keywords.addAll(((Keywordable)likelihood).getKeywords());
401 }
402 }
403 return keywords;
404 }
405
406 private class LikelihoodColumn extends dr.inference.loggers.NumberColumn implements Keywordable {
407 public LikelihoodColumn(String label) {
408 super(label);
409 }
410
411 public double getDoubleValue() {
412 return getLogLikelihood();
413 }
414
415 @Override
416 public void addKeyword(String keyword) {
417 throw new UnsupportedOperationException("Can't add keywords here");
418 }
419
420 @Override
421 public List<String> getKeywords() {
422 return CompoundLikelihood.this.getKeywords();
423 }
424 }
425
426 // **************************************************************
427 // Reportable IMPLEMENTATION
428 // **************************************************************
429
430 public String getReport() {
431 return getReport(0);
432 }
433
434 public String getReport(int indent) {
435 if (EVALUATION_TIMERS) {
436 String message = "\n";
437 boolean first = true;
438
439 final NumberFormatter nf = new NumberFormatter(6);
440
441 int index = 0;
442 for( Likelihood lik : likelihoods ) {
443
444 if( !first ) {
445 message += ", ";
446 } else {
447 first = false;
448 }
449
450 if (indent >= 0) {
451 message += "\n";
452 for (int i = 0; i < indent; i++) {
453 message += " ";
454 }
455 }
456 message += lik.prettyName() + "=";
457
458 if( lik instanceof CompoundLikelihood ) {
459 final String d = ((CompoundLikelihood) lik).getReport(indent < 0 ? -1 : indent + 2);
460 if( d != null && d.length() > 0 ) {
461 message += "(" + d;
462
463 if (indent >= 0) {
464 message += "\n";
465 for (int i = 0; i < indent; i++) {
466 message += " ";
467 }
468 }
469 message += ")";
470 }
471 } else {
472 double secs = (double)evaluationTimes[index] / 1.0E9;
473 message += evaluationCounts[index] + " evaluations in " +
474 nf.format(secs) + " secs (" +
475 nf.format(secs / evaluationCounts[index]) + " secs/eval)";
476 }
477 index++;
478 }
479
480 return message;
481 } else {
482 return "No evaluation timer report available";
483 }
484 }
485
486
487
488 // **************************************************************
489 // Identifiable IMPLEMENTATION
490 // **************************************************************
491
492 private String id = null;
493
494 public void setId(String id) {
495 this.id = id;
496 }
497
498 public String getId() {
499 return id;
500 }
501
502 private boolean used = false;
503
504 private final int threadCount;
505
506 private final ExecutorService pool;
507
508 private final ArrayList<Likelihood> likelihoods = new ArrayList<Likelihood>();
509 private final CompoundModel compoundModel = new CompoundModel("compoundModel");
510
511 private final ArrayList<Likelihood> earlyLikelihoods = new ArrayList<Likelihood>();
512 private final ArrayList<Likelihood> lateLikelihoods = new ArrayList<Likelihood>();
513
514 private final List<Callable<Double>> likelihoodCallers = new ArrayList<Callable<Double>>();
515
516 class LikelihoodCaller implements Callable<Double> {
517
518 public LikelihoodCaller(Likelihood likelihood, int index) {
519 this.likelihood = likelihood;
520 this.index = index;
521 }
522
523 public Double call() throws Exception {
524 if (DEBUG_PARALLEL_EVALUATION) {
525 System.err.print("Invoking thread #" + index + " for " + likelihood.getId() + ": ");
526 }
527 if (EVALUATION_TIMERS) {
528 long time = System.nanoTime();
529 double logL = likelihood.getLogLikelihood();
530 evaluationTimes[index] += System.nanoTime() - time;
531 evaluationCounts[index] ++;
532 return logL;
533 }
534 return likelihood.getLogLikelihood();
535 }
536
537 private final Likelihood likelihood;
538 private final int index;
539 }
540
541 public static final boolean DEBUG_PARALLEL_EVALUATION = false;
542
543 }
544