Debian Codegraph @

src/cmalign.c

raw symbols SCIP
1 /* cmalign: align sequences to a CM.
2 *
3 * EPN, Fri Dec 30 10:13:34 2011 [Updated for v1.1]
4 * SRE, Thu Jul 25 11:28:03 2002 [St. Louis]
5 */
6
7 #include <esl_config.h>
8 #include <p7_config.h>
9 #include "config.h"
10
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <ctype.h>
15 #include <float.h>
16 #include <limits.h>
17
18 #include "easel.h" /* general seq analysis library */
19 #include "esl_alphabet.h"
20 #include "esl_getopts.h"
21 #include "esl_mpi.h"
22 #include "esl_msa.h"
23 #include "esl_msafile.h"
24 #include "esl_msafile2.h"
25 #include "esl_msaweight.h"
26 #include "esl_random.h"
27 #include "esl_sq.h"
28 #include "esl_sqio.h"
29 #include "esl_stack.h"
30 #include "esl_sse.h"
31 #include "esl_stopwatch.h"
32 #include "esl_vectorops.h"
33 #include "esl_wuss.h"
34
35 #ifdef HAVE_MPI
36 #include "mpi.h"
37 #include "esl_mpi.h"
38 #endif /*HAVE_MPI*/
39
40 #ifdef HMMER_THREADS
41 #include <unistd.h>
42 #include "esl_threads.h"
43 #include "esl_workqueue.h"
44 #endif /*HMMER_THREADS*/
45
46 #include "hmmer.h"
47
48 #include "infernal.h"
49
50 /* Max number of sequences per tmp alignment, if seq file exceeds
51 * either of these, final output alignment will be in 1 line/seq Pfam
52 * format. Max number of residues is CM_MAX_RESIDUE_COUNT from infernal.h
53 * where it's currently defined as (1024 * 1024).
54 */
55 #define CMALIGN_MAX_NSEQ 10000 /* 10k sequences, average parsetree is 25 bytes/position this means ~250Mb for all parsetrees */
56
57 #define DEBUGSERIAL 0
58 #define DEBUGMPI 0
59
60 typedef struct {
61 #ifdef HMMER_THREADS
62 ESL_WORK_QUEUE *queue;
63 #endif /*HMMER_THREADS*/
64 CM_t *cm; /* a covariance model */
65 CM_ALNDATA **dataA; /* array of CM_ALNDATA objects with ptrs to sqs, parsetrees, scores */
66 int n; /* size of outdataA */
67 float mxsize; /* max size (Mb) of allowable DP mx */
68 int pass_idx; /* pipeline pass index, controls truncation bit sc penalty */
69 ESL_STOPWATCH *w; /* stopwatch for timing stages (band calc, alignment) */
70 ESL_STOPWATCH *w_tot; /* stopwatch for timing total time for processing 1 seq */
71 int do_failover; /* TRUE if we're trying to do HMM banded truncated alignment,
72 * and bands obscure all possible alignments (very rare) to
73 * failover into HMM banded standard alignment.
74 */
75 } WORKER_INFO;
76
77 #define ACCOPTS "--hbanded,--nonbanded" /* Exclusive choice for acceleration or not */
78 #define ALGOPTS "--cyk,--optacc,--sample" /* Exclusive choice for algorithm */
79 #if defined (HMMER_THREADS) && defined (HAVE_MPI)
80 #define CPUOPTS "--mpi"
81 #define MPIOPTS "--cpu"
82 #else
83 #define CPUOPTS NULL
84 #define MPIOPTS NULL
85 #endif
86
87 static ESL_OPTIONS options[] = {
88 /* name type default env range toggles reqs incomp help docgroup*/
89 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 1 },
90 { "-o", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "output the alignment to file <f>, not stdout", 1 },
91 { "-g", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "configure CM for global alignment [default: local]", 1 },
92 /* options controlling the alignment algorithm */
93 { "--optacc", eslARG_NONE, "default", NULL, NULL, ALGOPTS, NULL, "--small", "use the Holmes/Durbin optimal accuracy algorithm [default]", 2 },
94 { "--cyk", eslARG_NONE, FALSE, NULL, NULL, ALGOPTS, NULL, NULL, "use the CYK algorithm", 2 },
95 { "--sample", eslARG_NONE, FALSE, NULL, NULL, ALGOPTS, NULL, "--small", "sample alignment of each seq from posterior distribution", 2 },
96 { "--seed", eslARG_INT, "181", NULL, "n>=0", NULL, "--sample", NULL, "w/--sample, set RNG seed to <n> (if 0: one-time arbitrary seed)", 2 },
97 { "--notrunc", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "do not use truncated alignment algorithm", 2 },
98 { "--sub", eslARG_NONE, FALSE, NULL, NULL, NULL,"--notrunc,-g", NULL, "build sub CM for columns b/t HMM predicted start/end points", 2 },
99 /* options affecting speed and memory */
100 { "--hbanded", eslARG_NONE, "default", NULL, NULL, ACCOPTS, NULL, NULL, "accelerate using CM plan 9 HMM derived bands", 3 },
101 { "--tau", eslARG_REAL, "1e-7", NULL, "1e-18<x<1", NULL, NULL, "--nonbanded", "set tail loss prob for HMM bands to <x>", 3 },
102 { "--mxsize", eslARG_REAL, "1024.0", NULL, "x>0.", NULL, NULL, NULL, "set maximum allowable DP matrix size to <x> Mb", 3 },
103 { "--fixedtau", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--nonbanded", "do not adjust tau (tighten bands) until mx size is < limit", 3 },
104 { "--maxtau", eslARG_REAL, "0.05", NULL, "0<x<0.5", NULL, NULL, "--fixedtau,--nonbanded", "set max tau <x> when tightening HMM bands", 3 },
105 { "--nonbanded", eslARG_NONE, FALSE, NULL, NULL, ACCOPTS, NULL, NULL, "do not use HMM bands for faster alignment", 3 },
106 { "--small", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--mxsize", "use small memory divide and conquer (d&c) algorithm", 3 }, /* for --small, required opts are enforced below */
107 /* options controlling optional output */
108 { "--sfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "dump alignment score information to file <f>", 4 },
109 { "--tfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "dump individual sequence parsetrees to file <f>", 4 },
110 { "--ifile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "dump information on per-sequence inserts to file <f>", 4 },
111 { "--elfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, "-g", "dump information on per-sequence EL inserts to file <f>", 4 },
112 /* other expert options */
113 { "--mapali", eslARG_INFILE, NULL, NULL, NULL, NULL, NULL, NULL, "include alignment in file <f> (same ali that CM came from)", 5 },
114 { "--mapstr", eslARG_NONE, NULL, NULL, NULL, NULL, "--mapali", NULL, "include structure (w/pknots) from <f> from --mapali <f>", 5 },
115 { "--noss", eslARG_NONE, NULL, NULL, NULL, NULL, "--mapali", "--mapstr", "cmbuild --noss option was used w/aln from --mapali <f>", 5 },
116 { "--informat", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "assert <seqfile> is in format <s>: no autodetection", 5 },
117 { "--outformat", eslARG_STRING, "Stockholm", NULL, NULL, NULL, NULL, NULL, "output alignment in format <s>", 5 },
118 { "--dnaout", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "output alignment as DNA (not RNA) sequence data", 5 },
119 { "--noprob", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "do not include posterior probabilities in the alignment", 5 },
120 { "--matchonly", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "include only match columns in output alignment", 5 },
121 { "--miss", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "mark seqs w/terminal gaps as fragments w/missing (~) chars", 5 },
122 { "--ileaved", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--outformat","force output in interleaved Stockholm format", 5 },
123 { "--flanktoins", eslARG_REAL, NULL, NULL, "0<x<0.4", NULL,"--flankselfins", NULL, "change transition probs into ROOT_IL/IR to <x> (e.g. 0.1)", 5 },
124 { "--flankselfins",eslARG_REAL, NULL, NULL, "0<x<0.9", NULL,"--flanktoins", NULL, "change self transit probs for ROOT_IL/IR to <x> (e.g. 0.8)", 5 },
125 { "--regress", eslARG_OUTFILE, NULL, NULL, NULL, NULL, "--ileaved", "--mapali", "save regression test data to file <f>", 5 },
126 { "--verbose", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "report extra information; mainly useful for debugging", 5 },
127 /*{ "--noannot", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "do not add cmalign execution annotation to the alignment", 5 },*/
128 #ifdef HMMER_THREADS
129 { "--cpu", eslARG_INT, CMNCPU, "INFERNAL_NCPU","n>=0", NULL, NULL, CPUOPTS, "number of parallel CPU workers to use for multithreads", 5 },
130 #endif
131 #ifdef HAVE_MPI
132 { "--mpi", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, MPIOPTS, "run as an MPI parallel program", 5 },
133 { "--stall", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "arrest after start: for debugging MPI under gdb", 5 },
134 #endif
135 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
136 };
137
138 struct cfg_s {
139 char *cmfile; /* name of input CM file */
140 char *sqfile; /* name of sequence file */
141 CM_FILE *cmfp; /* open input CM file stream */
142 ESL_SQFILE *sqfp; /* open sequence input file stream */
143 ESL_ALPHABET *abc; /* alphabet for input */
144 ESL_ALPHABET *abc_out; /* alphabet for output */
145 int infmt; /* input alignment format */
146 int outfmt; /* output alignment format */
147 int be_verbose; /* TRUE if --verbose used */
148 int do_oneblock; /* TRUE to force output of full alignment
149 * in one block, if input file is really big,
150 * we'll fail and tell the user to pick a
151 * different format.
152 */
153 /* mpi */
154 int do_mpi;
155 int my_rank;
156 int nproc;
157 int do_stall; /* TRUE to stall the program until gdb attaches */
158
159 /* Masters only */
160 FILE *tmpfp; /* the temporary output file where alignments are initially written if !do_oneblock */
161 FILE *ofp; /* output file where alignments are ultimately written (default is stdout) */
162 FILE *tfp; /* optional output for parsetrees */
163 FILE *ifp; /* optional output for insert info */
164 FILE *efp; /* optional output for EL insert info */
165 FILE *sfp; /* optional output for alignment scores */
166 FILE *rfp; /* optional output for --regress alignment */
167 };
168
169 static char usage[] = "[-options] <cmfile> <seqfile>";
170 static char banner[] = "align sequences to a CM";
171
172 static void serial_master(ESL_GETOPTS *go, struct cfg_s *cfg);
173 static int serial_loop (WORKER_INFO *info, char *errbuf, ESL_SQ_BLOCK *sq_block, ESL_RANDOMNESS *r);
174
175 #ifdef HMMER_THREADS
176 static int thread_loop(WORKER_INFO *info, char *errbuf, ESL_THREADS *obj, ESL_WORK_QUEUE *queue, ESL_SQ_BLOCK *sq_block);
177 static void pipeline_thread(void *arg);
178 #endif /*HMMER_THREADS*/
179
180 #if HAVE_MPI
181 static int mpi_master (ESL_GETOPTS *go, struct cfg_s *cfg);
182 static int mpi_worker (ESL_GETOPTS *go, struct cfg_s *cfg);
183 static void mpi_failure (char *format, ...);
184 #define INFERNAL_ERROR_TAG 1
185 #define INFERNAL_DSQ_TAG 2
186 #define INFERNAL_INITIALREADY_TAG 3
187 #define INFERNAL_ALNDATA_TAG 4
188 #endif
189
190 /* Functions to avoid code duplication for common tasks */
191 static void process_commandline(int argc, char **argv, ESL_GETOPTS **ret_go, char **ret_cmfile, char **ret_sqfile, int *ret_infmt, int *ret_outfmt);
192 static int output_header(FILE *ofp, const ESL_GETOPTS *go, char *cmfile, char *sqfile, CM_t *cm, int ncpus);
193 static int init_master_cfg (const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf);
194 static int init_shared_cfg (const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf);
195 static int initialize_cm(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm);
196 static int map_alignment(const char *msafile, CM_t *cm, int noss_used, char *errbuf, CM_ALNDATA ***ret_dataA, int *ret_ndata, char **ret_ss);
197 static int output_alignment(ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, FILE *ofp, CM_ALNDATA **dataA, int ndata, char *map_sscons);
198 static void output_info_file_header(FILE *fp, char *firstline, char *elstring);
199 static int output_scores(FILE *ofp, CM_t *cm, char *errbuf, CM_ALNDATA **dataA, int ndata, int first_idx, int be_verbose);
200 /*static int add_annotation_to_msa(ESL_GETOPTS *go, char *errbuf, ESL_MSA *msa);*/
201
202 /* Functions that enable memory efficiency by storing only a fraction
203 * of the seqs/parsetrees from target file in memory at once.
204 */
205 static int create_and_output_final_msa(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm, int nali, char *tmpfile);
206 static void update_maxins_and_maxel(ESL_MSA *msa, int clen, int64_t alen, int *maxins, int *maxel);
207 static int determine_gap_columns_to_add(ESL_MSA *msa, int *maxins, int *maxel, int clen, int **ret_ngap_insA, int **ret_ngap_elA, int **ret_ngap_eitherA, char *errbuf);
208 static void inflate_gc_with_gaps_and_els(FILE *ofp, ESL_MSA *msa, int *ngap_insA, int *ngap_elA, char **ret_ss_cons2print, char **ret_rf2print);
209 static void configure_root_inserts(CM_t *cm, float to_insert_prob, float self_insert_prob);
210
211 int
212 main(int argc, char **argv)
213 {
214 int status = eslOK;
215
216 ESL_GETOPTS *go = NULL; /* command line processing */
217 struct cfg_s cfg; /* configuration data */
218
219 /* start stopwatch */
220 ESL_STOPWATCH *w = NULL; /* for overall timing */
221 if((w = esl_stopwatch_Create()) == NULL) cm_Fail("out of memory, trying to create stopwatch");
222 esl_stopwatch_Start(w);
223
224 /* Set processor specific flags */
225 impl_Init();
226
227 /* Initialize what we can in the config structure (without knowing the alphabet yet)
228 */
229 cfg.cmfile = NULL;
230 cfg.sqfile = NULL;
231 cfg.cmfp = NULL;
232 cfg.sqfp = NULL;
233 cfg.do_mpi = FALSE; /* this gets reset below, if we init MPI */
234 cfg.nproc = 0; /* this gets reset below, if we init MPI */
235 cfg.my_rank = 0; /* this gets reset below, if we init MPI */
236 cfg.abc = NULL;
237
238 cfg.tmpfp = NULL; /* opened in init_master_cfg() in masters, stays NULL for workers */
239 cfg.ofp = NULL; /* opened in init_master_cfg() in masters, stays NULL for workers */
240 cfg.tfp = NULL; /* opened in init_master_cfg() in masters, stays NULL for workers */
241 cfg.ifp = NULL; /* opened in init_master_cfg() in masters, stays NULL for workers */
242 cfg.efp = NULL; /* opened in init_master_cfg() in masters, stays NULL for workers */
243 cfg.sfp = NULL; /* opened in init_master_cfg() in masters, stays NULL for workers */
244 cfg.rfp = NULL; /* opened in init_master_cfg() in masters, stays NULL for workers */
245
246
247 cfg.infmt = eslSQFILE_UNKNOWN; /* reset below in process_commandline() */
248 cfg.outfmt = eslMSAFILE_STOCKHOLM; /* reset below in process_commandline() */
249 cfg.do_oneblock = FALSE; /* reset below after process_commandline() call */
250
251 /* Initializations */
252 init_ilogsum();
253 FLogsumInit();
254 process_commandline(argc, argv, &go, &(cfg.cmfile), &(cfg.sqfile), &(cfg.infmt), &(cfg.outfmt));
255
256 /* Determine if we need to output the alignment all at once in a
257 * single block. If not, and we can tell the alignment is going to
258 * be big, we'll output temporary alignments of one block of
259 * sequences at a time in Pfam format then go back and merge them
260 * all at the end. This saves memory by only requiring we keep 1
261 * block in memory at a time.
262 */
263 if((cfg.outfmt != eslMSAFILE_STOCKHOLM && cfg.outfmt != eslMSAFILE_PFAM) ||
264 (esl_opt_GetBoolean(go, "--ileaved"))) {
265 /* format is not Stockholm, nor Pfam OR --ileaved enabled for interleaved alignment */
266 cfg.do_oneblock = TRUE;
267 }
268 else {
269 cfg.do_oneblock = FALSE;
270 }
271
272 /* update cfg now that we have go */
273 cfg.abc_out = esl_opt_GetBoolean(go, "--dnaout") ? esl_alphabet_Create(eslDNA) : esl_alphabet_Create(eslRNA);
274
275 /* Figure out who we are, and send control there:
276 * we might be an MPI master, an MPI worker, or a serial program.
277 */
278 #ifdef HAVE_MPI
279
280 #if eslDEBUGLEVEL >= 1
281 pid_t pid;
282 /* get the process id */
283 pid = getpid();
284 printf("#DEBUG: The process id is %d\n", pid);
285 fflush(stdout);
286 #endif
287
288 /* pause the execution of the programs execution until the user has a
289 * chance to attach with a debugger and send a signal to resume execution
290 * i.e. (gdb) signal SIGCONT
291 */
292 if (esl_opt_GetBoolean(go, "--stall")) pause();
293
294 if (esl_opt_GetBoolean(go, "--mpi"))
295 {
296 cfg.do_mpi = TRUE;
297 MPI_Init(&argc, &argv);
298 MPI_Comm_rank(MPI_COMM_WORLD, &(cfg.my_rank));
299 MPI_Comm_size(MPI_COMM_WORLD, &(cfg.nproc));
300
301 if(cfg.nproc == 1) cm_Fail("MPI mode, but only 1 processor running... (did you execute mpirun?)");
302
303 if (cfg.my_rank > 0) status = mpi_worker(go, &cfg);
304 else status = mpi_master(go, &cfg);
305
306 MPI_Finalize();
307 }
308 else
309 #endif /*HAVE_MPI*/
310 {
311 serial_master(go, &cfg);
312 }
313 esl_stopwatch_Stop(w);
314
315 /* Close output files */
316 if(cfg.ofp != NULL && esl_opt_IsUsed(go, "-o")) {
317 fclose(cfg.ofp);
318 /* print timing to stdout, only if aln was not output to stdout */
319 printf("#\n");
320 esl_stopwatch_Display(stdout, w, "# CPU time: ");
321 }
322 if(cfg.tmpfp != NULL) fclose(cfg.tmpfp);
323 if(cfg.tfp != NULL) fclose(cfg.tfp);
324 if(cfg.ifp != NULL) fclose(cfg.ifp);
325 if(cfg.efp != NULL) fclose(cfg.efp);
326 if(cfg.sfp != NULL) fclose(cfg.sfp);
327 if(cfg.cmfp != NULL) cm_file_Close(cfg.cmfp);
328 if(cfg.sqfp != NULL) esl_sqfile_Close(cfg.sqfp);
329
330 if(cfg.abc != NULL) esl_alphabet_Destroy(cfg.abc);
331 if(cfg.abc_out != NULL) esl_alphabet_Destroy(cfg.abc_out);
332 esl_stopwatch_Destroy(w);
333 esl_getopts_Destroy(go);
334
335 return status;
336 }
337 /* serial_master()
338 * The serial version of cmalign.
339 *
340 * A master can only return if it's successful. All errors are handled immediately and fatally with cm_Fail().
341 */
342 static void
343 serial_master(ESL_GETOPTS *go, struct cfg_s *cfg)
344 {
345 int status; /* Easel status */
346 char errbuf[eslERRBUFSIZE]; /* for printing error messages */
347 CM_t *cm = NULL; /* a CM */
348 int i, k; /* counter over parsetrees and workers */
349 int nali; /* index of the (possibly temporary) alignment we are working on */
350 int nseq_cur; /* number of sequences in current alignment */
351 int nseq_aligned; /* number of sequences so far aligned */
352 int do_sample; /* TRUE if we're sampling alignments (--sample) */
353 ESL_RANDOMNESS *r = NULL; /* RNG, used only if --sample */
354
355 /* variables related to output, we may use a tmpfile if seqfile is large */
356 int use_tmpfile; /* print out current alignment to tmpfile? */
357 int created_tmpfile = FALSE; /* TRUE if we've created a tmp file for current CM */
358 char tmpfile[32] = "esltmpXXXXXX"; /* name of the tmpfile */
359 CM_ALNDATA **merged_dataA = NULL; /* array of all CM_ALNDATA pointers for current alignment */
360 int merged_data_idx = 0; /* index in merged_dataA */
361 int nmerged; /* size of merged_dataA */
362
363 /* variables related to reading sequence blocks */
364 int sstatus = eslOK; /* status from esl_sq_ReadBlock() */
365 ESL_SQ_BLOCK *sq_block; /* a sequence block */
366 ESL_SQ_BLOCK *nxt_sq_block; /* sequence block for next loop iteration */
367 int reached_eof; /* TRUE if we've reached EOF in target sequence file */
368
369 /* variables related to --mapali */
370 char *map_file = NULL; /* name of alignment file from --mapali */
371 CM_ALNDATA **map_dataA = NULL; /* array of CM_ALNDATA pointers for mapali alignment */
372 int nmap_data = 0; /* number of CM_ALNDATA ptrs in map_dataA */
373 int nmap_cur = 0; /* number of CM_ALNDATA ptrs to include in current iteration, 0 unless nali==0 */
374 char *map_sscons = NULL; /* SS_cons from mapali, only used if --mapstr */
375
376 /* variables related to threaded implementation */
377 int ncpus = 0; /* number of CPUs working */
378 ESL_SQ **init_sqA = NULL; /* for initializing workers */
379 WORKER_INFO *info = NULL; /* the worker info */
380 int infocnt = 0; /* number of worker infos */
381 #ifdef HMMER_THREADS
382 ESL_THREADS *threadObj = NULL;
383 ESL_WORK_QUEUE *queue = NULL;
384 #endif
385
386 /* General notes on {serial,mpi}_master()'s strategy:
387 *
388 * Ideally, we'd read in all sequences, align them all, and output
389 * the alignment. But we're worried about running out of memory, so
390 * we read in sequence blocks (sq_block) of at most CMALIGN_MAX_NRES
391 * (10 Mb) at a time, and process each in turn. (A parsetree is
392 * about 25 bytes per residue, so that should be about 250 Mb). If
393 * there's more than one such block, we output each to a tmp file
394 * and free the parsetrees afterwards so we don't require too much
395 * memory. Once finished, we go through the tmp file and merge all
396 * the alignments within it into a single one (without ever storing
397 * all of them simultaneously) and output it to the standard output
398 * file. In this case we need to use Pfam (1 line/seq) format so we
399 * don't have to store the full alignment/set of parsetrees at
400 * once. If there's only one block we just output it to the standard
401 * output file in interleaved format (which is what previous
402 * versions of cmalign did), no tmp file is needed.
403 *
404 * Each sequence in the current block is processed independently,
405 * i.e. a workunit for a threaded/MPI worker is a single
406 * sequence. We could make a workunit a smaller sequence block so
407 * workers wouldn't have to update as much, but empirically it seems
408 * there's not too much overhead to the updates and sequence
409 * alignment times vary significantly so it's advantageous to have a
410 * worker process a single sequence at a time, lest they have
411 * multiple difficult sequences in a single block. I originally
412 * implemented the strategy of splitting big blocks into smaller
413 * ones for the threaded implementation, each of which was an
414 * independent unit (r3808) but it was significantly more complex
415 * with little to no advantage in speed over this implementation.
416 */
417
418 if ((status = init_master_cfg(go, cfg, errbuf)) != eslOK) cm_Fail(errbuf);
419 do_sample = esl_opt_GetBoolean(go, "--sample") ? TRUE : FALSE;
420 if(do_sample) {
421 if((r = esl_randomness_Create(esl_opt_GetInteger(go, "--seed"))) == NULL) cm_Fail("out of memory, trying to create RNG");
422 }
423
424 #ifdef HMMER_THREADS
425 /* initialize thread data */
426 ncpus = ESL_MIN(esl_opt_GetInteger(go, "--cpu"), esl_threads_GetCPUCount());
427 if (ncpus > 0) {
428 threadObj = esl_threads_Create(&pipeline_thread);
429 queue = esl_workqueue_Create(ncpus * 2);
430 }
431 #endif
432
433 infocnt = (ncpus == 0) ? 1 : ncpus;
434 ESL_ALLOC(info, sizeof(WORKER_INFO) * infocnt);
435
436 /* Read one CM, and make sure there's only one. This fills cfg->abc. */
437 status = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm);
438 if(status != eslOK) cm_Fail(cfg->cmfp->errbuf);
439 status = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), NULL);
440 if(status != eslEOF) cm_Fail("CM file %s does not contain just one CM\n", cfg->cmfp->fname);
441
442 if(cfg->ofp != stdout) output_header(stdout, go, cfg->cmfile, cfg->sqfile, cm, ncpus);
443
444 for (k = 0; k < infocnt; ++k) {
445 info[k].cm = NULL;
446 info[k].dataA = NULL;
447 info[k].n = 0;
448 info[k].mxsize = esl_opt_GetReal(go, "--mxsize");
449 info[k].pass_idx = esl_opt_GetBoolean(go, "--notrunc") ? PLI_PASS_STD_ANY : PLI_PASS_5P_AND_3P_FORCE;
450 info[k].w = esl_stopwatch_Create();
451 info[k].w_tot = esl_stopwatch_Create();
452 info[k].do_failover = (esl_opt_GetBoolean(go, "--hbanded") && (! esl_opt_GetBoolean(go, "--notrunc"))) ? TRUE : FALSE;
453 #ifdef HMMER_THREADS
454 info[k].queue = queue;
455 #endif
456 }
457
458 #ifdef HMMER_THREADS
459 ESL_ALLOC(init_sqA, sizeof(ESL_SQ *) * ESL_MAX(1, ncpus * 2)); // avoid malloc of 0
460 for (k = 0; k < ncpus * 2; k++) {
461 init_sqA[k] = NULL;
462 if((init_sqA[k] = esl_sq_CreateDigital(cfg->abc)) == NULL) cm_Fail("Failed to allocate a sequence");
463 if((status = esl_workqueue_Init(queue, init_sqA[k])) != eslOK) cm_Fail("Failed to add sequence to work queue");
464 }
465 #endif
466
467 /* initialization */
468 nali = nseq_cur = nseq_aligned = 0;
469 if((status = initialize_cm(go, cfg, errbuf, cm)) != eslOK) cm_Fail(errbuf);
470 for (k = 0; k < infocnt; ++k) {
471 if((status = cm_Clone(cm, errbuf, &(info[k].cm))) != eslOK) cm_Fail(errbuf);
472 }
473 reached_eof = FALSE;
474
475 /* include the mapali, if nec */
476 if((map_file = esl_opt_GetString(go, "--mapali")) != NULL) {
477 if((status = map_alignment(map_file, cm, esl_opt_GetBoolean(go, "--noss"), errbuf, &map_dataA, &nmap_data, &map_sscons)) != eslOK) cm_Fail(errbuf);
478 if(esl_opt_GetBoolean(go, "--mapstr") && map_sscons == NULL) cm_Fail("Failed to read SS_cons for --mapstr from %s", map_file);
479 }
480
481 /* Our main loop will loop over reading a single large block
482 * (<sq_block>) of sequences, up to CM_MAX_RESIDUE_COUNT
483 * (100000) residues, and up to CMALIGN_MAX_NSEQ
484 * sequences (10,000), but potentially less if we reach the end of
485 * the sequence file first.
486 */
487
488 /* Read the first block */
489 sq_block = esl_sq_CreateDigitalBlock(CMALIGN_MAX_NSEQ, cfg->abc);
490 sstatus = esl_sqio_ReadBlock(cfg->sqfp, sq_block, -1, -1, /*max_init_window=*/FALSE, FALSE); /* FALSE says: read complete sequences */
491 nxt_sq_block = sq_block; /* special case of first block read */
492
493 while(sstatus == eslOK) {
494 #ifdef HMMER_THREADS
495 if (ncpus > 0) {
496 for (k = 0; k < infocnt; ++k) esl_threads_AddThread(threadObj, &info[k]);
497 }
498 #endif
499 sq_block = nxt_sq_block; /* our current sq_block becomes the one we read on the previous iteration */
500 sq_block->first_seqidx = nseq_aligned;
501 nseq_cur = sq_block->count;
502
503 /* Before we do any aligning, read the next sequence block, so we
504 * can determine if we've reached the end of the seqfile. We need
505 * to know this for two reasons:
506 *
507 * (1) if the first block read above included all sequences (which
508 * we won't know until we try to read another block), we don't
509 * need to go into memory-saving mode and output to a tmpfile, we
510 * can output (in interleaved mode) to the final output file.
511 *
512 * (2) if do_oneblock (we're trying to output the full alignment
513 * as a single block) we need to fail if we still have sequences
514 * left, because the sequence file exceeded the size limits. And
515 * we want to fail *before* we align all the sequences, so the
516 * user isn't cross when the job fails after seemingly going along
517 * fine for a while.
518 */
519 nxt_sq_block = esl_sq_CreateDigitalBlock(CMALIGN_MAX_NSEQ, cfg->abc);
520 sstatus = esl_sqio_ReadBlock(cfg->sqfp, nxt_sq_block, -1, -1, /*max_init_window=*/FALSE, FALSE); /* FALSE says: read complete sequences */
521 if(sstatus == eslEOF) {
522 reached_eof = TRUE; /* nxt_sq_block will not have been filled */
523 esl_sq_DestroyBlock(nxt_sq_block);
524 }
525 if((! reached_eof) && cfg->do_oneblock) esl_fatal("Error: the sequence file is too big (has > %d seqs or %d residues) for --ileaved or output\nformat other than Pfam. Use esl-reformat to reformat alignment later.", CMALIGN_MAX_NSEQ, CM_MAX_RESIDUE_COUNT);
526
527 /* align the sequences in the block */
528 #ifdef HMMER_THREADS
529 if (ncpus > 0) status = thread_loop(info, errbuf, threadObj, queue, sq_block);
530 else status = serial_loop(info, errbuf, sq_block, r);
531 #else
532 status = serial_loop(info, errbuf, sq_block, r);
533 #endif
534 if(status != eslOK) cm_Fail(errbuf);
535
536 /* create a single array of all CM_ALNDATA objects, in original (input) order */
537 nmap_cur = (nali == 0) ? nmap_data : 0;
538 nmerged = nseq_cur + nmap_cur;
539 ESL_ALLOC(merged_dataA, sizeof(CM_ALNDATA *) * ESL_MAX(1, nmerged)); // avoid malloc of 0
540 /* prepend mapali data if nec */
541 if(nmap_cur > 0) {
542 for(i = 0; i < nmap_cur; i++) merged_dataA[i] = map_dataA[i];
543 free(map_dataA); /* don't free the CM_ALNDATA objects, merged_dataA is pointing at them */
544 map_dataA = NULL;
545 }
546 for(k = 0; k < infocnt; ++k) {
547 for(i = 0; i < info[k].n; i++) {
548 merged_data_idx = (info[k].dataA[i]->idx - nseq_aligned) + nmap_cur;
549 merged_dataA[merged_data_idx] = info[k].dataA[i];
550 }
551 /* free dataA pointer from info, but not actual CM_ALNDATA objects, merged_dataA is pointing at them */
552 if(info[k].dataA != NULL) {
553 free(info[k].dataA);
554 info[k].dataA = NULL;
555 }
556 info[k].n = 0;
557 }
558
559 /* output alignment (if do_oneblock we died above if we didn't reach EOF yet) */
560 use_tmpfile = (reached_eof && (! created_tmpfile)) ? FALSE : TRUE; /* output to tmpfile only if this is the first alignment and we've aligned all seqs */
561 if(use_tmpfile && (! created_tmpfile)) {
562 /* first aln for temporary output file, open the file */
563 if ((status = esl_tmpfile_named(tmpfile, &(cfg->tmpfp))) != eslOK) cm_Fail("Failed to open temporary output file (status %d)", status);
564 created_tmpfile = TRUE;
565 }
566 if((status = output_alignment(go, cfg, errbuf, cm, (use_tmpfile ? cfg->tmpfp : cfg->ofp), merged_dataA, nseq_cur + nmap_cur, map_sscons)) != eslOK) cm_Fail(errbuf);
567 /* optionally output same alignment to regress file */
568 if(cfg->rfp != NULL) {
569 if((status = output_alignment(go, cfg, errbuf, cm, cfg->rfp, merged_dataA, nseq_cur + nmap_cur, map_sscons)) != eslOK) cm_Fail(errbuf);
570 }
571 nali++;
572 nseq_aligned += nseq_cur;
573
574 /* output scores to stdout, if -o used */
575 if(cfg->ofp != stdout) {
576 if((status = output_scores(stdout, cm, errbuf, merged_dataA, nseq_cur + nmap_cur, nmap_cur, cfg->be_verbose)) != eslOK) cm_Fail(errbuf);
577 }
578 /* output scores to scores file, if --sfp used */
579 if(cfg->sfp != NULL) {
580 if(nali == 1) output_header(stdout, go, cfg->cmfile, cfg->sqfile, cm, ncpus);
581 if((status = output_scores(cfg->sfp, cm, errbuf, merged_dataA, nseq_cur + nmap_cur, nmap_cur, cfg->be_verbose)) != eslOK) cm_Fail(errbuf);
582 }
583
584 /* free block and worker data */
585 esl_sq_DestroyBlock(sq_block);
586 sq_block = NULL;
587 for(i = 0; i < nmap_cur; i++) { /* free the mapali seqs if nec */
588 if(merged_dataA[i]->sq != NULL) esl_sq_Destroy(merged_dataA[i]->sq);
589 }
590 for(i = 0; i < nmerged; i++) {
591 cm_alndata_Destroy(merged_dataA[i], FALSE); /* FALSE: don't free sq's, we just free'd them by destroying the block */
592 }
593 free(merged_dataA);
594 } /* end of outer while loop 'while(sstatus == eslOK)' */
595 if (sstatus == eslEFORMAT) cm_Fail("Parse failed (sequence file %s):\n%s\n", cfg->sqfp->filename, esl_sqfile_GetErrorBuf(cfg->sqfp));
596 else if(sstatus == eslEMEM) cm_Fail("Out of memory");
597 else if(sstatus != eslEOF) cm_Fail("Unexpected error while reading sequence file");
598
599 /* if nec, close tmpfile then merge all alignments in it */
600 if(created_tmpfile) {
601 fclose(cfg->tmpfp); /* we're done writing to tmpfp */
602 cfg->tmpfp = NULL;
603 /* merge all temporary alignments now in cfg->tmpfp, and output merged alignment */
604 if((status = create_and_output_final_msa(go, cfg, errbuf, cm, nali, tmpfile)) != eslOK) cm_Fail(errbuf);
605 remove(tmpfile);
606 }
607
608 /* finish insert and el files */
609 if(cfg->ifp != NULL) { fprintf(cfg->ifp, "//\n"); }
610 if(cfg->efp != NULL) { fprintf(cfg->efp, "//\n"); }
611
612 /* clean up */
613 #ifdef HMMER_THREADS
614 if (ncpus > 0) {
615 esl_workqueue_Reset(queue);
616 if(init_sqA != NULL) {
617 for (k = 0; k < ncpus * 2; k++) {
618 if(init_sqA[k] != NULL) esl_sq_Destroy(init_sqA[k]);
619 }
620 free(init_sqA);
621 init_sqA = NULL;
622 }
623 esl_workqueue_Destroy(queue);
624 esl_threads_Destroy(threadObj);
625 }
626 if(init_sqA != NULL) free(init_sqA); /* init_sqA will be NULL if and only if ncpus == 0 */
627 #endif
628 if(r != NULL) esl_randomness_Destroy(r);
629 for(k = 0; k < infocnt; ++k) {
630 if(info[k].cm != NULL) FreeCM(info[k].cm);
631 if(info[k].dataA != NULL) free(info[k].dataA);
632 if(info[k].w != NULL) esl_stopwatch_Destroy(info[k].w);
633 if(info[k].w_tot != NULL) esl_stopwatch_Destroy(info[k].w_tot);
634 }
635 free(info);
636
637 if(map_sscons != NULL) free(map_sscons);
638 FreeCM(cm);
639
640 return;
641
642 ERROR:
643 cm_Fail("Memory allocation error.");
644 return;
645 }
646
647 /* serial_loop():
648 *
649 * Align all sequences in a sequence block and store parsetrees.
650 *
651 * serial_loop() unlike thread_loop() gets a ESL_RANDOMNESS <r> passed
652 * in, it is required for sampling alignments with --sample.
653 * serial_loop() will always be called if --sample is used, because we
654 * enforce that if HMMER_THREADS is defined --cpu 0 must accompany
655 * --sample. The reason for this is otherwise the sampled alignments
656 * would be affected by the number of threads, since each thread
657 * requires its own (separately-seeded) RNG.
658 */
659 static int
660 serial_loop(WORKER_INFO *info, char *errbuf, ESL_SQ_BLOCK *sq_block, ESL_RANDOMNESS *r)
661 {
662 int status;
663 int i; /* counter over sequences */
664 ESL_SQ *sqp = NULL; /* ptr to a ESL_SQ, only used if there's an error */
665
666 /* allocate dataA */
667 info->n = sq_block->count;
668 ESL_ALLOC(info->dataA, sizeof(CM_ALNDATA *) * info->n);
669 for(i = 0; i < info->n; i++) info->dataA[i] = NULL;
670
671 for(i = 0; i < info->n; i++) {
672 status = DispatchSqAlignment(info->cm, errbuf, sq_block->list + i, sq_block->first_seqidx + i, info->mxsize,
673 TRMODE_UNKNOWN, info->pass_idx, FALSE, /* FALSE: info->cm->cp9b not valid */
674 info->w, info->w_tot, r, &(info->dataA[i]));
675 /* If alignment failed: potentially retry alignment in HMM banded
676 * std (non-truncated) mode. We will only possibly do this if our
677 * initial try was HMM banded truncated alignment (if not,
678 * info->do_failover will be FALSE).
679 */
680 if(status == eslEAMBIGUOUS && info->do_failover == TRUE) {
681 assert(info->cm->align_opts & CM_ALIGN_TRUNC);
682 info->cm->align_opts &= ~CM_ALIGN_TRUNC; /* lower truncated alignment flag, just for this sequence */
683 status = DispatchSqAlignment(info->cm, errbuf, sq_block->list + i, sq_block->first_seqidx + i, info->mxsize,
684 TRMODE_UNKNOWN, PLI_PASS_STD_ANY, FALSE, /* USE PLI_PASS_STD_ANY; FALSE: info->cm->cp9b not valid */
685 info->w, info->w_tot, r, &(info->dataA[i]));
686 info->cm->align_opts |= CM_ALIGN_TRUNC; /* reraise truncated alignment flag */
687 }
688 if(status != eslOK) {
689 sqp = (sq_block->list + i);
690 fprintf(stderr, "Problem during alignment of sequence %s\n", sqp->name);
691 cm_Fail(errbuf);
692 }
693 }
694 return eslOK;
695
696 ERROR:
697 ESL_FAIL(status, errbuf, "out of memory");
698 return status; /* NEVERREACHED */
699 }
700
701 #ifdef HMMER_THREADS
702 static int
703 thread_loop(WORKER_INFO *info, char *errbuf, ESL_THREADS *obj, ESL_WORK_QUEUE *queue, ESL_SQ_BLOCK *sq_block)
704 {
705 int status = eslOK;
706 int i, k; /* counter over sequences, workers */
707 ESL_SQ *sq;
708 void *new_sq;
709 ESL_SQ *empty_sq;
710 int nworkers = esl_threads_GetWorkerCount(obj);
711
712 esl_workqueue_Reset(queue);
713 #if DEBUGSERIAL
714 printf("master threads reset\n");
715 #endif
716
717 esl_threads_WaitForStart(obj);
718
719 #if DEBUGSERIAL
720 printf("master threads started\n");
721 #endif
722
723 status = esl_workqueue_ReaderUpdate(queue, NULL, &new_sq);
724 if (status != eslOK) cm_Fail("Work queue reader failed");
725
726 #if DEBUGSERIAL
727 printf("master initial update\n");
728 #endif
729
730 /* main loop: */
731 for(i = 0; i < sq_block->count; i++) {
732 sq = (ESL_SQ *) new_sq;
733 sq = sq_block->list + i;
734 sq->W = sq_block->first_seqidx + i;
735 /* we overload sq->W w/seqidx (the original value is irrelevant in this context) */
736 status = esl_workqueue_ReaderUpdate(queue, sq, &new_sq);
737 if (status != eslOK) cm_Fail("Work queue reader failed");
738
739 #if DEBUGSERIAL
740 printf("master internal update\n");
741 #endif
742 }
743
744 /* now send a empty sq to all workers signaling them to stop */
745 empty_sq = esl_sq_Create();
746 for(k = 0; k < nworkers; k++) {
747 status = esl_workqueue_ReaderUpdate(queue, empty_sq, &new_sq);
748 if (status != eslOK) cm_Fail("Work queue reader failed");
749 #if DEBUGSERIAL
750 printf("master termination update\n");
751 #endif
752 }
753
754 status = esl_workqueue_ReaderUpdate(queue, sq, NULL);
755 #if DEBUGSERIAL
756 printf("master final update\n");
757 #endif
758
759 /* wait for all the threads to complete */
760 esl_threads_WaitForFinish(obj);
761 #if DEBUGSERIAL
762 printf("master got finish\n");
763 #endif
764
765 esl_workqueue_Complete(queue);
766 #if DEBUGSERIAL
767 printf("master completed\n");
768 #endif
769
770 esl_sq_Destroy(empty_sq);
771 return status;
772 }
773
774 /* pipeline_thread()
775 *
776 * Receive a block of sequences from the master,
777 * align them and store their parsetrees.
778 */
779 static void
780 pipeline_thread(void *arg)
781 {
782 int status;
783 int i, j;
784 int workeridx;
785 WORKER_INFO *info;
786 ESL_THREADS *obj;
787 ESL_SQ *sq = NULL;
788 void *new_sq = NULL;
789 char errbuf[eslERRBUFSIZE];
790 int nalloc = 0;
791 int allocsize = 1000;
792 #ifdef HAVE_FLUSH_ZERO_MODE
793 /* In order to avoid the performance penalty dealing with sub-normal
794 * values in the floating point calculations, set the processor flag
795 * so sub-normals are "flushed" immediately to zero.
796 * On OS X, need to reset this flag for each thread
797 * (see TW notes 05/08/10 for details)
798 */
799 _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
800 #endif
801 obj = (ESL_THREADS *) arg;
802 esl_threads_Started(obj, &workeridx);
803
804 #if DEBUGSERIAL
805 printf("started thread %d\n", workeridx);
806 #endif
807
808 info = (WORKER_INFO *) esl_threads_GetData(obj, workeridx);
809
810 #if DEBUGSERIAL
811 printf("got data %d\n", workeridx);
812 #endif
813
814 status = esl_workqueue_WorkerUpdate(info->queue, NULL, &new_sq);
815 if (status != eslOK) cm_Fail("Work queue worker failed\n");
816
817 #if DEBUGSERIAL
818 printf("initial update %d\n", workeridx);
819 #endif
820
821 /* loop until all sequences have been processed */
822 sq = (ESL_SQ *) new_sq;
823 i = 0;
824 while (sq->L != -1) {
825 /* reallocate info->dataA if necessary */
826 if(info->n == nalloc) {
827 ESL_REALLOC(info->dataA, sizeof(CM_ALNDATA *) * (nalloc + allocsize));
828 for(j = nalloc; j < info->n + allocsize; j++) info->dataA[j] = NULL;
829 nalloc += allocsize;
830 }
831 status = DispatchSqAlignment(info->cm, errbuf, sq, sq->W, info->mxsize,
832 TRMODE_UNKNOWN, info->pass_idx, FALSE, /* FALSE: info->cm->cp9b not valid */
833 info->w, info->w_tot, NULL, &(info->dataA[i]));
834 /* sq->W has been overloaded (its original value is irrelevant in this context).
835 * It is now the sequence index, defined in thread_loop()
836 */
837
838 /* If alignment failed: potentially retry alignment in HMM banded
839 * std (non-truncated) mode. We will only possibly do this if our
840 * initial try was HMM banded truncated alignment (if not,
841 * info->do_failover will be FALSE).
842 */
843 if(status == eslEAMBIGUOUS && info->do_failover == TRUE) {
844 assert(info->cm->align_opts & CM_ALIGN_TRUNC);
845 info->cm->align_opts &= ~CM_ALIGN_TRUNC; /* lower truncated alignment flag, just for this sequence */
846 status = DispatchSqAlignment(info->cm, errbuf, sq, sq->W, info->mxsize,
847 TRMODE_UNKNOWN, PLI_PASS_STD_ANY, FALSE, /* USE PLI_PASS_STD_ANY; FALSE: info->cm->cp9b not valid */
848 info->w, info->w_tot, NULL, &(info->dataA[i]));
849 info->cm->align_opts |= CM_ALIGN_TRUNC; /* reraise truncated alignment flag */
850 }
851 if(status != eslOK) {
852 fprintf(stderr, "Problem during alignment of sequence %s\n", sq->name);
853 cm_Fail(errbuf);
854 }
855
856 i++;
857 info->n++;
858
859 status = esl_workqueue_WorkerUpdate(info->queue, sq, &new_sq);
860 if (status != eslOK) cm_Fail("Work queue worker failed");
861 sq = (ESL_SQ *) new_sq;
862
863 #if DEBUGSERIAL
864 printf("internal update %d sq->L: %" PRId64 "\n", workeridx, sq->L);
865 #endif
866 }
867
868 status = esl_workqueue_WorkerUpdate(info->queue, sq, NULL);
869 if (status != eslOK) cm_Fail("Work queue worker failed");
870
871 #if DEBUGSERIAL
872 printf("final update %d\n", workeridx);
873 #endif
874
875 esl_threads_Finished(obj, workeridx);
876 return;
877
878 ERROR:
879 cm_Fail("out of memory");
880 return; /* NEVERREACHED */
881 }
882 #endif /* HMMER_THREADS */
883
884 #if HAVE_MPI
885 /* mpi_master()
886 * The MPI version of cmalign.
887 * Follows standard pattern for a master/worker load-balanced MPI program
888 * (SRE notes J1/78-79).
889 *
890 * A master returns eslOK if it's successful. Errors in an MPI master
891 * come in two classes: recoverable and nonrecoverable.
892 *
893 * Recoverable errors include most worker-side errors, and any
894 * master-side error that do not affect MPI communication. Error
895 * messages from recoverable messages are delayed until we've cleanly
896 * shut down the workers. The
897 *
898 * Some worker side errors (such as ESL_ALLOCs) are likely to be
899 * unrecoverable and will almost certainly cause MPI to crash
900 * uncleanly, they're only here because I couldn't find a way around
901 * them without massive reimplementation. Hopefully they rarely occur.
902 *
903 * Unrecoverable errors are master-side errors that may affect MPI
904 * communication, meaning we cannot count on being able to reach the
905 * workers and shut them down. Unrecoverable errors result in immediate
906 * cm_Fail()'s, which will cause MPI to shut down the worker processes
907 * uncleanly.
908 */
909 static int
910 mpi_master(ESL_GETOPTS *go, struct cfg_s *cfg)
911 {
912 int status; /* Easel status */
913 char errbuf[eslERRBUFSIZE]; /* for printing error messages */
914 CM_t *cm = NULL; /* a CM */
915 int i; /* counter over parsetrees */
916 int si; /* sequence index */
917 int nali; /* index of the (possibly temporary) alignment we are working on */
918 int nseq_cur; /* number of sequences in current alignment */
919 int nseq_aligned; /* number of sequences so far aligned */
920 /* MPI is incompatible with --sample, b/c it would not be reproducible */
921
922 /* variables related to output, we may use a tmpfile if seqfile is large */
923 int use_tmpfile; /* print out current alignment to tmpfile? */
924 int created_tmpfile = FALSE; /* TRUE if we've created a tmp file for current CM */
925 char tmpfile[32] = "esltmpXXXXXX"; /* name of the tmpfile */
926 CM_ALNDATA **merged_dataA = NULL; /* array of all CM_ALNDATA pointers for current alignment */
927 int merged_data_idx = 0; /* index in merged_dataA */
928 int nmerged; /* size of merged_dataA */
929
930 /* variables related to reading sequence blocks */
931 int sstatus = eslOK; /* status from esl_sq_ReadBlock() */
932 ESL_SQ_BLOCK *sq_block; /* a sequence block */
933 ESL_SQ_BLOCK *nxt_sq_block; /* sequence block for next loop iteration */
934 int reached_eof; /* TRUE if we've reached EOF in target sequence file */
935
936 /* variables related to --mapali */
937 char *map_file = NULL; /* name of alignment file from --mapali */
938 CM_ALNDATA **map_dataA = NULL; /* array of CM_ALNDATA pointers for mapali alignment */
939 int nmap_data = 0; /* number of CM_ALNDATA ptrs in map_dataA */
940 int nmap_cur = 0; /* number of CM_ALNDATA ptrs to include in current iteration, 0 unless nali==0 */
941 char *map_sscons = NULL; /* SS_cons from mapali, only used if --mapstr */
942
943 /* variables related to MPI implementation */
944 MPI_Status mpistatus; /* the mpi status */
945 char *mpibuf = NULL; /* buffer used to pack/unpack structures */
946 int mpibuf_size = 0; /* current size of mpibuf_size */
947 int buf_size; /* size of received buffer */
948 int pos; /* for packing/unpacking an MPI buffer */
949 int wi; /* worker index that we're about to send to or receive from */
950 int nworkers; /* number of workers */
951 int nworking; /* number of workers currently doing work */
952 int have_work; /* TRUE while work remains (sqs remain in sq_block) */
953 CM_ALNDATA *wkr_data = NULL; /* data recieved from a worker */
954 ESL_SQ *sq = NULL; /* sequence to send to a worker */
955
956 /* See 'General notes on {serial,mpi}_master()'s strategy' for details
957 * on the code organization here.
958 */
959
960 if ((status = init_master_cfg(go, cfg, errbuf)) != eslOK) mpi_failure(errbuf);
961 if(esl_opt_GetBoolean(go, "--sample")) mpi_failure("--sample does not work with in MPI mode (b/c results would not be exactly reproducible)");
962
963 /* Read one CM, and make sure there's only one. This fills cfg->abc. */
964 status = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm);
965 if(status != eslOK) mpi_failure(cfg->cmfp->errbuf);
966 status = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), NULL);
967 if(status != eslEOF) mpi_failure("CM file %s does not contain just one CM\n", cfg->cmfp->fname);
968
969 nworkers = cfg->nproc - 1;
970 if(cfg->ofp != stdout) output_header(stdout, go, cfg->cmfile, cfg->sqfile, cm, nworkers+1);
971
972 /* initialization */
973 nali = nseq_cur = nseq_aligned = 0;
974 if((status = initialize_cm(go, cfg, errbuf, cm)) != eslOK) mpi_failure(errbuf);
975 reached_eof = FALSE;
976
977 /* include the mapali, if nec */
978 if((map_file = esl_opt_GetString(go, "--mapali")) != NULL) {
979 if((status = map_alignment(map_file, cm, esl_opt_GetBoolean(go, "--noss"), errbuf, &map_dataA, &nmap_data, &map_sscons)) != eslOK) mpi_failure(errbuf);
980 if(esl_opt_GetBoolean(go, "--mapstr") && map_sscons == NULL) mpi_failure("Failed to read SS_cons for --mapstr from %s", map_file);
981 }
982
983 /* Our main loop will loop over reading a single large block
984 * (<sq_block>) of sequences, up to MAX_RESIDUE_COUNT
985 * (1024*1024=1048576) residues, and up to CMALIGN_MAX_NSEQ
986 * sequences (10,000), but potentially less if we reach the end of
987 * the sequence file first.
988 */
989
990 /* Read the first block */
991 sq_block = esl_sq_CreateDigitalBlock(CMALIGN_MAX_NSEQ, cfg->abc);
992 sstatus = esl_sqio_ReadBlock(cfg->sqfp, sq_block, -1, -1, /*max_init_window=*/FALSE, FALSE); /* FALSE says: read complete sequences */
993 nxt_sq_block = sq_block; /* special case of first block read */
994
995 #if DEBUGMPI
996 printf("master read the first block\n");
997 #endif
998
999 while(sstatus == eslOK) {
1000 sq_block = nxt_sq_block; /* our current sq_block becomes the one we read on the previous iteration */
1001 sq_block->first_seqidx = nseq_aligned;
1002 nseq_cur = sq_block->count;
1003
1004 /* Before we do any aligning, read the next sequence block, so we
1005 * can determine if we've reached the end of the seqfile. We need
1006 * to know this for two reasons:
1007 *
1008 * (1) if the first block read above included all sequences (which
1009 * we won't know until we try to read another block), we don't
1010 * need to go into memory-saving mode and output to a tmpfile, we
1011 * can output (in interleaved mode) to the final output file.
1012 *
1013 * (2) if do_oneblock (we're trying to output the full alignment
1014 * as a single block) we need to fail if we still have sequences
1015 * left, because the sequence file exceeded the size limits. And
1016 * we want to fail *before* we align all the sequences, so the
1017 * user isn't cross when the job fails after seemingly going along
1018 * fine for a while.
1019 */
1020 nxt_sq_block = esl_sq_CreateDigitalBlock(CMALIGN_MAX_NSEQ, cfg->abc);
1021 sstatus = esl_sqio_ReadBlock(cfg->sqfp, nxt_sq_block, -1, -1, /*max_init_window=*/FALSE, FALSE); /* FALSE says: read complete sequences */
1022 if(sstatus == eslEOF) {
1023 reached_eof = TRUE; /* nxt_sq_block will not have been filled */
1024 esl_sq_DestroyBlock(nxt_sq_block);
1025 }
1026 if((! reached_eof) && cfg->do_oneblock) esl_fatal("Error: the sequence file is too big (has > %d seqs or %d residues) for --ileaved or\noutput format other than Pfam. Use esl-reformat to reformat alignment later.", CMALIGN_MAX_NSEQ, MAX_RESIDUE_COUNT);
1027
1028 /* allocate an array for all CM_ALNDATA objects we'll receive from workers */
1029 nmap_cur = (nali == 0) ? nmap_data : 0;
1030 nmerged = nseq_cur + nmap_cur;
1031 ESL_ALLOC(merged_dataA, sizeof(CM_ALNDATA *) * ESL_MAX(1, nseq_cur + nmap_cur)); // avoid malloc of 0
1032 /* prepend mapali data if nec */
1033 if(nmap_cur > 0) {
1034 for(i = 0; i < nmap_cur; i++) merged_dataA[i] = map_dataA[i];
1035 free(map_dataA); /* don't free the CM_ALNDATA objects, merged_dataA is pointing at them */
1036 map_dataA = NULL;
1037 }
1038 #if DEBUGMPI
1039 printf("master about to enter main loop\n");
1040 #endif
1041
1042 /* main send/recv loop: send sequences to workers and receive their results */
1043 have_work = TRUE;
1044 nworking = 0;
1045 si = 0; /* sequence index */
1046 while(have_work || nworking > 0) {
1047 #if DEBUGMPI
1048 printf("master waiting for a message from any worker\n");
1049 #endif
1050 /* wait for message (results, ready tag or error) from any worker */
1051 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);
1052 if (MPI_Get_count(&mpistatus, MPI_PACKED, &buf_size) != 0) mpi_failure("MPI get count failed");;
1053 if (mpibuf == NULL || buf_size > mpibuf_size) {
1054 ESL_REALLOC(mpibuf, sizeof(char) * buf_size);
1055 mpibuf_size = buf_size;
1056 }
1057 wi = mpistatus.MPI_SOURCE;
1058 MPI_Recv(mpibuf, buf_size, MPI_PACKED, wi, mpistatus.MPI_TAG, MPI_COMM_WORLD, &mpistatus);
1059
1060 #if DEBUGMPI
1061 printf("master received message from worker %d, tag %d\n", wi, mpistatus.MPI_TAG);
1062 #endif
1063 /* tag should be either:
1064 * INFERNAL_INITIALREADY_TAG: worker just initialized, and is ready for work
1065 * INFERNAL_ALNDATA_TAG: worker finished work, and sent us results
1066 * INFERNAL_ERROR_TAG: worker sent us an error
1067 */
1068 if (mpistatus.MPI_TAG == INFERNAL_ALNDATA_TAG) {
1069 /* receive CM_ALNDATA result from worker, and point merged_dataA at it */
1070 pos = 0;
1071 status = cm_alndata_MPIUnpack(mpibuf, buf_size, &pos, MPI_COMM_WORLD, cfg->abc, &wkr_data);
1072 if(status != eslOK) mpi_failure("problem with alignment results received from worker %d", wi);
1073 merged_data_idx = wkr_data->idx - nseq_aligned + nmap_cur;
1074 merged_dataA[merged_data_idx] = wkr_data; /* wkr_data we received had everything we need except the sq */
1075 merged_dataA[merged_data_idx]->sq = sq_block->list + (wkr_data->idx - sq_block->first_seqidx); /* point sq at appropriate sequence */
1076 nworking--; /* one less worker is working now */
1077 #if DEBUGMPI
1078 printf("received results from worker %d, %d workers now working\n", wi, nworking);
1079 #endif
1080 }
1081 else if(mpistatus.MPI_TAG == INFERNAL_ERROR_TAG) {
1082 mpi_failure("MPI client %d raised error:\n%s\n", wi, mpibuf);
1083 }
1084 else if (mpistatus.MPI_TAG != INFERNAL_INITIALREADY_TAG) {
1085 mpi_failure("Unexpected tag %d from %d\n", mpistatus.MPI_TAG, wi);
1086 }
1087
1088 if(have_work) { /* send new sequence: si's dsq, L, and seqidx to the worker */
1089 sq = sq_block->list + si;
1090 status = cm_dsq_MPISend(sq->dsq, sq->L, sq_block->first_seqidx + si, wi, INFERNAL_DSQ_TAG, MPI_COMM_WORLD, &mpibuf, &mpibuf_size);
1091 if(status != eslOK) mpi_failure("problem sending dsq to worker %d", wi);
1092 nworking++; /* one more worker is working now */
1093 si++; /* move onto next sequence */
1094 #if DEBUGMPI
1095 printf("master sent dsq si: %d/%d to worker %d, %d workers now working\n", si, sq_block->count, wi, nworking);
1096 #endif
1097 if(si == sq_block->count) {
1098 have_work = FALSE;
1099 ESL_DPRINTF1(("#DEBUG: MPI master has sent all %d of its sequences\n", sq_block->count));
1100 #if DEBUGMPI
1101 printf("master is out of work\n");
1102 #endif
1103 }
1104 }
1105 }
1106 if(nworking != 0) mpi_failure("%d workers still working when all should be idle", nworking);
1107
1108 /* we're done with sq_block, tell the workers by sending a NULL dsq */
1109 #if DEBUGMPI
1110 printf("master sending NULL dsq to all workers signalling we're done with the file\n");
1111 #endif
1112 for (wi = 1; wi < cfg->nproc; wi++) {
1113 if((status = cm_dsq_MPISend(NULL, -1, -1, wi, INFERNAL_DSQ_TAG, MPI_COMM_WORLD, &mpibuf, &mpibuf_size)) != eslOK) mpi_failure(errbuf);
1114 }
1115
1116 /* output alignment (if do_oneblock we died above if we didn't reach EOF yet) */
1117 use_tmpfile = (reached_eof && (! created_tmpfile)) ? FALSE : TRUE; /* output to tmpfile only if this is the first alignment and we've aligned all seqs */
1118 if(use_tmpfile && (! created_tmpfile)) {
1119 /* first aln for temporary output file, open the file */
1120 if ((status = esl_tmpfile_named(tmpfile, &(cfg->tmpfp))) != eslOK) mpi_failure("Failed to open temporary output file (status %d)", status);
1121 created_tmpfile = TRUE;
1122 }
1123 if((status = output_alignment(go, cfg, errbuf, cm, (use_tmpfile ? cfg->tmpfp : cfg->ofp), merged_dataA, nseq_cur + nmap_cur, map_sscons)) != eslOK) cm_Fail(errbuf);
1124 /* optionally output same alignment to regress file */
1125 if(cfg->rfp != NULL) {
1126 if((status = output_alignment(go, cfg, errbuf, cm, cfg->rfp, merged_dataA, nseq_cur + nmap_cur, map_sscons)) != eslOK) mpi_failure(errbuf);
1127 }
1128 nali++;
1129 nseq_aligned += nseq_cur;
1130
1131 /* output scores to stdout, if -o used */
1132 if(cfg->ofp != stdout) {
1133 if((status = output_scores(stdout, cm, errbuf, merged_dataA, nseq_cur + nmap_cur, nmap_cur, cfg->be_verbose)) != eslOK) mpi_failure(errbuf);
1134 }
1135 /* output scores to scores file, if --sfp used */
1136 if(cfg->sfp != NULL) {
1137 if(nali == 1) output_header(stdout, go, cfg->cmfile, cfg->sqfile, cm, nworkers+1);
1138 if((status = output_scores(cfg->sfp, cm, errbuf, merged_dataA, nseq_cur + nmap_cur, nmap_cur, cfg->be_verbose)) != eslOK) mpi_failure(errbuf);
1139 }
1140
1141 /* free block and worker data */
1142 esl_sq_DestroyBlock(sq_block);
1143 sq_block = NULL;
1144 for(i = 0; i < nmerged; i++) {
1145 cm_alndata_Destroy(merged_dataA[i], FALSE); /* FALSE: don't free sq's, we just free'd them by destroying the block */
1146 }
1147 free(merged_dataA);
1148 } /* end of outer while loop 'while(sstatus == eslOK)' */
1149
1150 /* done with all sequences/blocks in the sequence file, tell the workers */
1151 #if DEBUGMPI
1152 printf("master sending NULL dsq to all workers signalling we're done with the file\n");
1153 #endif
1154 for (wi = 1; wi < cfg->nproc; wi++) {
1155 if((status = cm_dsq_MPISend(NULL, -1, -1, wi, INFERNAL_DSQ_TAG, MPI_COMM_WORLD, &mpibuf, &mpibuf_size)) != eslOK) mpi_failure(errbuf);
1156 }
1157
1158 if (sstatus == eslEFORMAT) mpi_failure("Parse failed (sequence file %s):\n%s\n", cfg->sqfp->filename, esl_sqfile_GetErrorBuf(cfg->sqfp));
1159 else if(sstatus == eslEMEM) mpi_failure("Out of memory");
1160 else if(sstatus != eslEOF) mpi_failure("Unexpected error while reading sequence file");
1161
1162 /* if nec, close tmpfile then merge all alignments in it */
1163 if(created_tmpfile) {
1164 fclose(cfg->tmpfp); /* we're done writing to tmpfp */
1165 cfg->tmpfp = NULL;
1166 /* merge all temporary alignments now in cfg->tmpfp, and output merged alignment */
1167 if((status = create_and_output_final_msa(go, cfg, errbuf, cm, nali, tmpfile)) != eslOK) mpi_failure(errbuf);
1168 remove(tmpfile);
1169 }
1170
1171 /* finish insert and el files */
1172 if(cfg->ifp != NULL) { fprintf(cfg->ifp, "//\n"); }
1173 if(cfg->efp != NULL) { fprintf(cfg->efp, "//\n"); }
1174
1175 /* clean up */
1176 if(map_sscons != NULL) free(map_sscons);
1177 FreeCM(cm);
1178 if(mpibuf != NULL) free(mpibuf);
1179
1180 return eslOK;
1181
1182 ERROR:
1183 mpi_failure("Memory allocation error.");
1184 return status;
1185 }
1186
1187 /* mpi_worker()
1188 *
1189 * Receive sequences from the master, align them and
1190 * send CM_ALNDATA results back to master.
1191 */
1192 static int
1193 mpi_worker(ESL_GETOPTS *go, struct cfg_s *cfg)
1194 {
1195 int status; /* Easel status */
1196 char errbuf[eslERRBUFSIZE]; /* for printing error messages */
1197 CM_t *cm = NULL; /* the CM */
1198 WORKER_INFO info; /* the worker info */
1199 ESL_SQ *sq = NULL; /* sequence we're aligning */
1200 ESL_DSQ *dsq = NULL; /* digitial sequence, rec'd from master */
1201 CM_ALNDATA *data = NULL; /* data we fill for each seq and send back to master */
1202 int64_t L, idx; /* sequence length, index, rec'd from master */
1203 char *mpibuf = NULL; /* buffer used to pack/unpack structures */
1204 int mpibuf_size = 0; /* size of the mpibuf */
1205 int blocks_remain_in_file; /* set to FALSE to break outer loop over blocks */
1206 int seqs_remain_in_block; /* set to FALSE to break inner loop over seqs */
1207
1208 if ((status = init_shared_cfg(go, cfg, errbuf)) != eslOK) mpi_failure(errbuf);
1209 if(esl_opt_GetBoolean(go, "--sample")) mpi_failure("--sample does not work with in MPI mode (b/c results would not be exactly reproducible)");
1210
1211 /* Read one CM, and make sure there's only one. This fills cfg->abc. */
1212 status = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), &cm);
1213 if(status != eslOK) mpi_failure(cfg->cmfp->errbuf);
1214 status = cm_file_Read(cfg->cmfp, TRUE, &(cfg->abc), NULL);
1215 if(status != eslEOF) mpi_failure("CM file %s does not contain just one CM\n", cfg->cmfp->fname);
1216
1217 if((status = initialize_cm(go, cfg, errbuf, cm)) != eslOK) mpi_failure(errbuf);
1218
1219 /* initialize our worker info */
1220 info.cm = cm;
1221 info.dataA = NULL;
1222 info.n = 0;
1223 info.mxsize = esl_opt_GetReal(go, "--mxsize");
1224 info.pass_idx = esl_opt_GetBoolean(go, "--notrunc") ? PLI_PASS_STD_ANY : PLI_PASS_5P_AND_3P_FORCE;
1225 info.w = esl_stopwatch_Create();
1226 info.w_tot = esl_stopwatch_Create();
1227 info.do_failover = (esl_opt_GetBoolean(go, "--hbanded") && (! esl_opt_GetBoolean(go, "--notrunc"))) ? TRUE : FALSE;
1228
1229 /* Main loop: actually two nested while loops, over sequence blocks
1230 * (while(blocks_remain_in_file)) and over sequences within blocks
1231 * (while(seqs_remain_in_block)). We exit each loop when the master
1232 * tells us to, by sending a NULL dsq. If we receive a NULL dsq,
1233 * we'll exit the inner loop over sequences, and if we immediately
1234 * receive another NULL dsq we'll exit the outer loop over blocks.
1235 */
1236 blocks_remain_in_file = TRUE;
1237 while(blocks_remain_in_file) {
1238 /* inform the master that we're ready for our first seq of the block */
1239 status = eslOK;
1240 MPI_Send(&status, 1, MPI_INT, 0, INFERNAL_INITIALREADY_TAG, MPI_COMM_WORLD);
1241
1242 #if DEBUGMPI
1243 printf("worker %d sent initial ready tag to master, waiting for 1st dsq\n", cfg->my_rank);
1244 #endif
1245
1246 /* receive first dsq in block, if it's NULL, we know we're out of blocks */
1247 status = cm_dsq_MPIRecv(0, INFERNAL_DSQ_TAG, MPI_COMM_WORLD, &mpibuf, &mpibuf_size, &dsq, &L, &idx);
1248 if (status == eslOK && dsq == NULL) mpi_failure("problem receiving 1st dsq");
1249 else if(status == eslEOD && dsq != NULL) mpi_failure("problem receiving termination signal");
1250 else if(status != eslOK && status != eslEOD) mpi_failure("problem receiving 1st dsq");
1251
1252 if(dsq == NULL) { /* master is telling us that we're finished with the sequence file */
1253 blocks_remain_in_file = FALSE;
1254 seqs_remain_in_block = FALSE;
1255 #if DEBUGMPI
1256 printf("worker %d received NULL 1st dsq from master, shutting down\n", cfg->my_rank);
1257 #endif
1258 }
1259 else { /* dsq is valid */
1260 blocks_remain_in_file = TRUE;
1261 seqs_remain_in_block = TRUE;
1262 }
1263
1264 while(seqs_remain_in_block) {
1265 #if DEBUGMPI
1266 printf("worker %d dsq %" PRId64 " of length %" PRId64 " received from master\n", cfg->my_rank, idx, L);
1267 #endif
1268 /* create a sequence object from dsq */
1269 if ((sq = esl_sq_CreateDigitalFrom(cfg->abc, "irrelevant", dsq, L, NULL, NULL, NULL)) == NULL) mpi_failure("out of memory");
1270 free(dsq); /* esl_sq_CreateDigitalFrom() makes a copy of dsq */
1271
1272 /* align the sequence */
1273 status = DispatchSqAlignment(info.cm, errbuf, sq, idx, info.mxsize, TRMODE_UNKNOWN, info.pass_idx, FALSE, /* FALSE: cm->cp9b not valid */
1274 info.w, info.w_tot, NULL, &data);
1275
1276 /* If alignment failed: potentially retry alignment in HMM banded
1277 * std (non-truncated) mode. We will only possibly do this if our
1278 * initial try was HMM banded truncated alignment (if not,
1279 * info.do_failover will be FALSE).
1280 */
1281 if(status == eslEAMBIGUOUS && info.do_failover == TRUE) {
1282 assert(info.cm->align_opts & CM_ALIGN_TRUNC);
1283 info.cm->align_opts &= ~CM_ALIGN_TRUNC; /* lower truncated alignment flag, just for this sequence */
1284 status = DispatchSqAlignment(info.cm, errbuf, sq, idx, info.mxsize,
1285 TRMODE_UNKNOWN, PLI_PASS_STD_ANY, FALSE, /* USE PLI_PASS_STD_ANY; FALSE: info->cm->cp9b not valid */
1286 info.w, info.w_tot, NULL, &data);
1287 info.cm->align_opts |= CM_ALIGN_TRUNC; /* reraise truncated alignment flag */
1288 }
1289 if(status != eslOK) {
1290 fprintf(stderr, "Problem during alignment of sequence %s\n", sq->name);
1291 mpi_failure(errbuf);
1292 }
1293
1294 /* pack up the data and send it back to the master (FALSE: don't send data->sq) */
1295 status = cm_alndata_MPISend(data, FALSE, errbuf, 0, INFERNAL_ALNDATA_TAG, MPI_COMM_WORLD, &mpibuf, &mpibuf_size);
1296 if(status != eslOK) mpi_failure(errbuf);
1297
1298 /* clean up old sequence */
1299 esl_sq_Destroy(sq);
1300 cm_alndata_Destroy(data, FALSE); /* don't free data->sq, it was pointing at the sq we just free'd */
1301
1302 /* receive next sequence from the master, if it's null that's our signal to stop with this block */
1303 status = cm_dsq_MPIRecv(0, INFERNAL_DSQ_TAG, MPI_COMM_WORLD, &mpibuf, &mpibuf_size, &dsq, &L, &idx);
1304 if (status == eslOK && dsq == NULL) mpi_failure("problem receiving dsq");
1305 else if(status == eslEOD && dsq != NULL) mpi_failure("problem receiving termination signal");
1306 else if(status != eslOK && status != eslEOD) mpi_failure("problem receiving dsq");
1307
1308 if(dsq == NULL) seqs_remain_in_block = FALSE; /* we're done with this block */
1309 #if DEBUGMPI
1310 if(dsq == NULL) printf("worker received NULL dsq from master, block is done");
1311 #endif
1312
1313 } /* end of 'while(seqs_remain_in_block)' */
1314 } /* end of 'while(blocks_remain_in_file)' */
1315
1316 if(info.cm != NULL) FreeCM(info.cm);
1317 if(info.dataA != NULL) free(info.dataA);
1318 if(info.w != NULL) esl_stopwatch_Destroy(info.w);
1319 if(info.w_tot != NULL) esl_stopwatch_Destroy(info.w_tot);
1320 if(mpibuf != NULL) free(mpibuf);
1321
1322 return eslOK;
1323 }
1324
1325 /* mpi_failure()
1326 * Generate an error message. If the clients rank is not 0, a
1327 * message is created with the error message and sent to the
1328 * master process for handling.
1329 */
1330 static void
1331 mpi_failure(char *format, ...)
1332 {
1333 va_list argp;
1334 int status = eslFAIL;
1335 int len;
1336 int rank;
1337 char str[512];
1338
1339 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
1340
1341 /* format the error mesg */
1342 va_start(argp, format);
1343 len = vsnprintf(str, sizeof(str), format, argp);
1344 va_end(argp);
1345
1346 /* make sure the error string is terminated */
1347 str[sizeof(str)-1] = '\0';
1348
1349 /* if the caller is the master, print the results and abort */
1350 if (rank == 0)
1351 {
1352 fprintf(stderr, "\nError: ");
1353 fprintf(stderr, "%s", str);
1354 fprintf(stderr, "\n");
1355 fflush(stderr);
1356
1357 MPI_Abort(MPI_COMM_WORLD, status);
1358 exit(1);
1359 }
1360 else
1361 {
1362 MPI_Send(str, len, MPI_CHAR, 0, INFERNAL_ERROR_TAG, MPI_COMM_WORLD);
1363 pause();
1364 }
1365 }
1366 #endif /*HAVE_MPI*/
1367
1368 static void
1369 process_commandline(int argc, char **argv, ESL_GETOPTS **ret_go, char **ret_cmfile, char **ret_sqfile, int *ret_infmt, int *ret_outfmt)
1370 {
1371 ESL_GETOPTS *go = NULL;
1372 int infmt = eslSQFILE_UNKNOWN;
1373 int outfmt = eslMSAFILE_STOCKHOLM;
1374
1375 if ((go = esl_getopts_Create(options)) == NULL) cm_Fail("Internal failure creating options object");
1376 if (esl_opt_ProcessEnvironment(go) != eslOK) { printf("Failed to process environment: %s\n", go->errbuf); goto ERROR; }
1377 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) { printf("Failed to parse command line: %s\n", go->errbuf); goto ERROR; }
1378 if (esl_opt_VerifyConfig(go) != eslOK) { printf("Failed to parse command line: %s\n", go->errbuf); goto ERROR; }
1379
1380 /* help format: */
1381 if (esl_opt_GetBoolean(go, "-h")) {
1382 cm_banner(stdout, argv[0], banner);
1383 esl_usage(stdout, argv[0], usage);
1384 puts("\nBasic options:");
1385 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1= group; 2 = indentation; 80=textwidth*/
1386 puts("\nOptions controlling alignment algorithm:");
1387 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
1388 puts("\nOptions controlling speed and memory requirements:");
1389 esl_opt_DisplayHelp(stdout, go, 3, 2, 80);
1390 puts("\nOptional output files:");
1391 esl_opt_DisplayHelp(stdout, go, 4, 2, 80);
1392 puts("\nOther options:");
1393 esl_opt_DisplayHelp(stdout, go, 5, 2, 80);
1394 puts("\nSequence input formats: FASTA, GenBank");
1395 puts("Alignment output formats: Stockholm, Pfam, AFA (aligned FASTA), A2M, Clustal, PHYLIP\n");
1396 exit(0);
1397 }
1398
1399 if (esl_opt_ArgNumber(go) != 2) { puts("Incorrect number of command line arguments."); goto ERROR; }
1400 if ((*ret_cmfile = esl_opt_GetArg(go, 1)) == NULL) { puts("Failed to get <cmfile> argument on command line"); goto ERROR; }
1401 if ((*ret_sqfile = esl_opt_GetArg(go, 2)) == NULL) { puts("Failed to get <seqfile> argument on command line"); goto ERROR; }
1402
1403 if (strcmp(*ret_cmfile, "-") == 0 && strcmp(*ret_sqfile, "-") == 0) {
1404 puts("\nERROR: Either <cmfile> or <seqfile> may be '-' (to read from stdin), but not both.\n");
1405 goto ERROR;
1406 }
1407
1408 /* If caller declared an input format, decode it */
1409 if (esl_opt_IsOn(go, "--informat")) {
1410 infmt = esl_sqio_EncodeFormat(esl_opt_GetString(go, "--informat"));
1411 if (infmt == eslSQFILE_UNKNOWN) {
1412 printf("\nERROR: %s is not a recognized input sequence file format\n\n", esl_opt_GetString(go, "--informat"));
1413 goto ERROR;
1414 }
1415 }
1416
1417 /* Determine output alignment file format */
1418 outfmt = esl_msafile_EncodeFormat(esl_opt_GetString(go, "--outformat"));
1419 if (outfmt == eslMSAFILE_UNKNOWN) {
1420 printf("\nERROR: %s is not a recognized output MSA file format\n\n", esl_opt_GetString(go, "--outformat"));
1421 goto ERROR;
1422 }
1423
1424 /* Check for incompatible option combinations too complex for esl_getopts to enforce during declaration */
1425
1426 #ifdef HMMER_THREADS
1427 /* if --sample, enforce that --cpu 0 is used if HMMER_THREADS, otherwise number of threads would
1428 * affect the sampled alignments (each thread requires its own RNG)
1429 */
1430 if (esl_opt_GetBoolean(go, "--sample")) {
1431 if((! esl_opt_IsUsed(go, "--cpu")) ||
1432 ( esl_opt_IsUsed(go, "--cpu") && (esl_opt_GetInteger(go, "--cpu") != 0))) {
1433 puts("\nERROR: --sample requires --cpu 0\n");
1434 goto ERROR;
1435 }
1436 }
1437 #endif /* HMMER_THREADS */
1438 #ifdef HAVE_MPI
1439 /* --sample is incompatible with --mpi b/c sampled parsetrees would be dependent
1440 * on number of workers (each of which needs its own (separately seeded) RNG)
1441 */
1442 if (esl_opt_GetBoolean(go, "--sample") && esl_opt_IsUsed(go, "--mpi")) {
1443 puts("\nERROR: --sample is incompatible with --mpi\n");
1444 goto ERROR;
1445 }
1446 #endif /* HAVE_MPI */
1447
1448 /* --verbose only makes sense in combination with -o or --sfile,
1449 * because if neither is used, scores are not output.
1450 */
1451 if (esl_opt_GetBoolean(go, "--verbose") && (! esl_opt_IsUsed(go, "-o")) && (! esl_opt_IsUsed(go, "--sfile"))) {
1452 puts("\nERROR: --verbose only makes sense in combination with -o or --sfile\n");
1453 goto ERROR;
1454 }
1455
1456 /* Finally, check for incompatible option combinations that
1457 * esl_getopts can handle, but that would require an error message
1458 * like: "Option 'x' is incompatible with options
1459 * y1,y2,y3,y4....yn", where there's so many y's that the message is
1460 * truncated because errbuf runs out of space. As a workaround we
1461 * laboriously check for all incompatible options of that type here.
1462 */
1463 if(esl_opt_IsUsed(go, "--small")) {
1464 if((! esl_opt_IsUsed(go, "--cyk")) || (! esl_opt_IsUsed(go, "--noprob")) || (! esl_opt_IsUsed(go, "--nonbanded")) || (! esl_opt_IsUsed(go, "--notrunc"))) {
1465 puts("Failed to parse command line: Option --small requires --cyk, --noprob, --nonbanded, --notrunc");
1466 goto ERROR;
1467 }
1468 }
1469
1470 *ret_go = go;
1471 *ret_infmt = infmt;
1472 *ret_outfmt = outfmt;
1473
1474 return;
1475
1476 ERROR: /* all errors handled here are user errors, so be polite. */
1477 esl_usage(stdout, argv[0], usage);
1478 puts("\nwhere basic options are:");
1479 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1= group; 2 = indentation; 80=textwidth*/
1480 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
1481 exit(1);
1482 }
1483
1484 /* output_header():
1485 *
1486 * In contrast with other Infernal applications, which output header
1487 * to stdout, we output the header to stdout only if the user has
1488 * specified a non-stdout output file for the alignment. Otherwise,
1489 * the alignment will be printed to stdout without a header because
1490 * we want it to be a valid Stockholm format (or other) alignment.
1491 */
1492
1493 static int
1494 output_header(FILE *ofp, const ESL_GETOPTS *go, char *cmfile, char *sqfile, CM_t *cm, int ncpus)
1495 {
1496 cm_banner(ofp, go->argv[0], banner);
1497 fprintf(ofp, "# CM file: %s\n", cmfile);
1498 fprintf(ofp, "# sequence file: %s\n", sqfile);
1499 fprintf(ofp, "# CM name: %s\n", cm->name);
1500 if (esl_opt_IsUsed(go, "-o")) { fprintf(ofp, "# saving alignment to file: %s\n", esl_opt_GetString(go, "-o")); }
1501 if (esl_opt_IsUsed(go, "-g")) { fprintf(ofp, "# model configuration: global\n"); }
1502
1503 if (esl_opt_IsUsed(go, "--optacc")) { fprintf(ofp, "# alignment algorithm: optimal accuracy\n"); }
1504 if (esl_opt_IsUsed(go, "--cyk")) { fprintf(ofp, "# alignment algorithm: CYK\n"); }
1505 if (esl_opt_IsUsed(go, "--sample")) { fprintf(ofp, "# sampling aln from posterior distribution: yes\n"); }
1506 if (esl_opt_IsUsed(go, "--seed")) {
1507 if (esl_opt_GetInteger(go, "--seed") == 0) fprintf(ofp, "# random number seed: one-time arbitrary\n");
1508 else fprintf(ofp, "# random number seed set to: %d\n", esl_opt_GetInteger(go, "--seed"));
1509 }
1510 if (esl_opt_IsUsed(go, "--notrunc")) { fprintf(ofp, "# truncated sequence alignment mode: off\n"); }
1511 if (esl_opt_IsUsed(go, "--sub")) { fprintf(ofp, "# alternative truncated seq alignment mode: on\n"); }
1512
1513 if (esl_opt_IsUsed(go, "--mxsize")) { fprintf(ofp, "# maximum total DP matrix size set to: %.2f Mb\n", esl_opt_GetReal(go, "--mxsize")); }
1514 if (esl_opt_IsUsed(go, "--hbanded")) { fprintf(ofp, "# using HMM bands for acceleration: yes\n"); }
1515 if (esl_opt_IsUsed(go, "--tau")) { fprintf(ofp, "# tail loss probability for HMM bands set to: %g\n", esl_opt_GetReal(go, "--tau")); }
1516 if (esl_opt_IsUsed(go, "--fixedtau")) { fprintf(ofp, "# tighten HMM bands when necessary: no\n"); }
1517 if (esl_opt_IsUsed(go, "--maxtau")) { fprintf(ofp, "# maximum tau allowed during band tightening: %g\n", esl_opt_GetReal(go, "--maxtau")); }
1518 if (esl_opt_IsUsed(go, "--nonbanded")) { fprintf(ofp, "# using HMM bands for acceleration: no\n"); }
1519 if (esl_opt_IsUsed(go, "--small")) { fprintf(ofp, "# small memory D&C alignment algorithm: on\n"); }
1520
1521 if (esl_opt_IsUsed(go, "--sfile")) { fprintf(ofp, "# saving alignment score info to file: %s\n", esl_opt_GetString(go, "--sfile")); }
1522 if (esl_opt_IsUsed(go, "--tfile")) { fprintf(ofp, "# saving parsetrees to file: %s\n", esl_opt_GetString(go, "--tfile")); }
1523 if (esl_opt_IsUsed(go, "--ifile")) { fprintf(ofp, "# saving insert information to file: %s\n", esl_opt_GetString(go, "--ifile")); }
1524 if (esl_opt_IsUsed(go, "--elfile")) { fprintf(ofp, "# saving local end information to file: %s\n", esl_opt_GetString(go, "--elfile")); }
1525
1526 if (esl_opt_IsUsed(go, "--mapali")) { fprintf(ofp, "# including alignment from file: %s\n", esl_opt_GetString(go, "--mapali")); }
1527 if (esl_opt_IsUsed(go, "--mapstr")) { fprintf(ofp, "# including structure from alnment from file: %s\n", esl_opt_GetString(go, "--mapali")); }
1528 if (esl_opt_IsUsed(go, "--informat")) { fprintf(ofp, "# input sequence file format specified as: %s\n", esl_opt_GetString(go, "--informat")); }
1529 if (esl_opt_IsUsed(go, "--outformat")) { fprintf(ofp, "# output alignment format specified as: %s\n", esl_opt_GetString(go, "--outformat")); }
1530 if (esl_opt_IsUsed(go, "--dnaout")) { fprintf(ofp, "# output alignment alphabet: DNA\n"); }
1531 if (esl_opt_IsUsed(go, "--noprob")) { fprintf(ofp, "# posterior probability annotation: off\n"); }
1532 if (esl_opt_IsUsed(go, "--matchonly")) { fprintf(ofp, "# include alignment insert columns: no\n"); }
1533 if (esl_opt_IsUsed(go, "--ileaved")) { fprintf(ofp, "# forcing interleaved Stockholm output aln: yes\n"); }
1534 if (esl_opt_IsUsed(go, "--regress")) { fprintf(ofp, "# saving alignment without author info to: %s\n", esl_opt_GetString(go, "--regress")); }
1535
1536 /* output number of processors being used, always (this differs from H3 which only does this if --cpu) */
1537 int output_ncpu = FALSE;
1538 #ifdef HAVE_MPI
1539 if (esl_opt_IsUsed(go, "--mpi")) { fprintf(ofp, "# MPI: on [%d processors]\n", ncpus); output_ncpu = TRUE; }
1540 #endif
1541 #ifdef HMMER_THREADS
1542 if (! output_ncpu) { fprintf(ofp, "# number of worker threads: %d%s\n", ncpus, (esl_opt_IsUsed(go, "--cpu") ? " [--cpu]" : "")); output_ncpu = TRUE; }
1543 #endif
1544 if (! output_ncpu) { fprintf(ofp, "# number of worker threads: 0 [serial mode; threading unavailable]\n"); }
1545 fprintf(ofp, "# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
1546
1547 return eslOK;
1548 }
1549
1550 /* init_master_cfg()
1551 * Called by masters, mpi or serial.
1552 *
1553 * Errors in the MPI master here are considered to be "recoverable",
1554 * in the sense that we'll try to delay output of the error message
1555 * until we've cleanly shut down the worker processes. Therefore
1556 * errors return (code, errbuf) by the ESL_FAIL mech.
1557 */
1558 static int
1559 init_master_cfg(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf)
1560 {
1561 int status;
1562
1563 /* initialize cfg variables used by masters and workers */
1564 if((status = init_shared_cfg(go, cfg, errbuf)) != eslOK) return status;
1565
1566 /* open output files */
1567 cfg->ofp = stdout;
1568 if (esl_opt_IsUsed(go, "-o")) {
1569 if ((cfg->ofp = fopen(esl_opt_GetString(go, "-o"), "w")) == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to open -o output file %s\n", esl_opt_GetString(go, "-o"));
1570 }
1571 if (esl_opt_IsUsed(go, "--tfile")) {
1572 if ((cfg->tfp = fopen(esl_opt_GetString(go, "--tfile"), "w")) == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to open --tfile output file %s\n", esl_opt_GetString(go, "--tfile"));
1573 }
1574 if (esl_opt_IsUsed(go, "--ifile")) {
1575 if ((cfg->ifp = fopen(esl_opt_GetString(go, "--ifile"), "w")) == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to open --ifile output file %s\n", esl_opt_GetString(go, "--ifile"));
1576 output_info_file_header(cfg->ifp, "Insert information file created by cmalign.", "");
1577 }
1578 if (esl_opt_IsUsed(go, "--elfile")) {
1579 if ((cfg->efp = fopen(esl_opt_GetString(go, "--elfile"), "w")) == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to open --elfile output file %s\n", esl_opt_GetString(go, "--elfile"));
1580 output_info_file_header(cfg->efp, "EL state (local end) insert information file created by cmalign.", "EL ");
1581 }
1582 if (esl_opt_IsUsed(go, "--sfile")) {
1583 if ((cfg->sfp = fopen(esl_opt_GetString(go, "--sfile"), "w")) == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to open --sfile output file %s\n", esl_opt_GetString(go, "--sfile"));
1584 }
1585 if (esl_opt_IsUsed(go, "--regress")) {
1586 if ((cfg->rfp = fopen(esl_opt_GetString(go, "--regress"), "w")) == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to open --regress output file %s\n", esl_opt_GetString(go, "--regress"));
1587 }
1588 return eslOK;
1589 }
1590
1591 /* init_shared_cfg()
1592 * Called by serial masters and mpi workers and masters.
1593 *
1594 * Errors in the MPI master here are considered to be "recoverable",
1595 * in the sense that we'll try to delay output of the error message
1596 * until we've cleanly shut down the worker processes. Therefore
1597 * errors return (code, errbuf) by the ESL_FAIL mech.
1598 */
1599 static int
1600 init_shared_cfg(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf)
1601 {
1602 int status;
1603
1604 /* open CM file */
1605 status = cm_file_Open(cfg->cmfile, NULL, FALSE, &(cfg->cmfp), errbuf);
1606 if (status == eslENOTFOUND) return status;
1607 else if (status == eslEFORMAT) return status;
1608 else if (status != eslOK) return status;
1609
1610 /* open sequence file */
1611 status = esl_sqfile_Open(cfg->sqfile, cfg->infmt, p7_SEQDBENV, &(cfg->sqfp));
1612 if (status == eslENOTFOUND) ESL_FAIL(status, errbuf, "Failed to open sequence file %s for reading\n", cfg->sqfile);
1613 else if (status == eslEFORMAT) ESL_FAIL(status, errbuf, "Sequence file %s is empty or misformatted\n", cfg->sqfile);
1614 else if (status == eslEINVAL && cfg->infmt == eslSQFILE_UNKNOWN) ESL_FAIL(status, errbuf, "Can't autodetect format of a stdin or .gz seqfile");
1615 else if (status != eslOK) ESL_FAIL(status, errbuf, "Unexpected error %d opening sequence file %s\n", status, cfg->sqfile);
1616
1617 cfg->be_verbose = esl_opt_GetBoolean(go, "--verbose");
1618
1619 return eslOK;
1620 }
1621
1622 /* initialize_cm()
1623 * Setup the CM based on the command-line options/defaults;
1624 * set flags and a few parameters. cm_Configure configures
1625 * the CM.
1626 */
1627 static int
1628 initialize_cm(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm)
1629 {
1630 int status;
1631
1632 /* set up alignment options in cm->align_opts */
1633 if ( esl_opt_GetBoolean(go, "--cyk")) cm->align_opts |= CM_ALIGN_CYK;
1634 else if( esl_opt_GetBoolean(go, "--sample")) cm->align_opts |= CM_ALIGN_SAMPLE;
1635 else cm->align_opts |= CM_ALIGN_OPTACC;
1636 if( esl_opt_GetBoolean(go, "--hbanded")) cm->align_opts |= CM_ALIGN_HBANDED;
1637 if( esl_opt_GetBoolean(go, "--nonbanded")) cm->align_opts |= CM_ALIGN_NONBANDED;
1638 if(! esl_opt_GetBoolean(go, "--noprob")) cm->align_opts |= CM_ALIGN_POST;
1639 if(! esl_opt_GetBoolean(go, "--notrunc")) cm->align_opts |= CM_ALIGN_TRUNC;
1640 if( esl_opt_GetBoolean(go, "--sub")) cm->align_opts |= CM_ALIGN_SUB; /* --sub requires --notrunc */
1641 if( esl_opt_GetBoolean(go, "--small")) cm->align_opts |= CM_ALIGN_SMALL; /* --small requires --noprob --nonbanded --cyk */
1642 if((! esl_opt_GetBoolean(go, "--fixedtau")) &&
1643 ( esl_opt_GetBoolean(go, "--hbanded"))) {
1644 cm->align_opts |= CM_ALIGN_XTAU;
1645 }
1646
1647 /* set up configuration options in cm->config_opts */
1648 if( esl_opt_GetBoolean(go, "--nonbanded")) cm->config_opts |= CM_CONFIG_NONBANDEDMX;
1649 if(! esl_opt_GetBoolean(go, "--notrunc")) cm->config_opts |= CM_CONFIG_TRUNC;
1650 if( esl_opt_GetBoolean(go, "--sub")) cm->config_opts |= CM_CONFIG_SUB; /* --sub requires --notrunc */
1651 if(! esl_opt_GetBoolean(go, "-g")) {
1652 cm->config_opts |= CM_CONFIG_LOCAL;
1653 cm->config_opts |= CM_CONFIG_HMMLOCAL;
1654 cm->config_opts |= CM_CONFIG_HMMEL;
1655 }
1656
1657 cm->tau = esl_opt_GetReal(go, "--tau");
1658 cm->maxtau = esl_opt_GetReal(go, "--maxtau");
1659
1660 if((esl_opt_IsUsed(go, "--flanktoins")) && (esl_opt_IsUsed(go, "--flankselfins"))) {
1661 configure_root_inserts(cm, esl_opt_GetReal(go, "--flanktoins"), esl_opt_GetReal(go, "--flankselfins"));
1662 }
1663
1664 /* configure */
1665 if((status = cm_Configure(cm, errbuf, -1)) != eslOK) return status;
1666
1667 return eslOK;
1668 }
1669
1670
1671 /* map_alignment()
1672 *
1673 * Called if the --mapali <f> option is used. Open and read a
1674 * MSA from <f>, confirm it was the same alignment used to
1675 * build the CM, and convert its aligned sequences to
1676 * parsetrees. Return data (sequences and parsetrees) gets
1677 * populated into <ret_dataA>.
1678 *
1679 * Also, return the dealigned (cm-> clen length) SS_cons
1680 * from the alignment in <ret_ss>. This will be used to
1681 * overwrite the output alignment's SS_cons if --mapstr
1682 * was used.
1683 */
1684 static int
1685 map_alignment(const char *msafile, CM_t *cm, int noss_used, char *errbuf, CM_ALNDATA ***ret_dataA, int *ret_ndata, char **ret_ss)
1686 {
1687 int status;
1688 ESL_MSAFILE *afp = NULL;
1689 ESL_MSA *msa = NULL;
1690 ESL_ALPHABET *abc = (ESL_ALPHABET *) cm->abc; /* removing const'ness to make compiler happy. Safe. */
1691 uint32_t chksum = 0;
1692 int i, x; /* counters */
1693 int apos, uapos, cpos; /* counter over aligned, unaligned, consensus positions */
1694 int *a2u_map = NULL; /* map from aligned to unaligned positions */
1695 Parsetree_t *mtr = NULL; /* the guide tree for mapali */
1696 CM_ALNDATA **dataA = NULL; /* includes ptrs to sq and parsetrees */
1697 char *aseq = NULL; /* aligned sequence, req'd by Transmogrify() */
1698 char *ss = NULL; /* msa's SS_cons, if there is one, dealigned to length cm->clen */
1699 int *used_el = NULL; /* [1..msa->alen] used_el[apos] = TRUE if apos is modeled by EL state, else FALSE */
1700 /* variables used for copying the structure and possibly removing broken basepairs (for which exactly 1 of the 2 paired positions is a consensus column */
1701 int opos; /* position that apos pairs with */
1702 int *i_am_rf = NULL; /* [1..msa->alen] i_am_rf[apos] = 1 if alignment position apos is a consensus (RF) position, else 0 */
1703 int *msa_ct = NULL; /* [1..msa->alen] msa_ct[apos] = x; x==0 if apos is unpaired, x==opos if apos is paired to opos in msa->ss_cons */
1704 char *msa_ss_cons_copy = NULL; /* copy of the msa's SS_cons we remove broken basepair halves from */
1705
1706 status = esl_msafile_Open(&abc, msafile, NULL, eslMSAFILE_UNKNOWN, NULL, &afp);
1707 if (status != eslOK) esl_msafile_OpenFailure(afp, status);
1708
1709 status = esl_msafile_Read(afp, &msa);
1710 if (status != eslOK) esl_msafile_ReadFailure(afp, status);
1711
1712 if (! (cm->flags & CMH_CHKSUM)) cm_Fail("CM has no checksum. --mapali unreliable without it.");
1713 if (! (cm->flags & CMH_MAP)) cm_Fail("CM has no map. --mapali can't work without it.");
1714 esl_msa_Checksum(msa, &chksum);
1715 if (cm->checksum != chksum) cm_Fail("--mapali MSA %s isn't same as the one CM came from (checksum mismatch)", msafile);
1716
1717 /* allocate and initialize dataA */
1718 ESL_ALLOC(dataA, sizeof(CM_ALNDATA *) * msa->nseq);
1719 for(i = 0; i < msa->nseq; i++) dataA[i] = cm_alndata_Create();
1720
1721 /* allocated msa_ct */
1722 ESL_ALLOC(msa_ct, sizeof(int) * (msa->alen+1));
1723
1724 /* if --noss used, potentially remove ss_cons and replace with no basepairs */
1725 if(noss_used) {
1726 if(msa->ss_cons != NULL) { free(msa->ss_cons); msa->ss_cons = NULL; }
1727 ESL_ALLOC(msa->ss_cons, sizeof(char) * (msa->alen+1)); msa->ss_cons[msa->alen] = '\0';
1728 memset(msa->ss_cons, '.', msa->alen);
1729 }
1730
1731 /* get SS_cons from the msa possibly for --mapstr, important to do it here, before it is potentially deknotted in HandModelmaker() */
1732 if(msa->ss_cons != NULL) {
1733 /* post 1.1.1 release modification [EPN, Tue Jul 28 15:34:45 2015]
1734 * Be careful to deal with basepairs where exactly one of the two paired positions is a consensus
1735 * position (other is an insert). The way we deal is to remove the structure annotation for the
1736 * one that is a consensus position. Replace it with a '.'.
1737 */
1738 /* set i_am_rf array, i_am_rf[apos] = 1 if apos is a consensus position, else it's 0 */
1739 ESL_ALLOC(i_am_rf, sizeof(int) * (msa->alen+1));
1740 esl_vec_ISet(i_am_rf, (msa->alen+1), 0);
1741 for(cpos = 1; cpos <= cm->clen; cpos++) i_am_rf[cm->map[cpos]] = 1;
1742
1743 /* get CT array that describes all basepairs in the ss_cons (ct array is 1..alen, not 0..alen-1 */
1744 if((status = esl_strdup(msa->ss_cons, msa->alen, &msa_ss_cons_copy)) != eslOK) cm_Fail("Out of memory");
1745 if((status = esl_wuss2ct(msa_ss_cons_copy, msa->alen, msa_ct)) != eslOK) cm_Fail("Problem including structure from --mapali, maybe out of memory");
1746 for(apos = 1; apos <= msa->alen; apos++) {
1747 if(i_am_rf[apos] && msa_ct[apos] != 0) {
1748 /* apos is a consensus position that is part of a pair, make
1749 * sure it's mate is also consensus, if not, remove the
1750 * annotation of both of them from the consensus structure
1751 */
1752 opos = msa_ct[apos];
1753 if(! i_am_rf[opos]) {
1754 msa_ss_cons_copy[apos-1] = '.';
1755 msa_ss_cons_copy[opos-1] = '.';
1756 }
1757 }
1758 }
1759
1760 ESL_ALLOC(ss, sizeof(char) * (cm->clen+1));
1761 ss[cm->clen] = '\0';
1762 for(cpos = 1; cpos <= cm->clen; cpos++) ss[cpos-1] = msa_ss_cons_copy[cm->map[cpos]-1];
1763 }
1764 else {
1765 cm_Fail("--mapali MSA in %s does not have any SS_cons annotation, use --noss if you used --noss with cmbuild", msafile);
1766 }
1767
1768 /* add RF annotation to the msa, so we can use it in HandModelMaker() */
1769 if(msa->rf != NULL) free(msa->rf);
1770 ESL_ALLOC(msa->rf, sizeof(char) * (msa->alen+1));
1771 /* init to all inserts, then set match states based on cm->map */
1772 for (apos = 0; apos < msa->alen; apos++) msa->rf[apos] = '.';
1773 for (cpos = 1; cpos <= cm->clen; cpos++) msa->rf[cm->map[cpos]-1] = 'x'; /* note off by one */
1774
1775 /* create a guide tree, which we'll need to convert aligned sequences to parsetrees */
1776 status = HandModelmaker(msa, errbuf,
1777 TRUE, /* use_rf */
1778 FALSE, /* use_el, no */
1779 FALSE, /* use_wts, irrelevant */
1780 0.5, /* symfrac, irrelevant */
1781 NULL, /* returned CM, irrelevant */
1782 &mtr); /* guide tree */
1783 if(status != eslOK) return status;
1784
1785 /* create a parsetree from each aligned sequence */
1786 ESL_ALLOC(used_el, sizeof(int) * (msa->alen+1));
1787 used_el[0] = FALSE; /* invalid */
1788 for(apos = 0; apos < msa->alen; apos++) {
1789 used_el[apos+1] = (msa->rf[apos] == '~') ? TRUE : FALSE;
1790 }
1791 ESL_ALLOC(a2u_map, sizeof(int) * (msa->alen+1));
1792 a2u_map[0] = -1; /* invalid */
1793 for (i = 0; i < msa->nseq; i++) {
1794 if((status = Transmogrify(cm, errbuf, mtr, msa->ax[i], used_el, msa->alen, &(dataA[i]->tr))) != eslOK) return status;
1795 /* dataA[i]->tr is in alignment coords, convert it to unaligned coords.
1796 * First we construct a map of aligned to unaligned coords, then
1797 * we use it to convert.
1798 */
1799 uapos = 1;
1800 for(apos = 1; apos <= msa->alen; apos++) {
1801 a2u_map[apos] = (esl_abc_XIsGap(msa->abc, msa->ax[i][apos])) ? -1 : uapos++;
1802 }
1803 for(x = 0; x < dataA[i]->tr->n; x++) {
1804 if(dataA[i]->tr->emitl[x] != -1) dataA[i]->tr->emitl[x] = a2u_map[dataA[i]->tr->emitl[x]];
1805 if(dataA[i]->tr->emitr[x] != -1) dataA[i]->tr->emitr[x] = a2u_map[dataA[i]->tr->emitr[x]];
1806 }
1807 }
1808
1809 /* get sequences */
1810 for (i = 0; i < msa->nseq; i++) esl_sq_FetchFromMSA(msa, i, &(dataA[i]->sq));
1811
1812 *ret_dataA = dataA;
1813 *ret_ndata = msa->nseq;
1814 *ret_ss = ss;
1815
1816 esl_msafile_Close(afp);
1817 esl_msa_Destroy(msa);
1818 FreeParsetree(mtr);
1819 free(a2u_map);
1820 free(used_el);
1821 if(i_am_rf != NULL) free(i_am_rf);
1822 if(msa_ct != NULL) free(msa_ct);
1823 if(msa_ss_cons_copy != NULL) free(msa_ss_cons_copy);
1824
1825 return eslOK;
1826
1827 ERROR:
1828 *ret_ndata = 0;
1829 *ret_dataA = NULL;
1830 if (dataA != NULL) {
1831 for(i = 0; i < msa->nseq; i++) cm_alndata_Destroy(dataA[i], TRUE);
1832 dataA = NULL;
1833 }
1834 if (afp != NULL) esl_msafile_Close(afp);
1835 if (msa != NULL) esl_msa_Destroy(msa);
1836 if (a2u_map != NULL) free(a2u_map);
1837 if (aseq != NULL) free(aseq);
1838 if(i_am_rf != NULL) free(i_am_rf);
1839 if(msa_ct != NULL) free(msa_ct);
1840 if(msa_ss_cons_copy != NULL) free(msa_ss_cons_copy);
1841
1842 ESL_FAIL(status, errbuf, "out of memory");
1843 }
1844
1845 static int
1846 output_alignment(ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, CM_t *cm, FILE *ofp, CM_ALNDATA **dataA, int ndata, char *map_sscons)
1847 {
1848 int status;
1849 ESL_MSA *msa = NULL;
1850 int j;
1851 ESL_SQ **sqpA = NULL; /* array of sequence pointers, only nec for Parsetrees2Alignment() */
1852 Parsetree_t **trA = NULL; /* array of Parsetree pointers, only nec for Parsetrees2Alignment() */
1853 char **ppstrA = NULL; /* array of PP string pointers, only nec for Parsetrees2Alignment() */
1854 float sc;
1855 float struct_sc;
1856 int first_ali = (dataA[0]->idx == 0) ? TRUE : FALSE;
1857 int cpos, apos; /* counters over consensus positions, alignment positions */
1858
1859 /* contract check */
1860 if(ofp == cfg->tmpfp && esl_opt_GetBoolean(go, "--ileaved")) ESL_FAIL(eslEINVAL, errbuf, "--ileaved enabled, but trying to output to temporary alignment file. This shouldn't happen.");
1861 if(ofp == cfg->tmpfp && cfg->outfmt != eslMSAFILE_PFAM && cfg->outfmt != eslMSAFILE_STOCKHOLM) ESL_FAIL(eslEINVAL, errbuf, "output format not Stockholm, nor Pfam, but trying to output to temporary alignment file. This shouldn't happen.");
1862 if(esl_opt_GetBoolean(go, "--mapstr") && map_sscons == NULL) ESL_FAIL(eslEINVAL, errbuf, "--mapstr enabled, but SS_cons not read from the --mapali alignment.");
1863
1864 /* output the parsetrees, if nec */
1865 if(cfg->tfp != NULL) {
1866 for (j = 0; j < ndata; j++) {
1867 if((status = ParsetreeScore(cm, NULL, errbuf, dataA[j]->tr, dataA[j]->sq->dsq, FALSE, &sc, &struct_sc, NULL, NULL, NULL)) != eslOK) return status;
1868 fprintf(cfg->tfp, ">%s\n", dataA[j]->sq->name);
1869 fprintf(cfg->tfp, " %16s %.2f bits\n", "SCORE:", sc);
1870 fprintf(cfg->tfp, " %16s %.2f bits\n", "STRUCTURE SCORE:", struct_sc);
1871 ParsetreeDump(cfg->tfp, dataA[j]->tr, cm, dataA[j]->sq->dsq);
1872 fprintf(cfg->tfp, "//\n");
1873 }
1874 }
1875
1876 /* print per-CM info to insertfp and elfp, if nec */
1877 if(first_ali && cfg->ifp != NULL) { fprintf(cfg->ifp, "%s %d\n", cm->name, cm->clen); }
1878 if(first_ali && cfg->efp != NULL) { fprintf(cfg->efp, "%s %d\n", cm->name, cm->clen); }
1879
1880 /* create the alignment */
1881 ESL_ALLOC(sqpA, sizeof(ESL_SQ *) * ndata); for(j = 0; j < ndata; j++) sqpA[j] = dataA[j]->sq;
1882 ESL_ALLOC(trA, sizeof(Parsetree_t *) * ndata); for(j = 0; j < ndata; j++) trA[j] = dataA[j]->tr;
1883 ESL_ALLOC(ppstrA, sizeof(char *) * ndata); for(j = 0; j < ndata; j++) ppstrA[j] = dataA[j]->ppstr;
1884 if((status = Parsetrees2Alignment(cm, errbuf, cfg->abc_out, sqpA, NULL, trA, ppstrA, ndata, cfg->ifp, cfg->efp,
1885 /*do_full=*/TRUE,
1886 /*do_matchonly=*/esl_opt_GetBoolean(go, "--matchonly"),
1887 /*allow_trunc=*/esl_opt_GetBoolean(go, "--miss"),
1888 &msa)) != eslOK) return status;
1889
1890 if(ofp == cfg->rfp) { /* --regress file, remove GF author annotation */
1891 free(msa->au);
1892 msa->au = NULL;
1893 }
1894
1895 /* rewrite SS_cons if --mapstr used */
1896 if(esl_opt_GetBoolean(go, "--mapstr")) {
1897 /* step along the existing SS_cons, overwriting consensus positions in place */
1898 cpos = 0; /* span 0..clen-1 */
1899 for(apos = 0; apos < msa->alen; apos++) { /* span 0..alen-1 */
1900 if((! esl_abc_CIsGap (cm->abc, msa->rf[apos])) &&
1901 (! esl_abc_CIsMissing(cm->abc, msa->rf[apos]))) {
1902 msa->ss_cons[apos] = map_sscons[cpos++];
1903 }
1904 }
1905 }
1906
1907 /* Determine format: if we're printing to a tmpfile we must use
1908 * Pfam format, so we can go back later and merge all alignments
1909 * in the tmpfile. If we're not printing to a tmpfile, then we
1910 * are about to output the full alignment in one block, and
1911 * we do that in the output format cfg->outfmt. We've checked
1912 * that this all makes sense earlier in the program, and the
1913 * contract of this function asserted so (see above).
1914 */
1915 status = esl_msafile_Write(ofp, msa, (ofp == cfg->tmpfp ? eslMSAFILE_PFAM : cfg->outfmt));
1916 if (status == eslEMEM) ESL_FAIL(status, errbuf, "Memory error when outputting alignment\n");
1917 else if (status != eslOK) ESL_FAIL(status, errbuf, "Writing alignment file failed with error %d\n", status);
1918
1919 if(msa != NULL) esl_msa_Destroy(msa);
1920 if(sqpA != NULL) free(sqpA);
1921 if(trA != NULL) free(trA);
1922 if(ppstrA != NULL) free(ppstrA);
1923
1924 return eslOK;
1925
1926 ERROR:
1927 if(msa != NULL) esl_msa_Destroy(msa);
1928 if(sqpA != NULL) free(sqpA);
1929 if(trA != NULL) free(trA);
1930 if(ppstrA != NULL) free(ppstrA);
1931 return status;
1932 }
1933
1934
1935 /* Function: output_info_file_header
1936 * Date: EPN, Fri Dec 4 08:15:31 2009
1937 *
1938 * Purpose: Print the header section of an insert or EL insert
1939 * (--ifile, --elfile) information file.
1940 *
1941 * Returns: void
1942 */
1943 void
1944 output_info_file_header(FILE *fp, char *firstline, char *elstring)
1945 {
1946 fprintf(fp, "# %s\n", firstline);
1947 fprintf(fp, "# This file includes 2+<nseq> non-'#' pre-fixed lines per model used for alignment,\n");
1948 fprintf(fp, "# where <nseq> is the number of sequences in the target file.\n");
1949 fprintf(fp, "# The first non-'#' prefixed line per model includes 2 tokens, separated by a single space (' '):\n");
1950 fprintf(fp, "# The first token is the model name and the second is the consensus length of the model (<clen>).\n");
1951 fprintf(fp, "# The following <nseq> lines include (4+3*<n>) whitespace delimited tokens per line.\n");
1952 fprintf(fp, "# The format for these <nseq> lines is:\n");
1953 fprintf(fp, "# <seqname> <seqlen> <spos> <epos> <c_1> <u_1> <i_1> <c_2> <u_2> <i_2> .... <c_x> <u_x> <i_x> .... <c_n> <u_n> <i_n>\n");
1954 fprintf(fp, "# indicating <seqname> has >= 1 %sinserted residues after <n> different consensus positions,\n", elstring);
1955 fprintf(fp, "# <seqname> is the name of the sequence\n");
1956 fprintf(fp, "# <seqlen> is the unaligned length of the sequence\n");
1957 fprintf(fp, "# <spos> is the first (5'-most) consensus position filled by a nongap for this sequence (-1 if 0 nongap consensus posns)\n");
1958 fprintf(fp, "# <epos> is the final (3'-most) consensus position filled by a nongap for this sequence (-1 if 0 nongap consensus posns)\n");
1959 fprintf(fp, "# <c_x> is a consensus position (between 0 and <clen>; if 0: inserts before 1st consensus posn)\n");
1960 fprintf(fp, "# <u_x> is the *unaligned* position (b/t 1 and <seqlen>) in <seqname> of the first %sinserted residue after <c_x>.\n", elstring);
1961 fprintf(fp, "# <i_x> is the number of %sinserted residues after position <c_x> for <seqname>.\n", elstring);
1962 fprintf(fp, "# Lines for sequences with 0 %sinserted residues will include only <seqname> <seqlen> <spos> <epos>.\n", elstring);
1963 fprintf(fp, "# The final non-'#' prefixed line per model includes only '//', indicating the end of info for a model.\n");
1964 fprintf(fp, "#\n");
1965
1966 return;
1967 }
1968
1969 /* Function: output_scores()
1970 * Date: EPN, Tue Jan 3 14:49:56 2012
1971 *
1972 * Purpose: Print scores and other information to a scores file.
1973 *
1974 * Returns: eslOK on success.
1975 * eslEMEM if out of memory.
1976 */
1977 int
1978 output_scores(FILE *ofp, CM_t *cm, char *errbuf, CM_ALNDATA **dataA, int ndata, int first_idx, int be_verbose)
1979 {
1980 int status; /* easel status */
1981 int i; /* counter */
1982 int namewidth = 8; /* length of 'seq name' */
1983 char *namedashes = NULL; /* namewidth-long string of dashes */
1984 int idxwidth; ; /* length of max index */
1985 char *idxdashes = NULL; /* idxwidth-long string of dashes */
1986 int64_t maxidx; /* maximum index */
1987
1988 /* alignment options */
1989 int do_nonbanded = (cm->align_opts & CM_ALIGN_NONBANDED) ? TRUE : FALSE;
1990 int do_post = (cm->align_opts & CM_ALIGN_POST) ? TRUE : FALSE;
1991 int do_sub = (cm->align_opts & CM_ALIGN_SUB) ? TRUE : FALSE;
1992 int do_trunc = (cm->align_opts & CM_ALIGN_TRUNC) ? TRUE : FALSE;
1993
1994 for(i = first_idx; i < ndata; i++) namewidth = ESL_MAX(namewidth, strlen(dataA[i]->sq->name));
1995
1996 maxidx = dataA[ndata-1]->idx+1;
1997 idxwidth = 0; do { idxwidth++; maxidx/=10; } while (maxidx); /* poor man's (int)log_10(maxidx)+1 */
1998 idxwidth = ESL_MAX(idxwidth, 3);
1999
2000 ESL_ALLOC(namedashes, sizeof(char) * (namewidth+1));
2001 namedashes[namewidth] = '\0';
2002 for(i = 0; i < namewidth; i++) namedashes[i] = '-';
2003
2004 ESL_ALLOC(idxdashes, sizeof(char) * (idxwidth+1));
2005 idxdashes[idxwidth] = '\0';
2006 for(i = 0; i < idxwidth; i++) idxdashes[i] = '-';
2007
2008 fprintf(ofp, "# %*s %-*s %6s %7s %7s %5s %8s %6s %-30s %8s", idxwidth, "", namewidth, "", " ", "", "", "", "", "", " running time (s)", "");
2009 if(be_verbose) fprintf(ofp, " %7s %7s %7s %8s", "", "", "", "");
2010 fprintf(ofp, "\n");
2011
2012 fprintf(ofp, "# %*s %-*s %6s %7s %7s %5s %8s %6s %30s %8s", idxwidth, "", namewidth, "", " ", "", "", "", "", "", "-------------------------------", "");
2013 if(be_verbose) fprintf(ofp, " %7s %7s %7s %8s", "", "", "", "");
2014 fprintf(ofp, "\n");
2015
2016 fprintf(ofp, "# %*s %-*s %6s %7s %7s %5s %8s %6s %9s %9s %9s %8s", idxwidth, "idx", namewidth, "seq name", "length", "cm from", "cm to", "trunc", "bit sc", "avg pp", "band calc", "alignment", "total", "mem (Mb)");
2017 if(be_verbose) fprintf(ofp, " %7s %7s %7s %8s", "tau", "thresh1", "thresh2", "failover");
2018 fprintf(ofp, "\n");
2019
2020 fprintf(ofp, "# %*s %-*s %6s %7s %7s %5s %8s %6s %9s %9s %9s %8s", idxwidth, idxdashes, namewidth, namedashes, "------", "-------", "-------", "-----", "--------", "------", "---------", "---------", "---------", "--------");
2021 if(be_verbose) fprintf(ofp, " %7s %7s %7s %8s", "-------", "-------", "-------", "--------");
2022 fprintf(ofp, "\n");
2023
2024 for(i = first_idx; i < ndata; i++) {
2025 fprintf(ofp, " %*" PRId64 " %-*s %6" PRId64 " %7d %7d", idxwidth, dataA[i]->idx+1, namewidth, dataA[i]->sq->name, dataA[i]->sq->n, dataA[i]->spos, dataA[i]->epos);
2026 if(do_sub) {
2027 if (dataA[i]->spos != 1 && dataA[i]->epos != cm->clen) fprintf(ofp, " %5s", "5'&3'");
2028 else if(dataA[i]->spos == 1 && dataA[i]->epos != cm->clen) fprintf(ofp, " %5s", "3'");
2029 else if(dataA[i]->spos != 1 && dataA[i]->epos == cm->clen) fprintf(ofp, " %5s", "5'");
2030 else if(dataA[i]->spos == 1 && dataA[i]->epos == cm->clen) fprintf(ofp, " %5s", "no");
2031 }
2032 else {
2033 if (dataA[i]->tr->mode[0] == TRMODE_T) fprintf(ofp, " %5s", "5'&3'");
2034 else if(dataA[i]->tr->mode[0] == TRMODE_L) fprintf(ofp, " %5s", "3'");
2035 else if(dataA[i]->tr->mode[0] == TRMODE_R) fprintf(ofp, " %5s", "5'");
2036 else fprintf(ofp, " %5s", "no");
2037 }
2038 fprintf(ofp, " %8.2f", dataA[i]->sc);
2039 if(do_post) fprintf(ofp, " %6.3f", dataA[i]->pp);
2040 else fprintf(ofp, " %6s", "-");
2041 if(! do_nonbanded) fprintf(ofp, " %9.2f", dataA[i]->secs_bands);
2042 else fprintf(ofp, " %9s", "-");
2043 fprintf(ofp, " %9.2f %9.2f", dataA[i]->secs_aln, dataA[i]->secs_tot);
2044 fprintf(ofp, " %8.2f", dataA[i]->mb_tot);
2045 if(be_verbose) {
2046 if(dataA[i]->tau > -0.5) fprintf(ofp, " %7.2g", dataA[i]->tau); /* tau is -1. if aln did not use HMM bands */
2047 else fprintf(ofp, " %7s", "-");
2048 if(do_trunc) fprintf(ofp, " %7.2f %7.2f", dataA[i]->thresh1, dataA[i]->thresh2);
2049 else fprintf(ofp, " %7s %7s", "-", "-");
2050 if(do_trunc && (! do_nonbanded)) {
2051 fprintf(ofp, " %8s", (dataA[i]->tr->is_std) ? "yes" : "no");
2052 }
2053 else {
2054 fprintf(ofp, " %8s", "-");
2055 }
2056 }
2057 fprintf(ofp, "\n");
2058 }
2059
2060 if(namedashes != NULL) free(namedashes);
2061 if(idxdashes != NULL) free(idxdashes);
2062 return eslOK;
2063
2064 ERROR:
2065 ESL_FAIL(status, errbuf, "out of memory");
2066 return status; /* NEVER REACHED */
2067 }
2068
2069 /* Function: create_and_output_final_msa
2070 * Incept: EPN, Mon Dec 14 05:35:51 2009
2071 *
2072 * Purpose: Read the >=1 MSAs that were written to a temporary file,
2073 * merge them and output the merged MSA to a file without
2074 * storing any of the full MSAs (incl. the final one) in
2075 * memory. To accomplish this a first pass of reading is
2076 * done to determine how many gap columns must be added to
2077 * each MSA to create the merged MSA during which only non
2078 * per-sequence information is stored. After this pass, with
2079 * the size of the merged alignment known, a second pass
2080 * occurs during which only GS annotation is regurgitated
2081 * (if any exists in at least 1 aln). Then a final pass
2082 * occurs during which all other per-sequence data (PPs,
2083 * aligned seqs) are regurgitated, taking care to add gap
2084 * columns as necessary to make each input alignment the
2085 * correct width of the merged alignment.
2086 *
2087 * Args: go - options
2088 * cfg - cmalign config
2089 * errbuf - for error messages
2090 * cm - CM used for alignment, useful for cm->clen
2091 * tmpfile - name of temporary file with alignments to merge
2092 *
2093 * Returns: <eslOK> on success.
2094 * Returns <eslEOF> if there are no more alignments in <afp>.
2095 * <eslEFORMAT> if parse fails because of a file format problem,
2096 * in which case afp->errbuf is set to contain a formatted message
2097 * that indicates the cause of the problem. <eslEMEM> on allocation
2098 * error.
2099 *
2100 * Xref: /groups/eddy/home/nawrockie/notebook/9_1211_inf_cmalign_memeff/
2101 */
2102 int
2103 create_and_output_final_msa(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm, int nali, char *tmpfile)
2104 {
2105 int status;
2106 int ai; /* counters over alignments */
2107 int nseq_tot; /* number of sequences in all alignments */
2108 int nseq_cur; /* number of sequences in current alignment */
2109 int64_t alen_cur; /* length of current alignment */
2110 int64_t *alenA = NULL; /* [0..nali_tot-1] alignment length of input msas (even after
2111 * potentially removingeinserts (--rfonly)) */
2112 ESL_MSA **msaA = NULL; /* [0..nali_tot-1] all msas read from all files */
2113 int *maxins = NULL; /* [0..cpos..cm->clen+1] max number of inserts
2114 * before each consensus position in all alignments */
2115 int *maxel = NULL; /* [0..cpos..cm->clen+1] max number of EL inserts ('~' missing data symbols)
2116 * before each consensus position in all alignments */
2117 int cur_clen; /* consensus length (non-gap #=GC RF length) of current alignment */
2118 int apos; /* alignment position */
2119 ESL_MSA *fmsa = NULL; /* the merged alignment created by merging all alignments in msaA */
2120 /*int alen_fmsa;*/ /* number of columns in merged MSA */
2121 int *ngap_insA = NULL; /* [0..alen] number of insert gap columns to add after each alignment column when merging */
2122 int *ngap_elA = NULL; /* [0..alen] number of missing data ('~') gap columns to add after each alignment column when merging */
2123 int *ngap_eitherA = NULL; /* [0..apos..alen] = ngap_insA[apos] + ngap_elA[apos] */
2124 char *rf2print = NULL; /* #=GC RF annotation for final alignment */
2125 char *ss_cons2print = NULL; /* #=GC SS_cons annotation for final alignment */
2126
2127 /* variables only used in small mode */
2128 int ngs_cur; /* number of GS lines in current alignment (only used if do_small) */
2129 int gs_exists = FALSE; /* set to TRUE if do_small and any input aln has >= 1 GS line */
2130 int maxname, maxgf, maxgc, maxgr; /* max length of seqname, GF tag, GC tag, GR tag in all input alignments */
2131 int maxname_cur, maxgf_cur, maxgc_cur, maxgr_cur; /* max length of seqname, GF tag, GC tag, GR tag in current input alignment */
2132 int margin = 0; /* total margin length for output msa */
2133 int regurg_header = FALSE; /* set to TRUE if we're printing out header */
2134 int regurg_gf = FALSE; /* set to TRUE if we're printing out GF */
2135 ESL_MSAFILE2 *afp;
2136
2137 /* Allocate and initialize */
2138 ESL_ALLOC(msaA, sizeof(ESL_MSA *) * nali);
2139 ESL_ALLOC(alenA, sizeof(int64_t) * nali);
2140
2141 /****************************************************************************
2142 * Read alignments one at a time, storing all non-sequence info, separately *
2143 ****************************************************************************/
2144 if((status = esl_msafile2_Open(tmpfile, NULL, &afp)) != eslOK) cm_Fail("unable to open temp file %s for reading", tmpfile);
2145
2146 ai = 0;
2147 nseq_tot = 0;
2148 maxname = maxgf = maxgc = maxgr = 0;
2149
2150 /* allocate maxins */
2151 ESL_ALLOC(maxins, sizeof(int) * (cm->clen+1));
2152 esl_vec_ISet(maxins, (cm->clen+1), 0);
2153 /* allocate maxel */
2154 ESL_ALLOC(maxel, sizeof(int) * (cm->clen+1));
2155 esl_vec_ISet(maxel, (cm->clen+1), 0); /* these will all stay 0 unless we see '~' in the alignments */
2156
2157 /* read all alignments, there should be nali of them */
2158 for(ai = 0; ai < nali; ai++) {
2159 status = esl_msafile2_ReadInfoPfam(afp, NULL, cfg->abc, -1, NULL, NULL, &(msaA[ai]), &nseq_cur, &alen_cur, &ngs_cur, &maxname_cur, &maxgf_cur, &maxgc_cur, &maxgr_cur, NULL, NULL, NULL, NULL, NULL);
2160 if (status == eslEFORMAT) cm_Fail("Rereading alignment %d for merging, parse error:\n%s\n", ai+1, afp->errbuf);
2161 else if (status == eslEINVAL) cm_Fail("Rereading alignment %d for merging, parse error:\n%s\n", ai+1, afp->errbuf);
2162 else if (status != eslOK) cm_Fail("Rereading alignment %d for merging, parse error:\n%s\n", ai+1, afp->errbuf);
2163
2164 msaA[ai]->abc = cfg->abc;
2165 if(msaA[ai]->rf == NULL) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "When rereading alignment %d for merging, no RF annotation found.", ai+1);
2166 cur_clen = 0;
2167 for(apos = 0; apos < (int) alen_cur; apos++) {
2168 if((! esl_abc_CIsGap(msaA[ai]->abc, msaA[ai]->rf[apos])) && (! esl_abc_CIsMissing(msaA[ai]->abc, msaA[ai]->rf[apos]))) cur_clen++;
2169 }
2170 if(cur_clen != cm->clen) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "When rereading alignment %d for merging, consensus length wrong (%d, when %d was expected)", ai, cur_clen, cm->clen);
2171 maxname = ESL_MAX(maxname, maxname_cur);
2172 maxgf = ESL_MAX(maxgf, maxgf_cur);
2173 maxgc = ESL_MAX(maxgc, maxgc_cur);
2174 maxgr = ESL_MAX(maxgr, maxgr_cur);
2175 msaA[ai]->alen = alen_cur;
2176 alenA[ai] = alen_cur; /* to remember total width of aln to expect in second pass */
2177 nseq_tot += nseq_cur;
2178 if(ngs_cur > 0) gs_exists = TRUE;
2179
2180 /* determine max number inserts and ELs between each position */
2181 update_maxins_and_maxel(msaA[ai], cm->clen, msaA[ai]->alen, maxins, maxel);
2182 }
2183 /* final check, make sure we've read all msas from the file, we should have, we only printed nali */
2184 status = esl_msafile2_ReadInfoPfam(afp, NULL, cfg->abc, -1, NULL, NULL, NULL,
2185 NULL, NULL, NULL, NULL, NULL, NULL, NULL,
2186 NULL, NULL, NULL, NULL, NULL);
2187 if(status != eslEOF) ESL_FAIL(status, errbuf, "More alignments in temp file than expected.");
2188 esl_msafile2_Close(afp);
2189
2190 /********************************************
2191 * Merge all alignments into the merged MSA *
2192 ********************************************/
2193
2194 /* We allocate space for all sequences, but leave sequences as NULL
2195 * (nseq = -1). We didn't store the sequences on the first pass
2196 * through the alignment files, and we'll never allocate space for
2197 * the sequences in fmsa, we'll just output them as we reread them
2198 * on another pass through the individual alignments. If we read >=
2199 * 1 GS line in any of the temporary alignments, we need to do an
2200 * additional pass through them, outputting only GS data. Then, in a
2201 * final (3rd) pass we'll output aligned data.
2202 */
2203 fmsa = esl_msa_Create(nseq_tot, -1);
2204 /*alen_fmsa = cm->clen + esl_vec_ISum(maxins, (cm->clen+1));*/
2205
2206 /* if there was any GS annotation in any of the individual alignments,
2207 * do second pass through alignment files, outputting GS annotation as we go. */
2208 if(gs_exists) {
2209 if((status = esl_msafile2_Open(tmpfile, NULL, &afp)) != eslOK) cm_Fail("unable to open temp file %s for reading on second pass", tmpfile);
2210 for(ai = 0; ai < nali; ai++) {
2211 regurg_header = (ai == 0) ? TRUE : FALSE;
2212 regurg_gf = (ai == 0) ? TRUE : FALSE;
2213 status = esl_msafile2_RegurgitatePfam(afp, cfg->ofp,
2214 maxname, maxgf, maxgc, maxgr, /* max width of a seq name, gf tag, gc tag, gr tag */
2215 regurg_header, /* regurgitate stockholm header ? */
2216 FALSE, /* regurgitate // trailer ? */
2217 regurg_header, /* regurgitate blank lines */
2218 regurg_header, /* regurgitate comments */
2219 regurg_gf, /* regurgitate GF ? */
2220 TRUE, /* regurgitate GS ? */
2221 FALSE, /* regurgitate GC ? */
2222 FALSE, /* regurgitate GR ? */
2223 FALSE, /* regurgitate aseq ? */
2224 NULL, /* output all seqs, not just those stored in a keyhash */
2225 NULL, /* output all seqs, don't skip those listed in a keyhash */
2226 NULL, /* useme, irrelevant, we're only outputting GS */
2227 NULL, /* add2me, irrelevant, we're only outputting GS */
2228 alenA[ai], /* alignment length, as we read it in first pass (inserts may have been removed since then) */
2229 '.', NULL, NULL);
2230 if(status == eslEOF) cm_Fail("Second pass, error out of temp alignments too soon, when trying to read aln %d", ai);
2231 if(status != eslOK) cm_Fail("Second pass, error reading temp alignment %d %s", ai, afp->errbuf);
2232 fflush(cfg->ofp);
2233 }
2234 esl_msafile2_Close(afp);
2235 fprintf(cfg->ofp, "\n"); /* a single blank line to separate GS annotation from aligned data */
2236 }
2237 /* do another (either second or third) pass through alignment files, outputting aligned sequence data (and GR) as we go */
2238
2239 if((status = esl_msafile2_Open(tmpfile, NULL, &afp)) != eslOK) cm_Fail("unable to open temp file %s for reading on second (or third) pass", tmpfile);
2240
2241 for(ai = 0; ai < nali; ai++) {
2242 /* determine how many all gap columns to insert after each alignment position
2243 * of the temporary msa when copying it to the merged msa */
2244 if((status = determine_gap_columns_to_add(msaA[ai], maxins, maxel, cm->clen, &(ngap_insA), &(ngap_elA), &(ngap_eitherA), errbuf)) != eslOK)
2245 cm_Fail("error determining number of all gap columns to add to temp alignment %d\n%s", ai, errbuf);
2246 regurg_header = ((! gs_exists) && (ai == 0)) ? TRUE : FALSE;
2247 regurg_gf = ((! gs_exists) && (ai == 0)) ? TRUE : FALSE;
2248
2249 status = esl_msafile2_RegurgitatePfam(afp, cfg->ofp,
2250 maxname, maxgf, maxgc, maxgr, /* max width of a seq name, gf tag, gc tag, gr tag */
2251 regurg_header, /* regurgitate stockholm header ? */
2252 FALSE, /* regurgitate // trailer ? */
2253 regurg_header, /* regurgitate blank lines */
2254 regurg_header, /* regurgitate comments */
2255 regurg_gf, /* regurgitate GF ? */
2256 FALSE, /* regurgitate GS ? */
2257 FALSE, /* regurgitate GC ? */
2258 TRUE, /* regurgitate GR ? */
2259 TRUE, /* regurgitate aseq ? */
2260 NULL, /* output all seqs, not just those stored in a keyhash */
2261 NULL, /* output all seqs, don't skip those stored in a keyhash */
2262 NULL, /* useme, not nec b/c we want to keep all columns */
2263 ngap_eitherA, /* number of all gap columns to add after each apos */
2264 alenA[ai], /* alignment length, as we read it in first pass, not strictly necessary */
2265 '.', NULL, NULL);
2266 if(status == eslEOF) cm_Fail("Second pass, error out of alignments too soon, when trying to read temp aln %d", ai);
2267 if(status != eslOK) cm_Fail("Second pass, error reading temp alignment %d: %s", ai, afp->errbuf);
2268 if(ai == 0) {
2269 /* create the GC SS_cons and GC RF to print from the first alignment,
2270 * we use the first alignment b/c this is the one potentially with rewritten pknots
2271 * from --withpknots.
2272 */
2273 inflate_gc_with_gaps_and_els(cfg->ofp, msaA[ai], ngap_insA, ngap_elA, &ss_cons2print, &rf2print);
2274 }
2275 free(ngap_insA);
2276 free(ngap_elA);
2277 free(ngap_eitherA);
2278
2279 esl_msa_Destroy(msaA[ai]);
2280 msaA[ai] = NULL;
2281 fflush(cfg->ofp);
2282 }
2283 /* output SS_cons and RF */
2284 margin = maxname+1;
2285 if (maxgc > 0 && maxgc+6 > margin) margin = maxgc+6;
2286 if (maxgr > 0 && maxname+maxgr+7 > margin) margin = maxname+maxgr+7;
2287 fprintf(cfg->ofp, "#=GC %-*s %s\n", margin-6, "SS_cons", ss_cons2print);
2288 fprintf(cfg->ofp, "#=GC %-*s %s\n", margin-6, "RF", rf2print);
2289 fprintf(cfg->ofp, "//\n");
2290
2291 esl_msafile2_Close(afp);
2292
2293 if(ss_cons2print != NULL) free(ss_cons2print);
2294 if(rf2print != NULL) free(rf2print);
2295 if(alenA != NULL) free(alenA);
2296 if(msaA != NULL) free(msaA);
2297 if(maxins != NULL) free(maxins);
2298 if(maxel != NULL) free(maxel);
2299 if(fmsa != NULL) esl_msa_Destroy(fmsa);
2300 return eslOK;
2301
2302 ERROR:
2303 esl_fatal("Out of memory. Reformat to Pfam with esl-reformat and try esl-alimerge --savemem.");
2304 return eslEMEM; /*NEVERREACHED*/
2305 }
2306
2307 /* Function: update_maxins_and_maxel
2308 * Date: EPN, Sun Nov 22 09:40:48 2009
2309 *
2310 * Update maxins[] and maxel[], arrays that keeps track of the
2311 * max number of inserted ('.' gap #=GC RF) columns and inserted EL
2312 * emissions ('~' gap #=GC RF) columns before each cpos (consensus
2313 * (non-gap #=GC RF) column)
2314 *
2315 * Consensus columns are index [0..cpos..clen].
2316 *
2317 * max{ins,el}[0] is number of {IL/IR inserts, EL inserts} before 1st cpos.
2318 * max{ins,el}[clen-1] is number of {IL/IR inserts, EL inserts} before final cpos.
2319 * max{ins,el}[clen] is number of {IL/IR inserts, EL inserts} after final cpos.
2320 *
2321 * Caller has already checked that msa->rf != NULL
2322 * and its non-gap length is clen. If we find either
2323 * of these is not true, we die (but this shouldn't happen).
2324 *
2325 * Returns: void.
2326 */
2327 void
2328 update_maxins_and_maxel(ESL_MSA *msa, int clen, int64_t alen, int *maxins, int *maxel)
2329 {
2330 int apos;
2331 int cpos = 0;
2332 int nins = 0;
2333 int nel = 0;
2334
2335 for(apos = 0; apos < alen; apos++) {
2336 if(esl_abc_CIsGap(msa->abc, msa->rf[apos])) {
2337 nins++;
2338 }
2339 else if (esl_abc_CIsMissing(msa->abc, msa->rf[apos])) {
2340 nel++;
2341 }
2342 else {
2343 maxins[cpos] = ESL_MAX(maxins[cpos], nins);
2344 maxel[cpos] = ESL_MAX(maxel[cpos], nel);
2345 cpos++;
2346 nins = 0;
2347 nel = 0;
2348 }
2349 }
2350
2351 /* update final value, max{ins,el}[clen+1], the number of inserts
2352 * after the final consensus position */
2353 maxins[cpos] = ESL_MAX(maxins[cpos], nins);
2354 maxel[cpos] = ESL_MAX(maxel[cpos], nel);
2355 if(cpos != clen) cm_Fail("Unexpected error in update_maxins_and_maxel(), expected clen (%d) not equal to actual clen (%d).\n", clen, cpos);
2356
2357 return;
2358 }
2359
2360 /* determine_gap_columns_to_add
2361 *
2362 * Given <maxins> and <maxel>, two arrays of the number of gap RF
2363 * (inserts) positions and '~' RF (EL inserts) after each non-gap RF
2364 * (consensus) position in the eventual final merged alignment,
2365 * calculate how many inserts and missing data inserts
2366 * we need to add at each position of <msa> to expand it out to the
2367 * appropriate size of the eventual merged alignment.
2368 *
2369 * max{ins,el}[0] is number of inserts,ELs before 1st cpos in merged aln
2370 * max{ins,el}[cpos] is number of inserts,ELs after final cpos in merged aln
2371 * for cpos = 1..clen
2372 * clen is the number of non-gap RF positions in msa (and in eventual merged msa).
2373 *
2374 * We allocate fill and return ret_ngap_insA[0..msa->alen], ret_ngap_elA[0..msa->alen],
2375 * and ret_ngap_eitherA[0..msa->alen] here.
2376 *
2377 * ret_n{ins,el}gapA[0] is number of inserts,ELs to add before 1st position of msa
2378 * ret_n{ins,el}gapA[apos] is number of inserts,ELs to add after alignment position apos
2379 * for apos = 1..msa->alen
2380 *
2381 * ret_ngap_eitherA[apos] = ngap_insA[apos] + ngap_elA[apos]
2382 *
2383 * This is similar to the esl_msa.c helper function of the same name,
2384 * but that function does not bother with missing data '~'.
2385 *
2386 * Returns eslOK on success.
2387 * eslEMEM on memory alloaction error
2388 * eslERANGE if a value exceeds what we expected (based on earlier
2389 * checks before this function was entered).
2390 * if !eslOK, errbuf if filled.
2391 */
2392 int
2393 determine_gap_columns_to_add(ESL_MSA *msa, int *maxins, int *maxel, int clen, int **ret_ngap_insA, int **ret_ngap_elA, int **ret_ngap_eitherA, char *errbuf)
2394 {
2395 int status;
2396 int apos;
2397 int prv_cpos = 0; /* alignment position corresponding to consensus position cpos-1 */
2398 int cpos = 0;
2399 int nins = 0;
2400 int nel = 0;
2401 int *ngap_insA = NULL;
2402 int *ngap_elA = NULL;
2403 int *ngap_eitherA = NULL;
2404
2405 /* contract check */
2406 if(maxel[0] != 0) ESL_FAIL(eslEINVAL, errbuf, "missing characters exist prior to first cpos, this shouldn't happen.\n");
2407 if(msa->ss_cons == NULL) ESL_FAIL(eslEINVAL, errbuf, "MSA's SS_cons is null in determine_gap_columns_to_add.\n");
2408
2409 ESL_ALLOC(ngap_insA, sizeof(int) * (msa->alen+1));
2410 ESL_ALLOC(ngap_elA, sizeof(int) * (msa->alen+1));
2411 ESL_ALLOC(ngap_eitherA, sizeof(int) * (msa->alen+1));
2412 esl_vec_ISet(ngap_insA, (msa->alen+1), 0);
2413 esl_vec_ISet(ngap_elA, (msa->alen+1), 0);
2414 esl_vec_ISet(ngap_eitherA, (msa->alen+1), 0);
2415
2416 for(apos = 0; apos < msa->alen; apos++) {
2417 if(esl_abc_CIsMissing(msa->abc, msa->rf[apos])) {
2418 nel++;
2419 if(nins > 0) ESL_FAIL(eslEINVAL, errbuf, "after nongap RF pos %d, %d gap columns precede a missing data column (none should)", cpos, nins);
2420 }
2421 else if(esl_abc_CIsGap(msa->abc, msa->rf[apos])) {
2422 nins++;
2423 }
2424 else { /* a consensus position */
2425 /* a few sanity checks */
2426 if(nins > maxins[cpos]) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "%d inserts before cpos %d greater than max expected (%d).\n", nins, cpos, maxins[cpos]);
2427 if(nel > maxel[cpos]) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "%d EL inserts before cpos %d greater than max expected (%d).\n", nel, cpos, maxel[cpos]);
2428
2429 if (cpos == 0) {
2430 if(nel != 0) ESL_FAIL(eslEINVAL, errbuf, "found missing chars prior to first cpos, shouldn't happen\n");
2431 ngap_insA[prv_cpos] = maxins[cpos] - nins; /* inserts before first position: flush right (so add all-gap columns after leftmost column) */
2432 /* we already checked that maxel[0] is 0 during contract check above */
2433 }
2434 else {
2435 /* Determine where to place inserts and/or missing data.
2436 * Handle each of 4 possibilities separately, note that if
2437 * maxins[cpos] == 0 then nins == 0, and if maxel[cpos] == 0 then nel == 0 (see sanity check above).
2438 */
2439 if(maxins[cpos] > 0 && maxel[cpos] == 0) { /* most common case */
2440 ngap_insA[prv_cpos + 1 + (nins/2)] = maxins[cpos] - nins; /* internal cpos: split */
2441 }
2442 else if(maxins[cpos] == 0 && maxel[cpos] > 0) {
2443 ngap_elA[prv_cpos + 1 + (nel/2)] = maxel[cpos] - nel; /* internal cpos: split */
2444 }
2445 else if(maxins[cpos] > 0 && maxel[cpos] > 0) {
2446 /* Rule is (as of SVN r4271, and version 1.1rc2) that
2447 * ELs always come before (5' of) insertions, even for the
2448 * rare case of a MATP node immediately prior to an END node.
2449 */
2450 ngap_elA[prv_cpos + 1 + (nel/2)] = maxel[cpos] - nel; /* internal cpos: split */
2451 ngap_insA[prv_cpos + 1 + nel + (nins/2)] = maxins[cpos] - nins; /* internal cpos: split */
2452 }
2453 /* final case is if (maxins[cpos] == 0 && maxel[cpos] == 0)
2454 * in this case we do nothing.
2455 */
2456 }
2457
2458 cpos++;
2459 prv_cpos = apos;
2460 nins = 0;
2461 nel = 0;
2462 }
2463 }
2464 /* first, validate that clen is what it should be */
2465 if(cpos != clen) {
2466 if(ngap_insA != NULL) free(ngap_insA);
2467 if(ngap_elA != NULL) free(ngap_elA);
2468 if(ngap_eitherA != NULL) free(ngap_eitherA);
2469 ESL_FAIL(eslEINCONCEIVABLE, errbuf, "consensus length (%d) is not the expected length (%d).", cpos, clen);
2470 }
2471
2472 if(maxins[cpos] > 0 && maxel[cpos] == 0) { /* most common case */
2473 ngap_insA[prv_cpos + 1 + nins] = maxins[cpos] - nins; /* flush left inserts (no missing) */
2474 }
2475 else if(maxins[cpos] == 0 && maxel[cpos] > 0) {
2476 ngap_elA[prv_cpos + 1 + nel] = maxel[cpos] - nel; /* flush left ELs (no gaps) */
2477 }
2478 else if(maxins[cpos] > 0 && maxel[cpos] > 0) {
2479 /* missing data (ELs) is always 5' of gaps */
2480 ngap_elA[prv_cpos + 1 + nel] = maxel[cpos] - nel; /* flush left */
2481 ngap_insA[prv_cpos + 1 + nel + nins] = maxins[cpos] - nins; /* flush left, after ELs */
2482 }
2483
2484 /* determine ngap_eitherA[], the number of gaps due to either inserts or missing data after each apos */
2485 for(apos = 0; apos <= msa->alen; apos++) {
2486 ngap_eitherA[apos] = ngap_insA[apos] + ngap_elA[apos];
2487 }
2488
2489 *ret_ngap_insA = ngap_insA;
2490 *ret_ngap_elA = ngap_elA;
2491 *ret_ngap_eitherA = ngap_eitherA;
2492
2493 return eslOK;
2494
2495 ERROR:
2496 if(ngap_insA != NULL) free(ngap_insA);
2497 if(ngap_elA != NULL) free(ngap_elA);
2498 if(ngap_eitherA != NULL) free(ngap_eitherA);
2499 ESL_FAIL(status, errbuf, "Memory allocation error.");
2500 return status; /*NEVERREACHED*/
2501 }
2502
2503 /* inflate_gc_with_gaps_and_els
2504 *
2505 * Given an MSA and two arrays specifying the number of inserts '.'
2506 * and EL inserts '~' to add after each position, create the
2507 * SS_cons and RF strings to output for the merged alignment
2508 * after adding the gaps and missing data symbols ('~') and
2509 * return them in ret_ss_cons2print and ret_rf2print. Caller
2510 * is responsible for freeing them.
2511 *
2512 * Returns void. If something unexpected occurs, including an
2513 * allocation error, we die here and print error message.
2514 */
2515 void
2516 inflate_gc_with_gaps_and_els(FILE *ofp, ESL_MSA *msa, int *ngap_insA, int *ngap_elA, char **ret_ss_cons2print, char **ret_rf2print)
2517 {
2518 int status;
2519 int apos = 0;
2520 int apos2print = 0;
2521 int i;
2522 int alen2print = 0;
2523 char *rf2print;
2524 char *ss_cons2print;
2525
2526 alen2print = msa->alen + esl_vec_ISum(ngap_insA, msa->alen+1) + esl_vec_ISum(ngap_elA, msa->alen+1);
2527 ESL_ALLOC(rf2print, sizeof(char) * (alen2print+1));
2528 ESL_ALLOC(ss_cons2print, sizeof(char) * (alen2print+1));
2529 rf2print[alen2print] = '\0';
2530 ss_cons2print[alen2print] = '\0';
2531
2532 if(msa->ss_cons == NULL) cm_Fail("Error: trying to add inserts to SS_cons, but unexpectedly it doesn't exist.");
2533 if(msa->rf == NULL) cm_Fail("Error: trying to add inserts to SS_cons, but unexpectedly it doesn't exist.");
2534 for(apos = 0; apos <= msa->alen; apos++) {
2535 /* ELs always come before (5' of) inserts */
2536 for(i = 0; i < ngap_elA[apos]; i++) {
2537 rf2print[apos2print] = '~';
2538 ss_cons2print[apos2print++] = '~';
2539 }
2540 for(i = 0; i < ngap_insA[apos]; i++) {
2541 rf2print[apos2print] = '.';
2542 ss_cons2print[apos2print++] = '.';
2543 }
2544 if(apos < msa->alen) {
2545 rf2print[apos2print] = msa->rf[apos];
2546 ss_cons2print[apos2print++] = msa->ss_cons[apos];
2547 }
2548 }
2549
2550 *ret_ss_cons2print = ss_cons2print;
2551 *ret_rf2print = rf2print;
2552
2553 return;
2554
2555 ERROR:
2556 cm_Fail("Allocation error when creating final alignment RF and SS_cons.");
2557 return; /* NEVERREACHED */
2558 }
2559
2560 /* configure_root_inserts
2561 *
2562 * Modify the transition probabilities into and out of the
2563 * ROOT_IL and ROOT_IR states.
2564 * The motivation is to allow cmalign to more accurately
2565 * align sequences that have extra nonhomologous sequence
2566 * on the ends. Defaultly-paramaterized models (especially
2567 * those with zero basepairs) tend to mess up the alignment
2568 * at the ends if there are extra nucleotides.
2569 *
2570 * The value of 'prob' was limited to be 0. < prob < 0.4 by
2571 * getopts but we also do a sanity check here.
2572 *
2573 * Returns void.
2574 */
2575 void
2576 configure_root_inserts(CM_t *cm, float to_insert_prob, float self_insert_prob)
2577 {
2578 float state0_sum = 0.; /* will store cumulative prob of transitinos out of state 1 */
2579 float state1_sum = 0.; /* will store cumulative prob of transitinos out of state 1 */
2580 float state2_sum = 0.; /* will store cumulative prob of transitinos out of state 1 */
2581
2582 if((to_insert_prob <= 0.) || to_insert_prob > 0.4) {
2583 cm_Fail("ERROR with --flanktoins <x>, <x> should be > 0. and < 0.4");
2584 }
2585 if((to_insert_prob <= 0.) || to_insert_prob > 0.4) {
2586 cm_Fail("ERROR with --flankselfins <x>, <x> should be > 0. and < 0.9");
2587 }
2588 if((to_insert_prob + self_insert_prob) > 0.95) {
2589 cm_Fail("ERROR with --flanktoins <x1> and --flankselfins <x2>, <x1> + <x2> must be less than 0.95");
2590 }
2591
2592 /* Deal with transitions out of ROOT_S first
2593 * first transition out of ROOT_S is always to ROOT_IL
2594 * second transition out of ROOT_S is always to ROOT_IR
2595 * third transition out of ROOT_S is always to 'match' state in split set of next node, e.g. MATL_ML, MATR_MR, MATP_MP or BIF_B
2596 * remaining number of transitions depend on next node type, but are all 'delete' states (unless BIF)
2597 */
2598 cm->t[0][0] = to_insert_prob; /* ROOT_S -> ROOT_IL */
2599 cm->t[0][1] = to_insert_prob; /* ROOT_S -> ROOT_IR */
2600 state0_sum = to_insert_prob + to_insert_prob;
2601
2602 cm->t[1][0] = self_insert_prob; /* ROOT_IL -> ROOT_IL */
2603 cm->t[1][1] = to_insert_prob; /* ROOT_IL -> ROOT_IR */
2604 state1_sum = self_insert_prob + to_insert_prob;
2605
2606 cm->t[2][0] = self_insert_prob; /* ROOT_IR -> ROOT_IR */
2607 state2_sum = self_insert_prob;
2608
2609 /* 3/4 of the remaining to_insert_probability goes to the match state, unless BIF_B */
2610 if(cm->ndtype[1] == BIF_nd) {
2611 cm->t[0][2] = 1. - state0_sum; /* ROOT_S -> BIF_B */
2612
2613 cm->t[1][2] = 1. - state1_sum; /* ROOT_IL -> BIF_B */
2614
2615 cm->t[2][1] = 1. - state2_sum; /* ROOT_IR -> BIF_B */
2616 }
2617 else if(cm->ndtype[1] == MATP_nd) {
2618 cm->t[0][2] = (1. - state0_sum) * 0.75; /* ROOT_S -> MATP_MP */
2619 cm->t[0][3] = ((1. - state0_sum) * 0.25) / 3.; /* ROOT_S -> MATP_ML */
2620 cm->t[0][4] = ((1. - state0_sum) * 0.25) / 3.; /* ROOT_S -> MATP_MR */
2621 cm->t[0][5] = ((1. - state0_sum) * 0.25) / 3.; /* ROOT_S -> MATP_D */
2622
2623 cm->t[1][2] = (1. - state1_sum) * 0.75; /* ROOT_IL -> MATP_MP */
2624 cm->t[1][3] = ((1. - state1_sum) * 0.25) / 3.; /* ROOT_IL -> MATP_ML */
2625 cm->t[1][4] = ((1. - state1_sum) * 0.25) / 3.; /* ROOT_IL -> MATP_MR */
2626 cm->t[1][5] = ((1. - state1_sum) * 0.25) / 3.; /* ROOT_IL -> MATP_D */
2627
2628 cm->t[2][1] = (1. - state2_sum) * 0.75; /* ROOT_IR -> MATP_MP */
2629 cm->t[2][2] = ((1. - state2_sum) * 0.25) / 3.; /* ROOT_IR -> MATP_ML */
2630 cm->t[2][3] = ((1. - state2_sum) * 0.25) / 3.; /* ROOT_IR -> MATP_MR */
2631 cm->t[2][4] = ((1. - state2_sum) * 0.25) / 3.; /* ROOT_IR -> MATP_MR */
2632 }
2633 else if((cm->ndtype[1] == MATL_nd) || (cm->ndtype[1] == MATR_nd)) {
2634 cm->t[0][2] = (1. - state0_sum) * 0.75; /* ROOT_S -> MAT{L,R}_M{L,R} */
2635 cm->t[0][3] = (1. - state0_sum) * 0.25; /* ROOT_S -> MAT{L,R}_D */
2636
2637 cm->t[1][2] = (1. - state1_sum) * 0.75; /* ROOT_IL -> MAT{L,R}_M{L,R} */
2638 cm->t[1][3] = (1. - state1_sum) * 0.25; /* ROOT_IL -> MAT{L,R}_D */
2639
2640 cm->t[2][1] = (1. - state2_sum) * 0.75; /* ROOT_IR -> MAT{L,R}_M{L,R} */
2641 cm->t[2][2] = (1. - state2_sum) * 0.25; /* ROOT_IR -> MAT{L,R}_D */
2642 }
2643 else {
2644 cm_Fail("ERROR, with --flankins, unexpected second node type, not one of BIF, MATP, MATL or MATR");
2645 }
2646
2647 /* should already be normalized, but to be safe: */
2648 esl_vec_FNorm(cm->t[0], cm->cnum[0]);
2649 esl_vec_FNorm(cm->t[1], cm->cnum[1]);
2650 esl_vec_FNorm(cm->t[2], cm->cnum[2]);
2651
2652 return;
2653 }
2654