Debian Codegraph @

hmmer/src/logsum.c

raw symbols SCIP
1 /* p7_FLogsum() function used in the Forward() algorithm.
2 *
3 * Contents:
4 * 1. Floating point log sum.
5 * 2. Benchmark driver.
6 * 3. Unit tests.
7 * 4. Test driver.
8 * 5. Example.
9 *
10 * Exegesis:
11 *
12 * Internally, HMMER3 profile scores are in nats: floating point
13 * log-odds probabilities, with the log odds taken relative to
14 * background residue frequencies, and the log to the base e.
15 *
16 * The Forward algorithm needs to calculate sums of probabilities.
17 * Given two log probabilities A and B, where s1 = \log
18 * \frac{a}{f}, and s2 = \log \frac{b}{g}, we need to
19 * calculate C = \log \frac{a + b}{h}.
20 *
21 * The Forward algorithm guarantees that the null model denominator
22 * terms f = g = h, because it is always concerned with summing terms
23 * that describe different parses of the same target sequence prefix,
24 * and the product of the background frequencies for the same sequence
25 * prefix is a constant.
26 *
27 * The naive solution is C = log(e^{A} + e^{B}), but this requires
28 * expensive calls to log() and exp().
29 *
30 * A better solution is C = A + log(1 + e^{-(A-B)}), for A >= B. For
31 * sufficiently small B << A, e^-{A-B} becomes less than the
32 * machine's FLT_EPSILON, and C ~= A. (This is at about (A-B) >
33 * -15.9, for the typical FLT_EPSILON of 1.2e-7.)
34 *
35 * With some loss of accuracy [1], we can precalculate log(1 +
36 * e^{-(A-B)}) for a discretized range of differences (A-B), and
37 * compute C = A + table_lookup(A-B). This is what HMMER's
38 * p7_FLogsum() function does.
39 *
40 * This only applies to the generic (serial) implementation.
41 * See footnote [2] for discussion of why we remain unable to
42 * implement an efficient log-space SIMD vector implementation of
43 * Forward.
44 */
45 #include <p7_config.h>
46 #include <math.h>
47 #include "hmmer.h"
48
49
50 /* p7_LOGSUM_SCALE defines the precision of the calculation; the
51 * default of 1000.0 means rounding differences to the nearest 0.001
52 * nat. p7_LOGSUM_TBL defines the size of the lookup table; the
53 * default of 16000 means entries are calculated for differences of 0
54 * to 16.000 nats (when p7_LOGSUM_SCALE is 1000.0). e^{-p7_LOGSUM_TBL /
55 * p7_LOGSUM_SCALE} should be on the order of the machine FLT_EPSILON,
56 * typically 1.2e-7.
57 */
58 #define p7_LOGSUM_SCALE 1000.f
59 #define p7_LOGSUM_TBL 16000
60
61 static float flogsum_lookup[p7_LOGSUM_TBL]; /* p7_LOGSUM_TBL=16000: (A-B) = 0..16 nats, steps of 0.001 */
62
63 /*****************************************************************
64 *# 1. floating point log sum
65 *****************************************************************/
66
67 /* Function: p7_FLogsumInit()
68 * Synopsis: Initialize the p7_Logsum() function.
69 *
70 * Purpose: Initialize the lookup table for <p7_FLogsum()>.
71 * This function must be called once before any
72 * call to <p7_FLogsum()>.
73 *
74 * The precision of the lookup table is determined
75 * by the compile-time <p7_LOGSUM_TBL> constant.
76 *
77 * Returns: <eslOK> on success.
78 */
79 int
80 p7_FLogsumInit(void)
81 {
82 static int firsttime = TRUE;
83 if (!firsttime) return eslOK;
84 firsttime = FALSE;
85
86 int i;
87 for (i = 0; i < p7_LOGSUM_TBL; i++)
88 flogsum_lookup[i] = log(1. + exp((double) -i / p7_LOGSUM_SCALE));
89 return eslOK;
90 }
91
92 /* Function: p7_FLogsum()
93 * Synopsis: Approximate $\log(e^a + e^b)$.
94 *
95 * Purpose: Returns a fast table-driven approximation to
96 * $\log(e^a + e^b)$.
97 *
98 * Either <a> or <b> (or both) may be $-\infty$,
99 * but neither may be $+\infty$ or <NaN>.
100 *
101 * Note: This function is a critical optimization target, because
102 * it's in the inner loop of generic Forward() algorithms.
103 */
104 float
105 p7_FLogsum(float a, float b)
106 {
107 const float max = ESL_MAX(a, b);
108 const float min = ESL_MIN(a, b);
109
110 //return (min == -eslINFINITY || (max-min) >= 15.7f) ? max : max + log(1.0 + exp(min-max)); /* SRE: While debugging SSE impl. Remember to remove! */
111 return (min == -eslINFINITY || (max-min) >= 15.7f) ? max : max + flogsum_lookup[(int)((max-min)*p7_LOGSUM_SCALE)];
112 }
113
114 /* Function: p7_FLogsumError()
115 * Synopsis: Compute absolute error in probability from Logsum.
116 *
117 * Purpose: Compute the absolute error in probability space
118 * resulting from <p7_FLogsum()>'s table lookup
119 * approximation: approximation result - exact result.
120 *
121 * This is of course computable analytically for
122 * any <a,b> given <p7_LOGSUM_TBL>; but the function
123 * is useful for some routines that want to determine
124 * if <p7_FLogsum()> has been compiled in its
125 * exact slow mode for debugging purposes. Testing
126 * <p7_FLogsumError(-0.4, -0.5) > 0.0001>
127 * for example, suffices to detect that the function
128 * is compiled in its fast approximation mode given
129 * the defaults.
130 */
131 float
132 p7_FLogsumError(float a, float b)
133 {
134 float approx = p7_FLogsum(a,b);
135 float exact = log(exp(a) + exp(b));
136 return (exp(approx) - exp(exact));
137 }
138
139
140 /*****************************************************************
141 * 2. Benchmark driver.
142 *****************************************************************/
143 #ifdef p7LOGSUM_BENCHMARK
144 /* gcc -o logsum_benchmark -g -O2 -I. -L. -I../easel -L../easel -Dp7LOGSUM_BENCHMARK logsum.c -leasel -lm
145 * ./logsum_benchmark
146 */
147
148 /* A table-driven FLogsum() is about 20x faster than a direct
149 * C = A + log(1+e^{-(A-B)}) implementation, "naive2()":
150 * time/call clocks/call
151 * naive1: 110 nsec 250 SRE:J8/71 10 Aug 2011
152 * naive2: 87 nsec 200 MacOS/X desktop, default build (gcc -O3), 2.26 GHz Xeon
153 * FLogsum(): 4 nsec 9
154 *
155 * Times in units of nanoseconds/iteration: cpu time * 10
156 * based on default 1e8 iterations (-N 100000000).
157 * Clocks based on 2.26GHz = 2.26 clocks/nsec
158 */
159 #include <p7_config.h>
160
161 #include <math.h>
162
163 #include "easel.h"
164 #include "esl_getopts.h"
165 #include "esl_random.h"
166 #include "esl_stopwatch.h"
167
168 #include "hmmer.h"
169
170 static ESL_OPTIONS options[] = {
171 /* name type default env range toggles reqs incomp help docgroup*/
172 { "-h", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
173 { "-n", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "naive time: A + log(1+exp(-(A-B)))", 0 },
174 { "-r", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "really naive time: log(exp(A)+exp(B))", 0 },
175 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
176 { "-v", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "be verbose: show individual results", 0 },
177 { "-N", eslARG_INT,"100000000",NULL,"n>0", NULL, NULL, NULL, "number of trials", 0 },
178 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
179 };
180 static char usage[] = "[-options]";
181 static char banner[] = "benchmark driver for logsum functions()";
182
183 static float
184 naive1(float s1, float s2)
185 {
186 return log(exp(s1) + exp(s2));
187 }
188
189 static float
190 naive2(float s1, float s2)
191 {
192 if (s1 > s2) return s1 + log(1 + exp(s2-s1));
193 else return s2 + log(1 + exp(s1-s2));
194 }
195
196 int
197 main(int argc, char **argv)
198 {
199 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 0, argc, argv, banner, usage);
200 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
201 ESL_STOPWATCH *w = esl_stopwatch_Create();
202 int N = esl_opt_GetInteger(go, "-N");
203 int i;
204 float *A, *B, *C;
205
206 p7_FLogsumInit();
207
208 /* Create the problem: sample N values A,B on interval -1000,1000: about the range of H3 scores */
209 A = malloc(sizeof(float) * N);
210 B = malloc(sizeof(float) * N);
211 C = malloc(sizeof(float) * N);
212 for (i = 0; i < N; i++)
213 {
214 A[i] = esl_random(r) * 2000. - 1000.;
215 B[i] = esl_random(r) * 2000. - 1000.;
216 }
217
218 /* Run */
219 esl_stopwatch_Start(w);
220
221 if (esl_opt_GetBoolean(go, "-n"))
222 {
223 for (i = 0; i < N; i++)
224 C[i] = naive2(A[i], B[i]);
225 }
226 else if (esl_opt_GetBoolean(go, "-r"))
227 {
228 for (i = 0; i < N; i++)
229 C[i] = naive1(A[i], B[i]);
230 }
231 else
232 {
233 for (i = 0; i < N; i++)
234 C[i] = p7_FLogsum(A[i], B[i]);
235 }
236
237 esl_stopwatch_Stop(w);
238 esl_stopwatch_Display(stdout, w, "# CPU time: ");
239
240 esl_stopwatch_Destroy(w);
241 esl_randomness_Destroy(r);
242 esl_getopts_Destroy(go);
243 return 0;
244 }
245 #endif /*p7LOGSUM_BENCHMARK*/
246 /*-------------------- end, benchmark ---------------------------*/
247
248
249 /*****************************************************************
250 * 3. Unit tests
251 *****************************************************************/
252 #ifdef p7LOGSUM_TESTDRIVE
253
254 #include "easel.h"
255 #include "esl_getopts.h"
256 #include "esl_random.h"
257
258 static void
259 utest_FLogsumError(ESL_GETOPTS *go, ESL_RANDOMNESS *r)
260 {
261 int N = esl_opt_GetInteger(go, "-N");
262 float maxval = esl_opt_GetReal(go, "-S");
263 int be_verbose = esl_opt_GetBoolean(go, "-v");
264 float maxerr = 0.0;
265 float avgerr = 0.0;
266 int i;
267 float a,b,result,exact,err;
268
269 for (i = 0; i < N; i++)
270 {
271 a = (esl_random(r) - 0.5) * maxval * 2.; /* uniform draws on -maxval..maxval */
272 b = (esl_random(r) - 0.5) * maxval * 2.;
273
274 exact = log(exp(a) + exp(b));
275 result = p7_FLogsum(a,b);
276 err = fabs(exact-result) / maxval;
277
278 avgerr += err;
279 maxerr = ESL_MAX(maxerr, err);
280
281 if (be_verbose)
282 printf("%8.4f %8.4f %8.4f %8.4f %8.4f\n", a, b, exact, result, err);
283 }
284 avgerr /= (float) N;
285
286 if (be_verbose) {
287 printf("average error = %f\n", avgerr);
288 printf("max error = %f\n", maxerr);
289 }
290
291 if (maxerr > 0.0001) esl_fatal("maximum error of %f is too high: logsum unit test fails", maxerr);
292 if (avgerr > 0.0001) esl_fatal("average error of %f is too high: logsum unit test fails", avgerr);
293 }
294
295 static void
296 utest_FLogsumSpecials(void)
297 {
298 char *msg = "logsum specials unit test failed";
299
300 if (p7_FLogsum(0.0, -eslINFINITY) != 0.0) esl_fatal(msg);
301 if (p7_FLogsum(-eslINFINITY, 0.0) != 0.0) esl_fatal(msg);
302 if (p7_FLogsum(-eslINFINITY, -eslINFINITY) != -eslINFINITY) esl_fatal(msg);
303 }
304 #endif /*p7LOGSUM_TESTDRIVE*/
305 /*------------------- end, unit tests ---------------------------*/
306
307 /*****************************************************************
308 * 4. Test driver.
309 *****************************************************************/
310 #ifdef p7LOGSUM_TESTDRIVE
311 /*
312 gcc -o logsum_utest -msse2 -g -Wall -I. -L. -I../easel -L../easel -Dp7LOGSUM_TESTDRIVE logsum.c -leasel -lm
313 ./logsum_utest
314 */
315 #include <p7_config.h>
316
317 #include <stdio.h>
318 #include <math.h>
319
320 #include "easel.h"
321 #include "esl_getopts.h"
322 #include "esl_random.h"
323
324 #include "hmmer.h"
325
326 static ESL_OPTIONS options[] = {
327 /* name type default env range togs reqs incomp help docgrp */
328 {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
329 {"-N", eslARG_INT, "1000", NULL, "n>0",NULL, NULL, NULL, "number of samples", 0},
330 {"-S", eslARG_REAL, "20.0", NULL, "x>0",NULL, NULL, NULL, "maximum operand value", 0},
331 {"-s", eslARG_INT, "42", NULL,"n>=0",NULL, NULL, NULL, "random number seed", 0},
332 {"-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show verbose output", 0},
333 { 0,0,0,0,0,0,0,0,0,0},
334 };
335 static char usage[] = "[-options]";
336 static char banner[] = "test driver for logsum.c";
337
338 int
339 main(int argc, char **argv)
340 {
341 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 0, argc, argv, banner, usage);
342 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
343
344 p7_FLogsumInit();
345
346 utest_FLogsumError(go, r);
347 utest_FLogsumSpecials();
348
349 esl_randomness_Destroy(r);
350 esl_getopts_Destroy(go);
351 return eslOK;
352 }
353 #endif /*p7LOGSUM_TESTDRIVE*/
354 /*------------------ end, test driver ---------------------------*/
355
356
357 /*****************************************************************
358 * 5. Example.
359 *****************************************************************/
360 #ifdef p7LOGSUM_EXAMPLE
361 /* gcc -o example -g -O2 -I. -L. -I../easel -L../easel -Dp7LOGSUM_EXAMPLE logsum.c -leasel -lm
362 * ./example -0.5 -0.5
363 */
364 #include <p7_config.h>
365 #include "easel.h"
366 #include "hmmer.h"
367
368 int
369 main(int argc, char **argv)
370 {
371 float a = atof(argv[1]);
372 float b = atof(argv[2]);
373 float result;
374
375 p7_FLogsumInit();
376 result = p7_FLogsum(a, b);
377 printf("p7_FLogsum(%f,%f) = %f\n", a, b, result);
378
379 result = log(exp(a) + exp(b));
380 printf("log(e^%f + e^%f) = %f\n", a, b, result);
381
382 printf("Absolute error in probability: %f\n", p7_FLogsumError(a,b));
383 return eslOK;
384 }
385 #endif /*p7LOGSUM_EXAMPLE*/
386 /*--------------------- end, example ----------------------------*/
387
388
389
390 /* Footnotes.
391 *
392 * [1] The maximum relative error is on the order of 1/SCALE, or 0.001.
393 * [xref SRE:J8/71].
394 *
395 * [2] SIMD vectorization of a log-space Forward remains vexing.
396 * Sparse-rescaled probability-space Forward vector
397 * implemementation only works for local; glocal or global may
398 * underflow long delete paths. Would be desirable to use a
399 * log-space implementation if we could make it fast. Problem is
400 * implementing the p7_FLogsum() lookup table in SIMD; lookup
401 * tables of this size in current SSE, Altivec appear to be
402 * infeasible. I considered the possibility of using a functional
403 * fit to f(x) = log(1+e^{-x}) for x >=0, for example with a
404 * Chebyshev polynomial, because a numerical f(x) would vectorize.
405 * Decided that this computation would necessarily be expensive on
406 * the order of log(x) or exp(x), so replacing log(1+exp(-x)) with
407 * f(x) doesn't look like compelling -- might as well compute
408 * log(1+exp(-x)) directly! The table-driven approach is about 20x
409 * faster (about 9 clocks, compared to about 200 for the direct
410 * log,exp calculation), and even if we could get an f(x)
411 * calculation to be as efficient as log(x) -- say 100 clocks --
412 * the 4x SIMD vectorization does not compensate for the 10x hit
413 * in speed. [xref SRE:J8/71]
414 */
415