Debian Codegraph @

src/dr/evomodel/epidemiology/ODEDemographicFunction.java

raw symbols SCIP
1 /*
2 * ODEDemographicFunction.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 /*
27 * Base class for demographic models based on numerically-integrated ODEs
28 *
29 */
30 package dr.evomodel.epidemiology;
31
32 import dr.evolution.coalescent.*;
33
34
35 /**
36 * This interface provides methods that describe a demographic function.
37 * @author Daniel Wilson
38 */
39
40 /*public interface ODEDemographicFunction extends DemographicFunction {
41 public abstract class Abstract implements ODEDemographicFunction {
42 public Abstract(Type units) {
43 setUnits(units);
44 }
45 public double getLogDemographic(double t) {
46 return Math.log(getDemographic(t));
47 }
48 public double getIntegral(double start, double finish)
49 {
50 return getIntensity(finish) - getIntensity(start);
51 }
52
53 }
54 }*/
55
56 public abstract class ODEDemographicFunction extends DemographicFunction.Abstract {
57 public ODEDemographicFunction(Type units) {
58 super(units);
59 }
60
61 // Implement abstract types from base class
62
63 /**
64 * Default implementation
65 * @param t
66 * @return log(demographic at t)
67 */
68 /*public double getLogDemographic(double t) {
69 return Math.log(getDemographic(t));
70 }*/
71
72 /**
73 * Calculates the integral 1/N(x) dx between start and finish.
74 */
75 /*public double getIntegral(double start, double finish)
76 {
77 return getIntensity(finish) - getIntensity(start);
78 }*/
79
80 /**
81 * Returns the integral of 1/N(x) between start and finish, calling either the getAnalyticalIntegral or
82 * getNumericalIntegral function as appropriate.
83 */
84 public double getNumericalIntegral(double start, double finish) {
85 throw new RuntimeException("not implemented");
86 }
87
88 public double getDemographic(double t) {
89 Evaluate(t);
90 if(RKfail) return 0.0;
91 return getDemographicFromPrevalence(Ynow,t);
92 }
93
94 public double getIntensity(double t) {
95 Evaluate(t);
96 if(RKfail) return Math.log(0.0);
97 return Ynow[0];
98 }
99
100 // Implement the following abstract functions:
101
102 /**
103 * Calculate the derivatives and store in dydt
104 */
105 abstract void derivs(double t, double[] y, double[] dydt);
106
107 /**
108 * Set initial values of y
109 * for(i=0;i<nvar;i++) Y[i][0] = ...;
110 */
111 abstract void setInit();
112
113 /**
114 * Calculate the effective population size from the prevalence, contained in y
115 * @return
116 */
117 abstract double getDemographicFromPrevalence(double[] y, double t);
118
119 // Implemented base functions
120
121 /**
122 * Evaluate the demographic functions at time Tnow.
123 * Store results in Ynow for immediate use by getDemographic or getIntensity
124 */
125 void Evaluate(double t) {
126 if(RKfail) return;
127 // if (t==Tnow) ???
128 if(t<0.0) throw new RuntimeException("t cannot be negative");
129 int i;
130 if(klast==-1 || t>T[klast]) {
131 if(klast+1>=kmax) {
132 // 3rd December 2011: Previous behaviour was stupid, now increase storage capacity
133 // Assume linear, but flag warning
134 //RKwarning = true;
135 //for(i=0;i<nvar;i++) Ynow[i] = Y[i][klast];
136 //Tnow = t;
137 //return;
138 RKresize();
139 }
140 // Continue integration
141 try {
142 RungeKutta(t);
143 } catch(RuntimeException e) {
144 System.err.println(e.getMessage());
145 RKfail = true;
146 return;
147 }
148 for(i=0;i<nvar;i++) Ynow[i] = Y[i][klast];
149 Tnow = t;
150 return;
151 }
152 if(t==T[klast]) {
153 for(i=0;i<nvar;i++) Ynow[i] = Y[i][klast];
154 Tnow = t;
155 return;
156 }
157 // Linearly interpolate
158 int k1 = (int)Math.floor(t/dtsav);
159 if(k1>klast-1) k1 = klast-1;
160 if(k1<0) k1 = 0;
161 int k2 = k1+1;
162 if(k2>klast || T[k1]>t) {
163 while(k2>klast || T[k1]>t) {
164 --k1;
165 --k2;
166 }
167 }
168 else if(k1<0 || T[k2]<=t) {
169 while(k1<0 || T[k2]<=t) {
170 ++k1;
171 ++k2;
172 }
173 }
174 if(T[k1]==t) {
175 for(i=0;i<nvar;i++) Ynow[i] = Y[i][k1];
176 }
177 else {
178 // Linearly interpolate
179 for(i=0;i<nvar;i++) Ynow[i] = Y[i][k1] + (t-T[k1])*(Y[i][k2]-Y[i][k1])/(T[k2]-T[k1]);
180 }
181 Tnow = t;
182 }
183
184 /**
185 * Initialize RK integration
186 */
187 void RKinit() {
188 klast = -1;
189 RKwarning = false;
190 RKfail = false;
191 if(Y==null || Y.length!=nvar || Y[0].length!=kmax) {
192 // Should be no memory leak
193 Y = new double[nvar][kmax];
194 T = new double[kmax];
195 Ynow = new double[nvar];
196 ak2 = new double[nvar];
197 ak3 = new double[nvar];
198 ak4 = new double[nvar];
199 ak5 = new double[nvar];
200 ak6 = new double[nvar];
201 Ytemp = new double[nvar];
202 Yerr = new double[nvar];
203 y = new double[nvar];
204 dydt = new double[nvar];
205 yscal = new double[nvar];
206 }
207 nok = nbad = 0;
208 }
209
210 /**
211 * Increase kmax by kinc on the hoof
212 */
213 void RKresize() {
214 if(Y==null) throw new RuntimeException("Y not yet allocated");
215 if(T==null) throw new RuntimeException("T not yet allocated");
216 if(kmax==kabsolutemax) throw new RuntimeException("kabsolutemax exceeded");
217 // Store old value of kmax before incrementing it
218 int oldkmax = kmax;
219 kmax += kinc;
220 // Temporary pointers to old arrays, should get garbage collected
221 double oldY[][] = Y;
222 double oldT[] = T;
223 // Allocate new memory for enlarged arrays
224 Y = new double[nvar][kmax];
225 T = new double[kmax];
226 // Copy across old values
227 int i,j;
228 for(i=0;i<oldkmax;i++) {
229 for(j=0;j<nvar;j++) {
230 Y[j][i] = oldY[j][i];
231 }
232 T[i] = oldT[i];
233 }
234 }
235
236 /**
237 * Flag if kmax is exceeded
238 * @return
239 */
240 public boolean RKwarn() {
241 return RKwarning;
242 }
243
244 /**
245 * Driving routine for RungeKutta integration
246 */
247 void RungeKutta(double t2) {
248 // if(h1<0) throw new RuntimeException("h1 must be positive");
249 if(klast==kmax-1) throw new RuntimeException("storage space is exceeded");
250 if(klast==-1) {
251 setInit(); // virtual function, over-ride in derived class
252 T[0] = 0;
253 ++klast;
254 }
255 if(t2==0.0) return;
256
257 int i,nstp;
258 double t1 = T[klast]; // beginning of time range
259 double t = t1; // current time
260 double tsav = t1; // time of last saved point
261 // Copy initial y values
262 for (i=0;i<nvar;i++) y[i]=Y[i][klast];
263 // Step size
264 double h=hinit; // NB h must be positive
265
266 for(nstp=0;nstp<MAXSTP;nstp++) {
267 double tmp = nstp;
268 if(nstp>MAXSTP/2) {
269 tmp = tmp+3;
270 }
271 // Calculate the derivatives at the present time
272 derivs(t,y,dydt);
273 // Calculate appropriate scalings for the error tolerance
274 for(i=0;i<nvar;i++)
275 yscal[i]=Math.abs(y[i])+Math.abs(dydt[i]*h)+TINY;
276 // Storage (ensure there's room for final state)
277 if(klast < kmax-2 && Math.abs(t-tsav) > Math.abs(dtsav)) {
278 ++klast;
279 for (i=0;i<nvar;i++) Y[i][klast]=y[i];
280 T[klast]=t;
281 tsav=t;
282 }
283 // Reduce step size to avoid over-stepping target time t2
284 if((t+h-t2)*(t+h-t1) > 0.0) h=t2-t;
285 // Perform the adaptive integration and update time
286 t = rkqs(y,dydt,t,h,yscal);
287 // Was the predicted step size used?
288 if(hdid == h) ++nok; else ++nbad;
289 // If the target t2 has been reached
290 if((t-t2)*(t2-t1) >= 0.0) {
291 // Store state at t2
292 if (klast < kmax-1) {
293 ++klast;
294 for (i=0;i<nvar;i++) Y[i][klast]=y[i];
295 T[klast]=t;
296 }
297 return;
298 }
299 if(Math.abs(hnext) <= hmin) {
300 throw new RuntimeException("Step size too small in odeint");
301 }
302 h=hnext;
303 }
304 throw new RuntimeException("Too many steps in routine odeint");
305 }
306
307 /**
308 * Take an adaptive step
309 *
310 * @return New time
311 */
312 // Cannot output primitive scalars by modifying arguments. So hdid and hnext become member variables and t is returned.
313 double rkqs(double[] y, double[] dydt, double t, double htry, double[] yscal) {
314 int i;
315 double errmax,h,htemp,tnew;
316
317 h=htry;
318 for(;;) {
319 rkck(y,dydt,t,h);
320 errmax=0.0;
321 for(i=0;i<nvar;i++) errmax=Math.max(errmax,Math.abs(Yerr[i]/yscal[i]));
322 errmax /= eps;
323 if(errmax <= 1.0) break;
324 if(Double.isNaN(errmax)) {
325 throw new RuntimeException("errmax NaN");
326 // Invalid value of one or more of the variables was chosen. Halve the step size
327 //h /= 2.0;
328 } else {
329 htemp=SAFETY*h*Math.pow(errmax,PSHRNK);
330 h=(h >= 0.0 ? Math.max(htemp,0.1*h) : Math.min(htemp,0.1*h));
331 }
332 tnew=t+h;
333 if(tnew == t) {
334 throw new RuntimeException("stepsize underflow in rkqs");
335 }
336 }
337 if(errmax > ERRCON) hnext=SAFETY*h*Math.pow(errmax,PGROW);
338 else hnext=5.0*h;
339 t += (hdid=h);
340 for(i=0;i<nvar;i++) y[i]=Ytemp[i];
341 return t;
342 }
343
344 /**
345 * Take one RK5 step
346 */
347 // NB: Arrays such as ak2 and yerr are objects. Pointers to these objects are passed by
348 // value into rkck. The whole array is not copied. So this should work...
349 void rkck(double[] y, double[] dydt, double t, double h) {
350 int i;
351
352 for(i=0;i<nvar;i++)
353 Ytemp[i]=y[i]+b21*h*dydt[i];
354 derivs(t+a2*h,Ytemp,ak2);
355 for(i=0;i<nvar;i++)
356 Ytemp[i]=y[i]+h*(b31*dydt[i]+b32*ak2[i]);
357 derivs(t+a3*h,Ytemp,ak3);
358 for(i=0;i<nvar;i++)
359 Ytemp[i]=y[i]+h*(b41*dydt[i]+b42*ak2[i]+b43*ak3[i]);
360 derivs(t+a4*h,Ytemp,ak4);
361 for(i=0;i<nvar;i++)
362 Ytemp[i]=y[i]+h*(b51*dydt[i]+b52*ak2[i]+b53*ak3[i]+b54*ak4[i]);
363 derivs(t+a5*h,Ytemp,ak5);
364 for(i=0;i<nvar;i++)
365 Ytemp[i]=y[i]+h*(b61*dydt[i]+b62*ak2[i]+b63*ak3[i]+b64*ak4[i]+b65*ak5[i]);
366 derivs(t+a6*h,Ytemp,ak6);
367 for(i=0;i<nvar;i++)
368 Ytemp[i]=y[i]+h*(c1*dydt[i]+c3*ak3[i]+c4*ak4[i]+c6*ak6[i]);
369 for(i=0;i<nvar;i++)
370 Yerr[i]=h*(dc1*dydt[i]+dc3*ak3[i]+dc4*ak4[i]+dc5*ak5[i]+dc6*ak6[i]);
371 }
372
373
374 // Member variables
375
376 protected int nvar = 0; // Default to zero
377
378 // Runge-Kutta integration variables
379 protected int kmax=200; // Maximum storage capacity for integration
380 protected int kinc=200; // Increment size for kmax when it is exceeded
381 protected int kabsolutemax=200000; // Absolute maximum storage capacity for integration allowable
382 protected int klast=-1; // Index of the last evaluation point
383 protected double hinit=0.1; // Initial suggested step size for RungeKutta integration
384 protected double[][] Y; // Storage for integration results. Y[0] must always contain Lambda, the integrated intensity function
385 protected double[] T; // Storage for evaluated time points: interpolate between
386 protected boolean RKwarning; // Warn if kmax is exceeded
387
388 // Temporary variables
389 protected double[] Ynow; // Instead of passing and returning vectors, store immediate value of Y
390 protected double Tnow; // Immediate value of T
391
392 // Static constants and storage used by rkck
393 static final double a2=0.2, a3=0.3, a4=0.6, a5=1.0, a6=0.875,
394 b21=0.2, b31=3.0/40.0, b32=9.0/40.0, b41=0.3, b42 = -0.9,
395 b43=1.2, b51 = -11.0/54.0, b52=2.5, b53 = -70.0/27.0,
396 b54=35.0/27.0, b61=1631.0/55296.0, b62=175.0/512.0,
397 b63=575.0/13824.0, b64=44275.0/110592.0, b65=253.0/4096.0,
398 c1=37.0/378.0, c3=250.0/621.0, c4=125.0/594.0, c6=512.0/1771.0,
399 dc1=c1-2825.0/27648.0, dc3=c3-18575.0/48384.0,
400 dc4=c4-13525.0/55296.0, dc5 = -277.00/14336.0, dc6=c6-0.25;
401 private double[] ak2, ak3, ak4, ak5, ak6;
402
403 // Static constants used by rkqs
404 static final double SAFETY=0.9, PGROW=-0.2, PSHRNK=-0.25, ERRCON=1.89e-4;
405
406 // Storage used by rkqs and RungeKutta
407 protected double hdid, hnext;
408
409 // Storage used by rkqs and rkck
410 protected double[] Ytemp, Yerr;
411
412 // Storage for RungeKutta
413 protected int MAXSTP=10000;
414 protected double TINY=1.0e-30;
415 protected int nok=0, nbad=0;
416 protected double[] y, dydt, yscal;
417 protected double dtsav = 0.1;
418 protected double hmin = 1.0e-16;
419 protected double eps = 1e-4;
420 protected boolean RKfail = false;
421 }
422