Debian Codegraph @

src/dr/math/MathUtils.java

raw symbols SCIP
1 /*
2 * MathUtils.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.math;
27
28 import java.text.NumberFormat;
29 import java.text.ParseException;
30
31 import dr.util.NumberFormatter;
32
33 /**
34 * Handy utility functions which have some Mathematical relavance.
35 *
36 * @author Matthew Goode
37 * @author Alexei Drummond
38 * @author Gerton Lunter
39 * @version $Id: MathUtils.java,v 1.13 2006/08/31 14:57:24 rambaut Exp $
40 */
41 public class MathUtils {
42
43 private MathUtils() {
44 }
45
46 /**
47 * A random number generator that is initialized with the clock when this
48 * class is loaded into the JVM. Use this for all random numbers.
49 * Note: This method or getting random numbers in not thread-safe. Since
50 * MersenneTwisterFast is currently (as of 9/01) not synchronized using
51 * this function may cause concurrency issues. Use the static get methods of the
52 * MersenneTwisterFast class for access to a single instance of the class, that
53 * has synchronization.
54 */
55 private static final MersenneTwisterFast random = MersenneTwisterFast.DEFAULT_INSTANCE;
56
57 // Chooses one category if a cumulative probability distribution is given
58 public static int randomChoice(double[] cf) {
59
60 double U = MathUtils.nextDouble();
61
62 int s;
63 if (U <= cf[0]) {
64 s = 0;
65 } else {
66 for (s = 1; s < cf.length; s++) {
67 if (U <= cf[s] && U > cf[s - 1]) {
68 break;
69 }
70 }
71 }
72
73 return s;
74 }
75
76
77 /**
78 * @param pdf array of unnormalized probabilities
79 * @return a sample according to an unnormalized probability distribution
80 */
81 public static int randomChoicePDF(double[] pdf) {
82
83 double U = MathUtils.nextDouble() * getTotal(pdf);
84 for (int i = 0; i < pdf.length; i++) {
85
86 U -= pdf[i];
87 if (U < 0.0) {
88 return i;
89 }
90
91 }
92 for (int i = 0; i < pdf.length; i++) {
93 System.out.println(i + "\t" + pdf[i]);
94 }
95 throw new Error("randomChoicePDF falls through -- negative, infinite or NaN components in input " +
96 "distribution, or all zeroes?");
97 }
98
99 /**
100 * @param logpdf array of unnormalised log probabilities
101 * @return a sample according to an unnormalised probability distribution
102 * <p/>
103 * Use this if probabilities are rounding to zero when converted to real space
104 */
105 public static int randomChoiceLogPDF(double[] logpdf) {
106
107 double scalingFactor = Double.NEGATIVE_INFINITY;
108
109 for (double aLogpdf : logpdf) {
110 if (aLogpdf > scalingFactor) {
111 scalingFactor = aLogpdf;
112 }
113 }
114
115 if (scalingFactor == Double.NEGATIVE_INFINITY) {
116 throw new Error("randomChoiceLogPDF falls through -- all -INF components in input distribution");
117 }
118
119 for (int j = 0; j < logpdf.length; j++) {
120 logpdf[j] = logpdf[j] - scalingFactor;
121 }
122
123 double[] pdf = new double[logpdf.length];
124
125 for (int j = 0; j < logpdf.length; j++) {
126 pdf[j] = Math.exp(logpdf[j]);
127 }
128
129 return randomChoicePDF(pdf);
130
131 }
132
133 /**
134 * @param array to normalize
135 * @return a new double array where all the values sum to 1.
136 * Relative ratios are preserved.
137 */
138 public static double[] getNormalized(double[] array) {
139 double[] newArray = new double[array.length];
140 double total = getTotal(array);
141 for (int i = 0; i < array.length; i++) {
142 newArray[i] = array[i] / total;
143 }
144 return newArray;
145 }
146
147
148 /**
149 * @param array entries to be summed
150 * @param start start position
151 * @param end the index of the element after the last one to be included
152 * @return the total of a the values in a range of an array
153 */
154 public static double getTotal(double[] array, int start, int end) {
155 double total = 0.0;
156 for (int i = start; i < end; i++) {
157 total += array[i];
158 }
159 return total;
160 }
161
162 /**
163 * @param array to sum over
164 * @return the total of the values in an array
165 */
166 public static double getTotal(double[] array) {
167 return getTotal(array, 0, array.length);
168
169 }
170
171 // ===================== (Synchronized) Static access methods to the private random instance ===========
172
173 /**
174 * Access a default instance of this class, access is synchronized
175 */
176 public static long getSeed() {
177 synchronized (random) {
178 return random.getSeed();
179 }
180 }
181
182 /**
183 * Access a default instance of this class, access is synchronized
184 */
185 public static void setSeed(long seed) {
186 synchronized (random) {
187 random.setSeed(seed);
188 }
189 }
190
191 /**
192 * Access a default instance of this class, access is synchronized
193 */
194 public static byte nextByte() {
195 synchronized (random) {
196 return random.nextByte();
197 }
198 }
199
200 /**
201 * Access a default instance of this class, access is synchronized
202 */
203 public static boolean nextBoolean() {
204 synchronized (random) {
205 return random.nextBoolean();
206 }
207 }
208
209 /**
210 * Access a default instance of this class, access is synchronized
211 */
212 public static void nextBytes(byte[] bs) {
213 synchronized (random) {
214 random.nextBytes(bs);
215 }
216 }
217
218 /**
219 * Access a default instance of this class, access is synchronized
220 */
221 public static char nextChar() {
222 synchronized (random) {
223 return random.nextChar();
224 }
225 }
226
227 /**
228 * Access a default instance of this class, access is synchronized
229 */
230 public static double nextGaussian() {
231 synchronized (random) {
232 return random.nextGaussian();
233 }
234 }
235
236 //Mean = alpha / lambda
237 //Variance = alpha / (lambda*lambda)
238
239 public static double nextGamma(double alpha, double lambda) {
240 synchronized (random) {
241 return random.nextGamma(alpha, lambda);
242 }
243 }
244
245 //Mean = alpha/(alpha+beta)
246 //Variance = (alpha*beta)/(alpha+beta)^2*(alpha+beta+1)
247
248 public static double nextBeta(double alpha, double beta) {
249 double x = nextGamma(alpha, 1);
250 double y = nextGamma(beta, 1);
251 return x / (x + y);
252 }
253
254
255 /**
256 * Access a default instance of this class, access is synchronized
257 *
258 * @return a pseudo random double precision floating point number in [01)
259 */
260 public static double nextDouble() {
261 synchronized (random) {
262 return random.nextDouble();
263 }
264 }
265
266 /**
267 * @return log of random variable in [0,1]
268 */
269 public static double randomLogDouble() {
270 return Math.log(nextDouble());
271 }
272
273 /**
274 * Access a default instance of this class, access is synchronized
275 */
276 public static double nextExponential(double lambda) {
277 synchronized (random) {
278 return -1.0 * Math.log(1 - random.nextDouble()) / lambda;
279 }
280 }
281
282 /**
283 * Access a default instance of this class, access is synchronized
284 */
285 public static double nextInverseGaussian(double mu, double lambda) {
286 synchronized (random) {
287 /* CODE TAKEN FROM WIKIPEDIA. TESTING DONE WITH RESULTS GENERATED IN R AND LOOK COMPARABLE */
288 double v = random.nextGaussian(); // sample from a normal distribution with a mean of 0 and 1 standard deviation
289 double y = v * v;
290 double x = mu + (mu * mu * y) / (2 * lambda) - (mu / (2 * lambda)) * Math.sqrt(4 * mu * lambda * y + mu * mu * y * y);
291 double test = MathUtils.nextDouble(); // sample from a uniform distribution between 0 and 1
292 if (test <= (mu) / (mu + x)) {
293 return x;
294 } else {
295 return (mu * mu) / x;
296 }
297 }
298 }
299
300
301 /**
302 * Access a default instance of this class, access is synchronized
303 */
304 public static float nextFloat() {
305 synchronized (random) {
306 return random.nextFloat();
307 }
308 }
309
310 /**
311 * Access a default instance of this class, access is synchronized
312 */
313 public static long nextLong() {
314 synchronized (random) {
315 return random.nextLong();
316 }
317 }
318
319 /**
320 * Access a default instance of this class, access is synchronized
321 */
322 public static short nextShort() {
323 synchronized (random) {
324 return random.nextShort();
325 }
326 }
327
328 /**
329 * Access a default instance of this class, access is synchronized
330 */
331 public static int nextInt() {
332 synchronized (random) {
333 return random.nextInt();
334 }
335 }
336
337 /**
338 * Access a default instance of this class, access is synchronized
339 */
340 public static int nextInt(int n) {
341 synchronized (random) {
342 return random.nextInt(n);
343 }
344 }
345
346 /**
347 * @param low
348 * @param high
349 * @return uniform between low and high
350 */
351 public static double uniform(double low, double high) {
352 return low + nextDouble() * (high - low);
353 }
354
355 /**
356 * Shuffles an array.
357 */
358 public static void shuffle(int[] array) {
359 synchronized (random) {
360 random.shuffle(array);
361 }
362 }
363
364 /**
365 * Shuffles an array. Shuffles numberOfShuffles times
366 */
367 public static void shuffle(int[] array, int numberOfShuffles) {
368 synchronized (random) {
369 random.shuffle(array, numberOfShuffles);
370 }
371 }
372
373 /**
374 * Returns an array of shuffled indices of length l.
375 *
376 * @param l length of the array required.
377 */
378 public static int[] shuffled(int l) {
379 synchronized (random) {
380 return random.shuffled(l);
381 }
382 }
383
384
385 public static int[] sampleIndicesWithReplacement(int length) {
386 synchronized (random) {
387 int[] result = new int[length];
388 for (int i = 0; i < length; i++)
389 result[i] = random.nextInt(length);
390 return result;
391 }
392 }
393
394 /**
395 * Permutes an array.
396 */
397 public static void permute(int[] array) {
398 synchronized (random) {
399 random.permute(array);
400 }
401 }
402
403 /**
404 * Returns a uniform random permutation of 0,...,l-1
405 *
406 * @param l length of the array required.
407 */
408 public static int[] permuted(int l) {
409 synchronized (random) {
410 return random.permuted(l);
411 }
412 }
413
414
415 public static double logHyperSphereVolume(int dimension, double radius) {
416 return dimension * (0.5723649429247001 + Math.log(radius)) +
417 -GammaFunction.lnGamma(dimension / 2.0 + 1.0);
418 }
419
420 /**
421 * Returns sqrt(a^2 + b^2) without under/overflow.
422 */
423 public static double hypot(double a, double b) {
424 double r;
425 if (Math.abs(a) > Math.abs(b)) {
426 r = b / a;
427 r = Math.abs(a) * Math.sqrt(1 + r * r);
428 } else if (b != 0) {
429 r = a / b;
430 r = Math.abs(b) * Math.sqrt(1 + r * r);
431 } else {
432 r = 0.0;
433 }
434 return r;
435 }
436
437 /**
438 * return double *.????
439 *
440 * @param value
441 * @param sf
442 * @return
443 */
444 public static double round(double value, int sf) {
445 NumberFormatter formatter = new NumberFormatter(sf);
446 try {
447 return NumberFormat.getInstance().parse(formatter.format(value)).doubleValue();
448 } catch (ParseException e) {
449 return value;
450 }
451 }
452
453 public static int[] getRandomState() {
454 synchronized (random) {
455 return random.getRandomState();
456 }
457 }
458
459 public static void setRandomState(int[] rngState) {
460 synchronized (random) {
461 random.setRandomState(rngState);
462 }
463 }
464 }