Debian Codegraph @

src/dr/inference/model/ThreadedCompoundLikelihood.java

raw symbols SCIP
1 /*
2 * ThreadedCompoundLikelihood.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 java.util.ArrayList;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Set;
32 import java.util.concurrent.locks.Condition;
33 import java.util.concurrent.locks.ReentrantLock;
34
35 import dr.evomodel.treelikelihood.BeagleTreeLikelihood;
36 import dr.util.NumberFormatter;
37
38 /**
39 * A likelihood function which is simply the product of a set of likelihood functions.
40 *
41 * @author Marc Suchard
42 * @author Andrew Rambaut
43 * @version $Id: CompoundLikelihood.java,v 1.19 2005/05/25 09:14:36 rambaut Exp $
44 */
45 public class ThreadedCompoundLikelihood implements Likelihood {
46
47 public static final boolean DEBUG = false;
48
49 public ThreadedCompoundLikelihood() {
50 }
51
52 public ThreadedCompoundLikelihood(List<Likelihood> likelihoods) {
53 for (Likelihood likelihood : likelihoods) {
54 addLikelihood(likelihood);
55 }
56 }
57
58 public void addLikelihood(Likelihood likelihood) {
59
60 if (!likelihoods.contains(likelihood)) {
61
62 likelihoods.add(likelihood);
63 if (likelihood.getModel() != null) {
64 compoundModel.addModel(likelihood.getModel());
65 }
66
67 likelihoodCallers.add(new LikelihoodCaller(likelihood));
68
69 //System.err.println("LikelihoodCallers size: " + likelihoodCallers.size());
70 }
71 }
72
73 @Override
74 public Set<Likelihood> getLikelihoodSet() {
75 Set<Likelihood> set = new HashSet<Likelihood>();
76 for (Likelihood l : likelihoods) {
77 set.add(l);
78 set.addAll(l.getLikelihoodSet());
79 }
80 return set;
81 }
82
83 public int getLikelihoodCount() {
84 return likelihoods.size();
85 }
86
87 public final Likelihood getLikelihood(int i) {
88 return likelihoods.get(i);
89 }
90
91 // **************************************************************
92 // Likelihood IMPLEMENTATION
93 // **************************************************************
94
95 public Model getModel() {
96 return compoundModel;
97 }
98
99 public double getLogLikelihood() {
100
101 double logLikelihood = 0.0;
102
103 boolean knownLikelihoods = true;
104 for (Likelihood likelihood : likelihoods) {
105 if (!((BeagleTreeLikelihood)likelihood).isLikelihoodKnown()) {
106 knownLikelihoods = false;
107 break;
108 } else {
109 logLikelihood += likelihood.getLogLikelihood();
110 }
111 }
112
113 if (knownLikelihoods) {
114
115 if (DEBUG) {
116 //System.err.println("BTLs are known; total logLikelihood = " + logLikelihood);
117 //double check if the total loglikelihood will be identical by recalculating
118 double backupLikelihood = logLikelihood;
119 logLikelihood = 0.0;
120
121 if (threads == null) {
122 // first call so setup a thread for each likelihood...
123 threads = new LikelihoodThread[likelihoodCallers.size()];
124 for (int i = 0; i < threads.length; i++) {
125 // and start them running...
126 threads[i] = new LikelihoodThread();
127 threads[i].start();
128 }
129 }
130
131 for (int i = 0; i < threads.length; i++) {
132 // set the caller which will be called in each thread
133 threads[i].setCaller(likelihoodCallers.get(i));
134 }
135
136 for (LikelihoodThread thread : threads) {
137 // now wait for the results to be set...
138 Double result = thread.getResult();
139 while (result == null) {
140 result = thread.getResult();
141 }
142 logLikelihood += result;
143 }
144
145 if (backupLikelihood != logLikelihood) {
146 //System.err.println("Likelihood recalculation does not return stored likelihood");
147 throw new RuntimeException("Likelihood recalculation does not return stored likelihood");
148 }
149 }
150 } else {
151 //System.err.println("BTLs are not known: recalculate");
152
153 logLikelihood = 0.0;
154
155 //double start = System.nanoTime();
156 //System.err.println("TCL getLogLikelihood()");
157
158 if (threads == null) {
159 //System.err.println("threads == null");
160 // first call so setup a thread for each likelihood...
161 threads = new LikelihoodThread[likelihoodCallers.size()];
162 //System.err.println("LikelihoodThreads: " + threads.length);
163 for (int i = 0; i < threads.length; i++) {
164 // and start them running...
165 threads[i] = new LikelihoodThread();
166 threads[i].start();
167 }
168 }
169
170 //double setStart = System.nanoTime();
171 for (int i = 0; i < threads.length; i++) {
172 // set the caller which will be called in each thread
173 threads[i].setCaller(likelihoodCallers.get(i));
174 }
175 //double setEnd = System.nanoTime();
176 //System.err.println("setting callers: " + (setEnd - setStart));
177
178 //start = System.nanoTime();
179 for (LikelihoodThread thread : threads) {
180 //double testone = System.nanoTime();
181 // now wait for the results to be set...
182 Double result = thread.getResult();
183 while (result == null) {
184 result = thread.getResult();
185 }
186 logLikelihood += result;
187 //double testtwo = System.nanoTime();
188 //System.err.println(thread.getName() + " - result = " + result + ": " + (testtwo - testone));
189 }
190 //end = System.nanoTime();
191 //double end = System.nanoTime();
192 //System.err.println("TCL total time: " + (end - start));
193 }
194 return logLikelihood; // * weightFactor;
195
196 }
197
198 public boolean evaluateEarly() {
199 return false;
200 }
201
202 public void makeDirty() {
203
204 for (Likelihood likelihood : likelihoods) {
205 likelihood.makeDirty();
206 }
207 }
208
209 public String prettyName() {
210 return Abstract.getPrettyName(this);
211 }
212
213 public String getDiagnosis() {
214 String message = "";
215 boolean first = true;
216
217 for (Likelihood lik : likelihoods) {
218
219 if (!first) {
220 message += ", ";
221 } else {
222 first = false;
223 }
224
225 String id = lik.getId();
226 if (id == null || id.trim().length() == 0) {
227 String[] parts = lik.getClass().getName().split("\\.");
228 id = parts[parts.length - 1];
229 }
230
231 message += id + "=";
232
233
234 if (lik instanceof ThreadedCompoundLikelihood) {
235 String d = ((ThreadedCompoundLikelihood) lik).getDiagnosis();
236 if (d != null && d.length() > 0) {
237 message += "(" + d + ")";
238 }
239 } else {
240
241 if (lik.getLogLikelihood() == Double.NEGATIVE_INFINITY) {
242 message += "-Inf";
243 } else if (Double.isNaN(lik.getLogLikelihood())) {
244 message += "NaN";
245 } else {
246 NumberFormatter nf = new NumberFormatter(6);
247 message += nf.formatDecimal(lik.getLogLikelihood(), 4);
248 }
249 }
250 }
251
252 return message;
253 }
254
255 public String toString() {
256
257 return Double.toString(getLogLikelihood());
258
259 }
260
261 public void setWeightFactor(double w) { weightFactor = w; }
262
263 public double getWeightFactor() { return weightFactor; }
264
265 // **************************************************************
266 // Loggable IMPLEMENTATION
267 // **************************************************************
268
269 /**
270 * @return the log columns.
271 */
272 public dr.inference.loggers.LogColumn[] getColumns() {
273 return new dr.inference.loggers.LogColumn[]{
274 new LikelihoodColumn(getId())
275 };
276 }
277
278 private class LikelihoodColumn extends dr.inference.loggers.NumberColumn {
279 public LikelihoodColumn(String label) {
280 super(label);
281 }
282
283 public double getDoubleValue() {
284 return getLogLikelihood();
285 }
286 }
287
288 // **************************************************************
289 // Identifiable IMPLEMENTATION
290 // **************************************************************
291
292 private String id = null;
293
294 public void setId(String id) {
295 this.id = id;
296 }
297
298 public String getId() {
299 return id;
300 }
301
302 private LikelihoodThread[] threads;
303
304 private final ArrayList<Likelihood> likelihoods = new ArrayList<Likelihood>();
305 private final CompoundModel compoundModel = new CompoundModel("compoundModel");
306
307 private final List<LikelihoodCaller> likelihoodCallers = new ArrayList<LikelihoodCaller>();
308
309 private double weightFactor = 1.0;
310
311 class LikelihoodCaller {
312
313 public LikelihoodCaller(Likelihood likelihood) {
314 this.likelihood = likelihood;
315 }
316
317 public double call() {
318 return likelihood.getLogLikelihood();
319 }
320
321 private final Likelihood likelihood;
322 }
323
324 class LikelihoodThread extends Thread {
325
326 public LikelihoodThread() {
327 }
328
329 public void setCaller(LikelihoodCaller caller) {
330 lock.lock();
331 resultAvailable = false;
332 try {
333 this.caller = caller;
334 condition.signal();
335 } finally {
336 lock.unlock();
337 }
338 }
339
340 /**
341 * Main run loop
342 */
343 public void run() {
344 while (true) {
345 lock.lock();
346 try {
347 while( caller == null)
348 condition.await();
349 result = caller.call(); // SLOW
350 resultAvailable = true;
351 caller = null;
352 } catch (InterruptedException e){
353
354 } finally {
355 lock.unlock();
356 }
357 }
358 }
359
360 public Double getResult() {
361 Double returnValue = null;
362 if (!lock.isLocked() && resultAvailable) { // thread is not busy and completed
363 resultAvailable = false; // TODO need to lock before changing resultAvailable?
364 returnValue = result;
365 }
366 return returnValue;
367 }
368
369 private LikelihoodCaller caller = null;
370 private Double result = Double.NaN;
371 private boolean resultAvailable = false;
372 private final ReentrantLock lock = new ReentrantLock();
373 private final Condition condition = lock.newCondition();
374 }
375
376 public boolean isUsed() {
377 return isUsed;
378 }
379
380 public void setUsed() {
381 isUsed = true;
382
383 for (Likelihood l : likelihoods) {
384 l.setUsed();
385 }
386 }
387
388 private boolean isUsed = false;
389
390 }