| 1 | /* |
| 2 | * DemographicFunction.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.evolution.coalescent; |
| 27 | |
| 28 | import dr.evolution.util.Units; |
| 29 | import dr.math.Binomial; |
| 30 | import dr.math.MathUtils; |
| 31 | import org.apache.commons.math.FunctionEvaluationException; |
| 32 | import org.apache.commons.math.MaxIterationsExceededException; |
| 33 | import org.apache.commons.math.analysis.UnivariateRealFunction; |
| 34 | import org.apache.commons.math.analysis.integration.RombergIntegrator; |
| 35 | |
| 36 | /** |
| 37 | * This interface provides methods that describe a demographic function. |
| 38 | * |
| 39 | * Parts of this class were derived from C++ code provided by Oliver Pybus. |
| 40 | * |
| 41 | * @version $Id: DemographicFunction.java,v 1.12 2005/05/24 20:25:55 rambaut Exp $ |
| 42 | * |
| 43 | * @author Andrew Rambaut |
| 44 | * @author Alexei Drummond |
| 45 | * @author Korbinian Strimmer |
| 46 | */ |
| 47 | public interface DemographicFunction extends UnivariateRealFunction, Units { |
| 48 | |
| 49 | /** |
| 50 | * @param t time |
| 51 | * @return value of the demographic function N(t) at time t |
| 52 | */ |
| 53 | double getDemographic(double t); |
| 54 | |
| 55 | double getLogDemographic(double t); |
| 56 | |
| 57 | /** |
| 58 | * @return value of demographic intensity function at time t (= integral 1/N(x) dx from 0 to t). |
| 59 | * @param t time |
| 60 | */ |
| 61 | double getIntensity(double t); |
| 62 | |
| 63 | /** |
| 64 | * @return value of inverse demographic intensity function |
| 65 | * (returns time, needed for simulation of coalescent intervals). |
| 66 | */ |
| 67 | double getInverseIntensity(double x); |
| 68 | |
| 69 | /** |
| 70 | * Calculates the integral 1/N(x) dx between start and finish. |
| 71 | * @param start point |
| 72 | * @param finish point |
| 73 | * @return integral value |
| 74 | */ |
| 75 | double getIntegral(double start, double finish); |
| 76 | |
| 77 | /** |
| 78 | * @return the number of arguments for this function. |
| 79 | */ |
| 80 | int getNumArguments(); |
| 81 | |
| 82 | /** |
| 83 | * @return the name of the n'th argument of this function. |
| 84 | */ |
| 85 | String getArgumentName(int n); |
| 86 | |
| 87 | /** |
| 88 | * @return the value of the n'th argument of this function. |
| 89 | */ |
| 90 | double getArgument(int n); |
| 91 | |
| 92 | /** |
| 93 | * Sets the value of the nth argument of this function. |
| 94 | */ |
| 95 | void setArgument(int n, double value); |
| 96 | |
| 97 | /** |
| 98 | * @return the lower bound of the nth argument of this function. |
| 99 | */ |
| 100 | double getLowerBound(int n); |
| 101 | |
| 102 | /** |
| 103 | * Returns the upper bound of the nth argument of this function. |
| 104 | */ |
| 105 | double getUpperBound(int n); |
| 106 | |
| 107 | /** |
| 108 | * Returns a copy of this function. |
| 109 | */ |
| 110 | // DemographicFunction getCopy(); |
| 111 | |
| 112 | /** |
| 113 | * A threshold for underflow on calculation of likelihood of internode intervals. |
| 114 | * Most demo functions could probably return 0.0 but (e.g.,) the Extended Skyline |
| 115 | * needs a non zero value to prevent a numerical problem. |
| 116 | * @return |
| 117 | */ |
| 118 | double getThreshold(); |
| 119 | |
| 120 | public abstract class Abstract implements DemographicFunction |
| 121 | { |
| 122 | // private static final double LARGE_POSITIVE_NUMBER = 1.0e50; |
| 123 | // private static final double LARGE_NEGATIVE_NUMBER = -1.0e50; |
| 124 | // private static final double INTEGRATION_PRECISION = 1.0e-5; |
| 125 | // private static final double INTEGRATION_MAX_ITERATIONS = 50; |
| 126 | |
| 127 | RombergIntegrator numericalIntegrator = null; |
| 128 | |
| 129 | /** |
| 130 | * Construct demographic model with default settings |
| 131 | */ |
| 132 | public Abstract(Type units) { |
| 133 | setUnits(units); |
| 134 | } |
| 135 | |
| 136 | // general functions |
| 137 | |
| 138 | /** |
| 139 | * Default implementation |
| 140 | * @param t |
| 141 | * @return log(demographic at t) |
| 142 | */ |
| 143 | public double getLogDemographic(double t) { |
| 144 | return Math.log(getDemographic(t)); |
| 145 | } |
| 146 | |
| 147 | public double getThreshold() { |
| 148 | return 0; |
| 149 | } |
| 150 | |
| 151 | /** |
| 152 | * Calculates the integral 1/N(x) dx between start and finish. |
| 153 | */ |
| 154 | public double getIntegral(double start, double finish) |
| 155 | { |
| 156 | return getIntensity(finish) - getIntensity(start); |
| 157 | } |
| 158 | |
| 159 | /** |
| 160 | * Returns the integral of 1/N(x) between start and finish, calling either the getAnalyticalIntegral or |
| 161 | * getNumericalIntegral function as appropriate. |
| 162 | */ |
| 163 | public double getNumericalIntegral(double start, double finish) { |
| 164 | // AER 19th March 2008: I switched this to use the RombergIntegrator from |
| 165 | // commons-math v1.2. |
| 166 | |
| 167 | if (start > finish) { |
| 168 | throw new RuntimeException("NumericalIntegration start > finish"); |
| 169 | } |
| 170 | |
| 171 | if (start == finish) { |
| 172 | return 0.0; |
| 173 | } |
| 174 | |
| 175 | if (numericalIntegrator == null) { |
| 176 | numericalIntegrator = new RombergIntegrator(this); |
| 177 | } |
| 178 | |
| 179 | try { |
| 180 | return numericalIntegrator.integrate(start, finish); |
| 181 | } catch (MaxIterationsExceededException e) { |
| 182 | throw new RuntimeException(e); |
| 183 | } catch (FunctionEvaluationException e) { |
| 184 | throw new RuntimeException(e); |
| 185 | } |
| 186 | |
| 187 | // double lastST = LARGE_NEGATIVE_NUMBER; |
| 188 | // double lastS = LARGE_NEGATIVE_NUMBER; |
| 189 | // |
| 190 | // assert(finish > start); |
| 191 | // |
| 192 | // for (int j = 1; j <= INTEGRATION_MAX_ITERATIONS; j++) { |
| 193 | // // iterate doTrapezoid() until answer obtained |
| 194 | // |
| 195 | // double st = doTrapezoid(j, start, finish, lastST); |
| 196 | // double s = (4.0 * st - lastST) / 3.0; |
| 197 | // |
| 198 | // // If answer is within desired accuracy then return |
| 199 | // if (Math.abs(s - lastS) < INTEGRATION_PRECISION * Math.abs(lastS)) { |
| 200 | // return s; |
| 201 | // } |
| 202 | // lastS = s; |
| 203 | // lastST = st; |
| 204 | // } |
| 205 | // |
| 206 | // throw new RuntimeException("Too many iterations in getNumericalIntegral"); |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Performs the trapezoid rule. |
| 211 | */ |
| 212 | // private double doTrapezoid(int n, double low, double high, double lastS) { |
| 213 | // |
| 214 | // double s; |
| 215 | // |
| 216 | // if (n == 1) { |
| 217 | // // On the first iteration s is reset |
| 218 | // double demoLow = getDemographic(low); // Value of N(x) obtained here |
| 219 | // assert(demoLow > 0.0); |
| 220 | // |
| 221 | // double demoHigh = getDemographic(high); |
| 222 | // assert(demoHigh > 0.0); |
| 223 | // |
| 224 | // s = 0.5 * (high - low) * ( (1.0 / demoLow) + (1.0 / demoHigh) ); |
| 225 | // } else { |
| 226 | // int it=1; |
| 227 | // for (int j = 1; j < n - 1; j++) { |
| 228 | // it *= 2; |
| 229 | // } |
| 230 | // |
| 231 | // double tnm = it; // number of points |
| 232 | // double del = (high - low) / tnm; // width of spacing between points |
| 233 | // |
| 234 | // double x = low + 0.5 * del; |
| 235 | // |
| 236 | // double sum = 0.0; |
| 237 | // for (int j = 1; j <= it; j++) { |
| 238 | // double demoX = getDemographic(x); // Value of N(x) obtained here |
| 239 | // assert(demoX > 0.0); |
| 240 | // |
| 241 | // sum += (1.0 / demoX); |
| 242 | // x += del; |
| 243 | // } |
| 244 | // s = 0.5 * (lastS + (high - low) * sum / tnm); // New s uses previous s value |
| 245 | // } |
| 246 | // |
| 247 | // return s; |
| 248 | // } |
| 249 | |
| 250 | // ************************************************************** |
| 251 | // UnivariateRealFunction IMPLEMENTATION |
| 252 | // ************************************************************** |
| 253 | |
| 254 | /** |
| 255 | * Return the intensity at a given time for numerical integration |
| 256 | * @param x the time |
| 257 | * @return the intensity |
| 258 | */ |
| 259 | public double value(double x) { |
| 260 | return 1.0 / getDemographic(x); |
| 261 | } |
| 262 | |
| 263 | // ************************************************************** |
| 264 | // Units IMPLEMENTATION |
| 265 | // ************************************************************** |
| 266 | |
| 267 | /** |
| 268 | * Units in which population size is measured. |
| 269 | */ |
| 270 | private Type units; |
| 271 | |
| 272 | /** |
| 273 | * sets units of measurement. |
| 274 | * |
| 275 | * @param u units |
| 276 | */ |
| 277 | public void setUnits(Type u) |
| 278 | { |
| 279 | units = u; |
| 280 | } |
| 281 | |
| 282 | /** |
| 283 | * returns units of measurement. |
| 284 | */ |
| 285 | public Type getUnits() |
| 286 | { |
| 287 | return units; |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | public static class Utils |
| 292 | { |
| 293 | private static double getInterval(double U, DemographicFunction demographicFunction, |
| 294 | int lineageCount, double timeOfLastCoalescent) { |
| 295 | final double intensity = demographicFunction.getIntensity(timeOfLastCoalescent); |
| 296 | final double tmp = -Math.log(U)/Binomial.choose2(lineageCount) + intensity; |
| 297 | |
| 298 | return demographicFunction.getInverseIntensity(tmp) - timeOfLastCoalescent; |
| 299 | } |
| 300 | |
| 301 | private static double getInterval(double U, DemographicFunction demographicFunction, int lineageCount, |
| 302 | double timeOfLastCoalescent, double earliestTimeOfFinalCoalescent){ |
| 303 | if(timeOfLastCoalescent>earliestTimeOfFinalCoalescent){ |
| 304 | throw new IllegalArgumentException("Given maximum height is smaller than given final coalescent time"); |
| 305 | } |
| 306 | final double fullIntegral = demographicFunction.getIntegral(timeOfLastCoalescent, |
| 307 | earliestTimeOfFinalCoalescent); |
| 308 | final double normalisation = 1-Math.exp(-Binomial.choose2(lineageCount)*fullIntegral); |
| 309 | final double intensity = demographicFunction.getIntensity(timeOfLastCoalescent); |
| 310 | |
| 311 | double tmp = -Math.log(1-U*normalisation)/Binomial.choose2(lineageCount) + intensity; |
| 312 | |
| 313 | return demographicFunction.getInverseIntensity(tmp) - timeOfLastCoalescent; |
| 314 | |
| 315 | } |
| 316 | |
| 317 | /** |
| 318 | * @return a random interval size selected from the Kingman prior of the demographic model. |
| 319 | */ |
| 320 | public static double getSimulatedInterval(DemographicFunction demographicFunction, |
| 321 | int lineageCount, double timeOfLastCoalescent) |
| 322 | { |
| 323 | final double U = MathUtils.nextDouble(); // create unit uniform random variate |
| 324 | return getInterval(U, demographicFunction, lineageCount, timeOfLastCoalescent); |
| 325 | } |
| 326 | |
| 327 | public static double getSimulatedInterval(DemographicFunction demographicFunction, int lineageCount, |
| 328 | double timeOfLastCoalescent, double earliestTimeOfFirstCoalescent){ |
| 329 | final double U = MathUtils.nextDouble(); |
| 330 | return getInterval(U, demographicFunction, lineageCount, timeOfLastCoalescent, |
| 331 | earliestTimeOfFirstCoalescent); |
| 332 | } |
| 333 | |
| 334 | public static double getMedianInterval(DemographicFunction demographicFunction, |
| 335 | int lineageCount, double timeOfLastCoalescent) |
| 336 | { |
| 337 | return getInterval(0.5, demographicFunction, lineageCount, timeOfLastCoalescent); |
| 338 | } |
| 339 | |
| 340 | /** |
| 341 | * This function tests the consistency of the |
| 342 | * getIntensity and getInverseIntensity methods |
| 343 | * of this demographic model. If the model is |
| 344 | * inconsistent then a RuntimeException will be thrown. |
| 345 | * @param demographicFunction the demographic model to test. |
| 346 | * @param steps the number of steps between 0.0 and maxTime to test. |
| 347 | * @param maxTime the maximum time to test. |
| 348 | */ |
| 349 | public static void testConsistency(DemographicFunction demographicFunction, int steps, double maxTime) { |
| 350 | |
| 351 | double delta = maxTime / (double)steps; |
| 352 | |
| 353 | for (int i = 0; i <= steps; i++) { |
| 354 | double time = (double)i * delta; |
| 355 | double intensity = demographicFunction.getIntensity(time); |
| 356 | double newTime = demographicFunction.getInverseIntensity(intensity); |
| 357 | |
| 358 | if (Math.abs(time - newTime) > 1e-12) { |
| 359 | throw new RuntimeException( |
| 360 | "Demographic model not consistent! error size = " + |
| 361 | Math.abs(time-newTime)); |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | } |