Debian Codegraph @

easel/esl_hyperexp.c

raw symbols SCIP
1 /* Statistical routines for hyperexponential distributions.
2 *
3 * Contents:
4 * 1. The ESL_HYPEREXP object
5 * 2. Evaluating densities and distributions
6 * 3. Generic API routines: for general interface w/ histogram module
7 * 4. Dumping plots for files
8 * 5. Sampling
9 * 6. File input
10 * 7. ML fitting to complete data
11 * 8. ML fitting to binned data
12 * 9. Test driver
13 * 10. Example
14 *
15 * Xrefs:
16 * STL9/140 : original implementation
17 * STL9/143-144 : ML fitting to binned data
18 *
19 * To-do:
20 * - Fit*() functions should return eslEINVAL on n=0, eslENORESULT
21 * on failure due to small n. Compare esl_gumbel. xref J12/93.
22 * SRE, Wed Nov 27 11:17:59 2013
23 */
24 #include <esl_config.h>
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <math.h>
29
30 #include "easel.h"
31 #include "esl_exponential.h"
32 #include "esl_fileparser.h"
33 #include "esl_histogram.h"
34 #include "esl_minimizer.h"
35 #include "esl_random.h"
36 #include "esl_stats.h"
37 #include "esl_vectorops.h"
38
39 #include "esl_hyperexp.h"
40
41 /****************************************************************************
42 *# 1. The ESL_HYPEREXP object
43 ****************************************************************************/
44
45 /* Function: esl_hyperexp_Create()
46 *
47 * Purpose: Creates an object to hold parameters for a <K>-component
48 * hyperexponential.
49 *
50 * Parameters in the object are initialized
51 * ($q_k = \frac{1}{K}$, $\lambda_k = 1$, $\mu = 0$), but
52 * the caller will want to set these according to its own
53 * purposes.
54 *
55 * Args: K - number of components in the mixture
56 *
57 * Returns: ptr to newly allocated/initialized <ESL_HYPEREXP> object.
58 *
59 * Throws: NULL on allocation failure.
60 */
61 ESL_HYPEREXP *
62 esl_hyperexp_Create(int K)
63 {
64 int status;
65 ESL_HYPEREXP *h = NULL;
66 int k;
67
68 ESL_ALLOC(h, sizeof(ESL_HYPEREXP));
69 h->q = h->lambda = h->wrk = NULL;
70 h->fixlambda = NULL;
71 h->K = K;
72 h->fixmix = FALSE;
73
74 ESL_ALLOC(h->q, sizeof(double) * K);
75 ESL_ALLOC(h->lambda, sizeof(double) * K);
76 ESL_ALLOC(h->wrk, sizeof(double) * K);
77 ESL_ALLOC(h->fixlambda, sizeof(char) * K);
78
79 for (k = 0; k < K; k++)
80 {
81 h->q[k] = 1. / (double) K;
82 h->lambda[k] = 1.;
83 h->fixlambda[k]= 0;
84 }
85 h->mu = 0.;
86 return h;
87
88 ERROR:
89 esl_hyperexp_Destroy(h);
90 return NULL;
91 }
92
93 /* Function: esl_hyperexp_Destroy()
94 *
95 * Purpose: Deallocates the hyperexponential parameter object <h>.
96 *
97 * Args: h - ptr to the object to be deallocated.
98 *
99 * Returns: (void).
100 */
101 void
102 esl_hyperexp_Destroy(ESL_HYPEREXP *h)
103 {
104 if (h == NULL) return;
105
106 if (h->q != NULL) free(h->q);
107 if (h->lambda != NULL) free(h->lambda);
108 if (h->wrk != NULL) free(h->wrk);
109 if (h->fixlambda!= NULL) free(h->fixlambda);
110 free(h);
111 }
112
113
114 /* Function: esl_hyperexp_Copy()
115 *
116 * Purpose: Makes a copy of the hyperexponential parameter object <src>
117 * in <dest>. Caller must have already allocated <dest> to have
118 * (at least) the same number of components as <src>.
119 *
120 * Args: src - object to be copied
121 * dest - allocated object to copy <src> into
122 *
123 * Returns: <eslOK> on success.
124 *
125 * Throws: <eslEINCOMPAT> if <dest> isn't allocated with enough
126 * components to hold a copy of <src>.
127 */
128 int
129 esl_hyperexp_Copy(ESL_HYPEREXP *src, ESL_HYPEREXP *dest)
130 {
131 int k;
132
133 if (dest->K < src->K)
134 ESL_EXCEPTION(eslEINCOMPAT, "hyperexponential too small to copy into");
135
136 for (k = 0; k < src->K; k++)
137 {
138 dest->q[k] = src->q[k];
139 dest->lambda[k] = src->lambda[k];
140 dest->fixlambda[k]= src->fixlambda[k];
141 }
142 dest->mu = src->mu;
143 dest->K = src->K;
144 dest->fixmix = src->fixmix;
145 return eslOK;
146 }
147
148 /* Function: esl_hyperexp_FixedUniformMixture()
149 *
150 * Purpose: Set the mixture coeffients to a uniform (1/K) distribution,
151 * and fix them there so they aren't estimable parameters.
152 */
153 int
154 esl_hyperexp_FixedUniformMixture(ESL_HYPEREXP *h)
155 {
156 int k;
157 for (k = 0; k < h->K; k++) h->q[k] = 1./(double)h->K;
158 h->fixmix = TRUE;
159 return eslOK;
160 }
161
162
163 /* Function: esl_hyperexp_SortComponents()
164 *
165 * Purpose: Rearrange the components in a hyperexponential in
166 * order of lambda values, with the highest lambda first.
167 *
168 * Stupid $O(K^2)$ selection sort algorithm here, because we
169 * expect $K$ to be small.
170 */
171 int
172 esl_hyperexp_SortComponents(ESL_HYPEREXP *h)
173 {
174 int k, kp;
175 char ctmp;
176 double dtmp;
177
178 for (k = 0; k < h->K-1; k++)
179 {
180 kp = k + esl_vec_DArgMax(h->lambda+k, h->K-k);
181 if (k != kp)
182 {
183 dtmp = h->q[k]; h->q[k] = h->q[kp]; h->q[kp] = dtmp;
184 dtmp = h->lambda[k]; h->lambda[k] = h->lambda[kp]; h->lambda[kp] = dtmp;
185 ctmp = h->fixlambda[k]; h->fixlambda[k] = h->fixlambda[kp]; h->fixlambda[kp] = ctmp;
186 }
187 }
188 return eslOK;
189 }
190
191
192 /* Function: esl_hyperexp_Write()
193 *
194 * Purpose: Write hyperexponential parameters from <hxp> to an open <fp>.
195 *
196 * The output format is suitable for input by <esl_hyperexp_Read()>.
197 *
198 * Returns: <eslOK> on success.
199 *
200 * Throws: <eslEWRITE> on any write error.
201 */
202 int
203 esl_hyperexp_Write(FILE *fp, ESL_HYPEREXP *hxp)
204 {
205 int k;
206
207 if (fprintf(fp, "%8d # number of components\n", hxp->K) < 0) ESL_EXCEPTION(eslEWRITE, "hyperexp write failed");
208 if (fprintf(fp, "%8.2f # mu (for all components)\n", hxp->mu) < 0) ESL_EXCEPTION(eslEWRITE, "hyperexp write failed");
209 for (k = 0; k < hxp->K; k++)
210 if (fprintf(fp, "%8.6f %12.6f # q[%d], lambda[%d]\n",
211 hxp->q[k], hxp->lambda[k], k, k) < 0) ESL_EXCEPTION(eslEWRITE, "hyperexp write failed");
212 return eslOK;
213 }
214
215
216 /* Function: esl_hyperexp_Dump()
217 *
218 * Purpose: Dump hyperexponential parameters from <hxp> to an open <fp>,
219 * all on one line with no comments.
220 *
221 * The output format is suitable for input by
222 * <esl_hyperexp_Read()>, like <esl_hyperexp_Write()>,
223 * though it's intended as a diagnostic dump of the
224 * contents of the object.
225 *
226 * Returns: <eslOK> on success.
227 */
228 int
229 esl_hyperexp_Dump(FILE *fp, ESL_HYPEREXP *hxp)
230 {
231 int k;
232
233 fprintf(fp, "%2d ", hxp->K);
234 fprintf(fp, "%6.2f ", hxp->mu);
235 for (k = 0; k < hxp->K; k++)
236 fprintf(fp, "%5.3f %9.6f ", hxp->q[k], hxp->lambda[k]);
237 fprintf(fp, "\n");
238 return eslOK;
239 }
240
241 /*----------------- end ESL_HYPEREXP object maintenance --------------------*/
242
243
244
245 /****************************************************************************
246 * 2. Evaluating densities and distributions
247 ****************************************************************************/
248 /* all lambda_k > 0
249 * all q_k are probabilities, \sum_k q_k = 1 [watch out for q_k=0 in log(q_k)].
250 * mu <= x < infinity [mu=x is not a problem]
251 */
252
253 /* Function: esl_hxp_pdf()
254 *
255 * Purpose: Returns the probability density function $P(X=x)$ for
256 * quantile <x>, given hyperexponential parameters <h>.
257 */
258 double
259 esl_hxp_pdf(double x, ESL_HYPEREXP *h)
260 {
261 double pdf = 0.;
262 int k;
263
264 if (x < h->mu) return 0.;
265
266 for (k = 0; k < h->K; k++)
267 pdf += h->q[k] * esl_exp_pdf(x, h->mu, h->lambda[k]);
268 return pdf;
269 }
270
271
272 /* Function: esl_hxp_logpdf()
273 *
274 * Purpose: Returns the log of the PDF ($\log P(X=x)$) for quantile <x>,
275 * given hyperexponential parameters <h>.
276 */
277 double
278 esl_hxp_logpdf(double x, ESL_HYPEREXP *h)
279 {
280 int k;
281 double z;
282
283 if (x < h->mu) return -eslINFINITY;
284
285 for (k = 0; k < h->K; k++)
286 if (h->q[k] == 0.0)
287 h->wrk[k] = -eslINFINITY;
288 else
289 h->wrk[k] = log(h->q[k]) + esl_exp_logpdf(x, h->mu, h->lambda[k]);
290
291 z = esl_vec_DLogSum(h->wrk, h->K);
292 return z;
293 }
294
295 /* Function: esl_hxp_cdf()
296 *
297 * Purpose: Returns the cumulative distribution function $P(X \leq x)$
298 * for quantile <x>, given hyperexponential parameters <h>.
299 */
300 double
301 esl_hxp_cdf(double x, ESL_HYPEREXP *h)
302 {
303 double cdf = 0.;
304 int k;
305
306 if (x < h->mu) return 0.;
307
308 for (k = 0; k < h->K; k++)
309 cdf += h->q[k] * esl_exp_cdf(x, h->mu, h->lambda[k]);
310 return cdf;
311 }
312
313 /* Function: esl_hxp_logcdf()
314 *
315 * Purpose: Returns the log of the CDF $\log P(X \leq x)$
316 * for quantile <x>, given hyperexponential parameters <h>.
317 */
318 double
319 esl_hxp_logcdf(double x, ESL_HYPEREXP *h)
320 {
321 int k;
322
323 if (x < h->mu) return -eslINFINITY;
324
325 for (k = 0; k < h->K; k++)
326 if (h->q[k] == 0.0)
327 h->wrk[k] = -eslINFINITY;
328 else
329 h->wrk[k] = log(h->q[k]) + esl_exp_logcdf(x, h->mu, h->lambda[k]);
330
331 return esl_vec_DLogSum(h->wrk, h->K);
332 }
333
334
335 /* Function: esl_hxp_surv()
336 *
337 * Purpose: Returns the survivor function $P(X > x)$ (1-CDF)
338 * for quantile <x>, given hyperexponential parameters <h>.
339 */
340 double
341 esl_hxp_surv(double x, ESL_HYPEREXP *h)
342 {
343 double srv = 0.;
344 int k;
345
346 if (x < h->mu) return 1.0;
347
348 for (k = 0; k < h->K; k++)
349 srv += h->q[k] * esl_exp_surv(x, h->mu, h->lambda[k]);
350 return srv;
351 }
352
353
354 /* Function: esl_hxp_logsurv()
355 *
356 * Purpose: Returns the log survivor function $\log P(X > x)$ (log(1-CDF))
357 * for quantile <x>, given hyperexponential parameters <h>.
358 */
359 double
360 esl_hxp_logsurv(double x, ESL_HYPEREXP *h)
361 {
362 int k;
363
364 if (x < h->mu) return 0.0;
365
366 for (k = 0; k < h->K; k++)
367 if (h->q[k] == 0.0)
368 h->wrk[k] = -eslINFINITY;
369 else
370 h->wrk[k] = log(h->q[k]) + esl_exp_logsurv(x, h->mu, h->lambda[k]);
371
372 return esl_vec_DLogSum(h->wrk, h->K);
373 }
374
375 /* Function: esl_hxp_invcdf()
376 *
377 * Purpose: Calculates the inverse CDF for a hyperexponential <h>
378 * returning the quantile <x> at which the CDF is <p>.
379 *
380 * The inverse CDF of a mixture model has no
381 * analytical expression as far as I'm aware. The calculation
382 * here is a computationally expensive, brute force bisection
383 * search in <x> using the CDF function. It will suffice for
384 * a small number of calls (for plotting applications, for example),
385 * but it is not sufficient for a large number of calls.
386 */
387 double
388 esl_hxp_invcdf(double p, ESL_HYPEREXP *h)
389 {
390 double x1, x2, xm; /* low, high guesses at x */
391 double f2, fm;
392 double tol = 1e-6;
393
394 x1 = h->mu;
395 x2 = h->mu + 1.;
396 do { /* bracket */
397 x2 = x2 + 2.*(x2-x1);
398 f2 = esl_hxp_cdf(x2, h);
399 } while (f2 < p);
400
401 do { /* bisection */
402 xm = (x1+x2) / 2.;
403 fm = esl_hxp_cdf(xm, h);
404
405 if (fm > p) x2 = xm;
406 else if (fm < p) x1 = xm;
407 else return xm; /* unlikely case of fm==cdf */
408 } while ( (x2-x1)/(x1+x2-2*h->mu) > tol);
409
410 xm = (x1+x2) / 2.;
411 return xm;
412
413 }
414 /*-------------------- end densities & distributions ------------------------*/
415
416
417
418
419 /****************************************************************************
420 * 3. Generic API routines: for general interface w/ histogram module
421 ****************************************************************************/
422
423 /* Function: esl_hxp_generic_pdf()
424 *
425 * Purpose: Generic-API version of PDF call.
426 */
427 double
428 esl_hxp_generic_pdf(double x, void *params)
429 {
430 ESL_HYPEREXP *h = (ESL_HYPEREXP *) params;
431 return esl_hxp_pdf(x, h);
432 }
433
434 /* Function: esl_hxp_generic_cdf()
435 *
436 * Purpose: Generic-API version of CDF call.
437 */
438 double
439 esl_hxp_generic_cdf(double x, void *params)
440 {
441 ESL_HYPEREXP *h = (ESL_HYPEREXP *) params;
442 return esl_hxp_cdf(x, h);
443 }
444
445 /* Function: esl_hxp_generic_surv()
446 *
447 * Purpose: Generic-API version of survivor function.
448 */
449 double
450 esl_hxp_generic_surv(double x, void *params)
451 {
452 ESL_HYPEREXP *h = (ESL_HYPEREXP *) params;
453 return esl_hxp_surv(x, h);
454 }
455
456 /* Function: esl_hxp_generic_invcdf()
457 *
458 * Purpose: Generic-API version of inverse CDF.
459 */
460 double
461 esl_hxp_generic_invcdf(double p, void *params)
462 {
463 ESL_HYPEREXP *h = (ESL_HYPEREXP *) params;
464 return esl_hxp_invcdf(p, h);
465 }
466 /*------------------------ end generic API ---------------------------------*/
467
468
469
470
471
472
473 /****************************************************************************
474 * 4. Dumping plots for files
475 ****************************************************************************/
476
477 /* Function: esl_hxp_Plot()
478 *
479 * Purpose: Plot some function <func> (for instance, <esl_hxp_pdf()>)
480 * for hyperexponential parameters <h>, for a range of
481 * quantiles x from <xmin> to <xmax> in steps of <xstep>;
482 * output to an open stream <fp> in xmgrace XY input format.
483 *
484 * Returns: <eslOK> on success.
485 *
486 * Throws: <eslEWRITE> on any system write error.
487 */
488 int
489 esl_hxp_Plot(FILE *fp, ESL_HYPEREXP *h,
490 double (*func)(double x, ESL_HYPEREXP *h),
491 double xmin, double xmax, double xstep)
492 {
493 double x;
494 for (x = xmin; x <= xmax; x += xstep)
495 if (fprintf(fp, "%f\t%g\n", x, (*func)(x, h)) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "hyperexp plot write failed");
496 if (fprintf(fp, "&\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "hyperexp plot write failed");
497 return eslOK;
498 }
499 /*-------------------- end plot dumping routines ---------------------------*/
500
501
502
503
504
505 /****************************************************************************
506 * 5. Sampling
507 ****************************************************************************/
508
509 /* Function: esl_hxp_Sample()
510 *
511 * Purpose: Sample a random variate x from a hyperexponential <h>,
512 * given random number source <r>.
513 */
514 double
515 esl_hxp_Sample(ESL_RANDOMNESS *r, ESL_HYPEREXP *h)
516 {
517 int k;
518 k = esl_rnd_DChoose(r, h->q, h->K);
519 return esl_exp_Sample(r, h->mu, h->lambda[k]);
520 }
521
522 /*--------------------------- end sampling ---------------------------------*/
523
524
525
526 /****************************************************************************
527 * 6. File input (mixture models are a little too complex to set on commandline)
528 ****************************************************************************/
529
530 /* Function: esl_hyperexp_Read()
531 *
532 * Purpose: Reads hyperexponential parameters from an open <e>.
533 * which is an <ESL_FILEPARSER> tokenizer for an open stream.
534 *
535 * The first token is <K>, the number of mixture components.
536 * The second token is <mu>, the x offset shared by all components.
537 * Then for each mixture component <k=1..K>, it reads
538 * a mixture coefficient <q[k]> and a decay parameter
539 * <lambda[k]>.
540 *
541 * The <2K+2> data tokens must occur in this order, but
542 * they can be grouped into any number of lines, because the
543 * parser ignores line breaks.
544 *
545 * Anything after a <\#> character on a line is a comment, and
546 * is ignored.
547 *
548 * Returns: <eslOK> on success, and <ret_hxp> points to a new <ESL_HYPEREXP>
549 * object.
550 * <eslEFORMAT> on "normal" parse failure caused by a bad file
551 * format that's likely the user's fault.
552 *
553 * Throws: <eslEMEM> if allocation of the new <ESL_HYPEREXP> fails.
554 *
555 *
556 * FIXME: All our mixture models (esl_dirichlet, for example) should be
557 * reconciled w/ identical interfaces & behaviour.
558 */
559 int
560 esl_hyperexp_Read(ESL_FILEPARSER *e, ESL_HYPEREXP **ret_hxp)
561 {
562 ESL_HYPEREXP *hxp = NULL;
563 char *tok;
564 int status = eslOK;
565 int nc;
566 int k;
567 double sum;
568
569 esl_fileparser_SetCommentChar(e, '#');
570
571 if ((status = esl_fileparser_GetToken(e, &tok, NULL)) != eslOK) goto ERROR;
572 nc = atoi(tok);
573 if (nc < 1) ESL_XFAIL(eslEFORMAT, e->errbuf, "Expected # of components K >= 1 as first token");
574
575 if ((hxp = esl_hyperexp_Create(nc)) == NULL) return eslEMEM; /* percolation */
576
577 if ((status = esl_fileparser_GetToken(e, &tok, NULL)) != eslOK) goto ERROR;
578 hxp->mu = atof(tok);
579
580 for (k = 0; k < hxp->K; k++)
581 {
582 if ((status = esl_fileparser_GetToken(e, &tok, NULL)) != eslOK) goto ERROR;
583 hxp->q[k] = atof(tok);
584
585 if ((status = esl_fileparser_GetToken(e, &tok, NULL)) != eslOK) goto ERROR;
586 hxp->lambda[k] = atof(tok);
587
588 if (hxp->q[k] < 0. || hxp->q[k] > 1.)
589 ESL_XFAIL(eslEFORMAT, e->errbuf, "Expected a mixture coefficient q[k], 0<=q[k]<=1");
590
591 if (hxp->lambda[k] <= 0.)
592 ESL_XFAIL(eslEFORMAT, e->errbuf, "Expected a lambda parameter, lambda>0");
593 }
594 sum = esl_vec_DSum(hxp->q, hxp->K);
595 if (fabs(sum-1.0) > 0.05)
596 ESL_XFAIL(eslEFORMAT, e->errbuf, "Expected mixture coefficients to sum to 1");
597
598 esl_vec_DNorm(hxp->q, hxp->K);
599 *ret_hxp = hxp;
600 return eslOK;
601
602 ERROR:
603 esl_hyperexp_Destroy(hxp);
604 return status;
605 }
606
607 /* Function: esl_hyperexp_ReadFile()
608 *
609 * Purpose: Convenience wrapper around <esl_hyperexp_Read()> that takes
610 * a filename as an argument, instead of an open <ESL_FILEPARSER>.
611 *
612 * This lets you quickly read an object from a file, but it
613 * limits your ability to deal gracefully and flexibly with
614 * 'normal' errors like 'file not found' or 'bad file format'.
615 * Here, all errors are fatal.
616 *
617 * Returns: <eslOK> on success.
618 *
619 * Throws: <eslEMEM> on an allocation failure.
620 *
621 * <eslEFORMAT> on any parse error. Diagnostic information is
622 * unavailable, because the <ESL_FILEPARSER> that's holding
623 * that information is internal to this function.
624 *
625 * <eslENOTFOUND> on any failure to open the file.
626 */
627 int
628 esl_hyperexp_ReadFile(char *filename, ESL_HYPEREXP **ret_hxp)
629 {
630 FILE *fp;
631 ESL_FILEPARSER *e;
632 int status;
633
634 if ((fp = fopen(filename, "r")) == NULL)
635 ESL_EXCEPTION(eslENOTFOUND, "file not found");
636
637 if ((e = esl_fileparser_Create(fp)) == NULL) {
638 fclose(fp);
639 ESL_EXCEPTION(eslEMEM, "failed to create fileparser");
640 }
641 esl_fileparser_SetCommentChar(e, '#');
642
643 status = esl_hyperexp_Read(e, ret_hxp);
644
645 esl_fileparser_Destroy(e);
646 fclose(fp);
647 return status;
648 }
649
650
651
652
653 /****************************************************************************
654 * 7. ML fitting to complete data
655 ****************************************************************************/
656
657 /* This structure is used to sneak the data into minimizer's generic
658 * (void *) API for all aux data
659 */
660 struct hyperexp_data {
661 double *x;
662 int n;
663 ESL_HYPEREXP *h;
664 };
665
666 /* Given hyperexponential parameters in <h>;
667 * do appropriate c.o.v.'s to unconstrained real parameters
668 * and fill in the packed parameter vector <p>.
669 *
670 * <p> must be allocated for at least (2K-1) doubles: K-1 mixture
671 * coefficients and K lambda parameters. (mu is not a free param).
672 *
673 * First K-1 are $Q_1..Q_{K-1}$ mixture coefficient parameters; $Q_0$ implicitly 0;
674 * cov is $q_k = \frac{e^{Q_k}}{\sum_j e^{Q_j}}$; $Q_k = \log(q_k) - \log(q_0)$.
675 * Then K lambda params;
676 * lambda cov is $\lambda = e^w$, $w = \log(\lambda)$.
677 */
678 static void
679 hyperexp_pack_paramvector(double *p, int np, ESL_HYPEREXP *h)
680 {
681 int i; /* counter in parameter vector p */
682 int k; /* counter in mixture components */
683 double z; /* tmp variable */
684
685 /* mixture coefficients */
686 i = 0;
687 if (! h->fixmix) {
688 z = log(h->q[0]);
689 for (k = 1; k < h->K; k++)
690 p[i++] = log(h->q[k]) - z;
691 }
692
693 /* exponential parameters */
694 for (k = 0; k < h->K; k++)
695 if (! h->fixlambda[k])
696 p[i++] = log(h->lambda[k]);
697 }
698
699 /* Same as above but in reverse: given parameter vector <p>,
700 * <np> = 2K-1, do appropriate c.o.v. back to desired parameter space, and
701 * update the hyperexponential <h>.
702 */
703 static void
704 hyperexp_unpack_paramvector(double *p, int np, ESL_HYPEREXP *h)
705 {
706 int i; /* counter in parameter vector p */
707 int k; /* counter in mixture components */
708 double z; /* tmp variable */
709
710 /* Fetch the params in their c.o.v. space first
711 */
712 i = 0;
713 if (! h->fixmix) {
714 h->q[0] = 0; /* implicitly */
715 for (k = 1; k < h->K; k++)
716 h->q[k] = p[i++];
717 }
718 for (k = 0; k < h->K; k++)
719 if (! h->fixlambda[k])
720 h->lambda[k] = p[i++];
721
722 /* Convert mix coefficients back to probabilities;
723 * their c.o.v. is q_k = e^{Q_k} / \sum_k e^{Q_k}
724 * which rearranges to exp(Q_k - log[\sum_k e^Q_k]),
725 * and we have the DLogSum() function to compute the log sum.
726 */
727 if (! h->fixmix) {
728 z = esl_vec_DLogSum(h->q, h->K);
729 for (k = 0; k < h->K; k++)
730 h->q[k] = exp(h->q[k] - z);
731 }
732
733 /* lambda c.o.v. is \lambda = e^w */
734 for (k = 0; k < h->K; k++)
735 if (! h->fixlambda[k])
736 h->lambda[k] = exp(h->lambda[k]);
737 }
738
739 /* The log likelihood function to be optimized by ML fitting:
740 * This needs to be careful of a case where a lambda = inf.
741 */
742 static double
743 hyperexp_complete_func(double *p, int np, void *dptr)
744 {
745 struct hyperexp_data *data = (struct hyperexp_data *) dptr;
746 ESL_HYPEREXP *h = data->h;
747 double logL = 0.;
748 int i;
749
750 hyperexp_unpack_paramvector(p, np, h);
751 for (i = 0; i < data->n; i++)
752 logL += esl_hxp_logpdf(data->x[i], h);
753 return -logL;
754 }
755
756 /* The gradient of the NLL w.r.t. each free parameter in p.
757 */
758 static void
759 hyperexp_complete_gradient(double *p, int np, void *dptr, double *dp)
760 {
761 struct hyperexp_data *data = (struct hyperexp_data *) dptr;
762 ESL_HYPEREXP *h = data->h;
763 double pdf;
764 int i,k;
765 int pidx;
766
767 hyperexp_unpack_paramvector(p, np, h);
768 esl_vec_DSet(dp, np, 0.);
769 for (i = 0; i < data->n; i++)
770 {
771 /* FIXME: I think the calculation below may need to be done
772 * in log space, to avoid underflow errors; see complete_binned_gradient()
773 */
774 /* Precalculate q_k PDF_k(x) terms, and their sum */
775 for (k = 0; k < h->K; k++)
776 h->wrk[k] = h->q[k] * esl_exp_pdf(data->x[i], h->mu, h->lambda[k]);
777 pdf = esl_vec_DSum(h->wrk, h->K);
778
779 pidx = 0;
780 if (! h->fixmix) {
781 for (k = 1; k < h->K; k++) /* generic d/dQ solution for mixture models */
782 dp[pidx++] -= h->wrk[k]/pdf - h->q[k];
783 }
784
785 for (k = 0; k < h->K; k++)
786 if (! h->fixlambda[k])
787 dp[pidx++] -= (1.-h->lambda[k]*(data->x[i]-h->mu))*h->wrk[k]/pdf; /* d/dw */
788 }
789 }
790
791
792 /* Function: esl_hxp_FitGuess()
793 *
794 * Purpose: Given a sorted vector of <n> observed data samples <x[]>,
795 * from smallest <x[0]> to largest <x[n-1]>, calculate a
796 * very crude guesstimate of a fit -- suitable only as a starting
797 * point for further optimization -- and return those parameters
798 * in <h>.
799 *
800 * Assigns $q_k \propto \frac{1}{k}$ and $\mu = \min_i x_i$;
801 * splits $x$ into $K$ roughly equal-sized bins, and
802 * and assigns $\lambda_k$ as the ML estimate from bin $k$.
803 * (If $q_k$ coefficients have already been fixed to
804 * known values, this step is skipped.)
805 */
806 int
807 esl_hxp_FitGuess(double *x, int n, ESL_HYPEREXP *h)
808 {
809 double tmu; /* current mu */
810 double mean; /* mean (x-tmu) in a bin */
811 int i,k;
812 int imin, imax;
813
814 h->mu = x[0]; /* minimum */
815 for (k = 0; k < h->K; k++)
816 {
817 if (! h->fixmix)
818 h->q[k] = 1 / (double)(k+1); /* priors ~ 1, 1/2, 1/3... */
819
820 imin = (int) ((double)(k*n)/(double)h->K);
821 imax = (int) ((double)((k+1)*n)/(double)h->K);
822 tmu = x[imin];
823 mean = 0.;
824 for (i = imin; i < imax; i++)
825 mean += x[i] - tmu;
826 mean /= (double)(imax-imin);
827 h->lambda[k] = 1 / mean;
828 }
829 esl_vec_DNorm(h->q, h->K);
830 return eslOK;
831 }
832
833 /* Function: esl_hxp_FitComplete()
834 *
835 * Purpose: Given a vector of <n> observed data samples <x[]>
836 * (sorted or unsorted), and an initial guess <h> for
837 * a hyperexponential, find maximum likelihood parameters
838 * by conjugate gradient descent optimization, starting
839 * from <h> and leaving the final optimized solution in
840 * <h>.
841 *
842 * Returns: <eslOK> on success, and <h> contains the fitted
843 * hyperexponential parameters.
844 *
845 * Throws: <eslEMEM> on allocation error, and <h> is left in
846 * in its initial state.
847 */
848 int
849 esl_hxp_FitComplete(double *x, int n, ESL_HYPEREXP *h)
850 {
851 struct hyperexp_data data;
852 double *p = NULL;
853 int np;
854 double fx;
855 int i;
856 int status;
857
858 /* Determine number of free parameters and allocate */
859 np = 0;
860 if (! h->fixmix) np += h->K-1; /* K-1 mix coefficients... */
861 for (i = 0; i < h->K; i++) /* ...and up to K lambdas free */
862 if (! h->fixlambda[i]) np++;
863 ESL_ALLOC(p, sizeof(double) * np);
864
865 /* Copy shared info into the "data" structure */
866 data.x = x;
867 data.n = n;
868 data.h = h;
869
870 /* From h, create the parameter vector. */
871 hyperexp_pack_paramvector(p, np, h);
872
873 /* Feed it all to the mighty optimizer. */
874 status = esl_min_ConjugateGradientDescent(NULL, p, np,
875 &hyperexp_complete_func,
876 &hyperexp_complete_gradient,
877 (void *) (&data), &fx, NULL);
878 if (status != eslOK) goto ERROR;
879
880 /* Convert the final parameter vector back to a hyperexponential
881 */
882 hyperexp_unpack_paramvector(p, np, h);
883
884 free(p);
885 esl_hyperexp_SortComponents(h);
886 return eslOK;
887
888 ERROR:
889 free(p);
890 return status;
891 }
892
893
894 /****************************************************************************
895 * 8. Maximum likelihood fitting, complete binned data xref STL9/143-144
896 ****************************************************************************/
897
898 /* minimizer API only allows us one generic void ptr to pass
899 * our data through:
900 */
901 struct hyperexp_binned_data {
902 ESL_HISTOGRAM *g;
903 ESL_HYPEREXP *h;
904 };
905
906 static double
907 hyperexp_complete_binned_func(double *p, int np, void *dptr)
908 {
909 struct hyperexp_binned_data *data = (struct hyperexp_binned_data *) dptr;
910 ESL_HISTOGRAM *g = data->g;
911 ESL_HYPEREXP *h = data->h;
912 double logL = 0.;
913 double ai, delta;
914 int i,k;
915
916 hyperexp_unpack_paramvector(p, np, h);
917 delta = g->w;
918 /* counting over occupied, uncensored histogram bins */
919 for (i = g->cmin; i <= g->imax; i++)
920 {
921 if (g->obs[i] == 0) continue; /* skip unoccupied ones */
922
923 ai = esl_histogram_Bin2LBound(g, i);
924 if (ai < h->mu) ai = h->mu; /* careful about the left boundary: no x < h->mu */
925
926 for (k = 0; k < h->K; k++)
927 {
928 h->wrk[k] = log(h->q[k]) - h->lambda[k]*(ai-h->mu);
929 if (delta * h->lambda[k] < eslSMALLX1)
930 h->wrk[k] += log(delta * h->lambda[k]);
931 else
932 h->wrk[k] += log(1 - exp(-delta * h->lambda[k]));
933 }
934 logL += g->obs[i] * esl_vec_DLogSum(h->wrk, h->K);
935 }
936 return -logL;
937 }
938
939 static void
940 hyperexp_complete_binned_gradient(double *p, int np, void *dptr, double *dp)
941 {
942 struct hyperexp_binned_data *data = (struct hyperexp_binned_data *) dptr;
943 ESL_HISTOGRAM *g = data->g;
944 ESL_HYPEREXP *h = data->h;
945 int i,k;
946 int pidx;
947 double z;
948 double tmp;
949 double ai, delta;
950
951 hyperexp_unpack_paramvector(p, np, h);
952 esl_vec_DSet(dp, np, 0.);
953 delta = g->w;
954
955 /* counting over occupied, uncensored histogram bins */
956 for (i = g->cmin; i <= g->imax; i++)
957 {
958 if (g->obs[i] == 0) continue;
959 ai = esl_histogram_Bin2LBound(g, i);
960 if (ai < h->mu) ai = h->mu; /* careful about the left boundary: no x < h->mu */
961
962 /* Calculate log (q_m alpha_m(a_i) terms
963 */
964 for (k = 0; k < h->K; k++)
965 {
966 h->wrk[k] = log(h->q[k]) - h->lambda[k]*(ai-h->mu);
967 if (delta * h->lambda[k] < eslSMALLX1)
968 h->wrk[k] += log(delta * h->lambda[k]);
969 else
970 h->wrk[k] += log(1 - exp(-delta * h->lambda[k]));
971 }
972 z = esl_vec_DLogSum(h->wrk, h->K); /* z= log \sum_k q_k alpha_k(a_i) */
973
974 /* Bump the gradients for Q_1..Q_{K-1} */
975 pidx = 0;
976 if (! h->fixmix) {
977 for (k = 1; k < h->K; k++)
978 dp[pidx++] -= g->obs[i] * (exp(h->wrk[k] - z) - h->q[k]);
979 }
980
981 /* Bump the gradients for w_0..w_{K-1}
982 */
983 for (k = 0; k < h->K; k++)
984 if (! h->fixlambda[k])
985 {
986 tmp = log(h->q[k]) + log(h->lambda[k])- h->lambda[k]*(ai-h->mu);
987 tmp = exp(tmp - z);
988 tmp *= (ai + delta - h->mu) * exp(-delta * h->lambda[k]) - (ai - h->mu);
989 dp[pidx++] -= g->obs[i] * tmp;
990 }
991 }
992 }
993
994 /* Function: esl_hxp_FitGuessBinned()
995 *
996 * Purpose: Given a histogram <g> with binned observations;
997 * obtain a very crude guesstimate of a fit -- suitable only
998 * as a starting point for further optimization -- and return
999 * those parameters in <h>.
1000 *
1001 * Assigns $q_k \propto \frac{1}{k}$ and $\mu = \min_i x_i$;
1002 * splits $x$ into $K$ roughly equal-sized bins, and
1003 * and assigns $\lambda_k$ as the ML estimate from bin $k$.
1004 * If the coefficients have already been set to known values,
1005 * this step is skipped.
1006 */
1007 int
1008 esl_hxp_FitGuessBinned(ESL_HISTOGRAM *g, ESL_HYPEREXP *h)
1009 {
1010 double sum;
1011 int n;
1012 int i,k;
1013 int nb;
1014 double ai;
1015
1016 if (g->is_tailfit) h->mu = g->phi; /* all x > mu in this case */
1017 else if (g->is_rounded) h->mu = esl_histogram_Bin2LBound(g, g->imin);
1018 else h->mu = g->xmin;
1019
1020 nb = g->imax - g->cmin + 1;
1021 k = h->K-1;
1022 sum = 0;
1023 n = 0;
1024 for (i = g->imax; i >= g->cmin; i--)
1025 {
1026 ai = esl_histogram_Bin2LBound(g,i);
1027 if (ai < g->xmin) ai = g->xmin;
1028 n += g->obs[i];
1029 sum += g->obs[i] * ai;
1030
1031 if (i == g->cmin + (k*nb)/h->K)
1032 h->lambda[k--] = 1 / ((sum/(double) n) - ai);
1033 }
1034
1035 if (! h->fixmix) {
1036 for (k = 0; k < h->K; k++)
1037 h->q[k] = 1 / (double) h->K;
1038 }
1039
1040 return eslOK;
1041 }
1042
1043
1044 /* Function: esl_hxp_FitCompleteBinned()
1045 *
1046 * Purpose: Given a histogram <g> with binned observations, where each
1047 * bin i holds some number of observed samples x with values from
1048 * lower bound l to upper bound u (that is, $l < x \leq u$),
1049 * and given a starting guess <h> for hyperexponential parameters;
1050 *
1051 * Find maximum likelihood parameters <h> by conjugate gradient
1052 * descent, starting from the initial <h> and leaving the
1053 * optimized solution in <h>.
1054 *
1055 * Returns: <eslOK> on success.
1056 *
1057 * Throws: <eslEMEM> on allocation error, and <h> is left in its
1058 * initial state.
1059 */
1060 int
1061 esl_hxp_FitCompleteBinned(ESL_HISTOGRAM *g, ESL_HYPEREXP *h)
1062 {
1063 struct hyperexp_binned_data data;
1064 double *p = NULL;
1065 double fx;
1066 int i;
1067 int np;
1068 int status;
1069
1070 np = 0;
1071 if (! h->fixmix) np = h->K-1; /* K-1 mix coefficients... */
1072 for (i = 0; i < h->K; i++) /* ...and up to K lambdas free. */
1073 if (! h->fixlambda[i]) np++;
1074
1075 ESL_ALLOC(p, sizeof(double) * np);
1076
1077 /* Copy shared info into the "data" structure */
1078 data.g = g;
1079 data.h = h;
1080
1081 /* From h, create the parameter vector. */
1082 hyperexp_pack_paramvector(p, np, h);
1083
1084 /* Feed it all to the mighty optimizer. */
1085 status = esl_min_ConjugateGradientDescent(NULL, p, np,
1086 &hyperexp_complete_binned_func,
1087 &hyperexp_complete_binned_gradient,
1088 (void *) (&data), &fx, NULL);
1089 if (status != eslOK) goto ERROR;
1090
1091 /* Convert the final parameter vector back to a hyperexponential
1092 */
1093 hyperexp_unpack_paramvector(p, np, h);
1094
1095 free(p);
1096 esl_hyperexp_SortComponents(h);
1097 return eslOK;
1098
1099 ERROR:
1100 free(p);
1101 return status;
1102 }
1103 /*--------------------------- end fitting ----------------------------------*/
1104
1105
1106
1107
1108
1109
1110 /****************************************************************************
1111 * 9. Test driver
1112 ****************************************************************************/
1113 #ifdef eslHYPEREXP_TESTDRIVE
1114 /* Compile:
1115 gcc -g -Wall -I. -I ~/src/easel -L ~/src/easel -o test\
1116 -DeslHYPEREXP_TESTDRIVE esl_hyperexp.c -leasel -lm
1117 */
1118 #include <stdio.h>
1119 #include <stdlib.h>
1120 #include <string.h>
1121
1122 #include "easel.h"
1123 #include "esl_random.h"
1124 #include "esl_histogram.h"
1125 #include "esl_hyperexp.h"
1126
1127 int
1128 main(int argc, char **argv)
1129 {
1130 ESL_HISTOGRAM *h;
1131 ESL_RANDOMNESS *r;
1132 ESL_HYPEREXP *hxp;
1133 ESL_HYPEREXP *ehxp;
1134 int n = 20000;
1135 double binwidth = 0.1;
1136 int i;
1137 double x;
1138 double *data;
1139 int ndata;
1140 int k, ek, mink;
1141 double mindiff, diff;
1142
1143 int opti;
1144 int be_verbose = FALSE;
1145 char *paramfile = NULL;
1146 char *plotfile = NULL;
1147 FILE *pfp = stdout;
1148 int plot_pdf = FALSE;
1149 int plot_logpdf = FALSE;
1150 int plot_cdf = FALSE;
1151 int plot_logcdf = FALSE;
1152 int plot_surv = FALSE;
1153 int plot_logsurv = FALSE;
1154 int xmin_set = FALSE;
1155 double xmin;
1156 int xmax_set = FALSE;
1157 double xmax;
1158 int xstep_set = FALSE;
1159 double xstep;
1160 int do_fixmix = FALSE;
1161 int status;
1162
1163 for (opti = 1; opti < argc && *(argv[opti]) == '-'; opti++)
1164 {
1165 if (strcmp(argv[opti], "-f") == 0) do_fixmix = TRUE;
1166 else if (strcmp(argv[opti], "-i") == 0) paramfile = argv[++opti];
1167 else if (strcmp(argv[opti], "-n") == 0) n = atoi(argv[++opti]);
1168 else if (strcmp(argv[opti], "-o") == 0) plotfile = argv[++opti];
1169 else if (strcmp(argv[opti], "-v") == 0) be_verbose = TRUE;
1170 else if (strcmp(argv[opti], "-w") == 0) binwidth = atof(argv[++opti]);
1171 else if (strcmp(argv[opti], "-C") == 0) plot_cdf = TRUE;
1172 else if (strcmp(argv[opti], "-LC") == 0) plot_logcdf = TRUE;
1173 else if (strcmp(argv[opti], "-P") == 0) plot_pdf = TRUE;
1174 else if (strcmp(argv[opti], "-LP") == 0) plot_logpdf = TRUE;
1175 else if (strcmp(argv[opti], "-S") == 0) plot_surv = TRUE;
1176 else if (strcmp(argv[opti], "-LS") == 0) plot_logsurv = TRUE;
1177 else if (strcmp(argv[opti], "-XL") == 0) { xmin_set = TRUE; xmin = atof(argv[++opti]); }
1178 else if (strcmp(argv[opti], "-XH") == 0) { xmax_set = TRUE; xmax = atof(argv[++opti]); }
1179 else if (strcmp(argv[opti], "-XS") == 0) { xstep_set = TRUE; xstep = atof(argv[++opti]); }
1180 else esl_fatal("bad option");
1181 }
1182
1183 if (paramfile != NULL)
1184 {
1185 status = esl_hyperexp_ReadFile(paramfile, &hxp);
1186 if (status == eslENOTFOUND) esl_fatal("Param file %s not found", paramfile);
1187 else if (status == eslEFORMAT) esl_fatal("Parse failed: param file %s invalid format", paramfile);
1188 else if (status != eslOK) esl_fatal("Unusual failure opening param file %s", paramfile);
1189 }
1190 else
1191 {
1192 hxp = esl_hyperexp_Create(3);
1193 hxp->mu = -2.0;
1194 hxp->q[0] = 0.5; hxp->q[1] = 0.3; hxp->q[2] = 0.2;
1195 hxp->lambda[0] = 1.0; hxp->lambda[1] = 0.3; hxp->lambda[2] = 0.1;
1196 }
1197 if (do_fixmix) esl_hyperexp_FixedUniformMixture(hxp); /* overrides q's above */
1198
1199 if (be_verbose) esl_hyperexp_Dump(stdout, hxp);
1200
1201 r = esl_randomness_Create(42);
1202 h = esl_histogram_CreateFull(hxp->mu, 100., binwidth);
1203 if (plotfile != NULL) {
1204 if ((pfp = fopen(plotfile, "w")) == NULL)
1205 esl_fatal("Failed to open plotfile");
1206 }
1207 if (! xmin_set) xmin = hxp->mu;
1208 if (! xmax_set) xmax = hxp->mu+ 20*(1. / esl_vec_DMin(hxp->lambda, hxp->K));
1209 if (! xstep_set) xstep = 0.1;
1210
1211 for (i = 0; i < n; i++)
1212 {
1213 x = esl_hxp_Sample(r, hxp);
1214 esl_histogram_Add(h, x);
1215 }
1216
1217 esl_histogram_GetData(h, &data, &ndata); /* get sorted data vector */
1218
1219 ehxp = esl_hyperexp_Create(hxp->K);
1220 if (do_fixmix) esl_hyperexp_FixedUniformMixture(ehxp);
1221 esl_hxp_FitGuess(data, ndata, ehxp);
1222 if ( esl_hxp_FitComplete(data, ndata, ehxp) != eslOK) esl_fatal("Failed to fit hyperexponential");
1223
1224 if (be_verbose) esl_hyperexp_Dump(stdout, ehxp);
1225
1226 if (fabs( (ehxp->mu-hxp->mu)/hxp->mu ) > 0.01)
1227 esl_fatal("Error in (complete) fitted mu > 1%\n");
1228 for (ek = 0; ek < ehxp->K; ek++)
1229 { /* try to match each estimated lambda up to a parametric lambda */
1230 mindiff = 1.0;
1231 mink = -1;
1232 for (k = 0; k < hxp->K; k++)
1233 {
1234 diff = fabs( (ehxp->lambda[ek] - hxp->lambda[k]) / hxp->lambda[k]);
1235 if (diff < mindiff) {
1236 mindiff = diff;
1237 mink = k;
1238 }
1239 }
1240 if (mindiff > 0.50)
1241 esl_fatal("Error in (complete) fitted lambda > 50%\n");
1242 if (fabs( (ehxp->q[ek] - hxp->q[mink]) / hxp->q[mink]) > 1.0)
1243 esl_fatal("Error in (complete) fitted q > 2-fold%\n");
1244 }
1245
1246 esl_hxp_FitGuessBinned(h, ehxp);
1247 if ( esl_hxp_FitCompleteBinned(h, ehxp) != eslOK) esl_fatal("Failed to fit binned hyperexponential");
1248 if (be_verbose) esl_hyperexp_Dump(stdout, ehxp);
1249
1250 if (fabs( (ehxp->mu-hxp->mu)/hxp->mu ) > 0.01)
1251 esl_fatal("Error in (binned) fitted mu > 1%\n");
1252 for (ek = 0; ek < ehxp->K; ek++)
1253 { /* try to match each estimated lambda up to a parametric lambda */
1254 mindiff = 1.0;
1255 mink = -1;
1256 for (k = 0; k < hxp->K; k++)
1257 {
1258 diff = fabs( (ehxp->lambda[ek] - hxp->lambda[k]) / hxp->lambda[k]);
1259 if (diff < mindiff) {
1260 mindiff = diff;
1261 mink = k;
1262 }
1263 }
1264 if (mindiff > 0.50)
1265 esl_fatal("Error in (binned) fitted lambda > 50%\n");
1266 if (fabs( (ehxp->q[ek] - hxp->q[mink]) / hxp->q[mink]) > 1.0)
1267 esl_fatal("Error in (binned) fitted q > 2-fold\n");
1268 }
1269
1270 if (plot_pdf) esl_hxp_Plot(pfp, hxp, &esl_hxp_pdf, xmin, xmax, xstep);
1271 if (plot_logpdf) esl_hxp_Plot(pfp, hxp, &esl_hxp_logpdf, xmin, xmax, xstep);
1272 if (plot_cdf) esl_hxp_Plot(pfp, hxp, &esl_hxp_cdf, xmin, xmax, xstep);
1273 if (plot_logcdf) esl_hxp_Plot(pfp, hxp, &esl_hxp_logcdf, xmin, xmax, xstep);
1274 if (plot_surv) esl_hxp_Plot(pfp, hxp, &esl_hxp_surv, xmin, xmax, xstep);
1275 if (plot_logsurv) esl_hxp_Plot(pfp, hxp, &esl_hxp_logsurv, xmin, xmax, xstep);
1276
1277 if (plotfile != NULL) fclose(pfp);
1278 esl_histogram_Destroy(h);
1279 esl_hyperexp_Destroy(hxp);
1280 esl_hyperexp_Destroy(ehxp);
1281 esl_randomness_Destroy(r);
1282 return 0;
1283 }
1284 #endif /*eslHYPEREXP_TESTDRIVE*/
1285
1286 /****************************************************************************
1287 * Example main()
1288 ****************************************************************************/
1289 #ifdef eslHYPEREXP_EXAMPLE
1290 /*::cexcerpt::hyperexp_example::begin::*/
1291 #include <stdio.h>
1292 #include "easel.h"
1293 #include "esl_random.h"
1294 #include "esl_histogram.h"
1295 #include "esl_hyperexp.h"
1296
1297 int
1298 main(int argc, char **argv)
1299 {
1300 ESL_RANDOMNESS *r; /* source of random numbers */
1301 ESL_HISTOGRAM *h; /* histogram to store the data */
1302 ESL_HYPEREXP *hxp; /* hyperexponential to sample from */
1303 ESL_HYPEREXP *ehxp; /* estimated hyperexponential */
1304 double x; /* sampled data point */
1305 int n = 100000; /* number of samples */
1306 double *data;
1307 int ndata;
1308 int i;
1309
1310 hxp = esl_hyperexp_Create(3);
1311 hxp->mu = -2.0;
1312 hxp->q[0] = 0.6; hxp->q[1] = 0.3; hxp->q[2] = 0.1;
1313 hxp->lambda[0] = 1.0; hxp->lambda[1] = 0.3; hxp->lambda[2] = 0.1;
1314
1315 r = esl_randomness_Create(0);
1316 h = esl_histogram_CreateFull(hxp->mu, 100, 1.0);
1317
1318 for (i = 0; i < n; i++)
1319 {
1320 x = esl_hxp_Sample(r, hxp);
1321 esl_histogram_Add(h, x);
1322 }
1323 esl_histogram_GetData(h, &data, &ndata);
1324
1325 /* Plot the empirical (sampled) and expected survivals */
1326 esl_histogram_PlotSurvival(stdout, h);
1327 esl_hxp_Plot(stdout, hxp, &esl_hxp_surv, h->xmin, h->xmax, 0.1);
1328
1329 /* ML fit to complete data, and plot fitted survival curve */
1330 ehxp = esl_hyperexp_Create(3);
1331 esl_hxp_FitGuess(data, ndata, ehxp);
1332 esl_hxp_FitComplete(data, ndata, ehxp);
1333 esl_hxp_Plot(stdout, ehxp, &esl_hxp_surv, h->xmin, h->xmax, 0.1);
1334
1335 /* ML fit to binned data, plot fitted survival curve */
1336 esl_hxp_FitGuessBinned(h, ehxp);
1337 esl_hxp_FitCompleteBinned(h, ehxp);
1338 esl_hxp_Plot(stdout, ehxp, &esl_hxp_surv, h->xmin, h->xmax, 0.1);
1339
1340 esl_randomness_Destroy(r);
1341 esl_histogram_Destroy(h);
1342 esl_hyperexp_Destroy(hxp);
1343 esl_hyperexp_Destroy(ehxp);
1344 return 0;
1345 }
1346 /*::cexcerpt::hyperexp_example::end::*/
1347 #endif /*eslHYPEREXP_EXAMPLE*/
1348
1349