| 1 | /* |
| 2 | * TwoColourSampler.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.colouring; |
| 27 | |
| 28 | import dr.evolution.tree.ColourChange; |
| 29 | import dr.evolution.tree.Tree; |
| 30 | import dr.math.MathUtils; |
| 31 | |
| 32 | import java.util.ArrayList; |
| 33 | import java.util.Collections; |
| 34 | import java.util.List; |
| 35 | |
| 36 | // This is probably redundant but is left in case it is needed as a comparison. |
| 37 | |
| 38 | |
| 39 | /** |
| 40 | * @author Alexei Drummond |
| 41 | * @author Gerton Lunter |
| 42 | * |
| 43 | * @version $Id: TwoColourSampler.java,v 1.2 2006/07/03 15:15:39 gerton Exp $ |
| 44 | */ |
| 45 | //public class TwoColourSampler implements ColourSampler { |
| 46 | abstract class TwoColourSampler implements ColourSampler { |
| 47 | |
| 48 | // m[0] is the rate of migration from population 1 to population 0 |
| 49 | // m[1] is the rate of migration from population 0 to population 1 |
| 50 | |
| 51 | /** |
| 52 | */ |
| 53 | public TwoColourSampler() { |
| 54 | } |
| 55 | |
| 56 | |
| 57 | /** |
| 58 | * @return the number of colours of this sampling model (always 2). |
| 59 | */ |
| 60 | public int getColourCount() { |
| 61 | return 2; |
| 62 | } |
| 63 | |
| 64 | public TreeColouring sampleTreeColouring(Tree tree, ColourChangeMatrix colourChangeMatrix, double[] N) { |
| 65 | return null; |
| 66 | } |
| 67 | |
| 68 | |
| 69 | /** |
| 70 | * Pr(T>v|x,y,t) |
| 71 | * The probability of surviving until time v without migrating, |
| 72 | * conditional on starting in state x at time 0 and being in state y at time t. |
| 73 | * |
| 74 | * @param x state at time 0 |
| 75 | * @param y state at time t |
| 76 | * @param v survival time |
| 77 | * @return probability of surviving until time v without migrating, |
| 78 | * conditional on starting in state x at time 0 and being in state y at time t. |
| 79 | */ |
| 80 | private final double conditionalSurvivalProbability(int x, double v, int y, double t, double[] m) { |
| 81 | |
| 82 | // the total rate of migration |
| 83 | double mt = m[0]+m[1]; |
| 84 | |
| 85 | if (v < 0 || v > t) { |
| 86 | throw new IllegalArgumentException("v must be non-negative and not exceed t\n v="+v+" t="+t); |
| 87 | } else { |
| 88 | |
| 89 | double a,b,c,d; |
| 90 | |
| 91 | if (x==y) { |
| 92 | |
| 93 | a = m[0]*m[1]; |
| 94 | b = -a; |
| 95 | c = m[1-x]; |
| 96 | d = m[x]; |
| 97 | |
| 98 | } else { |
| 99 | |
| 100 | a = m[1-y]; |
| 101 | b = m[1-x]; |
| 102 | c = 1; |
| 103 | d = -1; |
| 104 | |
| 105 | } |
| 106 | |
| 107 | double exponent = (b*c-a*d)/(c*d*-mt); |
| 108 | double C = Math.pow(c*Math.exp(-mt*t)+d, -exponent); |
| 109 | return C * Math.exp(b*v/d) * Math.pow( d + c * Math.exp(-mt*(t-v)), exponent); |
| 110 | |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | |
| 115 | |
| 116 | /** |
| 117 | * The inverse of the conditionalSurvivalProbability function. Returns the survival time until the next |
| 118 | * migration conditional on starting at state x at time 0, being in state y at time t and having a |
| 119 | * survival probability of w. |
| 120 | * @param x state at time 0 |
| 121 | * @param y state at time t |
| 122 | * @param t total elapsed time between x and y |
| 123 | * @param m rate parameters |
| 124 | * @return the survival time to the next migration |
| 125 | * conditional on starting at state x at time 0, being in state y at time t and having a |
| 126 | * survival probability of w. |
| 127 | */ |
| 128 | private double randomConditionalSurvivalTime(int x, int y, double t, double[] m) throws NoEventException { |
| 129 | |
| 130 | double U = MathUtils.nextDouble(); |
| 131 | double vLeft = 0.0; |
| 132 | double vRight = t; |
| 133 | double fLeft = 1.0-U; |
| 134 | double fRight = conditionalSurvivalProbability(x,t,y,t, m) - U; |
| 135 | |
| 136 | if (fRight >= 0.0) { |
| 137 | if (x != y) { |
| 138 | // No event but colours at ends are not identical |
| 139 | throw new IllegalArgumentException("Problem in randomConditionalSurvivalTime for x="+x+", y="+y+" t="+t+" U="+U+"fRight="+fRight); |
| 140 | } |
| 141 | throw new NoEventException(); |
| 142 | } |
| 143 | |
| 144 | // We are solving the equation "conditionalSurvivalprobability(x,v,y,t,m) - U == 0" |
| 145 | // for v. The solution is bound by [vLeft,vRight], with corresponding function |
| 146 | // values fLeft and fRight. The algorithm is basically Newton-Raphson, using an approximate |
| 147 | // derivative. Two limits bracketing the solution are kept as well, and a fallback is |
| 148 | // used if the Newton iteration jumps out of the bracket. This gives a robust and efficient |
| 149 | // root finder. |
| 150 | |
| 151 | double vNew = vLeft; // the bracket position that has changed |
| 152 | double vOld = vRight; // the previous value of vNew |
| 153 | double fNew = fLeft; |
| 154 | double fOld = fRight; |
| 155 | |
| 156 | while (Math.abs(vNew-vOld)>1e-9) { |
| 157 | |
| 158 | // Calculate proposed new v, using the changed bracket value. |
| 159 | // This is expected to give the highest performance, but may run out of the bracket |
| 160 | double vProp = vNew - fNew/((fOld-fNew)/(vOld-vNew)); |
| 161 | |
| 162 | if ((vLeft >= vProp) || (vProp >= vRight)) { |
| 163 | // Outside of bracket, so use safe option |
| 164 | vProp = vLeft - fLeft/((fRight-fLeft)/(vRight-vLeft)); |
| 165 | } |
| 166 | |
| 167 | // New function value |
| 168 | double fProp = conditionalSurvivalProbability(x,vProp,y,t, m) - U; |
| 169 | |
| 170 | vOld = vNew; |
| 171 | fOld = fNew; |
| 172 | vNew = vProp; |
| 173 | fNew = fProp; |
| 174 | |
| 175 | // Update bracket |
| 176 | if (fProp < 0.0) { |
| 177 | vRight = vProp; |
| 178 | fRight = fProp; |
| 179 | } else { |
| 180 | vLeft = vProp; |
| 181 | fLeft = fProp; |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | return vNew; |
| 186 | |
| 187 | } |
| 188 | |
| 189 | /** |
| 190 | * Samples a migration event on a two-coloured branch, conditional on colours at both ends/ |
| 191 | * Migration process is forwards in (natural) time, so we are going down the tree. |
| 192 | * @param currentColour indeed |
| 193 | * @param currentHeight indeed |
| 194 | * @param childColour colour of the branch at the child node (below current) |
| 195 | * @param childHeight height of the child node (below current, i.e. lower height) |
| 196 | * @param m migration parameters |
| 197 | * @return ColourChange event, with the colour referring to the branchlet *below* this point |
| 198 | */ |
| 199 | public ColourChange randomConditionalMigrationEvent(int currentColour, double currentHeight, |
| 200 | int childColour, double childHeight, double[] m) |
| 201 | throws NoEventException { |
| 202 | |
| 203 | // Draw a valid time (or throw NoEventException) |
| 204 | if (currentHeight < childHeight) { |
| 205 | throw new IllegalArgumentException("currentHeight "+currentHeight+" is below childHeight="+childHeight); |
| 206 | } |
| 207 | double time = randomConditionalSurvivalTime(currentColour, childColour, currentHeight-childHeight, m); |
| 208 | |
| 209 | // Return the corresponding event |
| 210 | return new ColourChange( currentHeight-time, 1-currentColour ); |
| 211 | |
| 212 | } |
| 213 | |
| 214 | /** |
| 215 | * Samples migration events on a two-coloured branch, conditional on colours at both ends |
| 216 | * Migration process is forwards in (natural) time, so we are going down the tree. |
| 217 | * Returns a list of events, ordered forward in time (i.e. colour refers to branch *below* the event) |
| 218 | * * |
| 219 | * @param parentColour indeed |
| 220 | * @param parentHeight indeed |
| 221 | * @param childColour colour of the branch at the child node (below parent) |
| 222 | * @param childHeight height of the child node (below parent, i.e. lower height) |
| 223 | * @param m migration parameters |
| 224 | * @return List of ColourChange events, with the colour referring to the branch *below* each event |
| 225 | */ |
| 226 | public List<ColourChange> sampleConditionalMigrationEvents2(int parentColour, double parentHeight, |
| 227 | int childColour, double childHeight, double[] m) { |
| 228 | |
| 229 | List<ColourChange> colourChanges = new ArrayList<ColourChange>(); |
| 230 | |
| 231 | if (parentHeight < childHeight) { |
| 232 | throw new IllegalArgumentException("sampleConditionalMigrationEvents: parentHeight="+parentHeight+" childHeight="+childHeight+", not good."); |
| 233 | } |
| 234 | |
| 235 | // Sample migration events, going from the parent (current) to the child, forward in natural time |
| 236 | // until a NoEventException breaks the loop. Migration events are returned as ColourChange-s |
| 237 | try { |
| 238 | |
| 239 | int currentColour = parentColour; |
| 240 | double currentHeight = parentHeight; |
| 241 | |
| 242 | while (true) { |
| 243 | ColourChange nextEvent = |
| 244 | randomConditionalMigrationEvent(currentColour, currentHeight, childColour, childHeight, m); |
| 245 | |
| 246 | // We abuse the ColorChange interface, which is supposed to record events going up the tree, |
| 247 | // (in the coalescent direction), for the duration of this loop. So, getColourAbove should |
| 248 | // really read 'getColourBelow' |
| 249 | currentHeight = nextEvent.getTime(); |
| 250 | currentColour = nextEvent.getColourAbove(); // colour *below* current height |
| 251 | |
| 252 | // record event |
| 253 | colourChanges.add(nextEvent); |
| 254 | |
| 255 | } |
| 256 | } catch (NoEventException nee) { |
| 257 | // no more events |
| 258 | } |
| 259 | |
| 260 | // Reverse the list |
| 261 | reverseColourChangeList( colourChanges, parentColour); |
| 262 | |
| 263 | return colourChanges; |
| 264 | } |
| 265 | |
| 266 | |
| 267 | /** |
| 268 | * Samples migration events on a two-coloured branch, conditional on colours at both ends |
| 269 | * Migration process is forwards in (natural) time, so we are going down the tree. |
| 270 | * Returns a list of events, ordered forward in time (i.e. colour refers to branch *below* the event) |
| 271 | * This version implements a rejection algorithm that can be easily extended to more than 2 colours |
| 272 | * * |
| 273 | * @param parentColour indeed |
| 274 | * @param parentHeight indeed |
| 275 | * @param childColour colour of the branch at the child node (below parent) |
| 276 | * @param childHeight height of the child node (below parent, i.e. lower height) |
| 277 | * @param m migration parameters |
| 278 | * @return List of ColourChange events, with the colour referring to the branch *below* each event |
| 279 | */ |
| 280 | public List<ColourChange> sampleConditionalMigrationEvents(int parentColour, double parentHeight, |
| 281 | int childColour, double childHeight, double[] m) { |
| 282 | |
| 283 | List<ColourChange> colourChanges = new ArrayList<ColourChange>(); |
| 284 | int currentColour; |
| 285 | double currentHeight; |
| 286 | |
| 287 | // Reject until we get the child colour |
| 288 | do { |
| 289 | |
| 290 | colourChanges.clear(); |
| 291 | currentColour = parentColour; |
| 292 | currentHeight = parentHeight; |
| 293 | |
| 294 | // Sample events until we reach the child |
| 295 | do { |
| 296 | |
| 297 | // Sample a waiting time |
| 298 | double totalRate = m[ 1-currentColour ]; |
| 299 | double U = MathUtils.nextDouble(); |
| 300 | |
| 301 | // Neat trick (Rasmus Nielsen): |
| 302 | // If colours of parent and child differ, sample conditioning on at least 1 event |
| 303 | if ((parentColour != childColour) && (colourChanges.size() == 0)) { |
| 304 | |
| 305 | double minU = Math.exp( -totalRate * (parentHeight-childHeight) ); |
| 306 | U = minU + U*(1.0-minU); |
| 307 | |
| 308 | } |
| 309 | |
| 310 | // Calculate the waiting time, and update currentHeight |
| 311 | double time = -Math.log( U )/totalRate; |
| 312 | currentHeight -= time; |
| 313 | |
| 314 | if (currentHeight > childHeight) { |
| 315 | // Not yet reached the child. "Sample" an event |
| 316 | currentColour = 1 - currentColour; |
| 317 | // Add it to the list |
| 318 | colourChanges.add( new ColourChange( currentHeight, currentColour ) ); |
| 319 | } |
| 320 | |
| 321 | } while (currentHeight > childHeight); |
| 322 | |
| 323 | } while (currentColour != childColour); |
| 324 | |
| 325 | // Reverse the list |
| 326 | reverseColourChangeList( colourChanges, parentColour); |
| 327 | |
| 328 | return colourChanges; |
| 329 | |
| 330 | } |
| 331 | |
| 332 | |
| 333 | class NoEventException extends Exception { |
| 334 | |
| 335 | /** |
| 336 | * |
| 337 | */ |
| 338 | private static final long serialVersionUID = -6860022343065166240L; |
| 339 | |
| 340 | } |
| 341 | /** |
| 342 | * The probability density of being in state x in the time interval [0,t) and migrating to state y |
| 343 | * at time t. |
| 344 | * |
| 345 | * In case x==y, the function returns the probability (not: density) of surviving in state x during |
| 346 | * the interval [0,t]. |
| 347 | * |
| 348 | * @param x state at time 0 |
| 349 | * @param y state at time t |
| 350 | * @param t total elapsed time |
| 351 | * @return probability density of being in state x in the time interval [0,t) and migrating to state y |
| 352 | * at time t. |
| 353 | */ |
| 354 | public double migrationEventProposalDensity(int x, int y, double t, double[] m) { |
| 355 | |
| 356 | // Bugfix: Did not use correct interpretation of m[] array |
| 357 | |
| 358 | if (x==y) { |
| 359 | return Math.exp(-t*m[1-x]); |
| 360 | } else { |
| 361 | return Math.exp(-t*m[1-x])*m[1-x]; |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | /** |
| 366 | * @return the equilibrium distribution of this sampling model |
| 367 | */ |
| 368 | public final double[] equilibrium(double[] m) { |
| 369 | |
| 370 | double mt = m[0]+m[1]; |
| 371 | return new double[] {m[0]/mt, m[1]/mt}; |
| 372 | } |
| 373 | |
| 374 | |
| 375 | |
| 376 | /** |
| 377 | * Reverse the migration events in a list, to convert from the natural sampling ordering (parent-to-child) |
| 378 | * to the natural coalescent ordering. On input, getColourAbove returns the colour of the branch *below* |
| 379 | * an event. |
| 380 | */ |
| 381 | protected final void reverseColourChangeList( List<ColourChange> colourChanges, int parentColour ) { |
| 382 | |
| 383 | Collections.reverse( colourChanges ); |
| 384 | int colour; |
| 385 | for (int i=0; i < colourChanges.size(); i++) { |
| 386 | if (i<colourChanges.size()-1) { |
| 387 | colour = (colourChanges.get( i+1 )).getColourAbove(); |
| 388 | } else { |
| 389 | colour = parentColour; |
| 390 | } |
| 391 | (colourChanges.get( i )).setColourAbove( colour ); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | /* |
| 396 | public static void main(String[] args) { |
| 397 | |
| 398 | TwoColourSampler model = new TwoColourSampler(); |
| 399 | |
| 400 | double[] m = new double[] {0.2, 0.5}; |
| 401 | int iterations = 500000; |
| 402 | |
| 403 | long time = System.currentTimeMillis(); |
| 404 | for (int j = 0; j < 4; j++) { |
| 405 | double[] times = new double[iterations]; |
| 406 | for (int i = 0; i < iterations; i++) { |
| 407 | List events = model.sampleConditionalMigrationEvents2(j/2,1.0,j%2,0.0,m); |
| 408 | if (events.size()==0) { |
| 409 | times[i] = 1.0; |
| 410 | } else { |
| 411 | times[i] = 1.0-((ColourChange)events.get(0)).getTime(); |
| 412 | } |
| 413 | } |
| 414 | System.out.println("Analytic:"+(j/2) + "\t" + (j%2) + "\t" + DiscreteStatistics.mean(times) + "\t" + (DiscreteStatistics.stdev(times)/Math.sqrt(100000.0))); |
| 415 | } |
| 416 | System.out.println("time taken:" + (System.currentTimeMillis()-time) + "ms"); |
| 417 | |
| 418 | time = System.currentTimeMillis(); |
| 419 | for (int j = 0; j < 4; j++) { |
| 420 | double[] times = new double[iterations]; |
| 421 | for (int i = 0; i < iterations; i++) { |
| 422 | List events = model.sampleConditionalMigrationEvents(j/2,1.0,j%2,0.0,m); |
| 423 | if (events.size()==0) { |
| 424 | times[i] = 1.0; |
| 425 | } else { |
| 426 | times[i] = 1.0-((ColourChange)events.get(0)).getTime(); |
| 427 | } |
| 428 | } |
| 429 | System.out.println("Rejection sampling:"+(j/2) + "\t" + (j%2) + "\t" + DiscreteStatistics.mean(times) + "\t" + (DiscreteStatistics.stdev(times)/Math.sqrt(100000.0))); |
| 430 | } |
| 431 | System.out.println("time taken:" + (System.currentTimeMillis()-time) + "ms"); |
| 432 | } |
| 433 | |
| 434 | */ |
| 435 | |
| 436 | } |