Debian Codegraph @

src/cmsim.c

raw symbols SCIP
1 /* cmsim: scoring CMs against simulated sequences.
2 * [INCOMPLETE: NOT CURRENTLY COMPILED EPN, Tue Mar 20 05:45:57 2012]
3 *
4 * Main testbed for exploring the statistical behavior of Infernal
5 * scores on random sequences, and importance sampling.
6 *
7 * EPN, Fri Apr 29 14:00:58 2011
8 */
9 #include <esl_config.h>
10 #include "config.h"
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <time.h>
16
17 #include "easel.h"
18 #include <esl_exponential.h>
19 #include <esl_getopts.h>
20 #include <esl_histogram.h>
21 #include <esl_random.h>
22 #include <esl_randomseq.h>
23 #include <esl_stats.h>
24 #include <esl_stopwatch.h>
25 #include <esl_vectorops.h>
26 #include <esl_wuss.h>
27
28 #include "hmmer.h"
29
30 #include "infernal.h"
31
32 #define ALPHOPTS "--rna,--dna" /* Exclusive options for alphabet choice */
33 #define OUTOPTS "-u,-c,-a,--ahmm,--shmm" /* Exclusive options for output */
34
35 static ESL_OPTIONS options[] = {
36 /* name type default env range toggles reqs incomp help docgroup*/
37 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 1 },
38 { "-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "verbose: print scores", 1 },
39 { "-i", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "do importance sampling", 1 },
40 { "-g", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "put CM in glocal mode", 1 },
41 { "--rL", eslARG_INT, "10000", NULL, "n>0", NULL, NULL, NULL, "length of random target seqs", 1 },
42 { "--rN", eslARG_INT, "10", NULL, "n>0", NULL, NULL, NULL, "number of random target seqs", 1 },
43 { "--rhmm", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "generate random sequences from realistic HMM", 1 },
44 { "--rtailp", eslARG_REAL, "0.02", NULL, "0.0<x<0.6",NULL, NULL, NULL, "set fraction of histogram tail to fit to exp tail to <x>", 1 },
45 { "--iN", eslARG_INT, "1000", NULL, "n>0", NULL, NULL, NULL, "number of sampled target seqs", 1 },
46 { "--iT", eslARG_REAL, NULL, NULL, NULL, NULL, NULL, NULL, "set min bit sc for hits in sampled seqs to <x>", 1 },
47 { "--ilocal", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "allow local begins/ends in sampled target seqs", 1 },
48 { "--iall", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "count all hits to sampled seqs, not just best", 1 },
49 { "--itailp", eslARG_REAL, "0.5", NULL, "0.0<x<=1.0",NULL, NULL, NULL, "sampled seqs: set fraction of tail to fit to exp to <x>", 1 },
50 { "--inonbanded",eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "do not use HMM bands to score sampled sequences", 1 },
51 { "--null3", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use NULL3 correction for random/sampled seqs", 1 },
52 { "--beta", eslARG_REAL, "1e-7", NULL, "0<x<1", NULL, NULL, NULL, "set tail loss prob for QDB calculation to <x>", 1 },
53 { "--noqdb", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--beta", "do not use QDBs", 1 },
54 { "--exp", eslARG_REAL, NULL, NULL, "x>0", NULL, NULL, NULL, "exponentiate CM probabilities by <x> before sampling", 1 },
55 { "--seed", eslARG_INT, "181", NULL, "n>=0", NULL, NULL, NULL, "set RNG seed to <n> (if 0: one-time arbitrary seed)", 1 },
56 { "--mxsize", eslARG_REAL,"2048.0", NULL, "x>0.", NULL, NULL, NULL, "set maximum allowable HMM banded DP matrix size to <x> Mb", 1 },
57 { "--ifile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save fit exp tails for range of tails of impt samples to file <f>", 2 },
58 { "--infit", eslARG_INT, "100", NULL, NULL, NULL,"--ifile",NULL,"with --ifile, do tail fits to <n> equally spaced tail probs", 2 },
59 { "--imax", eslARG_REAL, "1.00",NULL, NULL, NULL,"--rfile",NULL,"with --ifile, max tail prob to fit is <x>", 2 },
60 { "--imin", eslARG_REAL, "0.01",NULL, NULL, NULL,"--rfile",NULL,"with --ifile, min tail prob to fit is <x>", 2 },
61 { "--rfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save fit exp tails for range of tails of random samples to file <f>", 2 },
62 { "--rnfit", eslARG_INT, "100", NULL, NULL, NULL,"--rfile",NULL,"with --rfile, do tail fits to <n> equally spaced tail probs", 2 },
63 { "--rmax", eslARG_REAL, "0.10",NULL, NULL, NULL,"--rfile",NULL,"with --rfile, max tail prob to fit is <x>", 2 },
64 { "--rmin", eslARG_REAL, "0.002",NULL, NULL, NULL,"--rfile",NULL,"with --rfile, min tail prob to fit is <x>", 2 },
65
66 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
67 };
68
69 /* struct cfg_s : "Global" application configuration shared by all threads/processes
70 *
71 * This structure is passed to routines within main.c, as a means of semi-encapsulation
72 * of shared data amongst different parallel processes (threads or MPI processes).
73 * This strategy is used despite the fact that a MPI version of cmemit does not
74 * yet exist!
75 */
76 struct cfg_s {
77 char *cmfile; /* name of input CM file */
78 CM_FILE *cmfp; /* open input CM file stream */
79 ESL_ALPHABET *abc; /* digital alphabet for CM */
80 ESL_RANDOMNESS *r; /* source of randomness */
81 int ncm; /* number CM we're at in file */
82 int rN; /* number of random sequences to search */
83 int rL; /* length of random sequences to search */
84 int sN; /* number of sampled sequences to search */
85 float sT; /* bit sc threshold for collecting hits from sampled seqs */
86 int my_rank;
87
88 /* optional output files */
89 FILE *ifp; /* output file for impt sample fits */
90 FILE *rfp; /* output file for random sample fits */
91 };
92
93 static char usage[] = "[-options] <cmfile>";
94 static char banner[] = "score random sequences with a covariance model";
95
96 static int init_cfg(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf);
97
98 static void master(const ESL_GETOPTS *go, struct cfg_s *cfg);
99
100 static int initialize_cm(const ESL_GETOPTS *go, const struct cfg_s *cfg, CM_t *cm, char *errbuf);
101 static int print_run_info(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf);
102 static int get_command(const ESL_GETOPTS *go, char *errbuf, char **ret_command);
103 static int collect_scores(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, int N, int L, int *ret_scN, float **ret_scA);
104 static int fit_histogram(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, float tailp, int do_impt, float *scores, int nscores, int exp_mode, double *ret_mu, double *ret_lambda, double *ret_nrandhits);
105 static int sample_sequence_from_cm(struct cfg_s *cfg, char *errbuf, CM_t *cm, int *ret_L, ESL_DSQ **ret_dsq, Parsetree_t **ret_tr);
106 static int impt_exp_FitComplete(double *x, int n, double *ret_mu, double *ret_lambda, double *ret_scaled_nhits);
107
108 int
109 main(int argc, char **argv)
110 {
111 ESL_GETOPTS *go = NULL; /* command line processing */
112 ESL_STOPWATCH *w = esl_stopwatch_Create();
113 if(w == NULL) cm_Fail("Memory allocation error, stopwatch could not be created.");
114 esl_stopwatch_Start(w);
115 struct cfg_s cfg;
116
117 /* setup logsum lookups (could do this only if nec based on options, but this is safer) */
118 init_ilogsum();
119 FLogsumInit();
120
121 /***********************************************
122 * Parse command line
123 ***********************************************/
124
125 /* Process command line options.
126 */
127 go = esl_getopts_Create(options);
128 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK ||
129 esl_opt_VerifyConfig(go) != eslOK)
130 {
131 printf("Failed to parse command line: %s\n", go->errbuf);
132 esl_usage(stdout, argv[0], usage);
133 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
134 exit(1);
135 }
136 if (esl_opt_GetBoolean(go, "-h") == TRUE)
137 {
138 cm_banner(stdout, argv[0], banner);
139 esl_usage(stdout, argv[0], usage);
140 puts("\nwhere general options are:");
141 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1=docgroup, 2 = indentation; 80=textwidth*/
142 puts("\nmiscellaneous output options are:");
143 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
144 exit(0);
145 }
146 if (esl_opt_ArgNumber(go) != 1)
147 {
148 puts("Incorrect number of command line arguments.");
149 esl_usage(stdout, argv[0], usage);
150 puts("\n where basic options are:");
151 esl_opt_DisplayHelp(stdout, go, 1, 2, 80);
152 printf("\nTo see more help on other available options, do %s -h\n\n", argv[0]);
153 exit(1);
154 }
155 /* Initialize what we can in the config structure (without knowing the alphabet yet).
156 * We could assume RNA, but this HMMER3 based approach is more general.
157 */
158 cfg.cmfile = esl_opt_GetArg(go, 1);
159 cfg.cmfp = NULL; /* opened in init_cfg() */
160 cfg.abc = NULL; /* created in init_cfg() */
161 cfg.r = NULL; /* created in init_cfg() */
162
163 cfg.ifp = NULL;
164 cfg.rfp = NULL;
165
166 cm_banner(stdout, argv[0], banner);
167
168 /* do work */
169 master(go, &cfg);
170
171 /* Clean up the cfg.
172 */
173 if (cfg.abc != NULL) { esl_alphabet_Destroy(cfg.abc); cfg.abc = NULL; }
174 if (cfg.cmfp != NULL) cm_file_Close(cfg.cmfp);
175 if (cfg.r != NULL) esl_randomness_Destroy(cfg.r);
176
177 /* master specific cleaning */
178 if (cfg.ifp != NULL) {
179 fclose(cfg.ifp);
180 printf("# Important sampling fits to various tail masses saved to file %s.\n", esl_opt_GetString(go, "--ifile"));
181 }
182 if (cfg.rfp != NULL) {
183 fclose(cfg.rfp);
184 printf("# Random sequence histogram fits to various tail masses saved to file %s.\n", esl_opt_GetString(go, "--rfile"));
185 }
186
187 esl_getopts_Destroy(go);
188 esl_stopwatch_Stop(w);
189 printf("#\n");
190 esl_stopwatch_Display(stdout, w, "# CPU time: ");
191 esl_stopwatch_Destroy(w);
192 return 0;
193 }
194
195 /* init_cfg()
196 * Already set:
197 * cfg->cmfile - command line arg 1
198 * Sets:
199 * cfg->cmfp - open CM file
200 * cfg->ifp - optional output file (--ifile)
201 * cfg->rfp - optional output file (--rfile)
202 * cfg->r - source of randomness
203 */
204 static int
205 init_cfg(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf)
206 {
207 int status;
208
209 /* open CM file for reading */
210 if((status = cm_file_Open(cfg->cmfile, NULL, FALSE, &(cfg->cmfp), errbuf)) != eslOK) return status;
211
212 /* open optional output files, if nec */
213 if (esl_opt_GetString(go, "--ifile") != NULL) {
214 if ((cfg->ifp = fopen(esl_opt_GetString(go, "--ifile"), "w")) == NULL)
215 ESL_FAIL(eslFAIL, errbuf, "Failed to open important sampling fit save file %s for writing\n", esl_opt_GetString(go, "--ifile"));
216 }
217 if (esl_opt_GetString(go, "--rfile") != NULL) {
218 if ((cfg->rfp = fopen(esl_opt_GetString(go, "--rfile"), "w")) == NULL)
219 ESL_FAIL(eslFAIL, errbuf, "Failed to open important sampling fit save file %s for writing\n", esl_opt_GetString(go, "--rfile"));
220 }
221
222 /* create RNG */
223 cfg->r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "--seed"));
224 if (cfg->r == NULL) ESL_FAIL(eslEINVAL, errbuf, "Failed to create random number generator: probably out of memory");
225
226 cfg->rN = esl_opt_GetInteger(go, "--rN");
227 cfg->rL = esl_opt_GetInteger(go, "--rL");
228 cfg->sN = esl_opt_GetInteger(go, "--iN");
229
230 cfg->my_rank = 0;
231
232 return eslOK;
233 }
234
235 /* master()
236 * The serial version of cmsim. (There is no parallel version yet).
237 * For each CM, generate random sequences and search them.
238 *
239 * We only return if successful. All errors are handled immediately and fatally with cm_Fail().
240 */
241 static void
242 master(const ESL_GETOPTS *go, struct cfg_s *cfg)
243 {
244 int status;
245 char errbuf[eslERRBUFSIZE];
246 CM_t *cm = NULL;
247 int exp_mode; /* exp tail mode */
248 int rscN = 0; /* number of hits in random seqs reported thus far, for all seqs */
249 float *rscA = NULL; /* [0..rscN-1] hit scores for all random seqs */
250 int sscN = 0; /* number of hits in CM-sampled seqs reported thus far, for all seqs */
251 float *sscA = NULL; /* [0..sscN-1] hit scores for all CM-sampled seqs */
252 float min_cct = 1.;
253 float max_cct = 0.;
254 float sum_cct = 0.;
255 float cct;
256 ExpInfo_t *impt_expinfo;
257 ExpInfo_t *rand_expinfo;
258
259 double mu, lambda; /* temporary mu and lambda used for setting exp tails */
260 double nrandhits; /* temporary number of rand hits found */
261 double nsamphits; /* temporary number of rand hits found */
262 float tailp; /* temporary tail mass probability fit to an exponential */
263 float sc_tailp; /* scaled tailp */
264 float avg_hitlen;
265 float tailp_step; /* size of change in tailp parameter for --ifile, --rfile */
266 int nfits; /* number of fits for --ifile, --rfile */
267 int i; /* counter over fits */
268
269 if ((status = init_cfg(go, cfg, errbuf)) != eslOK) cm_Fail(errbuf);
270 if ((status = print_run_info (go, cfg, errbuf)) != eslOK) cm_Fail(errbuf);
271
272 cfg->ncm = 0;
273
274 while ((status = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm)) == eslOK)
275 {
276 if (cm == NULL) cm_Fail("Failed to read CM from %s -- file corrupt?\n", cfg->cmfile);
277 cfg->ncm++;
278
279 ESL_ALLOC(impt_expinfo, sizeof(ExpInfo_t *));
280 impt_expinfo = CreateExpInfo();
281
282 ESL_ALLOC(rand_expinfo, sizeof(ExpInfo_t *));
283 rand_expinfo = CreateExpInfo();
284
285 if((status = initialize_cm(go, cfg, cm, errbuf)) != eslOK) cm_Fail(errbuf);
286
287 printf("CM %d: %s\n", cfg->ncm, cm->name);
288
289 /* For now, search only with local inside */
290 exp_mode = EXP_CM_LI;
291 UpdateSearchInfoForExpMode(cm, 0, exp_mode);
292
293 /* Search random sequences and collect score histograms */
294 if((status = collect_scores(go, cfg, errbuf, cm, cfg->rN, cfg->rL, &rscN, &rscA) != eslOK)) cm_Fail(errbuf);
295 tailp = esl_opt_GetReal(go, "--rtailp");
296 if((status = fit_histogram (go, cfg, errbuf, tailp, FALSE, rscA, rscN, exp_mode, &mu, &lambda, &nrandhits)) != eslOK) cm_Fail(errbuf);
297 avg_hitlen = (double) (cfg->rL * cfg->rN) / (double) nrandhits;
298 printf("Random seq fit histogram:\n\t%12s: %9.5f\n\t%12s: %9.5f\n\t%12s: %9.5f\n\t%12s: %9.5f\n\t%12s: %9.5f\n\n",
299 "mu", mu, "lambda", lambda, "nrandhits", nrandhits, "tailp", tailp, "avg_len", avg_hitlen);
300 SetExpInfo(rand_expinfo, lambda, mu, (double) (cfg->rL * cfg->rN), (int) nrandhits, tailp);
301 debug_print_expinfo(rand_expinfo);
302
303 /* output to --rfile, if nec */
304 if(cfg->rfp != NULL) {
305 tailp = esl_opt_GetReal(go, "--rmax");
306 nfits = esl_opt_GetInteger(go, "--rnfit");
307 tailp_step = (tailp - esl_opt_GetReal(go, "--rmin")) / (float) nfits;
308 for (i = 0; i < nfits; i++) {
309 if((status = fit_histogram (go, cfg, errbuf, tailp, FALSE, rscA, rscN, exp_mode, &mu, &lambda, &nrandhits)) != eslOK) cm_Fail(errbuf);
310 fprintf(cfg->rfp, "%g %g %g %g %g\n",
311 tailp,
312 lambda,
313 (mu - log(1./tailp) / lambda),
314 mu,
315 nrandhits);
316 tailp -= tailp_step;
317 }
318 }
319
320 /* Search CM-sampled sequences and collect score histograms */
321 if(! esl_opt_GetBoolean(go, "--inonbanded")) {
322 cm->search_opts |= CM_SEARCH_HBANDED;
323 }
324
325 if((status = collect_scores(go, cfg, errbuf, cm, cfg->sN, -1, &sscN, &sscA) != eslOK)) cm_Fail(errbuf); /* the -1 passed as L tells collect_scores to sample from the CM */
326 int i;
327 for(i = 0; i < sscN; i++) {
328 cct = 1./ (pow(2., sscA[i]));
329 min_cct = ESL_MIN(min_cct, cct);
330 max_cct = ESL_MAX(max_cct, cct);
331 sum_cct += cct;
332 /*printf("SCALED %5d %6.2f bits %12.10f\n", i, sscA[i], cct);*/
333 }
334 printf("min_cct: %f\n", min_cct);
335 printf("max_cct: %f\n", max_cct);
336 printf("sum_cct: %f\n", sum_cct);
337
338 tailp = esl_opt_GetReal(go, "--itailp");
339 if((status = fit_histogram (go, cfg, errbuf, tailp, TRUE, sscA, sscN, exp_mode, &mu, &lambda, &nsamphits)) != eslOK) cm_Fail(errbuf);
340 printf("Sampled seq fit histogram:\n\t%12s: %9.5f\n\t%12s: %9.5f\n\t%12s: %9.5f\n\t%12s: %9.5f\n\n",
341 "mu", mu, "lambda", lambda, "nsamphits", nsamphits, "tailp", tailp);
342 sc_tailp = ((float) nsamphits / (float) nrandhits);
343 SetExpInfo(impt_expinfo, lambda, mu,
344 (double) (cfg->rL * cfg->rN),
345 (int) nrandhits, /* actually this is scaled_nhits */
346 sc_tailp);
347 debug_print_expinfo(impt_expinfo);
348
349 /* output to --ifile, if nec */
350 if(cfg->ifp != NULL) {
351 tailp = esl_opt_GetReal(go, "--imax");
352 nfits = esl_opt_GetInteger(go, "--infit");
353 tailp_step = (tailp - esl_opt_GetReal(go, "--imin")) / (float) nfits;
354 for (i = 0; i < nfits; i++) {
355 if((status = fit_histogram (go, cfg, errbuf, tailp, TRUE, sscA, sscN, exp_mode, &mu, &lambda, &nsamphits)) != eslOK) cm_Fail(errbuf);
356 sc_tailp = ((float) nsamphits / (float) nrandhits);
357 fprintf(cfg->ifp, "%g %g %g %g %g %g %g\n",
358 tailp,
359 sc_tailp,
360 lambda,
361 (mu - log(1./sc_tailp) / lambda),
362 mu,
363 nsamphits,
364 nrandhits);
365 tailp -= tailp_step;
366 }
367 }
368
369 FreeCM(cm);
370 }
371
372
373 if(status != eslEOF) cm_Fail(cfg->cmfp->errbuf);
374 return;
375
376 ERROR:
377 cm_Fail("Out of memory.");
378 return;
379 }
380
381 /* initialize_cm()
382 * Setup the CM based on the command-line options/defaults;
383 * only set flags and a few parameters. ConfigCM() configures
384 * the CM.
385 */
386 static int
387 initialize_cm(const ESL_GETOPTS *go, const struct cfg_s *cfg, CM_t *cm, char *errbuf)
388 {
389 int status;
390 float exp_cutoff;
391
392 /* config QDB? yes unless --noqdb enabled */
393 if(esl_opt_GetBoolean(go, "--noqdb")) {
394 cm->search_opts |= CM_SEARCH_NOQDB; /* don't use QDB to search */
395 /* cm->beta_qdb == cm->beta_W, both will be set as beta_W read from cmfile */
396 }
397 else {
398 cm->config_opts |= CM_CONFIG_QDB; /* configure QDB */
399 cm->beta_qdb = esl_opt_GetReal(go, "--beta");
400 }
401
402 /* process the --ilocal option, if emitted parsetrees can include
403 * local begins/ends, otherwise, they can't */
404 if(! esl_opt_GetBoolean(go, "--ilocal")) {
405 cm->flags |= CM_EMIT_NO_LOCAL_BEGINS;
406 cm->flags |= CM_EMIT_NO_LOCAL_ENDS;
407 }
408 cm->search_opts |= CM_SEARCH_NOALIGN;
409
410 if(esl_opt_GetBoolean(go, "--null3")) cm->search_opts |= CM_SEARCH_NULL3;
411
412 /* ALWAYS use the greedy overlap resolution algorithm to return hits for exp calculation
413 * it's irrelevant for filter threshold stats, we return best score per seq for that */
414 /* don't turn on CM_SEARCH_CMNOTGREEDY; */
415 cm->search_opts |= CM_SEARCH_HMMGREEDY;
416
417 /* exponentiate the CM, if nec. do this before possibly configuring to local alignment in ConfigCM */
418 if(esl_opt_IsOn(go, "--exp")) ExponentiateCM(cm, esl_opt_GetReal(go, "--exp"));
419
420 if((status = ConfigCM(cm, errbuf, FALSE, NULL, NULL)) != eslOK) return status; /* FALSE says do not calculate W unless nec b/c we're using QDBs */
421
422 /* create and initialize scan info for CYK/Inside scanning functions */
423 cm_CreateScanMatrixForCM(cm, TRUE, TRUE);
424 if(cm->smx == NULL) cm_Fail("initialize_cm(), CreateScanMatrixForCM() call failed.");
425
426 /* create the search info, which holds the thresholds for final round */
427 exp_cutoff = -eslINFINITY;
428 CreateSearchInfo(cm, SCORE_CUTOFF, exp_cutoff, -1.);
429 ValidateSearchInfo(cm, cm->si);
430
431 return eslOK;
432 }
433
434 /* Function: print_run_info
435 * Date: EPN, Mon Mar 3 06:01:13 2008
436 *
437 * Purpose: Print information on this run of cmsim.
438 * Command used to run it, and execution date.
439 *
440 * Returns: eslOK on success
441 */
442 static int
443 print_run_info(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf)
444 {
445 int status;
446 char *command;
447 char *date;
448
449 if((status = get_command(go, errbuf, &command)) != eslOK) return status;
450 if((status = GetDate (errbuf, &date)) != eslOK) return status;
451
452 fprintf(stdout, "%-10s %s\n", "# command:", command);
453 fprintf(stdout, "%-10s %s\n", "# date:", date);
454 fprintf(stdout, "%-10s %" PRIu32 "\n", "# seed:", esl_randomness_GetSeed(cfg->r));
455
456 fprintf(stdout, "#\n");
457 free(command);
458 free(date);
459 return eslOK;
460 }
461
462 /* Function: get_command
463 * Date: EPN, Fri Jan 25 13:56:10 2008
464 *
465 * Purpose: Return the command used to call cmscore
466 * in <ret_command>.
467 *
468 * Returns: eslOK on success; eslEMEM on allocation failure.
469 */
470 int
471 get_command(const ESL_GETOPTS *go, char *errbuf, char **ret_command)
472 {
473 int status;
474 int i;
475 char *command = NULL;
476
477 for (i = 0; i < go->argc; i++) { /* copy all command line options and args */
478 if((status = esl_strcat(&(command), -1, go->argv[i], -1)) != eslOK) goto ERROR;
479 if(i < (go->argc-1)) if((status = esl_strcat(&(command), -1, " ", 1)) != eslOK) goto ERROR;
480 }
481 *ret_command = command;
482
483 return eslOK;
484
485 ERROR:
486 ESL_FAIL(status, errbuf, "get_command(): memory allocation error.");
487 return status;
488 }
489
490 /* collect_scores()
491 *
492 * Generate and score sequences with a CM.
493 *
494 * Two different modes:
495 * 1. generate from the CM.
496 * 2. generated random sequences as either
497 * 25% ACGU (default) or from a hard-coded HMM
498 * that generates genome-like sequences (if
499 * --rhmm).
500 *
501 * Return scores in <ret_scA> and number of scores in
502 * <ret_scN>.
503 */
504 static int
505 collect_scores(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, int N, int L, int *ret_scN, float **ret_scA)
506 {
507 int status;
508 int scN = 0; /* number of hits reported thus far, for all seqs */
509 float *scA = NULL; /* [0..rscN-1] hit scores for all seqs */
510 ESL_DSQ *dsq = NULL; /* digitized sequence to search */
511 int i, h; /* counters */
512 int do_sample; /* TRUE to sample from the CM, FALSE to sample random seqs */
513 void *tmp; /* ptr for ESL_RALLOC */
514 search_results_t *results; /* results (hits) from current sequence */
515 float min_ssc = -eslINFINITY; /* minimum score to collect if(do_sample) */
516 Parsetree_t *tr = NULL;
517
518 /* the HMM that generates sequences for exponential tail fitting */
519 int ghmm_nstates = 0; /* number of states in the HMM */
520 double *ghmm_sA = NULL; /* start probabilities [0..ghmm_nstates-1] */
521 double **ghmm_tAA = NULL; /* transition probabilities [0..nstates-1][0..nstates-1] */
522 double **ghmm_eAA = NULL; /* emission probabilities [0..nstates-1][0..abc->K-1] */
523
524 do_sample = (L == -1) ? TRUE : FALSE;
525 if(do_sample) {
526 min_ssc = (esl_opt_IsUsed(go, "--iT")) ? esl_opt_GetReal(go, "--iT") : -eslINFINITY;
527 }
528
529 /* get HMM for generating random seqs, if nec */
530 if(esl_opt_GetBoolean(go, "--rhmm")) {
531 if((status = CreateGenomicHMM(cm->abc, errbuf, &ghmm_sA, &ghmm_tAA, &ghmm_eAA, &ghmm_nstates)) != eslOK) cm_Fail("ERROR unable to make HMM for generating random seqs");
532 }
533
534 /* Search sequences and collect score histograms */
535 /* Following code block was stolen and modified from cmcalibrate.c */
536
537 scN = 0;
538 for(i = 0; i < N; i++) {
539 /* generate sequence, either randomly from background null or from hard-wired 5 state HMM that emits genome like sequence */
540 if(do_sample) {
541 if((status = sample_sequence_from_cm(cfg, errbuf, cm, &L, &dsq, &tr)) != eslOK) cm_Fail(errbuf);
542 }
543 else { /* generate random sequence, either iid (25% ACGU) or from a 'genome-like' HMM */
544 L = cfg->rL;
545 if(esl_opt_GetBoolean(go, "--rhmm")) {
546 if((status = SampleGenomicSequenceFromHMM(cfg->r, cm->abc, errbuf, ghmm_sA, ghmm_tAA, ghmm_eAA, ghmm_nstates, cfg->rL, &dsq)) != eslOK) cm_Fail(errbuf);
547 }
548 else {
549 ESL_ALLOC(dsq, sizeof(ESL_DSQ) * (cfg->rL+2));
550 if ((status = esl_rsq_xfIID(cfg->r, cm->null, cm->abc->K, cfg->rL, dsq) != eslOK)) cm_Fail("ERROR, couldn't generate random sequence");
551 }
552 }
553
554 /************************************************/
555 /* to print seqs to stdout uncomment this block */
556 /* ESL_SQ *mytmpdsq;
557 mytmpdsq = esl_sq_CreateDigitalFrom(cm->abc, "irrelevant", dsq, cfg->rL, NULL, NULL, NULL);
558 esl_sq_Textize(mytmpdsq);
559 printf(">seq%d\n%s\n", i, mytmpdsq->seq);
560 esl_sq_Destroy(mytmpdsq);
561 fflush(stdout);*/
562 /************************************************/
563
564 if((status = ProcessSearchWorkunit (cm, errbuf, dsq, L,
565 cm->clen, /* guess at average hit len for HMM scanning functions (irrelevant since we don't do HMM functions) */
566 &results, esl_opt_GetReal(go, "--mxsize"), cfg->my_rank)) != eslOK) cm_Fail(errbuf);
567
568 /* Overlaps should have already been removed inside DispatchSearch called by ProcessSearchWorkunit() */
569 RemoveOverlappingHits(results, 1, L);
570
571 if(results->num_results > 0) {
572 if((! do_sample) || (esl_opt_GetBoolean(go, "--iall"))) {
573 /* collect all hits */
574 if(i == 0) ESL_ALLOC (scA, sizeof(float) * (scN + results->num_results));
575 else ESL_RALLOC(scA, tmp, sizeof(float) * (scN + results->num_results));
576 for(h = 0; h < results->num_results; h++) scA[(scN+h)] = results->data[h].score;
577 scN += results->num_results;
578 }
579 else { /* we're sampling and --iall not enabled, only collect top hit */
580 SortResultsByScore(results);
581 if(results->data[0].score > min_ssc) {
582 if(i == 0) ESL_ALLOC (scA, sizeof(float) * (scN + 1));
583 else ESL_RALLOC(scA, tmp, sizeof(float) * (scN + 1));
584 scA[scN] = results->data[0].score;
585 scN++;
586 }
587 }
588 }
589
590 /*printf("i: %4d after nresults: %8d\n", i, results->num_results);
591 for(zz = 0; zz < results->num_results; zz++)
592 printf("%5d %5d %10.3f\n", results->data[zz].start, results->data[zz].stop, results->data[zz].score);
593 fflush(stdout); */
594
595 FreeResults(results);
596 free(dsq);
597 if(tr != NULL) FreeParsetree(tr);
598 }
599 /* free HMM if nec */
600 if(esl_opt_GetBoolean(go, "--rhmm")) {
601 for(i = 0; i < ghmm_nstates; i++) {
602 free(ghmm_eAA[i]);
603 free(ghmm_tAA[i]);
604 }
605 free(ghmm_eAA);
606 free(ghmm_tAA);
607 free(ghmm_sA);
608 }
609
610 *ret_scN = scN;
611 *ret_scA = scA;
612
613 return eslOK;
614
615 ERROR:
616 cm_Fail("Out of memory.");
617 return eslEMEM;
618 }
619
620
621 /* fit_histogram()
622 * Create, fill and fit the tail of a histogram to an exponential tail. Data to fill the histogram
623 * is given as <scores>.
624 */
625 static int
626 fit_histogram(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, float tailp, int do_impt, float *scores, int nscores, int exp_mode, double *ret_mu, double *ret_lambda, double *ret_nrandhits)
627 {
628 int status;
629 double mu;
630 double lambda;
631 int i;
632 double *xv; /* raw data from histogram */
633 int n,z;
634 double params[2];
635 double nrandhits;
636 double scaled_nhits_total;
637 double scaled_nhits_tail;
638
639 ESL_HISTOGRAM *h = NULL; /* histogram of scores */
640
641 /* Initialize histogram; these numbers are guesses */
642 if((h = esl_histogram_CreateFull(-100., 100., .1)) == NULL) return eslEMEM;
643
644 /* fill histogram */
645 for(i = 0; i < nscores; i++) {
646 if((status = esl_histogram_Add(h, scores[i])) != eslOK) ESL_FAIL(status, errbuf, "fit_histogram(), esl_histogram_Add() call returned non-OK status: %d\n", status);
647 /* printf("%4d %.3f\n", i, scores[i]); */
648 }
649
650 /* fit scores to an exponential tail */
651 #if 0
652 if(cfg->rtfitfp != NULL) {
653 /* fit to 41 different tailp values and print lambda, mu to a save file*/
654 fprintf(cfg->exptfitfp, "# %11s %10s %10s %12s\n", "tail pmass", "lambda", "mu", "nhits");
655 fprintf(cfg->exptfitfp, "# %11s %10s %10s %12s\n", "-----------", "----------", "----------", "------------");
656 for(a = 0.; a >= -4.; a -= 0.1) {
657 tailp = pow(10., a);
658 esl_histogram_GetTailByMass(h, tailp, &xv, &n, &z);
659 if(n > 1) {
660 esl_exp_FitComplete(xv, n, &(params[0]), &(params[1]));
661 esl_histogram_SetExpectedTail(h, params[0], tailp, &esl_exp_generic_cdf, &params);
662 fprintf(cfg->exptfitfp, " %.9f %10.6f %10.4f %12d\n", tailp, params[1], params[0], n);
663 }
664 else {
665 fprintf(cfg->exptfitfp, " %.9f %10s %10s %12d\n", tailp, "N/A", "N/A", n);
666 }
667 }
668 fprintf(cfg->exptfitfp, "//\n");
669 }
670 /* end of if cfg->rtfitfp != NULL) */
671 #endif
672
673 esl_histogram_GetTailByMass(h, tailp, &xv, &n, &z); /* fit to right 'tailp' fraction */
674 if(n <= 1) ESL_FAIL(eslERANGE, errbuf, "fit_histogram(), too few points in right tailfit: %f fraction of histogram.", tailp);
675
676 if(do_impt) {
677 /* determine scaled sum of all scores */
678 scaled_nhits_total = 0.;
679 for(i = 0; i < nscores; i++) {
680 scaled_nhits_total += 1. / (pow(2., scores[i]));
681 }
682 //printf("scaled_nhits_total: %.2f\n", scaled_nhits_total);
683 /* fit only tailp tail mass to an exponential */
684 impt_exp_FitComplete(xv, n, &(params[0]), &(params[1]), &scaled_nhits_tail);
685 //printf("scaled_nhits_tail: %.2f\n", scaled_nhits_tail);
686 }
687 else {
688 esl_exp_FitComplete(xv, n, &(params[0]), &(params[1]));
689 }
690 esl_histogram_SetExpectedTail(h, params[0], tailp, &esl_exp_generic_cdf, &params);
691
692 mu = params[0];
693 lambda = params[1];
694 if(isnan(lambda)) ESL_FAIL(eslERANGE, errbuf, "fit_histogram(), exp tail fit lambda is NaN, too few hits in histogram. Increase --rL");
695 if(isinf(lambda)) ESL_FAIL(eslERANGE, errbuf, "fit_histogram(), exp tail fit lambda is inf, too few hits in histogram. Increase --rL");
696
697 if(do_impt) {
698 nrandhits = scaled_nhits_tail;
699 }
700 else {
701 nrandhits = h->n; /* total number of hits in the histogram */
702 }
703 /* print to output files if nec */
704 //if(cfg->exphfp != NULL)
705 //esl_histogram_Plot(cfg->exphfp, h);
706 //if(cfg->expqfp != NULL) {
707 //esl_histogram_PlotQQ(cfg->expqfp, h, &esl_exp_generic_invcdf, params);
708 //}
709
710 //if (cfg->expsfp != NULL) {
711 //esl_histogram_PlotSurvival(cfg->expsfp, h);
712 //esl_exp_Plot(cfg->expsfp, (params[0] - log(1./tailp) / params[1]), 0.693147, esl_exp_surv, h->xmin - 5., h->xmax + 5., 0.1); /* extrapolate mu */
713 //}
714
715 esl_histogram_Destroy(h);
716
717 *ret_mu = mu;
718 *ret_lambda = lambda;
719 *ret_nrandhits = nrandhits;
720 return eslOK;
721 }
722
723 /* Function: sample_sequence_from_cm()
724 * Date: EPN, Mon May 2 08:44:53 2011
725 *
726 * Purpose: Generate a dsq from a CM and return it.
727 *
728 * Returns: eslOK on success, ESL_DSQ is filled with newly alloc'ed dsq; some other status code on an error,
729 */
730 int sample_sequence_from_cm(struct cfg_s *cfg, char *errbuf, CM_t *cm, int *ret_L, ESL_DSQ **ret_dsq, Parsetree_t **ret_tr)
731 {
732 int status;
733 int L;
734 ESL_SQ *sq;
735 ESL_DSQ *dsq;
736 Parsetree_t *tr = NULL;
737
738 if((status = EmitParsetree(cm, errbuf, cfg->r, "irrelevant", TRUE, &tr, &sq, &L)) != eslOK) return status;
739 while(L == 0) {
740 esl_sq_Destroy(sq);
741 if((status = EmitParsetree(cm, errbuf, cfg->r, "irrelevant", TRUE, &tr, &sq, &L)) != eslOK) return status;
742 }
743
744 ESL_ALLOC(dsq, sizeof(ESL_DSQ) * (sq->n+2));
745 memcpy(dsq, sq->dsq, sizeof(ESL_DSQ) * (sq->n+2));
746
747 esl_sq_Destroy(sq);
748
749 *ret_L = L;
750 *ret_dsq = dsq;
751 *ret_tr = tr;
752
753 return eslOK;
754
755 ERROR:
756 cm_Fail("Out of memory.");
757 return eslEMEM;
758 }
759
760
761 /* Function: impt_exp_FitComplete()
762 * Incept: SRE, Wed Aug 10 10:53:47 2005 [St. Louis]
763 *
764 * Purpose: Given an array of <n> samples <x[0]..x[n-1]>, fit
765 * them to an exponential distribution.
766 * Return maximum likelihood parameters <ret_mu> and <ret_lambda>.
767 *
768 * Args: x - complete exponentially-distributed data [0..n-1]
769 * n - number of samples in <x>
770 * ret_mu - RETURN: lower bound of the distribution (all x_i >= mu)
771 * ret_lambda - RETURN: maximum likelihood estimate of lambda
772 * ret_scaled_nhits - RETURN: sum of scaled number of hits
773 *
774 * Returns: <eslOK> on success.
775 *
776 * Xref: STL9/138.
777 */
778 int
779 impt_exp_FitComplete(double *x, int n, double *ret_mu, double *ret_lambda, double *ret_scaled_nhits)
780 {
781 double mu, mean;
782 int i;
783
784 double scaled_x = 0;
785 double scaled_n = 0;
786 double diff = 0;
787
788 /* ML mu is the lowest score. mu=x is ok in the exponential.
789 */
790 mu = x[0];
791 for (i = 1; i < n; i++) if (x[i] < mu) mu = x[i];
792
793 mean = 0.;
794 for (i = 0; i < n; i++) {
795 diff = x[i] - mu;
796 scaled_x = 1. / (pow(2., x[i]));
797 mean += diff * scaled_x;
798 scaled_n += scaled_x;
799
800 /*printf("\t\ti: %4d x[i]: %12.10f diff: %12.10f scaled_x: %12.10f prod: %12.10f scaled_n: %12.10f\n",
801 i, x[i], diff, scaled_x, diff*scaled_x, scaled_n);*/
802 }
803 mean /= scaled_n;
804
805 //printf("impt n: %d\n", n);
806 //printf("impt scaled_n: %.3f\n", scaled_n);
807 //printf("impt mu: %.3f\n", mu);
808 //printf("impt lambda: %.3f\n", 1./mean);
809
810 *ret_mu = mu;
811 *ret_lambda = 1./mean; /* ML estimate trivial & analytic */
812 *ret_scaled_nhits = scaled_n; /* number of scaled hits */
813 return eslOK;
814 }