Debian Codegraph @

src/cmcalibrate.c

raw symbols SCIP
1 /* cmcalibrate: score a CM against random sequence data to fit
2 * exponential tail parameters for E-value determination.
3 *
4 * EPN, Thu Dec 15 19:40:16 2011 [Updated for v1.1 (removed CP9 and fthr)]
5 * EPN, Wed May 2 07:02:52 2007
6 * based on HMMER-2.3.2's hmmcalibrate.c from SRE
7 */
8
9 #include <esl_config.h>
10 #include <p7_config.h>
11 #include "config.h"
12
13 #include <assert.h>
14 #include <limits.h>
15 #include <math.h>
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <signal.h>
20 #include <time.h>
21
22 #include "easel.h"
23 #include "esl_alphabet.h"
24 #include "esl_dmatrix.h"
25 #include "esl_exponential.h"
26 #include "esl_getopts.h"
27 #include "esl_histogram.h"
28 #include "esl_mpi.h"
29 #include "esl_random.h"
30 #include "esl_randomseq.h"
31 #include "esl_ratematrix.h"
32 #include "esl_stack.h"
33 #include "esl_stopwatch.h"
34 #include "esl_vectorops.h"
35
36 #ifdef HAVE_MPI
37 #include "mpi.h"
38 #include "esl_mpi.h"
39 #endif /*HAVE_MPI*/
40
41 #ifdef HMMER_THREADS
42 #include <unistd.h>
43 #include "esl_threads.h"
44 #include "esl_workqueue.h"
45 #endif /*HMMER_THREADS*/
46
47 #include "hmmer.h"
48
49 #include "infernal.h"
50
51 #define REALLYSMALLX 1e-20
52 #define EXPTAIL_CHUNKLEN 10000 /* sequence chunk length for random sequence searches */
53 #define DEBUGMPI 0
54 #define INS_V_CYK_GUESS 3.0 /* ratio of time required for inside versus CYK used if --noforecast enabled */
55
56 typedef struct {
57 #ifdef HMMER_THREADS
58 ESL_WORK_QUEUE *queue;
59 #endif /*HMMER_THREADS*/
60 CM_t *cm; /* a covariance model */
61 float *scA; /* vector of scores of hits */
62 int64_t nhits; /* number of hits in scA */
63 float cutoff; /* minimum hit score to keep */
64 int nequals; /* number of '=' to print for current mode */
65 int ipart; /* partition index if --part, else -1 */
66 int npart; /* total num partitions if --part, else -1 */
67 } WORKER_INFO;
68
69 #if defined (HMMER_THREADS) && defined (HAVE_MPI)
70 #define CPUOPTS "--mpi,--forecast,--memreq"
71 #define MPIOPTS "--cpu,--forecast,--memreq"
72 #else
73 #define CPUOPTS "--forecast,--memreq"
74 #define MPIOPTS "--forecast,--memreq"
75 #endif
76
77 static ESL_OPTIONS options[] = {
78 /* name type default env range toggles reqs incomp help docgroup*/
79 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 1 },
80 { "-L", eslARG_REAL, "1.6", NULL, "0.01<=x<=160.", NULL, NULL, NULL, "set random seq length to search in Mb to <x>", 1 },
81 /* Options for predicting running time and memory requirements */
82 { "--forecast", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "don't do calibration, predict running time and exit", 2 },
83 { "--nforecast", eslARG_INT, NULL, NULL, "n>0", NULL, "--forecast", NULL, "w/--forecast, predict time with <n> processors (maybe for MPI)", 2 },
84 { "--memreq", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "don't do calibration, print required memory and exit", 2 },
85 { "--noforecast", eslARG_NONE, NULL, NULL, NULL, NULL, NULL,"--forecast", "do calibration, but skip running time prediction", 2 },
86 /* Options controlling exponential tail fits */
87 { "--gtailn", eslARG_INT, "250", NULL, "n>=100", NULL, NULL, "--tailp", "fit the top <n> hits/Mb in histogram for glocal modes [df: 250]", 3 },
88 { "--ltailn", eslARG_INT, "750", NULL, "n>=100", NULL, NULL, "--tailp", "fit the top <n> hits/Mb in histogram for local modes [df: 750]", 3 },
89 { "--tailp", eslARG_REAL, NULL, NULL, "0.0<x<0.6", NULL, NULL, NULL, "set fraction of histogram tail to fit to exp tail to <x>", 3 },
90 /* Optional output files */
91 { "--hfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save fitted score histogram(s) to file <f>", 4 },
92 { "--sfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save survival plot to file <f>", 4 },
93 { "--qqfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save Q-Q plot for score histograms to file <f>", 4 },
94 { "--ffile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save lambdas for different tail fit probs to file <f>", 4 },
95 { "--xfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save scores in fit tail to file <f>", 4 },
96 /* Options for split or partition or merge modes */
97 { "--split", eslARG_NONE, NULL, NULL, NULL, NULL,"--ptot,--cfile", "--forecast", "prepare partitioned calibration", 5 },
98 { "--cfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, "--split", NULL, "with --split, save file with commands for each partition to <f>", 5 },
99 { "--cbash", eslARG_NONE, NULL, NULL, NULL, NULL, "--cfile", NULL, "with --split, output commands as a bash for loop script", 5 },
100 { "--proot", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "with --split or --merge, root for partition output files is <s>", 5 },
101 { "--part", eslARG_INT, NULL, NULL, "n>0", NULL,"--ptot,--pfile", NULL, "this is partition number <n> (1..<n2> from --ptot <n2>)", 5 },
102 { "--ptot", eslARG_INT, NULL, NULL, "n>0", NULL, NULL, NULL, "total number of partitions is <n>", 5 },
103 { "--pfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, "--part", "--split", "with --part, save scores to file <f>", 5 },
104 { "--merge", eslARG_NONE, NULL, NULL, NULL, NULL, "--ptot", "--forecast", "merge scores from multiple partitions for calibration", 5 },
105 /* Other options: */
106 { "--seed", eslARG_INT, "181", NULL, "n>=0", NULL, NULL, NULL, "set RNG seed to <n> (if 0: one-time arbitrary seed)", 6 },
107 { "--beta", eslARG_REAL, "1E-15", NULL, "x>0", NULL, NULL, NULL, "set tail loss prob for query dependent banding (QDB) to <x>", 6 },
108 { "--nonbanded", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--beta", "do not use QDB", 6 },
109 { "--nonull3", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "turn OFF the NULL3 post hoc additional null model", 6 },
110 { "--random", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "use GC content of random null background model of CM", 6 },
111 { "--gc", eslARG_INFILE, NULL, NULL, NULL, NULL, NULL, NULL, "use GC content distribution from file <f>", 6 },
112 #ifdef HMMER_THREADS
113 { "--cpu", eslARG_INT, CMNCPU, "INFERNAL_NCPU", "n>=0", NULL, NULL, CPUOPTS, "number of parallel CPU workers to use for multithreads", 6 },
114 #endif
115 #ifdef HAVE_MPI
116 { "--mpi", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, MPIOPTS, "run as an MPI parallel program", 6 },
117 { "--stall", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "arrest after start: for debugging MPI under gdb", 6 },
118 #endif
119 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
120 };
121
122 struct cfg_s {
123 char *cmfile; /* name of input CM file */
124 ESL_RANDOMNESS *r; /* random number generator, for sequences to search */
125 ESL_RANDOMNESS *r_est; /* random number generator, for sequences used in time estimates */
126 ESL_ALPHABET *abc; /* alphabet */
127 ESL_STOPWATCH *w; /* stopwatch for each calibration */
128 double *gc_freq; /* gc frequence [0..100], only used if --gc */
129 ExpInfo_t ***expAA; /* the exponential tail info, 1st dim: 1 for each CM, 2nd dim: EXP_NMODES */
130 char **namesA; /* names of all the CMs we'll calibrate */
131 char **comlogsA; /* comlog for each CM, only relevant if --merge */
132 int ncm; /* what number CM we're on */
133 int cmalloc; /* number of expAA we have allocated (1st dim) */
134 char *tmpfile; /* tmp file we're writing to */
135 char *mode; /* write mode, "w" or "wb" */
136 double *dnull; /* double version of cm->null, for generating random seqs */
137 float sc_cutoff; /* minimum score of a hit we'll consider (-eslINFINITY by default) */
138
139 /* the HMM that generates sequences for exponential tail fitting */
140 int ghmm_nstates; /* number of states in the HMM */
141 double *ghmm_sA; /* start probabilities [0..ghmm_nstates-1] */
142 double **ghmm_tAA; /* transition probabilities [0..nstates-1][0..nstates-1] */
143 double **ghmm_eAA; /* emission probabilities [0..nstates-1][0..abc->K-1] */
144
145 /* number of sequences and the length of each seq for exp tail
146 * fitting, set such that: exp_cmN is the number of 10 Kb
147 * seqs we'll search for CM local/glocal exponential tail fitting:
148 *
149 * N = (esl_opt_GetBoolean(go, "-L") * 10^6) / EXPTAIL_CHUNKLEN(10000);
150 *
151 * We don't search just 1 long sequence (i.e. 1.5 Mb) b/c using
152 * sequence lengths above 10 Kb for exp tail calibration can yield
153 * millions of hits (for CM searches) before overlaps are removed,
154 * which requires a lot of memory.
155 */
156 int N; /* number of 10 Kb seqs for local CM exp tail fitting */
157 int L; /* the size of seq chunks to search, set as 10,000 (10 Kb) */
158
159 /* mpi */
160 int do_mpi;
161 int my_rank;
162 int nproc;
163 int do_stall; /* TRUE to stall the program until gdb attaches */
164
165 /* partition */
166 int do_part; /* TRUE if --part, we won't fit any histograms */
167
168 /* Masters only (i/o streams) */
169 CM_FILE *cmfp; /* open input CM file stream */
170 FILE *hfp; /* optional output for exp tail histograms */
171 FILE *sfp; /* optional output for exp tail survival plot */
172 FILE *qfp; /* optional output for exp tail QQ file */
173 FILE *ffp; /* optional output for exp tail fit file */
174 FILE *xfp; /* optional output for exp tail fit scores */
175 FILE *cfp; /* optional output for commands in split mode */
176 FILE *pfp; /* optional output for scores files with --part mode */
177 };
178
179 static char usage[] = "[-options] <cmfile>";
180 static char banner[] = "fit exponential tails for CM E-values";
181
182 static void serial_master(ESL_GETOPTS *go, struct cfg_s *cfg);
183 static int serial_loop (WORKER_INFO *info, char *errbuf, ESL_SQ_BLOCK *sq_block);
184
185 #ifdef HMMER_THREADS
186 #define BLOCK_SIZE 150
187 static int thread_loop(WORKER_INFO *info, char *errbuf, ESL_THREADS *obj, ESL_WORK_QUEUE *queue, ESL_SQ_BLOCK *sq_block);
188 static void pipeline_thread(void *arg);
189 #endif /*HMMER_THREADS*/
190
191 #ifdef HAVE_MPI
192 static int mpi_master (ESL_GETOPTS *go, struct cfg_s *cfg);
193 static int mpi_worker (ESL_GETOPTS *go, struct cfg_s *cfg);
194 static void mpi_failure (char *format, ...);
195 #define INFERNAL_ERROR_TAG 1
196 #define INFERNAL_SEQIDX_TAG 2
197 #define INFERNAL_SCORES_TAG 3
198 #define INFERNAL_TERMINATING_TAG 4
199 #define INFERNAL_READY_TAG 5
200 #endif /*HAVE_MPI*/
201
202 /* Functions to avoid code duplication for common tasks */
203 static void process_commandline(int argc, char **argv, ESL_GETOPTS **ret_go, char **ret_cmfile);
204 static int output_header(FILE *ofp, const ESL_GETOPTS *go, char *cmfile, int relevant_ncpus, int ncpus);
205 static int init_master_cfg (const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf);
206 static int init_shared_cfg (const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf);
207 static int initialize_cm (const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, int do_local);
208 static int initialize_stats(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf);
209 static int fit_histogram(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, float *scores, int nscores, int exp_mode, double *ret_mu, double *ret_lambda, int *ret_nrandhits, float *ret_tailp);
210 static int get_random_dsq(const struct cfg_s *cfg, char *errbuf, CM_t *cm, int L, ESL_RANDOMNESS *r, ESL_DSQ **ret_dsq);
211 static int set_dnull(struct cfg_s *cfg, CM_t *cm, char *errbuf);
212 static void print_calibration_column_headings(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm, int relevant_ncpus);
213 static void print_forecasted_time(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm, double psec);
214 static void print_total_time(const ESL_GETOPTS *go, double total_asec, double total_psec);
215 static void print_summary(const struct cfg_s *cfg);
216 static int expand_exp_and_name_arrays(struct cfg_s *cfg);
217 static int generate_sequences(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, ESL_SQ_BLOCK **ret_sq_block);
218 static int process_search_workunit(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float cutoff, CM_TOPHITS **ret_th);
219 static int forecast_time(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, int ncpus, int relevant_ncpus, double *ret_psec, int *ret_ins_v_cyk);
220 static void print_required_memory(CM_t *cm, int L, int N, int ncpus, int do_header, int do_nonbanded);
221 static void print_required_memory_tail(int ncpus);
222 static int read_partition_scores_files_for_one_cm(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, int cmi, float ***ret_pmerged_scAAA, int64_t **ret_pmerged_nhitsAA);
223
224 int
225 main(int argc, char **argv)
226 {
227 int status = eslOK;
228
229 ESL_GETOPTS *go = NULL; /* command line processing */
230 struct cfg_s cfg; /* configuration data */
231 char errbuf[eslERRBUFSIZE];
232 int i, i2;
233 ESL_STOPWATCH *w = esl_stopwatch_Create();
234 if(w == NULL) cm_Fail("Memory allocation error, stopwatch could not be created.");
235 esl_stopwatch_Start(w);
236
237 /* variables related to --split and --part */
238 int do_split; /* is --split used? */
239 int npart; /* value from --ptot */
240 int do_part; /* is --part used? */
241 CM_t *cm = NULL; /* the CM, only filled if --split */
242
243 /* variables used if do_split to recreate options string */
244 char *cmdopt = NULL; /* command line string */
245 int optlen = 0; /* length of option string */
246 int n = 0; /* token length */
247
248 /* Set processor specific flags */
249 impl_Init();
250
251 /* Initialize what we can in the config structure (without knowing the alphabet yet)
252 */
253 cfg.cmfile = NULL;
254 cfg.do_mpi = FALSE; /* this gets reset below, if we init MPI */
255 cfg.nproc = 0; /* this gets reset below, if we init MPI */
256 cfg.my_rank = 0; /* this gets reset below, if we init MPI */
257 cfg.r = NULL;
258 cfg.r_est = NULL;
259 cfg.abc = NULL;
260 cfg.w = NULL;
261 cfg.cmalloc = 128;
262 cfg.tmpfile = NULL;
263 cfg.mode = NULL;
264 cfg.dnull = NULL;
265 cfg.gc_freq = NULL;
266 cfg.ghmm_nstates = 0;
267 cfg.ghmm_sA = NULL;
268 cfg.ghmm_tAA = NULL;
269 cfg.ghmm_eAA = NULL;
270 cfg.ncm = 0;
271 cfg.L = EXPTAIL_CHUNKLEN; /* 10 Kb chunks are searched */
272 cfg.N = 0; /* gets set below, after go is setup */
273 cfg.cmfp = NULL; /* remains NULL for mpi workers */
274 cfg.hfp = NULL; /* remains NULL for mpi workers */
275 cfg.sfp = NULL; /* remains NULL for mpi workers */
276 cfg.qfp = NULL; /* remains NULL for mpi workers */
277 cfg.ffp = NULL; /* remains NULL for mpi workers */
278 cfg.xfp = NULL; /* remains NULL for mpi workers */
279 cfg.cfp = NULL; /* remains NULL for mpi workers */
280 cfg.pfp = NULL; /* remains NULL for mpi workers */
281
282 ESL_ALLOC(cfg.expAA, sizeof(ExpInfo_t **) * cfg.cmalloc); /* this will grow if needed */
283 ESL_ALLOC(cfg.namesA, sizeof(char *) * cfg.cmalloc); /* this will grow if needed */
284 ESL_ALLOC(cfg.comlogsA, sizeof(char *) * cfg.cmalloc); /* this will grow if needed */
285 for(i = 0; i < cfg.cmalloc; i++) cfg.expAA[i] = NULL;
286 for(i = 0; i < cfg.cmalloc; i++) cfg.namesA[i] = NULL;
287 for(i = 0; i < cfg.cmalloc; i++) cfg.comlogsA[i] = NULL;
288
289 ESL_DASSERT1((EXP_CM_GC == 0));
290 ESL_DASSERT1((EXP_CM_GI == 1));
291 ESL_DASSERT1((EXP_CM_LC == 2));
292 ESL_DASSERT1((EXP_CM_LI == 3));
293 ESL_DASSERT1((EXP_NMODES == 4));
294
295 /* Initializations */
296 init_ilogsum();
297 FLogsumInit();
298 process_commandline(argc, argv, &go, &(cfg.cmfile));
299 cfg.N = (int) (((esl_opt_GetReal(go, "-L") * 1000000.) / (float) cfg.L) + 0.5);
300
301 /* If --part, open --pfile file */
302 do_part = esl_opt_IsUsed(go, "--part") ? TRUE : FALSE;
303 if(do_part) {
304 if (esl_opt_GetString(go, "--pfile") != NULL) {
305 if ((cfg.pfp = fopen(esl_opt_GetString(go, "--pfile"), "w")) == NULL) {
306 ESL_FAIL(eslFAIL, errbuf, "Failed to open partition score file %s for writing\n", esl_opt_GetString(go, "--pfile"));
307 }
308 }
309 else {
310 ESL_FAIL(eslFAIL, errbuf, "--pfile is required in combination with --part\n");
311 }
312 }
313
314 /* Deal with --split if nec */
315 do_split = esl_opt_GetBoolean(go, "--split");
316 if(do_split) {
317 npart = esl_opt_GetInteger(go, "--ptot");
318 if(cfg.N < npart) {
319 ESL_FAIL(eslFAIL, errbuf, "Trying to split into %d partitions, but only have %d sequences, retry with <= %d partitions\n", npart, cfg.N, cfg.N);
320 }
321 if (esl_opt_GetString(go, "--cfile") != NULL) {
322 if ((cfg.cfp = fopen(esl_opt_GetString(go, "--cfile"), "w")) == NULL)
323 ESL_FAIL(eslFAIL, errbuf, "Failed to open command file %s for writing\n", esl_opt_GetString(go, "--cfile"));
324 }
325 else {
326 ESL_FAIL(eslFAIL, errbuf, "--cfile is required in combination with --split\n");
327 }
328
329 /* make sure the CM file exists and we can read it */
330 /* open CM file */
331 if((status = cm_file_Open(cfg.cmfile, NULL, FALSE, &(cfg.cmfp), errbuf)) != eslOK) cm_Fail(errbuf);
332 if((status = cm_file_Read(cfg.cmfp, TRUE, &(cfg.abc), &cm)) != eslOK) cm_Fail(cfg.cmfp->errbuf);
333 if(cm != NULL) FreeCM(cm);
334
335 output_header(stdout, go, cfg.cmfile, 0, cfg.nproc); /* 0 is 'relevant_ncpus', normally not important, only used if --forecast, which is incompatible with --split */
336 /* get command line options, code adapted from esl_opt_SpoofCmdline */
337 /* Application name/path */
338 optlen = strlen(go->argv[0]) + 1; // +1 for the space
339 ESL_ALLOC(cmdopt, sizeof(char) * (optlen+1));
340 snprintf(cmdopt, optlen+1, "%s ", go->argv[0]);
341 for (i = 0; i < go->nopts; i++) {
342 /* skip --split, --cfile, --proot, --cbash options */
343 if((strcmp(go->opt[i].name, "--split") != 0) &&
344 (strcmp(go->opt[i].name, "--cfile") != 0) &&
345 (strcmp(go->opt[i].name, "--cbash") != 0) &&
346 (strcmp(go->opt[i].name, "--proot"))) {
347 if (go->setby[i] != eslARG_SETBY_DEFAULT) {
348 if (go->opt[i].type == eslARG_NONE) n = strlen(go->opt[i].name) + 1;
349 else n = (strlen(go->opt[i].name) + strlen(go->val[i])) + 2;
350 ESL_REALLOC(cmdopt, sizeof(char) * (optlen + n + 1));
351
352 if (go->opt[i].type == eslARG_NONE) snprintf(cmdopt + optlen, n+1, "%s ", go->opt[i].name);
353 else snprintf(cmdopt + optlen, n+1, "%s %s ", go->opt[i].name, go->val[i]);
354
355 optlen += n;
356 }
357 }
358 }
359
360 if(esl_opt_GetBoolean(go, "--cbash")) {
361 fprintf(cfg.cfp, "# !/bin/bash\n");
362 fprintf(cfg.cfp, "for ((i = 1; i <= %d; i++)); do\n", esl_opt_GetInteger(go, "--ptot"));
363 fprintf(cfg.cfp, " %s--part $i --pfile %s.%s$i %s\n",
364 cmdopt, /* executable and options, will include --ptot */
365 esl_opt_IsUsed(go, "--proot") ? esl_opt_GetString(go, "--proot") : cfg.cmfile, /* root of output file */
366 esl_opt_IsUsed(go, "--proot") ? "" : "calib.", /* "calib." unless --proot used */
367 cfg.cmfile); /* cm file name */
368 fprintf(cfg.cfp, "done\n");
369 }
370 else { /* --cbash not used, list each command on separate line */
371 for(i = 1; i <= npart; i++) {
372 fprintf(cfg.cfp, "%s--part %d --pfile %s.%s%d %s\n",
373 cmdopt, /* executable and options, will include --ptot */
374 i,
375 esl_opt_IsUsed(go, "--proot") ? esl_opt_GetString(go, "--proot") : cfg.cmfile, /* root of output file */
376 esl_opt_IsUsed(go, "--proot") ? "" : "calib.", /* "calib." unless --proot used */
377 i, /* index of this partition */
378 cfg.cmfile); /* cm file name */
379 }
380 }
381 }
382 else { /* ! do_split */
383 /* Figure out who we are, and send control there:
384 * we might be an MPI master, an MPI worker, or a serial program.
385 */
386 #ifdef HAVE_MPI
387
388 #if eslDEBUGLEVEL >= 1
389 pid_t pid;
390 pid = getpid();
391 printf("#DEBUG: The process id is %d\n", pid);
392 fflush(stdout);
393 #endif
394
395 /* pause the execution of the programs execution until the user has a
396 * chance to attach with a debugger and send a signal to resume execution
397 * i.e. (gdb) signal SIGCONT
398 */
399 if (esl_opt_GetBoolean(go, "--stall")) pause();
400
401 if (esl_opt_GetBoolean(go, "--mpi"))
402 {
403 /* make sure --part is not used (they're not set as incompatible because --mpi is not always a valid option) */
404 if(esl_opt_IsUsed(go, "--part")) {
405 cm_Fail("--part and --mpi are incompatible, rerun cmcalibrate --split without --mpi");
406 }
407
408 cfg.do_mpi = TRUE;
409 MPI_Init(&argc, &argv);
410 MPI_Comm_rank(MPI_COMM_WORLD, &(cfg.my_rank));
411 MPI_Comm_size(MPI_COMM_WORLD, &(cfg.nproc));
412
413 if(cfg.nproc == 1) cm_Fail("MPI mode, but only 1 processor running... (did you execute mpirun?)");
414
415 if (cfg.my_rank > 0) status = mpi_worker(go, &cfg);
416 else status = mpi_master(go, &cfg);
417
418 MPI_Finalize();
419 }
420 else
421 #endif /*HAVE_MPI*/
422 {
423 serial_master(go, &cfg);
424 }
425 } /* end of 'else' entered if !do_split */
426 if(cfg.my_rank == 0 &&
427 (! esl_opt_IsUsed(go, "--forecast")) &&
428 (! esl_opt_IsUsed(go, "--memreq")) &&
429 (! do_split) &&
430 (! do_part)) { /* master, serial or mpi (not --split and not --part) */
431
432 /* before writing new CM file, output summary statistics (this requires cfg->expAA) */
433 print_summary(&cfg);
434
435 /* Rewind the CM file for a second pass.
436 * Write a temporary CM file with new stats information in it
437 */
438 int status;
439 int cmi;
440 CM_t *cm;
441 FILE *outfp;
442 sigset_t blocksigs; /* list of signals to protect from */
443
444 cm_file_Position(cfg.cmfp, (off_t) 0);
445
446 if (esl_FileExists(cfg.tmpfile)) cm_Fail("Ouch. Temporary file %s appeared during the run.", cfg.tmpfile);
447 if ((outfp = fopen(cfg.tmpfile, cfg.mode)) == NULL) cm_Fail("Ouch. Temporary file %s couldn't be opened for writing.", cfg.tmpfile);
448
449 for (cmi = 0; cmi < cfg.ncm; cmi++) {
450 if ((status = cm_file_Read(cfg.cmfp, TRUE, &(cfg.abc), &cm)) != eslOK) cm_Fail("Ran out of CMs too early in pass 2");
451 if (cm == NULL) cm_Fail("CM file %s was corrupted? Parse failed in pass 2", cfg.cmfile);
452
453 if(cm->expA != NULL) {
454 for(i = 0; i < EXP_NMODES; i++) {
455 free(cm->expA[i]);
456 }
457 free(cm->expA);
458 }
459
460 cm->expA = cfg.expAA[cmi];
461 cm->flags |= CMH_EXPTAIL_STATS;
462
463 if(esl_opt_GetBoolean(go, "--merge")) {
464 status = esl_strcat(&cm->comlog, -1, "\n", -1);
465 status = esl_strcat(&cm->comlog, -1, cfg.comlogsA[cmi], -1);
466 if(status != eslOK) cm_Fail("Problem copying comlog from partition score files to CM file");
467 }
468
469 cm_AppendComlog(cm, go->argc, go->argv, FALSE, 0); /* we don't check return status, it should be fine, but if not, we don't want to die now... */
470
471 if(cfg.cmfp->is_binary) {
472 if ((status = cm_file_WriteBinary(outfp, -1, cm, NULL)) != eslOK) ESL_FAIL(status, errbuf, "binary CM save failed");
473 }
474 else {
475 if ((status = cm_file_WriteASCII(outfp, -1, cm)) != eslOK) ESL_FAIL(status, errbuf, "CM save failed");
476 }
477 FreeCM(cm);
478 } /* end of from idx = 0 to ncm */
479
480 /* Now, carefully remove original file and replace it
481 * with the tmpfile. Note the protection from signals;
482 * we wouldn't want a user to ctrl-C just as we've deleted
483 * their CM file but before the new one is moved.
484 */
485 cm_file_Close(cfg.cmfp);
486 if (fclose(outfp) != 0) cm_Fail("system error during rewrite of CM file");
487 if (sigemptyset(&blocksigs) != 0) cm_Fail("system error during rewrite of CM file.");
488 if (sigaddset(&blocksigs, SIGINT) != 0) cm_Fail("system error during rewrite of CM file.");
489 if (sigprocmask(SIG_BLOCK, &blocksigs, NULL) != 0) cm_Fail("system error during rewrite of CM file.");
490 if (remove(cfg.cmfile) != 0) cm_Fail("system error during rewrite of CM file.");
491 if (rename(cfg.tmpfile, cfg.cmfile) != 0) cm_Fail("system error during rewrite of CM file.");
492 if (sigprocmask(SIG_UNBLOCK, &blocksigs, NULL) != 0) cm_Fail("system error during rewrite of CM file.");
493 free(cfg.tmpfile);
494 cfg.tmpfile = NULL;
495
496 /* master specific cleaning */
497 if (cfg.hfp || cfg.sfp || cfg.qfp || cfg.ffp || cfg.xfp || cfg.cfp) printf("#\n");
498
499 if (cfg.hfp != NULL) {
500 fclose(cfg.hfp);
501 printf("# Histogram of high scoring hits in random seqs saved to file %s.\n", esl_opt_GetString(go, "--hfile"));
502 }
503 if (cfg.sfp != NULL) {
504 fclose(cfg.sfp);
505 printf("# Survival plot for exponential tails saved to file %s.\n", esl_opt_GetString(go, "--sfile"));
506 }
507 if (cfg.qfp != NULL) {
508 fclose(cfg.qfp);
509 printf("# Exponential tail QQ plots saved to file %s.\n", esl_opt_GetString(go, "--qqfile"));
510 }
511 if (cfg.ffp != NULL) {
512 fclose(cfg.ffp);
513 printf("# Exponential tail fit points saved to file %s.\n", esl_opt_GetString(go, "--ffile"));
514 }
515 if (cfg.xfp != NULL) {
516 fclose(cfg.xfp);
517 printf("# Scores from tail fits saved to file %s.\n", esl_opt_GetString(go, "--xfile"));
518 }
519
520 if (cfg.expAA != NULL) free(cfg.expAA);
521 if (cfg.namesA != NULL) { for(i = 0; i < cfg.cmalloc; i++) if(cfg.namesA[i] != NULL) free(cfg.namesA[i]); free(cfg.namesA); }
522 if (cfg.comlogsA != NULL) { for(i = 0; i < cfg.cmalloc; i++) if(cfg.comlogsA[i] != NULL) free(cfg.comlogsA[i]); free(cfg.comlogsA); }
523 } /* end of if(cfg.my_rank == 0 && (! esl_opt_IsUsed(go, "--forecast")) && (! esl_opt_IsUsed(go, "--memreq")) && (! do_split)) */
524 else { /* non-master, --forecast, --memreq, --part and --split -specific cleaning */
525 if (cfg.cmfp != NULL) cm_file_Close(cfg.cmfp);
526 if (cfg.expAA != NULL) { for(i = 0; i < cfg.cmalloc; i++) if(cfg.expAA[i] != NULL) { for(i2 = 0; i2 < EXP_NMODES; i2++) { free(cfg.expAA[i][i2]); } free(cfg.expAA[i]); } free(cfg.expAA); }
527 if (cfg.namesA != NULL) { for(i = 0; i < cfg.cmalloc; i++) if(cfg.namesA[i] != NULL) free(cfg.namesA[i]); free(cfg.namesA); }
528 if (cfg.comlogsA != NULL) { for(i = 0; i < cfg.cmalloc; i++) if(cfg.comlogsA[i] != NULL) free(cfg.comlogsA[i]); free(cfg.comlogsA); }
529 if (cfg.pfp != NULL) {
530 fclose(cfg.pfp);
531 printf("# Scores for this partition for later merge saved to file %s.\n", esl_opt_GetString(go, "--pfile"));
532 }
533 if (cfg.cfp != NULL) {
534 fclose(cfg.cfp);
535 printf("# List of commands for each partition saved to file %s.\n", esl_opt_GetString(go, "--cfile"));
536 printf("#\n");
537 printf("# Command to merge per-partition scores after all commands are finished:\n");
538 printf("# %s --merge --ptot %d %s%s%s%s\n",
539 go->argv[0], /* cmcalibrate command */
540 esl_opt_GetInteger(go, "--ptot"), /* --ptot <n> option */
541 esl_opt_IsUsed(go, "--proot") ? "--proot " : "",
542 esl_opt_IsUsed(go, "--proot") ? esl_opt_GetString(go, "--proot") : "",
543 esl_opt_IsUsed(go, "--proot") ? " " : "",
544 cfg.cmfile);
545 }
546 }
547
548 /* clean up */
549 if (cfg.abc != NULL) esl_alphabet_Destroy(cfg.abc);
550 if (cfg.w != NULL) esl_stopwatch_Destroy(cfg.w);
551 if (cfg.r != NULL) esl_randomness_Destroy(cfg.r);
552 if (cfg.r_est != NULL) esl_randomness_Destroy(cfg.r_est);
553 if (cfg.gc_freq != NULL) free(cfg.gc_freq);
554 if (cfg.tmpfile != NULL) free(cfg.tmpfile);
555 if (cfg.dnull != NULL) free(cfg.dnull);
556 if (cfg.ghmm_sA != NULL) free(cfg.ghmm_sA);
557 if (cfg.ghmm_tAA != NULL) { for(i = 0; i < cfg.ghmm_nstates; i++) if(cfg.ghmm_tAA[i] != NULL) free(cfg.ghmm_tAA[i]); free(cfg.ghmm_tAA); }
558 if (cfg.ghmm_eAA != NULL) { for(i = 0; i < cfg.ghmm_nstates; i++) if(cfg.ghmm_eAA[i] != NULL) free(cfg.ghmm_eAA[i]); free(cfg.ghmm_eAA); }
559 if (cmdopt != NULL) free(cmdopt);
560
561 esl_stopwatch_Stop(w);
562 if (cfg.my_rank == 0) {
563 printf("#\n");
564 esl_stopwatch_Display(stdout, w, "# CPU time: ");
565 printf("[ok]\n");
566 }
567
568 esl_stopwatch_Destroy(w);
569 esl_getopts_Destroy(go);
570 return eslOK;
571
572 ERROR:
573 cm_Fail("Memory allocation error.");
574 return status; /* NEVERREACHED */
575 }
576
577 /* serial_master()
578 * The serial version of cmcalibrate.
579 *
580 * A master can only return if it's successful. All errors are handled immediately and fatally with cm_Fail().
581 */
582 static void
583 serial_master(ESL_GETOPTS *go, struct cfg_s *cfg)
584 {
585 int status; /* Easel status */
586 int qhstatus = eslOK; /* status from cm_file_Read() */
587 char errbuf[eslERRBUFSIZE]; /* for printing error messages */
588 CM_t *cm = NULL; /* the CM */
589 CM_t *nc_cm = NULL; /* a non-configured copy of the CM */
590 int i, h; /* counters */
591 int cmi; /* CM index, which model we're working on */
592 char time_buf[128]; /* string for printing elapsed time (safely holds up to 10^14 years) */
593 int exp_mode; /* ctr over exp tail modes */
594 double psec; /* predicted number of seconds for calibrating current CM */
595 double total_psec = 0.; /* predicted number of seconds for calibrating all CMs */
596 double total_asec = 0.; /* actual number of seconds for calibrating all CMs */
597 int ncpus = 0; /* number of CPUs working */
598 int nequals; /* number of '=' to output to progress bar for this mode */
599 int64_t merged_nhits = 0; /* number of hits reported thus far, for all seqs */
600 float *merged_scA = NULL; /* [0..merged_nhits-1] hit scores for all seqs */
601 int ins_v_cyk; /* ratio of predicted inside versus cyk running time */
602 double tmp_mu, tmp_lambda; /* temporary mu and lambda used for setting exp tails */
603 int tmp_nrandhits; /* temporary number of rand hits found */
604 float tmp_tailp; /* temporary tail mass probability fit to an exponential */
605 int relevant_ncpus = 1; /* number of CPUs being used or would be used if --forecast or --memreq not used */
606 ESL_SQ_BLOCK *sq_block = NULL; /* block of sequences */
607
608 /* variables related to --merge */
609 int do_merge; /* TRUE if --merge, else FALSE */
610 int64_t *pmerged_nhitsA = NULL; /* [0..EXP_NMODES-1] number of hits reported for all seqs for each exp mode, read from input score files from each partition */
611 float **pmerged_scAA = NULL; /* [0..EXP_NMODES-1][0..merged_nhits-1] hit scores for all seqs for each exp mode */
612
613 /* variables needed for threaded implementation */
614 ESL_SQ **init_sqA = NULL; /* for initializing workers */
615 WORKER_INFO *info = NULL; /* the worker info */
616 int infocnt = 0; /* number of worker infos */
617 #ifdef HMMER_THREADS
618 ESL_THREADS *threadObj = NULL;
619 ESL_WORK_QUEUE *queue = NULL;
620 #endif
621
622 if ((status = init_master_cfg(go, cfg, errbuf)) != eslOK) cm_Fail(errbuf);
623
624 #ifdef HMMER_THREADS
625 /* initialize thread data */
626 if (esl_opt_IsUsed(go, "--forecast")) ncpus = 0;
627 else if (esl_opt_IsUsed(go, "--memreq")) ncpus = 0;
628 else ncpus = ESL_MIN(esl_opt_GetInteger(go, "--cpu"), esl_threads_GetCPUCount());
629 if (ncpus > 0) {
630 threadObj = esl_threads_Create(&pipeline_thread);
631 queue = esl_workqueue_Create(ncpus * 2);
632 }
633 relevant_ncpus = ESL_MIN(esl_opt_GetInteger(go, "--cpu"), esl_threads_GetCPUCount());
634 #endif
635
636 infocnt = (ncpus == 0) ? 1 : ncpus;
637 ESL_ALLOC(info, sizeof(WORKER_INFO) * infocnt);
638
639 do_merge = esl_opt_GetBoolean(go, "--merge");
640
641 /* <cfg->abc> is not known 'til first CM is read. Could be DNA or RNA*/
642 qhstatus = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm);
643
644 if (qhstatus == eslOK) {
645 /* One-time initializations after alphabet <abc> becomes known */
646 output_header(stdout, go, cfg->cmfile, relevant_ncpus, ncpus);
647
648 if(! do_merge) {
649 if((status = CreateGenomicHMM(cfg->abc, errbuf, &(cfg->ghmm_sA), &(cfg->ghmm_tAA), &(cfg->ghmm_eAA), &cfg->ghmm_nstates)) != eslOK) cm_Fail("unable to create generative HMM\n%s", errbuf);
650 }
651 if((status = set_dnull(cfg, cm, errbuf)) != eslOK) cm_Fail("unable to create set_dnull\n%s\n", errbuf);
652
653 for (i = 0; i < infocnt; ++i) {
654 info[i].cm = NULL;
655 info[i].scA = NULL;
656 info[i].nhits = 0;
657 info[i].cutoff = cfg->sc_cutoff;
658 #ifdef HMMER_THREADS
659 info[i].queue = queue;
660 #endif
661 }
662
663 #ifdef HMMER_THREADS
664 if(ncpus > 0) {
665 ESL_ALLOC(init_sqA, sizeof(ESL_SQ *) * (ncpus * 2));
666 }
667 for (i = 0; i < ncpus * 2; i++) {
668 init_sqA[i] = NULL;
669 if((init_sqA[i] = esl_sq_CreateDigital(cfg->abc)) == NULL) cm_Fail("Failed to allocate a sequence");
670 if((status = esl_workqueue_Init(queue, init_sqA[i])) != eslOK) cm_Fail("Failed to add sequence to work queue");
671 }
672 #endif
673 }
674
675 /* Outer loop: over each query CM in <cmfile>. */
676 while (qhstatus == eslOK) {
677 cfg->ncm++;
678 cmi = cfg->ncm-1;
679 if(cmi == 0 && (! esl_opt_IsUsed(go, "--memreq"))) print_calibration_column_headings(go, cfg, errbuf, cm, relevant_ncpus);
680 if((status = expand_exp_and_name_arrays(cfg)) != eslOK) cm_Fail("out of memory");
681 if((status = esl_strdup(cm->name, -1, &(cfg->namesA[cmi]))) != eslOK) cm_Fail("unable to duplicate CM name");
682
683 if(cfg->pfp != NULL) { /* --part and --pfile used, partition mode: output command to pfp */
684 /* output command line, when cmcalibrate is called with --merge this will be added to CM file */
685 for (i = 0; i < go->argc-1; i++) {
686 fprintf(cfg->pfp, "%s ", go->argv[i]);
687 }
688 fprintf(cfg->pfp, "%s\n", go->argv[(go->argc-1)]);
689 }
690 /* clone the non-configured CM we just read, we'll come back to it when we switch from global to local */
691 if((! do_merge) && (! esl_opt_IsUsed(go, "--memreq"))) {
692 if((status = cm_Clone(cm, errbuf, &nc_cm)) != eslOK) cm_Fail("unable to clone CM");
693 }
694 if((status = initialize_cm(go, cfg, errbuf, cm, FALSE)) != eslOK) cm_Fail(errbuf);
695
696 if(esl_opt_IsUsed(go, "--memreq")) { /* special case: if --memreq, print required memory and skip to reading next CM */
697 print_required_memory(cm, cfg->L, cfg->N, relevant_ncpus, (cmi == 0) ? TRUE : FALSE, esl_opt_IsUsed(go, "--nonbanded"));
698 }
699 else { /* normal case */
700 if((status = initialize_stats(go, cfg, errbuf)) != eslOK) cm_Fail(errbuf);
701 if((! esl_opt_GetBoolean(go, "--noforecast")) && (! do_merge)) {
702 if((status = forecast_time(go, cfg, errbuf, cm, ncpus, relevant_ncpus, &psec, &ins_v_cyk)) != eslOK) cm_Fail(errbuf);
703 }
704 else {
705 psec = 0.;
706 ins_v_cyk = INS_V_CYK_GUESS;
707 }
708 total_psec += psec;
709 if(! do_merge) {
710 print_forecasted_time(go, cfg, errbuf, cm, psec);
711 }
712
713 if(do_merge) { /* open the scores files, read the scores for this CM, then close the files */
714 if((status = read_partition_scores_files_for_one_cm(go, cfg, errbuf, cm, cmi, &pmerged_scAA, &pmerged_nhitsA)) != eslOK) cm_Fail(errbuf);
715 }
716 else { /* ! do_merge, normal case, generate sequences to use for calibration */
717 if((status = generate_sequences(go, cfg, errbuf, cm, &sq_block)) != eslOK) cm_Fail(errbuf);
718 }
719
720 if(! esl_opt_IsUsed(go, "--forecast")) {
721 esl_stopwatch_Start(cfg->w);
722 for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++) {
723 if(! do_merge) { /* we don't do the searches if --merge */
724 /* clone CM for each worker, do this here so --forecast and --memreq don't do it */
725 if(exp_mode == 0) {
726 for (i = 0; i < infocnt; i++) {
727 if((status = cm_Clone(cm, errbuf, &(info[i].cm))) != eslOK) cm_Fail(errbuf);
728 }
729 }
730
731 /* do we need to switch from global configuration to local? */
732 if(exp_mode > 0 && (! ExpModeIsLocal(exp_mode-1)) && ExpModeIsLocal(exp_mode)) {
733 /* switch from global to local by copying the current exptail stats from <cm>
734 * into <nc_cm> and then configure <nc_cm> for local mode. We do it this
735 * way because as a rule we don't allow reconfiguration of CMs (to limit
736 * execution paths through configuration functions)
737 */
738 FreeCM(cm);
739 cm = nc_cm;
740 if((status = initialize_cm(go, cfg, errbuf, cm, TRUE)) != eslOK) cm_Fail(errbuf);
741 for (i = 0; i < infocnt; i++) {
742 if(info[i].cm != NULL) { FreeCM(info[i].cm); info[i].cm = NULL; }
743 if((status = cm_Clone(cm, errbuf, &(info[i].cm))) != eslOK) cm_Fail(errbuf);
744 }
745 }
746 /* set search_opts and determine how many '=' to print to status bar for this mode,
747 * there is space for 20 '=' for glocal (cyk + ins) and 20 '=' for local (cyk + ins)
748 */
749 if(ExpModeIsInside(exp_mode)) {
750 cm->search_opts |= CM_SEARCH_INSIDE;
751 for (i = 0; i < infocnt; i++) info[i].cm->search_opts |= CM_SEARCH_INSIDE;
752 nequals = 20 - (int) ((20. / (float) (ins_v_cyk+1)) + 0.5); /* round up */
753 }
754 else {
755 cm->search_opts &= ~CM_SEARCH_INSIDE;
756 for (i = 0; i < infocnt; i++) info[i].cm->search_opts &= ~CM_SEARCH_INSIDE;
757 nequals = (int) ((20. / (float) (ins_v_cyk+1)) + 0.5); /* round up */
758 }
759 fflush(stdout);
760
761 /* initialize worker info */
762 for (i = 0; i < infocnt; ++i) {
763 if(info[i].scA != NULL) free(info[i].scA);
764 info[i].scA = NULL;
765 info[i].nhits = 0;
766 info[i].cutoff = cfg->sc_cutoff;
767 info[i].nequals = nequals;
768 info[i].ipart = esl_opt_IsUsed(go, "--part") ? esl_opt_GetInteger(go, "--part") : -1;
769 info[i].npart = esl_opt_IsUsed(go, "--ptot") ? esl_opt_GetInteger(go, "--ptot") : -1;
770 #ifdef HMMER_THREADS
771 if (ncpus > 0) esl_threads_AddThread(threadObj, &info[i]);
772 #endif
773 }
774
775 #ifdef HMMER_THREADS
776 if (ncpus > 0) status = thread_loop(info, errbuf, threadObj, queue, sq_block);
777 else status = serial_loop(info, errbuf, sq_block);
778 #else
779 status = serial_loop(info, errbuf, sq_block);
780 #endif
781 if(status != eslOK) cm_Fail(errbuf);
782
783 merged_nhits = 0;
784 for (i = 0; i < infocnt; ++i) {
785 if(info[i].nhits > 0) {
786 ESL_REALLOC(merged_scA, sizeof(float) * (merged_nhits + info[i].nhits)); /* this works even if merged_scA == NULL */
787 for(h = 0; h < info[i].nhits; h++) merged_scA[(merged_nhits+h)] = info[i].scA[h];
788 merged_nhits += info[i].nhits;
789 }
790 }
791 } /* end of 'if(! do_merge)' */
792
793 if(cfg->ffp != NULL) {
794 fprintf(cfg->ffp, "# CM: %s\n", cm->name);
795 fprintf(cfg->ffp, "# mode: %12s\n", DescribeExpMode(exp_mode));
796 }
797
798 if(cfg->pfp != NULL) { /* --part and --pfile used, partition mode: output scores to pfp and don't fit histogram */
799 fprintf(cfg->pfp, "%" PRId64 "", merged_nhits);
800 for(i = 0; i < merged_nhits; i++) {
801 fprintf(cfg->pfp, " %.5f", merged_scA[i]);
802 }
803 fprintf(cfg->pfp, "\n");
804 }
805 else { /* normal mode (cfg->pfp is NULL, so --part now used), fit the histogram */
806 if((status = fit_histogram(go, cfg, errbuf,
807 ((do_merge) ? pmerged_scAA[exp_mode] : merged_scA),
808 ((do_merge) ? pmerged_nhitsA[exp_mode] : merged_nhits),
809 exp_mode, &tmp_mu, &tmp_lambda, &tmp_nrandhits, &tmp_tailp)) != eslOK) cm_Fail(errbuf);
810 SetExpInfo(cfg->expAA[cmi][exp_mode], tmp_lambda, tmp_mu, (double) (cfg->L * cfg->N), tmp_nrandhits, tmp_tailp);
811 }
812 if(merged_scA != NULL) { free(merged_scA); merged_scA = NULL; }
813 } /* end of for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++) */
814
815 /* free pmerged* data only after all exp_modes are done, b/c
816 * they were read all at once prior to the for(exp_mode...)
817 * loop that ends above
818 */
819 if(pmerged_scAA != NULL) {
820 for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++)
821 if(pmerged_scAA[exp_mode] != NULL) {
822 free(pmerged_scAA[exp_mode]);
823 pmerged_scAA[exp_mode] = NULL;
824 }
825 free(pmerged_scAA);
826 pmerged_scAA = NULL;
827 }
828 if(pmerged_nhitsA != NULL) {
829 free(pmerged_nhitsA);
830 pmerged_nhitsA = NULL;
831 }
832
833 esl_stopwatch_Stop(cfg->w);
834 FormatTimeString(time_buf, 128, cfg->w->elapsed, FALSE); /* 128: buffer size */
835 if(! do_merge) {
836 printf("] %12s\n", time_buf);
837 fflush(stdout);
838 }
839 total_asec += cfg->w->elapsed;
840
841 } /* end of if(! esl_opt_IsUsed(go, "--forecast")) */
842 else { /* --forecast */
843 FreeCM(nc_cm);
844 }
845 } /* end of else, entered if (! esl_opt_IsUsed(go, "--memreq")) */
846 FreeCM(cm);
847 for(i = 0; i < infocnt; i++) {
848 if(info[i].cm != NULL) { FreeCM(info[i].cm); info[i].cm = NULL; }
849 if(info[i].scA != NULL) { free(info[i].scA); info[i].scA = NULL; }
850 }
851 if(sq_block != NULL) esl_sq_DestroyBlock(sq_block);
852
853 fflush(stdout);
854
855 /* read the next CM */
856 qhstatus = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm);
857 } /* end of while(qhstatus == eslOK) */
858 if(qhstatus != eslEOF) cm_Fail(cfg->cmfp->errbuf);
859
860 if(esl_opt_IsUsed(go, "--memreq")) print_required_memory_tail(relevant_ncpus);
861 else if((cfg->ncm > 1) && (! do_merge)) print_total_time(go, total_asec, total_psec);
862
863 /* free the generative HMM parameters */
864
865 #ifdef HMMER_THREADS
866 if (ncpus > 0) {
867 esl_workqueue_Reset(queue);
868 if(init_sqA != NULL) {
869 for (i = 0; i < ncpus * 2; i++) {
870 if(init_sqA[i] != NULL) esl_sq_Destroy(init_sqA[i]);
871 }
872 free(init_sqA);
873 init_sqA = NULL;
874 }
875 esl_workqueue_Destroy(queue);
876 esl_threads_Destroy(threadObj);
877 }
878 #endif
879 if(info != NULL) { free(info); info = NULL; }
880
881 return;
882
883 ERROR:
884 cm_Fail("Memory allocation error.");
885 return;
886 }
887
888 /* serial_loop():
889 *
890 * Search each sequence and collect scores of hits.
891 */
892 static int
893 serial_loop(WORKER_INFO *info, char *errbuf, ESL_SQ_BLOCK *sq_block)
894 {
895 int status;
896 CM_TOPHITS *th = NULL;
897 int i, h; /* counters */
898 int equalidx; /* when i reaches this, we updated progress bar by printing a '=' */
899 int equalcnt; /* number of sequences that need to be searched to warrant a '=' */
900 int nprinted = 0; /* number of equals printed thus far */
901
902 /* variables related to --part */
903 int *searchmeA = NULL; /* [0..sq_block->count-1]: 1 if we search this seq, 0 if not */
904 ESL_ALLOC(searchmeA, sizeof(int) * sq_block->count);
905
906 /* reinitialize array of hit scores */
907 info->nhits = 0;
908 if(info->scA != NULL) free(info->scA);
909
910 /* Determine which sequences to search
911 * if --part not used: search all sequences (normal)
912 * if --part used: only search (1/npart) fraction of the sequences
913 * these won't be consecutive sequences,
914 * e.g. if 10 seqs and 3 parts, part 1 is seqs 1,4,7,10
915 * (very simple to implement this way, see block below)
916 */
917 if(info->ipart != -1) {
918 esl_vec_ISet(searchmeA, sq_block->count, FALSE);
919 for(i = 0; i < sq_block->count; i++) {
920 if(((i % info->npart) + 1) == info->ipart) {
921 searchmeA[i] = TRUE;
922 }
923 }
924 }
925 else { /* --part not used, search all sequences */
926 esl_vec_ISet(searchmeA, sq_block->count, TRUE);
927 }
928
929 /* determine how many sequences we need to complete to print a '=' to progress bar */
930 equalcnt = (int) (((float) sq_block->count / (float) info->nequals) + 0.9999999);
931 equalcnt = ESL_MAX(equalcnt, 1);
932 equalidx = equalcnt;
933
934 for(i = 0; i < sq_block->count; i++) {
935 if(searchmeA[i]) { /* searchmeA[i] is always TRUE unless --part used */
936 if((status = process_search_workunit(info->cm, errbuf, sq_block->list[i].dsq, sq_block->list[i].L, info->cutoff, &th)) != eslOK) cm_Fail(errbuf);
937 /* append copy of hit scores to scA */
938 if(th->N > 0) {
939 ESL_REALLOC(info->scA, sizeof(float) * (info->nhits + th->N)); /* this works even if info->scA == NULL */
940 for(h = 0; h < th->N; h++) info->scA[(info->nhits+h)] = th->unsrt[h].score;
941 info->nhits += th->N;
942 }
943 cm_tophits_Destroy(th);
944 }
945 if ((i+1) == equalidx) {
946 putchar('=');
947 fflush(stdout);
948 nprinted++;
949 equalidx += equalcnt;
950 }
951 }
952 while(nprinted < info->nequals) { putchar('='); fflush(stdout); nprinted++; }
953
954 if(searchmeA != NULL) {
955 free(searchmeA);
956 searchmeA = NULL;
957 }
958
959 return eslOK;
960
961 ERROR:
962 if(searchmeA != NULL) {
963 free(searchmeA);
964 searchmeA = NULL;
965 }
966
967 ESL_FAIL(status, errbuf, "out of memory");
968 return status; /* NEVERREACHED */
969 }
970
971 #ifdef HMMER_THREADS
972 static int
973 thread_loop(WORKER_INFO *info, char *errbuf, ESL_THREADS *obj, ESL_WORK_QUEUE *queue, ESL_SQ_BLOCK *sq_block)
974 {
975 int status = eslOK;
976 ESL_SQ *sq = NULL;
977 void *new_sq = NULL;
978 ESL_SQ *empty_sq = NULL;
979 int nworkers = esl_threads_GetWorkerCount(obj);
980 int i, j;
981 int equalidx; /* when i reaches this, we updated progress bar by printing a '=' */
982 int equalcnt; /* number of sequences that need to be searched to warrant a '=' */
983 int nprinted = 0; /* number of equals printed thus far */
984
985 /* variables related to --part */
986 int *searchmeA = NULL; /* [0..sq_block->count-1]: 1 if we search this seq, 0 if not */
987 ESL_ALLOC(searchmeA, sizeof(int) * sq_block->count);
988
989 esl_workqueue_Reset(queue);
990 esl_threads_WaitForStart(obj);
991
992 /* Determine which sequences to search
993 * if --part not used: search all sequences (normal)
994 * if --part used: only search (1/npart) fraction of the sequences
995 * these won't be consecutive sequences,
996 * e.g. if 10 seqs and 3 parts, part 1 is seqs 1,4,7,10
997 * (very simple to implement this way, see block below)
998 */
999 if(info->ipart != -1) {
1000 esl_vec_ISet(searchmeA, sq_block->count, FALSE);
1001 for(i = 0; i < sq_block->count; i++) {
1002 if(((i % info->npart) + 1) == info->ipart) {
1003 searchmeA[i] = TRUE;
1004 }
1005 }
1006 }
1007 else { /* --part not used, search all sequences */
1008 esl_vec_ISet(searchmeA, sq_block->count, TRUE);
1009 }
1010
1011 /* determine how many sequences we need to complete to print a '=' to progress bar */
1012 equalcnt = (int) (((float) sq_block->count / (float) info->nequals) + 0.9999999);
1013 equalcnt = ESL_MAX(equalcnt, 1);
1014 equalidx = equalcnt;
1015
1016 status = esl_workqueue_ReaderUpdate(queue, NULL, &new_sq);
1017 if (status != eslOK) cm_Fail("Work queue reader failed");
1018
1019 /* Main loop: */
1020 for(i = 0; i < sq_block->count; i++) {
1021 if(searchmeA[i]) {
1022 sq = (ESL_SQ *) new_sq;
1023 sq = sq_block->list + i;
1024 status = esl_workqueue_ReaderUpdate(queue, sq, &new_sq);
1025 if (status != eslOK) cm_Fail("Work queue reader failed");
1026 }
1027 if ((i+1) == equalidx) {
1028 putchar('=');
1029 fflush(stdout);
1030 nprinted++;
1031 equalidx += equalcnt;
1032 }
1033 }
1034 while(nprinted < info->nequals) { putchar('='); fflush(stdout); nprinted++; }
1035
1036 /* now send a empty sq to all workers signaling them to stop */
1037 empty_sq = esl_sq_Create();
1038 for(j = 0; j < nworkers; j++) {
1039 status = esl_workqueue_ReaderUpdate(queue, empty_sq, &new_sq);
1040 if (status != eslOK) cm_Fail("Work queue reader failed");
1041 }
1042
1043 status = esl_workqueue_ReaderUpdate(queue, sq, NULL);
1044
1045 /* wait for all the threads to complete */
1046 esl_threads_WaitForFinish(obj);
1047 esl_workqueue_Complete(queue);
1048
1049 esl_sq_Destroy(empty_sq);
1050 if(searchmeA != NULL) free(searchmeA);
1051 return status;
1052
1053 ERROR:
1054 if(searchmeA != NULL) free(searchmeA);
1055 ESL_FAIL(status, errbuf, "out of memory");
1056 return status; /* NEVERREACHED */
1057 }
1058
1059 /* pipeline_thread()
1060 *
1061 * Receive a sequence from the master, search it
1062 * with the CM, and add scores of hits to info->scA.
1063 */
1064
1065 static void
1066 pipeline_thread(void *arg)
1067 {
1068 int status;
1069 int workeridx;
1070 WORKER_INFO *info;
1071 ESL_THREADS *obj;
1072 ESL_SQ *sq = NULL;
1073 void *new_sq;
1074 int h;
1075 CM_TOPHITS *th = NULL;
1076 char errbuf[eslERRBUFSIZE];
1077
1078 #ifdef HAVE_FLUSH_ZERO_MODE
1079 /* In order to avoid the performance penalty dealing with sub-normal
1080 * values in the floating point calculations, set the processor flag
1081 * so sub-normals are "flushed" immediately to zero.
1082 * On OS X, need to reset this flag for each thread
1083 * (see TW notes 05/08/10 for details)
1084 */
1085 _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
1086 #endif
1087
1088 obj = (ESL_THREADS *) arg;
1089 esl_threads_Started(obj, &workeridx);
1090
1091 info = (WORKER_INFO *) esl_threads_GetData(obj, workeridx);
1092
1093 status = esl_workqueue_WorkerUpdate(info->queue, NULL, &new_sq);
1094 if (status != eslOK) cm_Fail("Work queue worker failed");
1095
1096 /* reinitialize array of hit scores */
1097 info->nhits = 0;
1098 if(info->scA != NULL) free(info->scA);
1099
1100 /* loop until all sequences have been processed */
1101 sq = (ESL_SQ *) new_sq;
1102 while (sq->L != -1) {
1103 if((status = process_search_workunit(info->cm, errbuf, sq->dsq, sq->L, info->cutoff, &th)) != eslOK) cm_Fail(errbuf);
1104 /* append copy of hit scores to scA */
1105 if(th->N > 0) {
1106 ESL_REALLOC(info->scA, sizeof(float) * (info->nhits + th->N)); /* this works even if info->scA == NULL */
1107 for(h = 0; h < th->N; h++) info->scA[(info->nhits+h)] = th->unsrt[h].score;
1108 info->nhits += th->N;
1109 }
1110 cm_tophits_Destroy(th);
1111
1112 status = esl_workqueue_WorkerUpdate(info->queue, sq, &new_sq);
1113 if (status != eslOK) cm_Fail("Work queue worker failed");
1114 sq = (ESL_SQ *) new_sq;
1115 }
1116
1117 status = esl_workqueue_WorkerUpdate(info->queue, sq, NULL);
1118 if (status != eslOK) cm_Fail("Work queue worker failed");
1119
1120 esl_threads_Finished(obj, workeridx);
1121 return;
1122
1123 ERROR:
1124 cm_Fail("out of memory");
1125 return; /* NEVERREACHED */
1126 }
1127 #endif /* HMMER_THREADS */
1128
1129 #ifdef HAVE_MPI
1130 /* mpi_master()
1131 * The MPI version of cmcalibrate.
1132 * Follows standard pattern for a master/worker load-balanced MPI program
1133 * (SRE notes J1/78-79).
1134 *
1135 * A master returns eslOK if it's successful. Errors in an MPI master
1136 * come in two classes: recoverable and nonrecoverable.
1137 *
1138 * Recoverable errors include most worker-side errors, and any
1139 * master-side error that do not affect MPI communication. Error
1140 * messages from recoverable messages are delayed until we've cleanly
1141 * shut down the workers. The
1142 *
1143 * Some worker side errors (such as ESL_ALLOCs) are likely to be
1144 * unrecoverable and will almost certainly cause MPI to crash
1145 * uncleanly, they're only here because I couldn't find a way around
1146 * them without massive reimplementation. Hopefully they rarely occur.
1147 *
1148 * Unrecoverable errors are master-side errors that may affect MPI
1149 * communication, meaning we cannot count on being able to reach the
1150 * workers and shut them down. Unrecoverable errors result in immediate
1151 * cm_Fail()'s, which will cause MPI to shut down the worker processes
1152 * uncleanly.
1153 */
1154 static int
1155 mpi_master(ESL_GETOPTS *go, struct cfg_s *cfg)
1156 {
1157 int status; /* Easel status */
1158 int qhstatus = eslOK; /* status from cm_file_Read() */
1159 char errbuf[eslERRBUFSIZE]; /* for printing error messages */
1160 CM_t *cm = NULL; /* the CM */
1161 CM_t *nc_cm = NULL; /* a non-configured copy of the CM */
1162 int i, h; /* counters */
1163 int cmi; /* CM index, which model we're working on */
1164 char time_buf[128]; /* string for printing elapsed time (safely holds up to 10^14 years) */
1165 int exp_mode; /* ctr over exp tail modes */
1166 double psec; /* predicted number of seconds for calibrating current CM */
1167 double total_psec = 0.; /* predicted number of seconds for calibrating all CMs */
1168 double total_asec = 0.; /* predicted number of seconds for calibrating all CMs */
1169 int64_t merged_nhits = 0; /* number of hits reported thus far, for all seqs */
1170 float *merged_scA = NULL; /* [0..merged_nhits-1] hit scores for all seqs */
1171 int ins_v_cyk; /* ratio of predicted inside versus cyk running time */
1172 double tmp_mu, tmp_lambda; /* temporary mu and lambda used for setting exp tails */
1173 int tmp_nrandhits; /* temporary number of rand hits found */
1174 float tmp_tailp; /* temporary tail mass probability fit to an exponential */
1175 int nequals; /* number of '=' to output to progress bar for this mode */
1176 int equalidx; /* when i reaches this, we updated progress bar by printing a '=' */
1177 int equalcnt; /* number of sequences that need to be searched to warrant a '=' */
1178 int nprinted = 0; /* number of equals printed thus far */
1179 int nready_recd = 0; /* number of ready signals we've received for this CM/mode pair */
1180
1181 MPI_Status mpistatus; /* the mpi status */
1182 char *mpibuf = NULL; /* buffer used to pack/unpack structures */
1183 int mpibuf_size = 0; /* current size of mpibuf_size */
1184 int buf_size; /* size of received buffer */
1185 int dest; /* destination for MPISend() */
1186 int pos; /* for packing/unpacking an MPI buffer */
1187 int64_t nhits; /* nhits received from a worker */
1188
1189 if ((status = init_master_cfg(go, cfg, errbuf)) != eslOK) cm_Fail(errbuf);
1190
1191 /* <cfg->abc> is not known 'til first CM is read. Could be DNA or RNA*/
1192 qhstatus = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm);
1193
1194 if (qhstatus == eslOK) {
1195 /* One-time initializations after alphabet <abc> becomes known */
1196 output_header(stdout, go, cfg->cmfile, 0, cfg->nproc); /* 0 is 'relevant_ncpus', normally not important, only used if --forecast, which is incompatible with --mpi */
1197
1198 /* master needs to be able to generate sequences only for timing predictions */
1199 if((status = CreateGenomicHMM(cfg->abc, errbuf, &(cfg->ghmm_sA), &(cfg->ghmm_tAA), &(cfg->ghmm_eAA), &cfg->ghmm_nstates)) != eslOK) cm_Fail("unable to create generative HMM\n%s", errbuf);
1200 if((status = set_dnull(cfg, cm, errbuf)) != eslOK) mpi_failure("unable to create set_dnull\n%s\n", errbuf);
1201 }
1202
1203 /* Outer loop: over each query CM in <cmfile>. */
1204 while (qhstatus == eslOK) {
1205 /* clone the non-configured CM we just read, we'll come back to it when we switch from global to local */
1206 if((status = cm_Clone(cm, errbuf, &nc_cm)) != eslOK) mpi_failure("unable to clone CM");
1207
1208 cfg->ncm++;
1209 cmi = cfg->ncm-1;
1210
1211 if((status = expand_exp_and_name_arrays(cfg)) != eslOK) mpi_failure("out of memory");
1212 if((status = esl_strdup(cm->name, -1, &(cfg->namesA[cmi]))) != eslOK) mpi_failure("unable to duplicate CM name");
1213 if((status = initialize_cm(go, cfg, errbuf, cm, FALSE)) != eslOK) mpi_failure(errbuf);
1214 if((status = initialize_stats(go, cfg, errbuf)) != eslOK) mpi_failure(errbuf);
1215
1216 if(cmi == 0) print_calibration_column_headings(go, cfg, errbuf, cm, 1); /* 1 is irrelevant here, since --forecast can't have been enabled */
1217 if((! esl_opt_GetBoolean(go, "--noforecast")) && (! esl_opt_GetBoolean(go, "--merge"))) {
1218 if((status = forecast_time(go, cfg, errbuf, cm, cfg->nproc-1, 1, &psec, &ins_v_cyk)) != eslOK) mpi_failure(errbuf);
1219 }
1220 else {
1221 psec = 0.;
1222 ins_v_cyk = INS_V_CYK_GUESS;
1223 }
1224 total_psec += psec;
1225 if(! esl_opt_GetBoolean(go, "--merge")) {
1226 print_forecasted_time(go, cfg, errbuf, cm, psec);
1227 }
1228
1229 /* Time forecast complete, send ready signal to all workers.
1230 * (This 'fixes' bug i35: in 1.1rc1, calibrations for large models
1231 * on large numbers of processors (W>~1000, nproc>~80) would fail,
1232 * seemingly due to too long a wait by mpi_worker()'s first
1233 * MPI_Send(), but I never figured out exactly why. Regardless,
1234 * sending a specific signal to each worker, who is waiting for
1235 * it before it begins working solves the issue.)
1236 */
1237 for(dest = 1; dest < cfg->nproc; dest++) {
1238 if (MPI_Send(&status, 1, MPI_INT, dest, INFERNAL_READY_TAG, MPI_COMM_WORLD) != 0) mpi_failure("mpi send failed");
1239 #if DEBUG_MPI
1240 printf("master sent ready signal to worker %d\n", dest);
1241 #endif
1242 }
1243
1244 esl_stopwatch_Start(cfg->w);
1245 for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++) {
1246 /* do we need to switch from global configuration to local? */
1247 if(exp_mode > 0 && (! ExpModeIsLocal(exp_mode-1)) && ExpModeIsLocal(exp_mode)) {
1248 /* switch from global to local by copying the current exptail stats from <cm>
1249 * into <nc_cm> and then configure <nc_cm> for local mode. We do it this
1250 * way because as a rule we don't allow reconfiguration of CMs (to limit
1251 * execution paths through configuration functions)
1252 */
1253 FreeCM(cm);
1254 cm = nc_cm;
1255 if((status = initialize_cm(go, cfg, errbuf, cm, TRUE)) != eslOK) mpi_failure(errbuf);
1256 }
1257 /* set search_opts and determine how many '=' to print to status bar for this mode,
1258 * there is space for 20 '=' for glocal (cyk + ins) and 20 '=' for local (cyk + ins)
1259 */
1260 if(ExpModeIsInside(exp_mode)) {
1261 cm->search_opts |= CM_SEARCH_INSIDE;
1262 nequals = 20 - (int) ((20. / (float) (ins_v_cyk+1)) + 0.5); /* round up */
1263 }
1264 else {
1265 cm->search_opts &= ~CM_SEARCH_INSIDE;
1266 nequals = (int) ((20. / (float) (ins_v_cyk+1)) + 0.5); /* round up */
1267 }
1268 /* determine how many sequences we need to complete to print a '=' to progress bar */
1269 equalcnt = (int) (((float) cfg->N / (float) nequals) + 0.9999999);
1270 equalcnt = ESL_MAX(equalcnt, 1);
1271 equalidx = equalcnt;
1272 nprinted = 0;
1273 nready_recd = 0;
1274
1275 /* for each sequence i from 0..N-1, tell the appropriate worker (widx = (i+1) % nworkers) to search it */
1276 for(i = 0; i < cfg->N; i++) {
1277 if (MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &mpistatus) != 0) mpi_failure("MPI error %d receiving message from %d\n", mpistatus.MPI_SOURCE);
1278
1279 MPI_Get_count(&mpistatus, MPI_PACKED, &buf_size);
1280 if (mpibuf == NULL || buf_size > mpibuf_size) {
1281 ESL_REALLOC(mpibuf, sizeof(char) * buf_size);
1282 mpibuf_size = buf_size;
1283 }
1284 dest = mpistatus.MPI_SOURCE;
1285 MPI_Recv(mpibuf, buf_size, MPI_PACKED, dest, mpistatus.MPI_TAG, MPI_COMM_WORLD, &mpistatus);
1286
1287 if (mpistatus.MPI_TAG == INFERNAL_ERROR_TAG) mpi_failure("MPI client %d raised error:\n%s\n", dest, mpibuf);
1288 if (mpistatus.MPI_TAG != INFERNAL_READY_TAG) mpi_failure("Unexpected tag %d from %d\n", mpistatus.MPI_TAG, dest);
1289
1290 nready_recd++;
1291 if ((nready_recd - (cfg->nproc-1)) == equalidx) { /* ignore the first ready signal from each worker (cfg->nproc-1 of them) */
1292 putchar('=');
1293 fflush(stdout);
1294 nprinted++;
1295 equalidx += equalcnt;
1296 }
1297
1298 #if DEBUGMPI
1299 printf("master rec'd INFERNAL_READY_TAG from worker %d\n", dest);
1300 #endif
1301
1302 /* send the int 'i' to the worker, telling it to search his copy of the i'th sequence for this CM/mode pair */
1303 if (MPI_Send(&i, 1, MPI_INT, dest, INFERNAL_SEQIDX_TAG, MPI_COMM_WORLD) != 0) mpi_failure("mpi send failed");
1304 #if DEBUGMPI
1305 printf("master sent i: %d to worker %d\n", i, dest);
1306 #endif
1307 }
1308
1309 /* wait for all workers to finish up their work blocks */
1310 for (i = 1; i < cfg->nproc; ++i) {
1311 if (MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &mpistatus) != 0) mpi_failure("MPI error %d receiving message from %d\n", mpistatus.MPI_SOURCE);
1312
1313 MPI_Get_count(&mpistatus, MPI_PACKED, &buf_size);
1314 if (mpibuf == NULL || buf_size > mpibuf_size) {
1315 ESL_REALLOC(mpibuf, sizeof(char) * buf_size);
1316 mpibuf_size = buf_size;
1317 }
1318 dest = mpistatus.MPI_SOURCE;
1319 MPI_Recv(mpibuf, buf_size, MPI_PACKED, dest, mpistatus.MPI_TAG, MPI_COMM_WORLD, &mpistatus);
1320
1321 if (mpistatus.MPI_TAG == INFERNAL_ERROR_TAG) mpi_failure("MPI client %d raised error:\n%s\n", dest, mpibuf);
1322 if (mpistatus.MPI_TAG != INFERNAL_READY_TAG) mpi_failure("Unexpected tag %d from %d\n", mpistatus.MPI_TAG, dest);
1323 #if DEBUGMPI
1324 printf("master done sending indices, received INFERNAL_READY_TAG from worker %d\n", dest);
1325 #endif
1326 nready_recd++;
1327 if ((nready_recd - (cfg->nproc-1)) == equalidx) { /* ignore the first ready signal from each worker (cfg->nproc-1 of them) */
1328 putchar('=');
1329 fflush(stdout);
1330 nprinted++;
1331 equalidx += equalcnt;
1332 }
1333 }
1334 while(nprinted < nequals) { putchar('='); fflush(stdout); nprinted++; }
1335
1336 /* merge the arrays of scores we get back from the workers */
1337 for (dest = 1; dest < cfg->nproc; ++dest) {
1338 /* send -1 to the worker, telling it we're done with this CM/mode pair */
1339 i = -1;
1340 if (MPI_Send(&i, 1, MPI_INT, dest, INFERNAL_SEQIDX_TAG, MPI_COMM_WORLD) != 0) ESL_EXCEPTION(eslESYS, "mpi send failed");
1341 #if DEBUGMPI
1342 printf("master sent -1 to worker %d\n", dest);
1343 #endif
1344
1345 /* wait for the results */
1346 if (MPI_Probe(dest, MPI_ANY_TAG, MPI_COMM_WORLD, &mpistatus) != 0) mpi_failure("MPI error %d receiving message from %d\n", mpistatus.MPI_SOURCE);
1347 MPI_Get_count(&mpistatus, MPI_PACKED, &buf_size);
1348 if (mpibuf == NULL || buf_size > mpibuf_size) {
1349 ESL_REALLOC(mpibuf, sizeof(char) * buf_size);
1350 mpibuf_size = buf_size;
1351 }
1352
1353 /* receive and unpack the array of hit scores */
1354 MPI_Recv(mpibuf, buf_size, MPI_PACKED, dest, mpistatus.MPI_TAG, MPI_COMM_WORLD, &mpistatus);
1355 #if DEBUGMPI
1356 printf("master received results from worker %d\n", dest);
1357 #endif
1358
1359 if (mpistatus.MPI_TAG == INFERNAL_ERROR_TAG) mpi_failure("MPI client %d raised error:\n%s\n", dest, mpibuf);
1360 if (mpistatus.MPI_TAG != INFERNAL_SCORES_TAG) mpi_failure("Unexpected tag %d from %d\n", mpistatus.MPI_TAG, dest);
1361 pos = 0;
1362 if (MPI_Unpack(mpibuf, buf_size, &pos, &nhits, 1, MPI_LONG_LONG_INT, MPI_COMM_WORLD) != 0) ESL_XEXCEPTION(eslESYS, "unpack failed");
1363 if(nhits > 0) {
1364 if(merged_nhits == 0) ESL_ALLOC (merged_scA, sizeof(float) * (merged_nhits + nhits));
1365 else ESL_REALLOC(merged_scA, sizeof(float) * (merged_nhits + nhits));
1366 for(h = 0; h < nhits; h++) {
1367 if (MPI_Unpack(mpibuf, buf_size, &pos, &(merged_scA[merged_nhits+h]), 1, MPI_FLOAT, MPI_COMM_WORLD) != 0) ESL_XEXCEPTION(eslESYS, "unpack failed");
1368 }
1369 merged_nhits += nhits;
1370 #if DEBUGMPI
1371 printf("master added %" PRId64 " hits to merged_nhits, now %" PRId64 " total\n", nhits, merged_nhits);
1372 #endif
1373 }
1374 }
1375
1376 if(cfg->ffp != NULL) {
1377 fprintf(cfg->ffp, "# CM: %s\n", cm->name);
1378 fprintf(cfg->ffp, "# mode: %12s\n", DescribeExpMode(exp_mode));
1379 }
1380 #if DEBUGMPI
1381 printf("about to call fit_histogram, %" PRId64 " hits\n", merged_nhits);
1382 #endif
1383 if((status = fit_histogram(go, cfg, errbuf, merged_scA, merged_nhits, exp_mode, &tmp_mu, &tmp_lambda, &tmp_nrandhits, &tmp_tailp)) != eslOK) mpi_failure(errbuf);
1384 SetExpInfo(cfg->expAA[cmi][exp_mode], tmp_lambda, tmp_mu, (double) (cfg->L * cfg->N), tmp_nrandhits, tmp_tailp);
1385
1386 /* clear hits */
1387 if(merged_scA != NULL) { free(merged_scA); merged_scA = NULL; }
1388 merged_nhits = 0;
1389 } /* end of for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++) */
1390
1391 esl_stopwatch_Stop(cfg->w);
1392 if(! esl_opt_GetBoolean(go, "--merge")) {
1393 FormatTimeString(time_buf, 128, cfg->w->elapsed, FALSE); /* 128: buffer size */
1394 printf("] %12s\n", time_buf);
1395 fflush(stdout);
1396 }
1397 total_asec += cfg->w->elapsed;
1398
1399 FreeCM(cm);
1400
1401 fflush(stdout);
1402
1403 /* read the next CM */
1404 qhstatus = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm);
1405 } /* end of while(qhstatus == eslOK) */
1406 if(qhstatus != eslEOF) mpi_failure(cfg->cmfp->errbuf);
1407
1408 if(cfg->ncm > 1) print_total_time(go, total_asec, total_psec);
1409
1410 return eslOK;
1411
1412 ERROR:
1413 mpi_failure("Memory allocation error.");
1414 return eslEMEM;
1415 }
1416
1417 /* mpi_worker()
1418 *
1419 * Receive information from the master on which sequences to search
1420 * and send back hit scores for, and do it.
1421 */
1422
1423
1424 static int
1425 mpi_worker(ESL_GETOPTS *go, struct cfg_s *cfg)
1426 {
1427 int status; /* Easel status */
1428 int qhstatus = eslOK; /* status from cm_file_Read() */
1429 char errbuf[eslERRBUFSIZE]; /* for printing error messages */
1430 CM_t *cm = NULL; /* the CM */
1431 CM_t *nc_cm = NULL; /* a non-configured copy of the CM */
1432 int i, h; /* counters */
1433 int exp_mode; /* ctr over exp tail modes */
1434
1435 char *mpibuf = NULL; /* buffer used to pack/unpack structures */
1436 int mpibuf_size = 0; /* size of the mpibuf */
1437 ESL_SQ_BLOCK *sq_block = NULL;
1438 WORKER_INFO info; /* the worker info */
1439
1440 MPI_Status mpistatus; /* the mpi status */
1441 int buf_size, n, pos; /* for packing/unpacking an MPI buffer */
1442 CM_TOPHITS *th = NULL;
1443
1444 if ((status = init_shared_cfg(go, cfg, errbuf)) != eslOK) mpi_failure(errbuf);
1445
1446 /* <cfg->abc> is not known 'til first CM is read. Could be DNA or RNA*/
1447 qhstatus = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm);
1448
1449 if (qhstatus == eslOK) {
1450 /* One-time initializations after alphabet <abc> becomes known */
1451 if((status = CreateGenomicHMM(cfg->abc, errbuf, &(cfg->ghmm_sA), &(cfg->ghmm_tAA), &(cfg->ghmm_eAA), &cfg->ghmm_nstates)) != eslOK) mpi_failure("unable to create generative HMM\n%s", errbuf);
1452 if((status = set_dnull(cfg, cm, errbuf)) != eslOK) mpi_failure("unable to create set_dnull\n%s\n", errbuf);
1453
1454 info.cm = NULL;
1455 info.scA = NULL;
1456 info.nhits = 0;
1457 info.cutoff = cfg->sc_cutoff;
1458 }
1459
1460 /* Outer loop: over each query CM in <cmfile>. */
1461 while (qhstatus == eslOK) {
1462 /* clone the non-configured CM we just read, we'll come back to it when we switch from global to local */
1463 if((status = cm_Clone(cm, errbuf, &nc_cm)) != eslOK) mpi_failure("unable to clone CM");
1464
1465 cfg->ncm++;
1466
1467 if((status = expand_exp_and_name_arrays(cfg)) != eslOK) mpi_failure("out of memory");
1468 if((status = initialize_cm(go, cfg, errbuf, cm, FALSE)) != eslOK) mpi_failure(errbuf);
1469 if((status = generate_sequences(go, cfg, errbuf, cm, &sq_block)) != eslOK) mpi_failure(errbuf);
1470
1471 /* wait for ready signal from master (this addresses bug i35, see comment in mpi_master()) */
1472 #if DEBUG_MPI
1473 printf("worker %d waiting for ready signal from master\n", cfg->my_rank);
1474 #endif
1475 if((status = MPI_Recv(&status, 1, MPI_INT, 0, INFERNAL_READY_TAG, MPI_COMM_WORLD, &mpistatus)) != 0) mpi_failure("failed to receive ready signal");
1476
1477 for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++) {
1478 /* do we need to switch from global configuration to local? */
1479 if(exp_mode > 0 && (! ExpModeIsLocal(exp_mode-1)) && ExpModeIsLocal(exp_mode)) {
1480 /* switch from global to local by copying the current exptail stats from <cm>
1481 * into <nc_cm> and then configure <nc_cm> for local mode. We do it this
1482 * way because as a rule we don't allow reconfiguration of CMs (to limit
1483 * execution paths through configuration functions)
1484 */
1485 FreeCM(cm);
1486 cm = nc_cm;
1487 if((status = initialize_cm(go, cfg, errbuf, cm, TRUE)) != eslOK) mpi_failure(errbuf);
1488 }
1489 /* update search info for round 0 (final round) for exp tail mode */
1490 if(ExpModeIsInside(exp_mode)) cm->search_opts |= CM_SEARCH_INSIDE;
1491 else cm->search_opts &= ~CM_SEARCH_INSIDE;
1492
1493 info.cm = cm;
1494
1495 /* inform the master that we're ready for our first index */
1496 status = 0;
1497 MPI_Send(&status, 1, MPI_INT, 0, INFERNAL_READY_TAG, MPI_COMM_WORLD);
1498
1499 #if DEBUGMPI
1500 printf("worker %d waiting for 1st index from master\n", cfg->my_rank);
1501 #endif
1502 /* receive a sequence index from the master */
1503 if((status = MPI_Recv(&i, 1, MPI_INT, 0, INFERNAL_SEQIDX_TAG, MPI_COMM_WORLD, &mpistatus)) != 0) mpi_failure("failed to receive sequence index to search");
1504
1505 while(i != -1) {
1506 #if DEBUGMPI
1507 printf("worker %d received i: %d from master\n", cfg->my_rank, i);
1508 #endif
1509
1510 if((status = process_search_workunit(info.cm, errbuf, sq_block->list[i].dsq, sq_block->list[i].L, info.cutoff, &th)) != eslOK) mpi_failure("(worker) %s", errbuf);
1511 #if DEBUGMPI
1512 printf("worker %d finished with i: %d\n", cfg->my_rank, i);
1513 #endif
1514 /* append copy of hit scores to scA */
1515 if(th->N > 0) {
1516 ESL_REALLOC(info.scA, sizeof(float) * (info.nhits + th->N)); /* this works even if info.scA is NULL */
1517 for(h = 0; h < th->N; h++) info.scA[(info.nhits+h)] = th->unsrt[h].score;
1518 info.nhits += th->N;
1519 }
1520 #if DEBUGMPI
1521 printf("worker %d just added %" PRId64" hits to scA, now %" PRId64 " hits\n", cfg->my_rank, th->N, info.nhits);
1522 #endif
1523 cm_tophits_Destroy(th);
1524
1525 /* inform the master we need another sequence index */
1526 status = 0;
1527 MPI_Send(&status, 1, MPI_INT, 0, INFERNAL_READY_TAG, MPI_COMM_WORLD);
1528
1529 #if DEBUGMPI
1530 printf("worker %d sent ready tag back to master\n", cfg->my_rank);
1531 #endif
1532
1533 /* wait for the next sequence index */
1534 if((status = MPI_Recv(&i, 1, MPI_INT, 0, INFERNAL_SEQIDX_TAG, MPI_COMM_WORLD, &mpistatus)) != 0) mpi_failure("failed to receive sequence index to search");
1535 }
1536
1537 #if DEBUGMPI
1538 printf("worker %d received -1 seq idx from master, about to pack up hits\n", cfg->my_rank);
1539 #endif
1540
1541 /* done with this CM/mode pair, pack up results */
1542 buf_size = 0;
1543 status = MPI_Pack_size(1, MPI_LONG_LONG_INT, MPI_COMM_WORLD, &n); buf_size += n; if (status != 0) mpi_failure("pack size failed");
1544 for(h = 0; h < info.nhits; h++) {
1545 status = MPI_Pack_size(1, MPI_FLOAT, MPI_COMM_WORLD, &n); buf_size += n; if (status != 0) mpi_failure("pack size failed");
1546 }
1547 if (mpibuf == NULL || buf_size > mpibuf_size) {
1548 ESL_REALLOC(mpibuf, sizeof(char) * buf_size);
1549 mpibuf_size = buf_size;
1550 }
1551 pos = 0;
1552 if (MPI_Pack(&(info.nhits), 1, MPI_LONG_LONG_INT, mpibuf, buf_size, &pos, MPI_COMM_WORLD) != 0) mpi_failure("mpi pack failed");
1553 for(h = 0; h < info.nhits; h++) {
1554 if (MPI_Pack(&(info.scA[h]), 1, MPI_FLOAT, mpibuf, buf_size, &pos, MPI_COMM_WORLD) != 0) mpi_failure("mpi pack failed");
1555 }
1556 #if DEBUGMPI
1557 printf("worker %d about to send %d byte-sized buf back to master\n", cfg->my_rank, n);
1558 #endif
1559
1560 /* send results back to master */
1561 if (MPI_Send(mpibuf, buf_size, MPI_PACKED, 0, INFERNAL_SCORES_TAG, MPI_COMM_WORLD) != 0) mpi_failure("mpi send failed");
1562
1563 if(info.scA != NULL) { free(info.scA); info.scA = NULL; }
1564 info.nhits = 0;
1565 } /* end of for loop over exp_mode */
1566 FreeCM(cm);
1567 if(sq_block != NULL) esl_sq_DestroyBlock(sq_block);
1568 /* read the next CM */
1569 qhstatus = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm);
1570 }
1571 if(qhstatus != eslEOF) mpi_failure(cfg->cmfp->errbuf);
1572
1573 return eslOK;
1574
1575 ERROR:
1576 mpi_failure("Memory allocation error.");
1577 return eslEMEM;
1578 }
1579
1580 /* mpi_failure()
1581 * Generate an error message. If the clients rank is not 0, a
1582 * message is created with the error message and sent to the
1583 * master process for handling.
1584 */
1585 static void
1586 mpi_failure(char *format, ...)
1587 {
1588 va_list argp;
1589 int status = eslFAIL;
1590 int len;
1591 int rank;
1592 char str[512];
1593
1594 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
1595
1596 /* format the error mesg */
1597 va_start(argp, format);
1598 len = vsnprintf(str, sizeof(str), format, argp);
1599 va_end(argp);
1600
1601 /* make sure the error string is terminated */
1602 str[sizeof(str)-1] = '\0';
1603
1604 /* if the caller is the master, print the results and abort */
1605 if (rank == 0)
1606 {
1607 fprintf(stderr, "\nError: ");
1608 fprintf(stderr, "%s", str);
1609 fprintf(stderr, "\n");
1610 fflush(stderr);
1611
1612 MPI_Abort(MPI_COMM_WORLD, status);
1613 exit(1);
1614 }
1615 else
1616 {
1617 MPI_Send(str, len, MPI_CHAR, 0, INFERNAL_ERROR_TAG, MPI_COMM_WORLD);
1618 pause();
1619 }
1620 }
1621 #endif /*HAVE_MPI*/
1622
1623
1624 static void
1625 process_commandline(int argc, char **argv, ESL_GETOPTS **ret_go, char **ret_cmfile)
1626 {
1627 ESL_GETOPTS *go = NULL;
1628
1629 if ((go = esl_getopts_Create(options)) == NULL) cm_Fail("Internal failure creating options object");
1630 if (esl_opt_ProcessEnvironment(go) != eslOK) { printf("Failed to process environment: %s\n", go->errbuf); goto ERROR; }
1631 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) { printf("Failed to parse command line: %s\n", go->errbuf); goto ERROR; }
1632 if (esl_opt_VerifyConfig(go) != eslOK) { printf("Failed to parse command line: %s\n", go->errbuf); goto ERROR; }
1633
1634 /* help format: */
1635 if (esl_opt_GetBoolean(go, "-h")) {
1636 cm_banner(stdout, argv[0], banner);
1637 esl_usage(stdout, argv[0], usage);
1638 puts("\nBasic options:");
1639 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1= group; 2 = indentation; 80=textwidth*/
1640 puts("\nOptions for predicting running time and memory requirements:");
1641 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
1642 puts("\nOptions controlling exponential tail fits:");
1643 esl_opt_DisplayHelp(stdout, go, 3, 2, 80);
1644 puts("\nOptional output files:");
1645 esl_opt_DisplayHelp(stdout, go, 4, 2, 80);
1646 puts("\nOptions controlling split, partition and merge modes:");
1647 esl_opt_DisplayHelp(stdout, go, 5, 2, 80);
1648 puts("\nOther options:");
1649 esl_opt_DisplayHelp(stdout, go, 6, 2, 80);
1650 exit(0);
1651 }
1652
1653 if (esl_opt_ArgNumber(go) != 1) { puts("Incorrect number of command line arguments."); goto ERROR; }
1654 if ((*ret_cmfile = esl_opt_GetArg(go, 1)) == NULL) { puts("Failed to get <cmfile> argument on command line"); goto ERROR; }
1655
1656 *ret_go = go;
1657 return;
1658
1659 ERROR: /* all errors handled here are user errors, so be polite. */
1660 esl_usage(stdout, argv[0], usage);
1661 puts("\nwhere basic options are:");
1662 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1= group; 2 = indentation; 80=textwidth*/
1663 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
1664 exit(1);
1665 }
1666
1667 static int
1668 output_header(FILE *ofp, const ESL_GETOPTS *go, char *cmfile, int relevant_ncpus, int ncpus)
1669 {
1670 cm_banner(ofp, go->argv[0], banner);
1671
1672 fprintf(ofp, "# CM file: %s\n", cmfile);
1673 if (esl_opt_IsUsed(go, "-L")) { fprintf(ofp, "# total sequence length to search per mode: %g Mb\n", esl_opt_GetReal(go, "-L")); }
1674
1675 if (esl_opt_IsUsed(go, "--forecast")) { fprintf(ofp, "# forecast mode (no calibration): on\n"); }
1676 if (esl_opt_IsUsed(go, "--memreq")) { fprintf(ofp, "# memory-requirement mode (no calibration): on\n"); }
1677
1678 if (esl_opt_IsUsed(go, "--gtailn")) { fprintf(ofp, "# number of hits/Mb to fit (glocal): %d\n", esl_opt_GetInteger(go, "--gtailn")); }
1679 if (esl_opt_IsUsed(go, "--ltailn")) { fprintf(ofp, "# number of hits/Mb to fit (local): %d\n", esl_opt_GetInteger(go, "--ltailn")); }
1680 if (esl_opt_IsUsed(go, "--tailp")) { fprintf(ofp, "# fraction of histogram tail to fit: %g\n", esl_opt_GetReal(go, "--tailp")); }
1681
1682 if (esl_opt_IsUsed(go, "--hfile")) { fprintf(ofp, "# saving fitted score histograms to file: %s\n", esl_opt_GetString(go, "--hfile")); }
1683 if (esl_opt_IsUsed(go, "--sfile")) { fprintf(ofp, "# saving survival plot to file: %s\n", esl_opt_GetString(go, "--sfile")); }
1684 if (esl_opt_IsUsed(go, "--qqfile")) { fprintf(ofp, "# saving Q-Q plot for histograms to file: %s\n", esl_opt_GetString(go, "--qqfile")); }
1685 if (esl_opt_IsUsed(go, "--ffile")) { fprintf(ofp, "# saving lambdas for tail fit probs to file: %s\n", esl_opt_GetString(go, "--ffile")); }
1686 if (esl_opt_IsUsed(go, "--xfile")) { fprintf(ofp, "# saving scores from fit tails to file: %s\n", esl_opt_GetString(go, "--xfile")); }
1687
1688 if (esl_opt_IsUsed(go, "--split")) { fprintf(ofp, "# split mode: on\n"); }
1689 if (esl_opt_IsUsed(go, "--cfile")) { fprintf(ofp, "# saving partition commands to file: %s\n", esl_opt_GetString(go, "--cfile")); }
1690 if (esl_opt_IsUsed(go, "--cbash")) { fprintf(ofp, "# saving partition commands as bash script: on\n"); }
1691 if (esl_opt_IsUsed(go, "--proot")) { fprintf(ofp, "# root name for partition score files : %s\n", esl_opt_GetString(go, "--proot")); }
1692 if (esl_opt_IsUsed(go, "--part")) { fprintf(ofp, "# partition mode, partition number: %d\n", esl_opt_GetInteger(go, "--part")); }
1693 if (esl_opt_IsUsed(go, "--ptot")) { fprintf(ofp, "# total number of partitions: %d\n", esl_opt_GetInteger(go, "--ptot")); }
1694 if (esl_opt_IsUsed(go, "--pfile")) { fprintf(ofp, "# saving scores for this partition to file: %s\n", esl_opt_GetString(go, "--pfile")); }
1695 if (esl_opt_IsUsed(go, "--merge")) { fprintf(ofp, "# merge mode: on\n"); }
1696
1697 if (esl_opt_IsUsed(go, "--seed")) {
1698 if (esl_opt_GetInteger(go, "--seed") == 0) fprintf(ofp, "# random number seed: one-time arbitrary\n");
1699 else fprintf(ofp, "# random number seed set to: %d\n", esl_opt_GetInteger(go, "--seed"));
1700 }
1701 if (esl_opt_IsUsed(go, "--beta")) { fprintf(ofp, "# tail loss probability for QDBs: %g\n", esl_opt_GetReal(go, "--beta")); }
1702 if (esl_opt_IsUsed(go, "--nonbanded")) { fprintf(ofp, "# query dependent bands (QDBs): off\n"); }
1703 if (esl_opt_IsUsed(go, "--nonull3")) { fprintf(ofp, "# null3 bias corrections: off\n"); }
1704 if (esl_opt_IsUsed(go, "--random")) { fprintf(ofp, "# generating seqs with cm->null (usually iid): yes\n"); }
1705 if (esl_opt_IsUsed(go, "--gc")) { fprintf(ofp, "# nucleotide distribution from file: %s\n", esl_opt_GetString(go, "--gc")); }
1706 /* output number of processors being used, unless --forecast or --memreq is used */
1707 int output_ncpu = FALSE;
1708 if ((! esl_opt_IsUsed(go, "--forecast")) && (! esl_opt_IsUsed(go, "--memreq"))) {
1709 #ifdef HAVE_MPI
1710 if (esl_opt_IsUsed(go, "--mpi")) { fprintf(ofp, "# MPI: on [%d processors]\n", ncpus); output_ncpu = TRUE; }
1711 #endif
1712 #ifdef HMMER_THREADS
1713 if (! output_ncpu) { fprintf(ofp, "# number of worker threads: %d%s\n", ncpus, (esl_opt_IsUsed(go, "--cpu") ? " [--cpu]" : "")); output_ncpu = TRUE; }
1714 #endif
1715 if (! output_ncpu) { fprintf(ofp, "# number of worker threads: 0 [serial mode; threading unavailable]\n"); }
1716 }
1717 fprintf(ofp, "# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
1718 return eslOK;
1719 }
1720
1721
1722 /* init_master_cfg()
1723 * Called by masters, mpi or serial.
1724 * Allocates/sets:
1725 * cfg->hfp - optional output file
1726 * cfg->xfp - optional output file
1727 * cfg->ffp - optional output file
1728 * cfg->sfp - optional output file
1729 * cfg->qfp - optional output file
1730 * cfg->w - stopwatch
1731 * cfg->tmpfile - temp file for rewriting cm file
1732 *
1733 * Errors in the MPI master here are considered to be "recoverable",
1734 * in the sense that we'll try to delay output of the error message
1735 * until we've cleanly shut down the worker processes. Therefore
1736 * errors return (code, errbuf) by the ESL_FAIL mech.
1737 */
1738 static int
1739 init_master_cfg(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf)
1740 {
1741 int status;
1742
1743 /* initialize cfg variables used by masters and workers */
1744 if((status = init_shared_cfg(go, cfg, errbuf)) != eslOK) return status;
1745
1746 /* Masters only initializations: */
1747 /* open optional output files */
1748 if (esl_opt_GetString(go, "--hfile") != NULL) {
1749 if ((cfg->hfp = fopen(esl_opt_GetString(go, "--hfile"), "w")) == NULL)
1750 ESL_FAIL(eslFAIL, errbuf, "Failed to open exp tail histogram save file %s for writing\n", esl_opt_GetString(go, "--hfile"));
1751 }
1752 if (esl_opt_GetString(go, "--sfile") != NULL) {
1753 if ((cfg->sfp = fopen(esl_opt_GetString(go, "--sfile"), "w")) == NULL)
1754 ESL_FAIL(eslFAIL, errbuf, "Failed to open survival plot save file %s for writing\n", esl_opt_GetString(go, "--sfile"));
1755 }
1756 if (esl_opt_GetString(go, "--qqfile") != NULL) {
1757 if ((cfg->qfp = fopen(esl_opt_GetString(go, "--qqfile"), "w")) == NULL)
1758 ESL_FAIL(eslFAIL, errbuf, "Failed to open exp tail QQ plot save file %s for writing\n", esl_opt_GetString(go, "--qqfile"));
1759 }
1760 if (esl_opt_GetString(go, "--ffile") != NULL) {
1761 if ((cfg->ffp = fopen(esl_opt_GetString(go, "--ffile"), "w")) == NULL)
1762 ESL_FAIL(eslFAIL, errbuf, "Failed to open exp tail save file %s for writing\n", esl_opt_GetString(go, "--ffile"));
1763 }
1764 if (esl_opt_GetString(go, "--xfile") != NULL) {
1765 if ((cfg->xfp = fopen(esl_opt_GetString(go, "--xfile"), "w")) == NULL)
1766 ESL_FAIL(eslFAIL, errbuf, "Failed to open exp tail scores save file %s for writing\n", esl_opt_GetString(go, "--xfile"));
1767 }
1768
1769 /* create the stopwatch */
1770 cfg->w = esl_stopwatch_Create();
1771 if(cfg->w == NULL) ESL_FAIL(eslEMEM, errbuf, "Failed to create stopwatch.");
1772
1773 /* From HMMER 2.4X hmmcalibrate.c:
1774 * Generate calibrated CM(s) in a tmp file in the current
1775 * directory. When we're finished, we delete the original
1776 * CM file and rename() this one. That way, the worst
1777 * effect of a catastrophic failure should be that we
1778 * leave a tmp file lying around, but the original CM
1779 * file remains uncorrupted. tmpnam() doesn't work portably here,
1780 * because it'll put the file in /tmp and we won't
1781 * necessarily be able to rename() it from there.
1782 */
1783 ESL_ALLOC(cfg->tmpfile, (sizeof(char) * (strlen(cfg->cmfile) + 5)));
1784 strcpy(cfg->tmpfile, cfg->cmfile);
1785 strcat(cfg->tmpfile, ".xxx"); /* could be more inventive here... */
1786 if (esl_FileExists(cfg->tmpfile)) ESL_FAIL(eslFAIL, errbuf, "temporary file %s already exists; please delete it first", cfg->tmpfile);
1787 if (cfg->cmfp->is_binary) cfg->mode = "wb";
1788 else cfg->mode = "w";
1789
1790 return eslOK;
1791
1792 ERROR:
1793 ESL_FAIL(eslEMEM, errbuf, "init_master_cfg(), memory allocation error.");
1794 return eslEMEM; /* NEVER REACHED */
1795 }
1796
1797
1798 /* init_shared_cfg()
1799 * Called by serial masters and mpi workers and masters.
1800 * Allocates/sets:
1801 * cfg->cmfp - open CM file
1802 * cfg->gc_freq - observed GC freqs (if --gc invoked)
1803 * cfg->r - source of randomness
1804 * cfg->r_est - another source of randomness
1805 * cfg->sc_cutoff - cutoff score for collecting hits
1806 *
1807 * Errors in the MPI master here are considered to be "recoverable",
1808 * in the sense that we'll try to delay output of the error message
1809 * until we've cleanly shut down the worker processes. Therefore
1810 * errors return (code, errbuf) by the ESL_FAIL mech.
1811 */
1812 static int
1813 init_shared_cfg(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf)
1814 {
1815 int status;
1816
1817 /* open CM file */
1818 status = cm_file_Open(cfg->cmfile, NULL, FALSE, &(cfg->cmfp), errbuf);
1819 if (status == eslENOTFOUND) return status;
1820 else if (status == eslEFORMAT) return status;
1821 else if (status != eslOK) return status;
1822
1823 /* optionally, get distribution of GC content from an input database (default is use cm->null for GC distro) */
1824 if(esl_opt_GetString(go, "--gc") != NULL) {
1825 ESL_ALPHABET *tmp_abc = NULL;
1826 tmp_abc = esl_alphabet_Create(eslRNA);
1827 ESL_SQFILE *dbfp;
1828 status = esl_sqfile_Open(esl_opt_GetString(go, "--gc"), eslSQFILE_UNKNOWN, NULL, &dbfp);
1829 if (status == eslENOTFOUND) ESL_FAIL(status, errbuf, "No such file: %s.", esl_opt_GetString(go, "--gc"));
1830 else if (status == eslEFORMAT) ESL_FAIL(status, errbuf, "file: %s format unrecognized.", esl_opt_GetString(go, "--gc"));
1831 else if (status != eslOK) ESL_FAIL(status, errbuf, "Failed to open sequence database file %s, code %d.", esl_opt_GetString(go, "--gc"), status);
1832 if((status = GetDBInfo(tmp_abc, dbfp, errbuf, NULL, NULL, &(cfg->gc_freq))) != eslOK) return status;
1833 esl_vec_DNorm(cfg->gc_freq, GC_SEGMENTS);
1834 esl_alphabet_Destroy(tmp_abc);
1835 esl_sqfile_Close(dbfp);
1836 }
1837
1838 /* create and seed RNG, slightly wasteful in that we reseed before each CM's calibration/estimation, oh well. */
1839 cfg->r = esl_randomness_Create(esl_opt_GetInteger(go, "--seed"));
1840 cfg->r_est = esl_randomness_Create(esl_opt_GetInteger(go, "--seed"));
1841
1842 if(cfg->r == NULL) ESL_FAIL(eslEMEM, errbuf, "Failed to create RNG.");
1843 if(cfg->r_est == NULL) ESL_FAIL(eslEMEM, errbuf, "Failed to create RNG.");
1844
1845 cfg->sc_cutoff = -eslINFINITY;
1846
1847 return eslOK;
1848 }
1849
1850 /* initialize_cm()
1851 * Setup the CM based on the command-line options/defaults;
1852 * only set flags and a few parameters. cm_Configure() configures
1853 * the CM.
1854 */
1855 static int
1856 initialize_cm(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, int do_local)
1857 {
1858 int status;
1859
1860 /* config QDB? */
1861 if(esl_opt_GetBoolean(go, "--nonbanded")) {
1862 cm->search_opts |= CM_SEARCH_NONBANDED; /* don't use QDB to search */
1863 /* no need to recalculate QDBs, don't raise CM_CONFIG_QDB */
1864 }
1865 else {
1866 cm->search_opts |= CM_SEARCH_QDB; /* use QDB to search */
1867 /* check if cm->qdbinfo->beta2 == <x> from --beta, if so we don't need to recalculate QDBs */
1868 if(CheckCMQDBInfo(cm->qdbinfo, 0., FALSE, esl_opt_GetReal(go, "--beta"), TRUE) != eslOK) {
1869 /* we'll use beta2 for calibration, setting them both as equal makes it slightly more efficient */
1870 cm->config_opts |= CM_CONFIG_QDB; /* configure QDB */
1871 cm->qdbinfo->beta1 = esl_opt_GetReal(go, "--beta");
1872 cm->qdbinfo->beta2 = esl_opt_GetReal(go, "--beta");
1873 }
1874 }
1875
1876 cm->search_opts |= CM_SEARCH_NOALIGN;
1877
1878 if(! esl_opt_GetBoolean(go, "--nonull3")) cm->search_opts |= CM_SEARCH_NULL3;
1879
1880 /* ALWAYS use the greedy overlap resolution algorithm to return hits for exp calculation
1881 * it's irrelevant for filter threshold stats, we return best score per seq for that */
1882 /* don't turn on CM_SEARCH_CMNOTGREEDY */
1883
1884 if(do_local) {
1885 cm->config_opts |= CM_CONFIG_LOCAL;
1886 cm->config_opts |= CM_CONFIG_HMMLOCAL;
1887 cm->config_opts |= CM_CONFIG_HMMEL;
1888 }
1889 /* we'll need a scan matrix too */
1890 if(! esl_opt_IsUsed(go, "--memreq")) {
1891 cm->config_opts |= CM_CONFIG_SCANMX;
1892 /* if --memreq, we don't create the scan matrix, we just tell the user how big it will be */
1893 }
1894
1895 /* configure */
1896 if((status = cm_Configure(cm, errbuf, -1)) != eslOK) return status;
1897
1898 if(! esl_opt_IsUsed(go, "--memreq")) {
1899 if(cm->smx == NULL) ESL_FAIL(eslEINVAL, errbuf, "unable to create scan matrix for CM");
1900 }
1901
1902 return eslOK;
1903 }
1904
1905 /* initialize_stats()
1906 * Allocate and initialize cfg->expAA */
1907 static int
1908 initialize_stats(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf)
1909 {
1910 int status;
1911 int i;
1912 int cmi = cfg->ncm-1;
1913
1914 ESL_DPRINTF1(("#DEBUG: initializing cmstats\n"));
1915
1916 ESL_ALLOC(cfg->expAA[cmi], sizeof(ExpInfo_t *) * EXP_NMODES);
1917 for(i = 0; i < EXP_NMODES; i++) cfg->expAA[cmi][i] = CreateExpInfo();
1918
1919 return eslOK;
1920
1921 ERROR:
1922 return status;
1923 }
1924
1925 /* fit_histogram()
1926 * Create, fill and fit the tail of a histogram to an exponential tail. Data to fill the histogram
1927 * is given as <scores>.
1928 */
1929 static int
1930 fit_histogram(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, float *scores, int nscores, int exp_mode, double *ret_mu, double *ret_lambda, int *ret_nrandhits, float *ret_tailp)
1931 {
1932 int status;
1933 double mu;
1934 double lambda;
1935 int i;
1936 double *xv; /* raw data from histogram */
1937 int n,z;
1938 float tailp;
1939 double params[2];
1940 int nrandhits;
1941 float a;
1942 float nhits_to_fit;
1943
1944 ESL_HISTOGRAM *h = NULL; /* histogram of scores */
1945
1946 /* Initialize histogram; these numbers are guesses */
1947 if((h = esl_histogram_CreateFull(-100., 100., .1)) == NULL) return eslEMEM;
1948
1949 /* fill histogram */
1950 for(i = 0; i < nscores; i++) {
1951 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);
1952 /* printf("%4d %.3f\n", i, scores[i]); */
1953 }
1954
1955 /* fit scores to an exponential tail */
1956 if(cfg->ffp != NULL) {
1957 /* fit to 41 different tailp values and print lambda, mu to a save file */
1958 fprintf(cfg->ffp, "# %11s %10s %10s %12s\n", "tail pmass", "lambda", "mu", "nhits");
1959 fprintf(cfg->ffp, "# %11s %10s %10s %12s\n", "-----------", "----------", "----------", "------------");
1960 for(a = 0.; a >= -4.; a -= 0.1) {
1961 tailp = pow(10., a);
1962 esl_histogram_GetTailByMass(h, tailp, &xv, &n, &z);
1963 if(n > 1) {
1964 esl_exp_FitComplete(xv, n, &(params[0]), &(params[1]));
1965 esl_histogram_SetExpectedTail(h, params[0], tailp, &esl_exp_generic_cdf, &params);
1966 fprintf(cfg->ffp, " %.9f %10.6f %10.4f %12d\n", tailp, params[1], params[0], n);
1967 }
1968 else {
1969 fprintf(cfg->ffp, " %.9f %10s %10s %12d\n", tailp, "N/A", "N/A", n);
1970 }
1971 }
1972 fprintf(cfg->ffp, "//\n");
1973 }
1974 /* end of if cfg->ffp != NULL) */
1975
1976 /* determine the fraction of the tail to fit, if --tailp, it's easy */
1977 if(esl_opt_IsOn(go, "--tailp")) {
1978 tailp = esl_opt_GetReal(go, "--tailp");
1979 }
1980 else { /* number of hits is per Mb and specific to local or glocal fits */
1981 if(ExpModeIsLocal(exp_mode)) { /* local mode */
1982 nhits_to_fit = (float) esl_opt_GetInteger(go, "--ltailn") * ((cfg->N * cfg->L) / 1000000.);
1983 tailp = nhits_to_fit / (float) h->n;
1984 if(tailp > 1.) ESL_FAIL(eslERANGE, errbuf, "--ltailn <n>=%d cannot be used, there's only %.3f hits per Mb in the histogram! Lower <n> or use --tailp.", esl_opt_GetInteger(go, "--ltailn"), (h->n / ((float) cfg->N * ((float) cfg->L) / 1000000.)));
1985 }
1986 else { /* glocal mode */
1987 nhits_to_fit = (float) esl_opt_GetInteger(go, "--gtailn") * ((cfg->N * cfg->L) / 1000000.);
1988 tailp = nhits_to_fit / (float) h->n;
1989 if(tailp > 1.) ESL_FAIL(eslERANGE, errbuf, "--gtailn <n>=%d cannot be used, there's only %.3f hits per Mb in the histogram! Lower <n> or use --tailp.", esl_opt_GetInteger(go, "--gtailn"), (h->n / ((float) cfg->N * ((float) cfg->L) / 1000000.)));
1990 }
1991 }
1992
1993 esl_histogram_GetTailByMass(h, tailp, &xv, &n, &z); /* fit to right 'tailfit' fraction, 'tailfit' was determined in above block */
1994 if(n <= 1) ESL_FAIL(eslERANGE, errbuf, "fit_histogram(), too few points in right tailfit: %f fraction of histogram. Increase <x> with -L <x>.", tailp);
1995 if(cfg->xfp != NULL) { for(i = 0; i < n; i++) { fprintf(cfg->xfp, "%.5f\n", xv[i]); } fprintf(cfg->xfp, "&\n"); }
1996 esl_exp_FitComplete(xv, n, &(params[0]), &(params[1]));
1997 esl_histogram_SetExpectedTail(h, params[0], tailp, &esl_exp_generic_cdf, &params);
1998
1999 /* printf("# Exponential fit to %.7f%% tail: lambda = %f\n", tailp*100.0, params[1]); */
2000 mu = params[0];
2001 lambda = params[1];
2002 if(isnan(lambda)) ESL_FAIL(eslERANGE, errbuf, "fit_histogram(), exp tail fit lambda is NaN, too few hits in histogram. Increase <x> with -L <x>.");
2003 if(isinf(lambda)) ESL_FAIL(eslERANGE, errbuf, "fit_histogram(), exp tail fit lambda is inf, too few hits in histogram. Increase <x> with -L <x>.");
2004 nrandhits = h->n; /* total number of hits in the histogram */
2005
2006 /* print to output files if nec */
2007 if(cfg->hfp != NULL) esl_histogram_Plot(cfg->hfp, h);
2008 if(cfg->qfp != NULL) esl_histogram_PlotQQ(cfg->qfp, h, &esl_exp_generic_invcdf, params);
2009 if (cfg->sfp != NULL) {
2010 esl_histogram_PlotSurvival(cfg->sfp, h);
2011 esl_exp_Plot(cfg->sfp, (params[0] - log(1./tailp) / params[1]), 0.693147, esl_exp_surv, h->xmin - 5., h->xmax + 5., 0.1); /* extrapolate mu */
2012 }
2013 esl_histogram_Destroy(h);
2014
2015 *ret_mu = mu;
2016 *ret_lambda = lambda;
2017 *ret_nrandhits = nrandhits;
2018 *ret_tailp = tailp;
2019 return eslOK;
2020 }
2021
2022 /* Function: get_random_dsq()
2023 * Date: EPN, Tue Sep 11 08:31:47 2007
2024 *
2025 * Purpose: Generate a random digitized seq and return it.
2026 * Two possible modes:
2027 * 1. if(cfg->gc_freq == NULL)
2028 * use dnull disto (a double version of cm->null) to generate
2029 * 2. if(cfg->gc_freq != NULL)
2030 * use choose a GC frequency from cfg->gc_freq
2031 * and generate with that
2032 *
2033 * Returns: eslOK on success, ret_dsq filled with newly alloc'ed ESL_DSQ *,
2034 * some other status code on failure.
2035 */
2036 int
2037 get_random_dsq(const struct cfg_s *cfg, char *errbuf, CM_t *cm, int L, ESL_RANDOMNESS *r, ESL_DSQ **ret_dsq)
2038 {
2039 int status;
2040 double gc_comp;
2041 double *distro = NULL;
2042 int do_free_distro = FALSE;
2043 ESL_DSQ *dsq = NULL;
2044
2045 /* generate sequence */
2046 if (cfg->gc_freq == NULL) distro = cfg->dnull;
2047 else { /* cfg->gc_freq != NULL, use that */
2048 assert(cm->abc->K == 4);
2049 ESL_ALLOC(distro, sizeof(double) * cm->abc->K);
2050 do_free_distro = TRUE;
2051 gc_comp = 0.01 * esl_rnd_DChoose(r, cfg->gc_freq, GC_SEGMENTS);
2052 distro[1] = distro[2] = 0.5 * gc_comp;
2053 distro[0] = distro[3] = 0.5 * (1. - gc_comp);
2054 }
2055 /* generate sequence */
2056 ESL_ALLOC(dsq, sizeof(ESL_DSQ) * (L+2));
2057 if ((status = esl_rsq_xIID(r, distro, cm->abc->K, L, dsq) != eslOK)) return status;
2058
2059 if (do_free_distro) free(distro);
2060 *ret_dsq = dsq;
2061 return eslOK;
2062
2063 ERROR:
2064 return status;
2065 }
2066
2067 /* Function: set_dnull
2068 * Date: EPN, Thu Jan 24 09:48:54 2008
2069 *
2070 * Purpose: Allocate, fill and return dnull, a double version of cm->null used
2071 * for generating random seqs.
2072 *
2073 * Returns: eslOK on success
2074 */
2075 static int
2076 set_dnull(struct cfg_s *cfg, CM_t *cm, char *errbuf)
2077 {
2078 int status;
2079 int i;
2080
2081 if(cfg->dnull != NULL) { free(cfg->dnull); }
2082 ESL_ALLOC(cfg->dnull, sizeof(double) * cm->abc->K);
2083 for(i = 0; i < cm->abc->K; i++) cfg->dnull[i] = (double) cm->null[i];
2084 esl_vec_DNorm(cfg->dnull, cm->abc->K);
2085
2086 return eslOK;
2087
2088 ERROR:
2089 ESL_FAIL(eslEINCOMPAT, errbuf, "set_dnull(), memory allocation error.");
2090 }
2091
2092 /* print_calibration_column_headings()
2093 * print_forecasted_time()
2094 * print_total_time()
2095 * print_summary()
2096 *
2097 * Output functions called by masters.
2098 */
2099 static void
2100 print_calibration_column_headings(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm, int relevant_ncpus)
2101 {
2102 printf("#\n");
2103 if(esl_opt_IsUsed(go, "--forecast")) {
2104 printf("# Forecasting running time for CM calibration(s) on %d cpus:\n",
2105 (esl_opt_IsUsed(go, "--nforecast") ? esl_opt_GetInteger(go, "--nforecast") : relevant_ncpus));
2106 printf("#\n");
2107 printf("# %-20s %12s\n", "", " predicted");
2108 printf("# %-20s %12s\n", "", "running time");
2109 printf("# %-20s %12s\n", "model name", "(hr:min:sec)");
2110 printf("# %-20s %12s\n", "--------------------", "------------");
2111 }
2112 else if(esl_opt_IsUsed(go, "--merge")) {
2113 printf("# Merging partition scores and calibrating CM(s):\n");
2114 printf("#\n");
2115 }
2116 else {
2117 printf("# Calibrating CM(s):\n");
2118 printf("#\n");
2119 printf("# %-20s %-12s %-42s %-12s\n", "", " predicted", "", " actual");
2120 printf("# %-20s %-12s %-42s %-12s\n", "", "running time", " percent complete", "running time");
2121 printf("# %-20s %12s %42s %12s\n", "model name", "(hr:min:sec)", "[........25........50........75..........]", "(hr:min:sec)");
2122 printf("# %-20s %12s %42s %12s\n", "--------------------", "------------", "------------------------------------------", "------------");
2123 }
2124 return;
2125 }
2126
2127 static void
2128 print_forecasted_time(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm, double psec)
2129 {
2130 char time_buf[128]; /* for printing run time */
2131
2132 if(esl_opt_IsUsed(go, "--ptot")) {
2133 psec = (psec / esl_opt_GetInteger(go, "--ptot"));
2134 }
2135
2136 if(esl_opt_GetBoolean(go, "--noforecast")) { /* no forecast performed, print '?' */
2137 printf(" %-20s %12s", cm->name, "?");
2138 }
2139 else {
2140 FormatTimeString(time_buf, 128, psec, FALSE); /* 128: buffer size */
2141 printf(" %-20s %12s", cm->name, time_buf);
2142 }
2143 if(! esl_opt_IsUsed(go, "--forecast")) fputs(" [", stdout);
2144 else fputs("\n", stdout);
2145 fflush(stdout);
2146
2147 return;
2148 }
2149
2150 static void
2151 print_total_time(const ESL_GETOPTS *go, double total_asec, double total_psec)
2152 {
2153 char time_buf[128];
2154
2155 printf("# %20s %12s", "--------------------", "------------");
2156 if(! esl_opt_IsUsed(go, "--forecast")) {
2157 FormatTimeString(time_buf, 128, total_asec, FALSE);
2158 printf(" %42s %12s", "------------------------------------------", "------------");
2159 }
2160 printf("\n");
2161 FormatTimeString(time_buf, 128, total_psec, FALSE); /* 128: buffer size */
2162 printf("# %-20s %12s", "all models", time_buf);
2163 if(! esl_opt_IsUsed(go, "--forecast")) {
2164 FormatTimeString(time_buf, 128, total_asec, FALSE); /* 128: buffer size */
2165 printf(" %42s %12s", "", time_buf);
2166 }
2167 printf("\n");
2168
2169 return;
2170 }
2171
2172 static void
2173 print_summary(const struct cfg_s *cfg)
2174 {
2175 int i;
2176
2177 printf("#\n");
2178 printf("# Calibration summary statistics:\n");
2179 printf("#\n");
2180 printf("# %20s %-31s %-31s %-31s\n", "", " exponential tail fit mu", " exponential tail fit lambda", " total number of hits");
2181 printf("# %20s %31s %31s %31s\n", "", "-------------------------------", "-------------------------------", "-------------------------------");
2182 printf("# %-20s %7s %7s %7s %7s %7s %7s %7s %7s %7s %7s %7s %7s\n", "model name",
2183 "glc cyk", "glc ins", "loc cyk", "loc ins",
2184 "glc cyk", "glc ins", "loc cyk", "loc ins",
2185 "glc cyk", "glc ins", "loc cyk", "loc ins");
2186 printf("# %20s %7s %7s %7s %7s %7s %7s %7s %7s %7s %7s %7s %7s\n", "--------------------",
2187 "-------", "-------", "-------", "-------",
2188 "-------", "-------", "-------", "-------",
2189 "-------", "-------", "-------", "-------");
2190 for(i = 0; i < cfg->ncm; i++) {
2191 printf(" %-20s", cfg->namesA[i]);
2192 printf(" %7.2f %7.2f %7.2f %7.2f", cfg->expAA[i][EXP_CM_GC]->mu_orig, cfg->expAA[i][EXP_CM_GI]->mu_orig, cfg->expAA[i][EXP_CM_LC]->mu_orig, cfg->expAA[i][EXP_CM_LI]->mu_orig);
2193 printf(" %7.3f %7.3f %7.3f %7.3f", cfg->expAA[i][EXP_CM_GC]->lambda, cfg->expAA[i][EXP_CM_GI]->lambda, cfg->expAA[i][EXP_CM_LC]->lambda, cfg->expAA[i][EXP_CM_LI]->lambda);
2194 printf(" %7d %7d %7d %7d\n", cfg->expAA[i][EXP_CM_GC]->nrandhits, cfg->expAA[i][EXP_CM_GI]->nrandhits, cfg->expAA[i][EXP_CM_LC]->nrandhits, cfg->expAA[i][EXP_CM_LI]->nrandhits);
2195 }
2196
2197 return;
2198 }
2199
2200 /* Function: expand_exp_and_name_arrays()
2201 * Date: EPN, Thu Dec 29 11:15:12 2011
2202 *
2203 * Purpose: Expand arrays that depend on total number of
2204 * CMs in the file, which we don't know until
2205 * we've finished.
2206 *
2207 * Returns: eslOK on success
2208 */
2209 static int
2210 expand_exp_and_name_arrays(struct cfg_s *cfg)
2211 {
2212 int status;
2213 int i;
2214
2215 if(cfg->ncm == cfg->cmalloc) { /* expand our memory */
2216 ESL_REALLOC(cfg->expAA, sizeof(ExpInfo_t **) * (cfg->cmalloc + 128));
2217 ESL_REALLOC(cfg->namesA, sizeof(char *) * (cfg->cmalloc + 128));
2218 ESL_REALLOC(cfg->comlogsA, sizeof(char *) * (cfg->cmalloc + 128));
2219 for(i = cfg->cmalloc; i < cfg->cmalloc + 128; i++) {
2220 cfg->namesA[i] = NULL;
2221 cfg->comlogsA[i] = NULL;
2222 }
2223 cfg->cmalloc += 128;
2224 }
2225 return eslOK;
2226
2227 ERROR:
2228 return status;
2229 }
2230
2231 /* Function: generate_sequences()
2232 * Date: EPN, Fri Dec 16 09:41:32 2011
2233 *
2234 * Purpose: Generate all sequences to be used for fitting a single
2235 * model in a single mode, and return them as a single
2236 * ESL_SQ_BLOCK in <*ret_sq_block>.
2237 *
2238 * By default, we reseed the RNG before we generate
2239 * the sequences, so all models (if we have more than
2240 * one) will be calibrated with the same sequences.
2241 * This eliminates run-to-run variation.
2242 * However, if seed==0 means we chose an arbitrary
2243 * seed and we shut off the reinitialization;
2244 * this allows run-to-run variation.
2245 *
2246 * Returns: eslOK on success, filled block is in *ret_sq_block.
2247 * eslEMEM if out of memory.
2248 */
2249 int
2250 generate_sequences(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, ESL_SQ_BLOCK **ret_sq_block)
2251 {
2252 int status;
2253 ESL_SQ_BLOCK *sq_block = NULL;
2254 ESL_SQ *sq = NULL;
2255 ESL_DSQ *dsq = NULL;
2256 int i;
2257 int namelen = strlen("irrelevant");
2258
2259 /* reseed RNG, unless --seed 0 */
2260 if(esl_opt_GetInteger(go, "--seed") != 0) {
2261 esl_randomness_Init(cfg->r, esl_randomness_GetSeed(cfg->r));
2262 }
2263
2264 sq_block = esl_sq_CreateDigitalBlock(cfg->N, cfg->abc);
2265 for(i = 0; i < cfg->N; i++) {
2266 /* generate the dsq */
2267 if(esl_opt_GetBoolean(go, "--random") || esl_opt_IsUsed(go, "--gc")) {
2268 if((status = get_random_dsq(cfg, errbuf, cm, cfg->L, cfg->r, &dsq)) != eslOK) goto ERROR;
2269 }
2270 else {
2271 if((status = SampleGenomicSequenceFromHMM(cfg->r, cfg->abc, errbuf, cfg->ghmm_sA, cfg->ghmm_tAA, cfg->ghmm_eAA, cfg->ghmm_nstates, cfg->L, &dsq)) != eslOK) goto ERROR;
2272 }
2273
2274 /* Copy dsq we just created into sq_block->list+i
2275 * We can't use esl_sq_CreateDigitalFrom() bc sq_block->list already contains a contiguous set of ESL_SQ objects
2276 */
2277 sq = sq_block->list + i;
2278 /* esl_sq_CreateDigitalBlock() allocates sq->dsq and sq->name for each sq in the block, we'll refill them, so free them first */
2279 free(sq->dsq);
2280 sq->dsq = NULL;
2281 free(sq->name);
2282 sq->name = NULL;
2283
2284 if ((status = esl_abc_dsqdup(dsq, cfg->L, &(sq->dsq))) != eslOK) goto ERROR;
2285 free(dsq); /* we just duplicated it */
2286 sq->L = cfg->L;
2287 /* set the name (we don't actually use it, but all valid ESL_SQ objects are supposed to have it) */
2288 ESL_ALLOC(sq->name, sizeof(char) * (namelen+1));
2289 strcpy(sq->name, "irrelevant");
2290 sq->nalloc = namelen;
2291 sq_block->count++;
2292 /* note: we don't use esl_sq_CreateDigitalFrom() above because we're dealing with a ESL_SQ_BLOCK which allocates
2293 * all its sequences in a contiguous blocks (not as pointers)
2294 */
2295 }
2296 sq_block->first_seqidx = 0;
2297 sq_block->complete = TRUE;
2298
2299 *ret_sq_block = sq_block;
2300 return eslOK;
2301
2302 ERROR:
2303 if(sq_block != NULL) {
2304 esl_sq_DestroyBlock(sq_block);
2305 }
2306 *ret_sq_block = NULL;
2307 return status;
2308 }
2309
2310 /* Function: process_search_workunit()
2311 * Date: EPN, Thu Dec 8 13:48:02 2011
2312 *
2313 * Purpose: Perform search workunit, which consists of a CM, digitized sequence
2314 * and indices i and j. The job is to search dsq from i..j and return
2315 * search results in <*ret_results>.
2316 *
2317 * Args: cm - the covariance model, must have valid searchinfo (si).
2318 * errbuf - char buffer for reporting errors
2319 * dsq - the digitized sequence
2320 * L - length of target sequence
2321 * cutoff - minimum bit score cutoff to report
2322 * ret_th - search_results_t to create and fill
2323 *
2324 * Returns: eslOK on succes;
2325 * <ret_th> is filled with a newly alloc'ed and filled CM_TOPHITS structure, must be freed by caller
2326 */
2327 int
2328 process_search_workunit(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float cutoff, CM_TOPHITS **ret_th)
2329 {
2330 int status;
2331 CM_TOPHITS *th = NULL;
2332 int use_qdbs = (cm->search_opts & CM_SEARCH_QDB) ? TRUE : FALSE;
2333
2334 th = cm_tophits_Create();
2335 if(th == NULL) ESL_FAIL(eslEMEM, errbuf, "out of memory");
2336
2337 if(cm->search_opts & CM_SEARCH_INSIDE) {
2338 if((status = FastIInsideScan(cm, errbuf, cm->smx,
2339 use_qdbs ? SMX_QDB2_LOOSE : SMX_NOQDB, /* qdbidx, indicates which QDBs to use */
2340 dsq, 1, L, /* sequence, bounds */
2341 cutoff, /* minimum score to report */
2342 th, /* hitlist to add to */
2343 cm->search_opts & CM_SEARCH_NULL3, /* do the NULL3 correction? */
2344 0., NULL, NULL, /* vars for redefining envelopes, which we won't do */
2345 NULL, NULL)) /* ret_vsc, ret_sc, irrelevant here */
2346 != eslOK) return status;
2347 }
2348 else {
2349 if((status = FastCYKScan(cm, errbuf, cm->smx,
2350 use_qdbs ? SMX_QDB2_LOOSE : SMX_NOQDB, /* qdbidx, indicates which QDBs to use */
2351 dsq, 1, L, /* sequence, bounds */
2352 cutoff, /* minimum score to report */
2353 th, /* hitlist to add to */
2354 cm->search_opts & CM_SEARCH_NULL3, /* do the NULL3 correction? */
2355 0., NULL, NULL, /* vars for redefining envelopes, which we won't do */
2356 NULL, NULL)) /* ret_vsc, ret_sc, irrelevant here */
2357 != eslOK) return status;
2358 }
2359 /* we don't have to remove overlaps, that's already been done in
2360 * FastCYKScan() or FastIInsideScan()
2361 */
2362
2363 if(ret_th != NULL) *ret_th = th;
2364 else cm_tophits_Destroy(th);
2365 return eslOK;
2366 }
2367
2368 /* Function: forecast_time
2369 * Date: EPN, Wed Mar 5 05:46:45 2008
2370 * EPN, Thu Dec 29 09:33:01 2011 [Updated]
2371 *
2372 * Purpose: Estimate search time for calibration of a CM. We do this
2373 * by timing a search of a sequence of length 2*W with
2374 * both glocal CYK and glocal Inside and extrapolating that
2375 * running time to what it should be for the full
2376 * calibration, taking into account the fact that the first
2377 * W residues require fewer DP calculations.
2378 *
2379 * We must be in glocal mode upon entering, and we assume
2380 * that local mode searches will take the same time as
2381 * glocal ones, which is roughly true (their differences are
2382 * within the margin of error almost certainly).
2383 *
2384 * Returns: <ret_psec>: predicted number of seconds for calibration (accounting for parallelization)
2385 * <ret_ins_v_cyk>: ratio of inside to cyk running time, rounded to nearest int
2386 * eslOK on success.
2387 *
2388 */
2389 int forecast_time(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, int ncpus, int relevant_ncpus, double *ret_psec, int *ret_ins_v_cyk)
2390 {
2391 int status;
2392 int L; /* length of sequence we'll generate and search to get time estimate, 2 * cm->W */
2393 float Mc; /* millions of DP calculations we're going to do */
2394 float Mc_per_res_corr; /* millions of DP calcs per residue, if searching with CM, corrects for first W residues requiring less dp calcs */
2395 float Mc_per_res; /* millions of DP calcs per residue, if searching with CM, does not correct for first W residues requiring less dp calcs */
2396 int orig_search_opts; /* cm->search_opts when function was entered, restored before leaving */
2397 float cyk_sec_per_res; /* seconds per residue for glocal CYK */
2398 float ins_sec_per_res; /* seconds per residue for glocal Inside */
2399 int use_qdb; /* TRUE if we're using QDB, FALSE if not */
2400 ESL_DSQ *dsq = NULL; /* the random seq we'll create and search to get predicted time */
2401 double psec; /* total number of seconds predicted for calibrating the CM (accounting for parallelization) */
2402 int ins_v_cyk; /* ratio of predicted inside versus cyk running time */
2403 int denom; /* denominator used for dividing psec if --forecast */
2404
2405 /* contract check */
2406 if(cm->flags & CMH_LOCAL_BEGIN) ESL_FAIL(eslEINCOMPAT, errbuf, "forecast_running_time() CM has local begins on");
2407 if(cm->flags & CMH_LOCAL_END) ESL_FAIL(eslEINCOMPAT, errbuf, "forecast_running_time() CM has local ends on");
2408 if(cm->search_opts & CM_SEARCH_INSIDE) ESL_FAIL(eslEINCOMPAT, errbuf, "forecast_running_time() CM wants to search with Inside");
2409 if(cm->smx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "forecast_running_time(), cm->smx is NULL");
2410
2411 /* reseed RNG, unless --seed 0 */
2412 if(esl_opt_GetInteger(go, "--seed") != 0) {
2413 esl_randomness_Init(cfg->r_est, esl_randomness_GetSeed(cfg->r_est));
2414 }
2415
2416 orig_search_opts = cm->search_opts; /* we'll restore this at end of function */
2417
2418 use_qdb = (cm->search_opts & CM_SEARCH_QDB) ? TRUE : FALSE;
2419
2420 /* generate a sequence of length L=2*W (or 200, whichever is bigger) */
2421 L = ESL_MAX((2 * cm->W), 200);
2422 if(esl_opt_GetBoolean(go, "--random") || esl_opt_IsUsed(go, "--gc")) {
2423 if((status = get_random_dsq(cfg, errbuf, cm, L, cfg->r_est, &dsq)) != eslOK) return status;
2424 }
2425 else {
2426 if((status = SampleGenomicSequenceFromHMM(cfg->r_est, cm->abc, errbuf, cfg->ghmm_sA, cfg->ghmm_tAA, cfg->ghmm_eAA, cfg->ghmm_nstates, L, &dsq)) != eslOK) cm_Fail(errbuf);
2427 }
2428
2429 /* determine number of DP calculations we'll do for a sequence of
2430 * length L, FALSE in the following function call indicates not to
2431 * correct for fewer dp calcs for first W residues, we want to know
2432 * how many total DP calcs there will be for L residues
2433 */
2434 if(use_qdb) { if((status = cm_CountSearchDPCalcs(cm, errbuf, L, NULL, NULL, cm->W, FALSE, NULL, &Mc_per_res)) != eslOK) return status; }
2435 else { if((status = cm_CountSearchDPCalcs(cm, errbuf, L, cm->qdbinfo->dmin2, cm->qdbinfo->dmax2, cm->W, FALSE, NULL, &Mc_per_res)) != eslOK) return status; }
2436 Mc = Mc_per_res * L; /* total number of DP calcs we're about to do in the simulated workunit */
2437
2438 /* now determine how many Mc there are per residue, and do correct
2439 * for the first W residues (i.e. ignore the first W residues)
2440 */
2441 if(use_qdb) { if((status = cm_CountSearchDPCalcs(cm, errbuf, 10*cm->W, NULL, NULL, cm->W, TRUE, NULL, &Mc_per_res_corr)) != eslOK) return status; }
2442 else { if((status = cm_CountSearchDPCalcs(cm, errbuf, 10*cm->W, cm->qdbinfo->dmin2, cm->qdbinfo->dmax2, cm->W, TRUE, NULL, &Mc_per_res_corr)) != eslOK) return status; }
2443
2444 /* search our sequence, first with glocal CYK */
2445 esl_stopwatch_Start(cfg->w);
2446 if((status = process_search_workunit(cm, errbuf, dsq, L, cfg->sc_cutoff, NULL)) != eslOK) cm_Fail(errbuf);
2447 esl_stopwatch_Stop(cfg->w);
2448 cyk_sec_per_res = cfg->w->user * (Mc_per_res_corr / Mc);
2449
2450 /* search it again, with glocal Inside */
2451 cm->search_opts |= CM_SEARCH_INSIDE;
2452 esl_stopwatch_Start(cfg->w);
2453 if((status = process_search_workunit(cm, errbuf, dsq, L, cfg->sc_cutoff, NULL)) != eslOK) cm_Fail(errbuf);
2454 esl_stopwatch_Stop(cfg->w);
2455 ins_sec_per_res = cfg->w->user * (Mc_per_res_corr / Mc);
2456
2457 /* restore original search_opts */
2458 cm->search_opts = orig_search_opts;
2459
2460 /* determine ratio inside to cyk */
2461 ins_v_cyk = (int) ((ins_sec_per_res / cyk_sec_per_res) + 0.5); /* round up */
2462 ins_v_cyk = ESL_MAX(ins_v_cyk, 1);
2463
2464 /* sum up total predicted time */
2465 psec = 2. * (cyk_sec_per_res + ins_sec_per_res); /* local and glocal, assumed to be same run time */
2466 psec *= (float) cfg->L * (float) cfg->N;
2467 /* correct for parallelization */
2468 if(esl_opt_IsUsed(go, "--forecast")) {
2469 denom = (esl_opt_IsUsed(go, "--nforecast")) ? esl_opt_GetInteger(go, "--nforecast") : relevant_ncpus;
2470 psec /= (float) ESL_MAX(1, denom);
2471 /* Note, this is correct for MPI but will be slightly off for
2472 * threaded - because all threads do searches, whereas in MPI
2473 * master doesn't do searches.
2474 */
2475 }
2476 else if(ncpus > 0) {
2477 psec /= ncpus;
2478 }
2479
2480 /*printf("L: %d\n", L);
2481 printf("w->user: %g\n", cfg->w->user);
2482 printf("cyk_sec_per_res: %g\n", cyk_sec_per_res);
2483 printf("ins_sec_per_res: %g\n", ins_sec_per_res);
2484 printf("Mc_per_res: %g\n", Mc_per_res);
2485 printf("Mc: %g\n", Mc);
2486 */
2487
2488 if(dsq != NULL) free(dsq);
2489 if(ret_psec != NULL) *ret_psec = psec;
2490 if(ret_ins_v_cyk != NULL) *ret_ins_v_cyk = ins_v_cyk;
2491
2492 return eslOK;
2493 }
2494
2495
2496 /* Function: print_required_memory()
2497 * Date: EPN, Tue Jan 17 20:30:13 2012
2498 *
2499 * Purpose: Print how much memory is required for calibration
2500 * to stdout.
2501 *
2502 * Returns: void
2503 *
2504 */
2505 void print_required_memory(CM_t *cm, int L, int N, int ncpus, int do_header, int do_nonbanded)
2506 {
2507 float cm_reqmb = 0.;
2508 float smx_reqmb = 0.;
2509 float seq_reqmb = 0.;
2510 float hit_reqmb = 0.;
2511 float ser_reqmb = 0.;
2512 float thr_reqmb = 0.;
2513
2514 if(do_header) {
2515 printf("# Predicting required memory for calibration:\n");
2516 printf("#\n");
2517 if(ncpus > 1) {
2518 printf("# %-20s %10s %10s\n", "", " total Mb", " total Mb");
2519 printf("# %-20s %10s %2s%3d%5s\n", "", "single CPU", "", ncpus, " CPUs");
2520 printf("# %-20s %10s %10s\n", "--------------------", "----------", "----------");
2521 }
2522 else {
2523 printf("# %-20s %10s\n", "", " total Mb");
2524 printf("# %-20s %10s\n", "--------------------", "----------");
2525 }
2526 }
2527
2528 /* determine size of the CM (it's already been configured) */
2529 cm_reqmb = cm_Sizeof(cm);
2530
2531 /* if --memreq, we didn't create the scan matrix when we configured the CM (in case it was too big!) */
2532 smx_reqmb = cm_scan_mx_SizeNeeded(cm, TRUE, TRUE);
2533
2534 /* calculate size of digitized sequences we'll search */
2535 seq_reqmb = N * (sizeof(ESL_DSQ) * (L+2));
2536 seq_reqmb += N * sizeof(ESL_SQ);
2537 seq_reqmb += N * sizeof(char) * strlen("irrelevant");
2538 seq_reqmb /= 1000000.;
2539
2540 /* Estimate size of CM_HITLIST tmp_hitlist (based on number of hits)
2541 * within FastCYKScan() and FastIInsideScan() *before* overlaps are
2542 * removed. It's difficult to predict what this will be, so we use
2543 * an empirical estimate based on all Rfam 11 CMs. See
2544 * ~nawrockie/notebook/12_0927_inf_cmcalibrate_mpi_memory/00LOG
2545 * for details.
2546 */
2547 if(do_nonbanded) {
2548 hit_reqmb = 572.; /* max seen in all Rfam 11 with --nonbanded */
2549 }
2550 else {
2551 hit_reqmb = 72.; /* max seen in all Rfam 11 with default, note we don't adjust for different beta values */
2552 }
2553
2554 /* total up memory requirements */
2555 ser_reqmb = cm_reqmb + smx_reqmb + hit_reqmb + seq_reqmb;
2556 thr_reqmb = ((cm_reqmb + smx_reqmb + hit_reqmb) * ncpus) + seq_reqmb;
2557
2558 if(ncpus > 1) {
2559 printf(" %-20s %10.1f %10.1f\n", cm->name, ser_reqmb, thr_reqmb);
2560 }
2561 else {
2562 printf(" %-20s %10.1f\n", cm->name, ser_reqmb);
2563 }
2564 return;
2565 }
2566
2567
2568 /* Function: print_required_memory_tail()
2569 * Date: EPN, Wed Jan 18 11:39:34 2012
2570 *
2571 * Purpose: Print some explanatory information on
2572 * required memory output.
2573 *
2574 * Returns: void
2575 *
2576 */
2577 void print_required_memory_tail(int ncpus)
2578 {
2579 printf("#\n");
2580 if(ncpus > 1) {
2581 printf("# To enforce a single CPU be used, use the '--cpu 0' option.\n");
2582 printf("# To enforce <n> CPUs be used, use '--cpu <n>'.\n");
2583 printf("# By default (if '--cpu' is not used), %d CPUs will be used.\n", ncpus);
2584 #if HAVE_MPI
2585 printf("#\n");
2586 #endif
2587 }
2588 #if HAVE_MPI
2589 printf("# With MPI ('--mpi'), <n>-CPU machines will require <n> times\n");
2590 printf("# more memory than single-CPU machines.\n");
2591 #endif
2592
2593 return;
2594 }
2595
2596 /* Function: read_partition_scores_files_for_one_cm()
2597 * Date: EPN, Wed May 18 14:04:26 2022
2598 *
2599 * Purpose: Read scores for all exp modes from all partition scores files for
2600 * CM index <cmi> and store them in *ret_pmerged_scAA and *ret_pmerged_nhitsA.
2601 *
2602 * Returns: eslOK on success, else an error code and fills errbuf with error message.
2603 */
2604 static int
2605 read_partition_scores_files_for_one_cm(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, int cmi, float ***ret_pmerged_scAAA, int64_t **ret_pmerged_nhitsAA)
2606 {
2607 int status;
2608 int ptot = esl_opt_GetInteger(go, "--ptot");
2609 int exp_mode = 0;
2610
2611 int64_t *pmerged_nhitsA = NULL; /* [0..EXP_NMODES-1] number of hits reported for all seqs for each exp mode, read from input score files from each partition */
2612 float **pmerged_scAA = NULL; /* [0..EXP_NMODES-1][0..merged_nhits-1] hit scores for all seqs for each exp mode */
2613
2614 int cm_idx;
2615 int p; /* counter over partitions */
2616 int i; /* counter over hits */
2617 int64_t ip; /* offset for index in pmerged_scAA[0..EXP_NMODES-1] */
2618
2619 FILE *pfp;
2620
2621 char *tok = NULL;
2622 ESL_FILEPARSER *efp = NULL;
2623
2624 int64_t nhits;
2625 float sc;
2626 char *filename = NULL;
2627
2628 /* initialize storage for scores */
2629 ESL_ALLOC(pmerged_nhitsA, sizeof(int64_t) * EXP_NMODES);
2630 ESL_ALLOC(pmerged_scAA, sizeof(float *) * EXP_NMODES);
2631 for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++) {
2632 pmerged_nhitsA[exp_mode] = 0;
2633 pmerged_scAA[exp_mode] = NULL;
2634 }
2635
2636 /* open each of the partitions' scores files and read the scores (for the appropriate cm) */
2637 printf("# Reading scores for CM number %d named %s ... ", (cmi+1), cm->name);
2638
2639 for(p = 1; p <= ptot; p++) {
2640 /* determine file name */
2641 if ((status = esl_sprintf(&filename, "%s.%s%d",
2642 (esl_opt_IsUsed(go, "--proot") ? esl_opt_GetString(go, "--proot") : cfg->cmfile),
2643 (esl_opt_IsUsed(go, "--proot") ? "" : "calib."),
2644 p) != eslOK)) ESL_XFAIL(status, errbuf, "esl_sprintf failed");
2645 if ((pfp = fopen(filename, "r")) == NULL) ESL_XFAIL(eslENOTFOUND, errbuf, "Failed to open partition file %s\n", filename);
2646 if ((efp = esl_fileparser_Create(pfp)) == NULL) ESL_XFAIL(eslFAIL, errbuf, "Unable to create fileparser, out of memory?");
2647 esl_fileparser_SetCommentChar(efp, '#');
2648
2649 /* should be 1 line per CM/exp_mode pair */
2650 /* read through CMs we've already dealt with */
2651 for(cm_idx = 0; cm_idx < cmi; cm_idx++) {
2652 status = esl_fileparser_NextLine(efp); /* skip command line, only exists for 1st CM */
2653 for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++) {
2654 status = esl_fileparser_NextLine(efp); /* skip line with scores for this exp_mode */
2655 if(status == eslEOF) ESL_XFAIL(status, errbuf, "Ran out of lines in file %s, on CM index %d\n", filename, (cm_idx+1));
2656 if(status != eslOK) ESL_XFAIL(status, errbuf, "Problem reading lines in file %s, on CM index %d\n", filename, (cm_idx+1));
2657 }
2658 }
2659
2660 /* Now we are at the CM we currently care about
2661 * first line should be command used, if this is the first partition,
2662 * store it in cfg->comlogsA[cmi] for later output to CM file
2663 */
2664 status = esl_fileparser_NextLine(efp); /* places us on the next line */
2665 if(status == eslEOF) ESL_XFAIL(status, errbuf, "Ran out of lines in file %s, on CM index %d\n", filename, (cm_idx+1));
2666 if(status != eslOK) ESL_XFAIL(status, errbuf, "Problem reading lines in file %s, on CM index %d\n", filename, (cm_idx+1));
2667 if(p == 1) {
2668 status = esl_fileparser_GetRemainingLine(efp, &tok);
2669 if(status == eslEOF) ESL_XFAIL(status, errbuf, "Ran out of lines in file %s, on CM index %d\n", filename, (cm_idx+1));
2670 if(status != eslOK) ESL_XFAIL(status, errbuf, "Problem reading lines in file %s, on CM index %d\n", filename, (cm_idx+1));
2671 if((status = esl_strdup(tok, -1, &(cfg->comlogsA[cmi]))) != eslOK) goto ERROR;
2672 }
2673
2674 /* Read scores data for the CM we are interested in */
2675 for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++) {
2676 status = esl_fileparser_NextLine(efp);
2677 if(status == eslEOF) ESL_XFAIL(status, errbuf, "Ran out of lines in file %s, on CM index %d\n", filename, (cm_idx+1));
2678 if(status != eslOK) ESL_XFAIL(status, errbuf, "Problem reading lines in file %s, on CM index %d\n", filename, (cm_idx+1));
2679 status = esl_fileparser_GetTokenOnLine(efp, &tok, NULL);
2680 if(status != eslOK) ESL_XFAIL(status, errbuf, "Unexpected early end to line %d in file %s\n", efp->linenumber, filename);
2681 nhits = atoi(tok);
2682 if(nhits < 0) ESL_XFAIL(eslFAIL, errbuf, "Invalid number of hits %s on line %d of partition file %s.%d", tok, efp->linenumber,
2683 (esl_opt_IsUsed(go, "--proot") ? esl_opt_GetString(go, "--proot") : cfg->cmfile), p);
2684 ip = pmerged_nhitsA[exp_mode];
2685 pmerged_nhitsA[exp_mode] += nhits;
2686
2687 ESL_REALLOC(pmerged_scAA[exp_mode], sizeof(float) * pmerged_nhitsA[exp_mode]);
2688 for(i = 0; i < nhits; i++) {
2689 if((status = esl_fileparser_GetTokenOnLine(efp, &tok, NULL)) != eslOK) {
2690 ESL_XFAIL(status, errbuf, "Unexpected early end to line %d in file %s\n", efp->linenumber, filename);
2691 }
2692 sc = atof(tok);
2693 pmerged_scAA[exp_mode][(ip+i)] = sc;
2694 }
2695 }
2696 if(efp != NULL) { esl_fileparser_Destroy(efp); efp = NULL; }
2697 if(filename != NULL) { free(filename); filename = NULL; }
2698 fclose(pfp);
2699 }
2700 printf("done.\n");
2701
2702 *ret_pmerged_scAAA = pmerged_scAA;
2703 *ret_pmerged_nhitsAA = pmerged_nhitsA;
2704
2705 if(filename != NULL) free(filename);
2706 filename = NULL;
2707
2708 return eslOK;
2709
2710 ERROR:
2711 if(filename != NULL) free(filename);
2712 filename = NULL;
2713
2714 if(efp != NULL) esl_fileparser_Destroy(efp);
2715 efp = NULL;
2716
2717 if (pmerged_nhitsA != NULL) {
2718 free(pmerged_nhitsA);
2719 }
2720 pmerged_nhitsA = NULL;
2721 if (pmerged_scAA != NULL) {
2722 for(exp_mode = 0; exp_mode < EXP_NMODES; exp_mode++) {
2723 if(pmerged_scAA[exp_mode] != NULL) {
2724 free(pmerged_scAA[exp_mode]);
2725 pmerged_scAA[exp_mode] = NULL;
2726 }
2727 }
2728 }
2729 pmerged_scAA = NULL;
2730
2731 return status;
2732 }