Debian Codegraph @

hmmer/easel/miniapps/esl-alimask.c

raw symbols SCIP
1 /* Remove columns from a multiple sequence alignment.
2 */
3 #include <esl_config.h>
4
5 #include <stdlib.h>
6 #include <stdio.h>
7
8 #include "easel.h"
9 #include "esl_alphabet.h"
10 #include "esl_arr2.h"
11 #include "esl_fileparser.h"
12 #include "esl_getopts.h"
13 #include "esl_msa.h"
14 #include "esl_msafile.h"
15 #include "esl_msafile2.h"
16 #include "esl_regexp.h"
17 #include "esl_stopwatch.h"
18 #include "esl_vectorops.h"
19
20 static char banner[] = "remove columns from a multiple sequence alignment";
21 static char usage1[] = "[options] <msafile> <maskfile> (use mask from maskfile)";
22 static char usage2[] = "[options] -t <msafile> <coords> (truncate alignment to coords)";
23 static char usage3[] = "[options] -g <msafile> (use gap frequencies in aln)";
24 static char usage4[] = "[options] -p <msafile> (use post probs (PP) in aln)";
25 static char usage5[] = "[options] --rf-is-mask <msafile> (use #=GC RF in aln as mask)";
26
27 static int read_mask_file(char *filename, char *errbuf, int **ret_useme, int *ret_mlen);
28 static int map_rfpos_to_apos(ESL_MSA *msa, ESL_ALPHABET *abc, char *errbuf, int **i_am_rf, int **ret_rf2a_map, int *ret_rflen);
29 static int expand_rf_useme_to_alen(int *useme_rf, int *rf2a_map, int rflen, int alen, char *errbuf, int *useme_a);
30 static int count_gaps_in_msa(ESL_MSA *msa, ESL_ALPHABET *abc, int *countme, char *errbuf, double **ret_gap_ct);
31 static int count_postprobs_in_msa(ESL_MSA *msa, ESL_ALPHABET *abc, int *countme, char *errbuf, double ***ret_pp_ct);
32 static int mask_based_on_gapfreq(double *gap_ct, int64_t alen, int nseq, float gapthresh, int *i_am_eligible, char *errbuf, int **ret_useme);
33 static int get_pp_idx(ESL_ALPHABET *abc, char ppchar);
34 static int mask_based_on_postprobs(double **pp_ct, int64_t alen, int nseq, float pthresh, float pfract, int do_pavg, float pavg_min, int do_ppcons, float ppcons_min, char *pp_cons, ESL_ALPHABET *abc, int *i_am_eligible, int allgapok, char *errbuf, int **ret_useme);
35 static int output_mask(char *filename, int *useme, int *i_am_eligible, int64_t alen, char *errbuf);
36 static int determine_nkept_rf(int *useme, int *i_am_rf, int64_t len);
37 static int parse_coord_string(const char *cstring, uint32_t *ret_start, uint32_t *ret_end);
38
39 static ESL_OPTIONS options[] = {
40 /* name type default env range togs reqs incomp help docgroup */
41 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "help; show brief info on version and usage", 1 },
42 { "-o", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "output the final alignment to file <f>, not stdout", 1 },
43 { "-q", eslARG_NONE, FALSE, NULL, NULL, NULL, "-o", NULL, "be quiet; w/-o, don't print mask info to stdout", 1 },
44 { "--small", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use minimal RAM (RAM usage will be independent of aln size)", 1 },
45 { "--informat", eslARG_STRING, FALSE, NULL, NULL, NULL, NULL, NULL, "specify that input file is in format <s>", 1 },
46 { "--outformat", eslARG_STRING, FALSE, NULL, NULL, NULL, NULL, NULL, "specify that output aln be format <s>", 1 },
47 { "--fmask-rf", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "output final mask of non-gap RF len to file <f>", 1 },
48 { "--fmask-all", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "output final mask of full aln len to file <f>", 1 },
49
50 { "--amino", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--dna,--rna", "<msafile> contains protein alignments", 2 },
51 { "--dna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--amino,--rna","<msafile> contains DNA alignments", 2 },
52 { "--rna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--amino,--dna","<msafile> contains RNA alignments", 2 },
53
54 { "--t-rf", eslARG_NONE, NULL, NULL, NULL, NULL, "-t", NULL, "<coords> string corresponds to non-gap RF positions", 3 },
55 { "--t-rmins", eslARG_NONE, NULL, NULL, NULL, NULL, "-t", NULL, "remove all gap RF positions within <coords>", 3 },
56
57 { "--gapthresh", eslARG_REAL, "0.5", NULL, "0<=x<=1", NULL, "-g", NULL, "only keep columns with <= <x> fraction of gaps in them", 4 },
58 { "--gmask-rf", eslARG_OUTFILE, NULL, NULL, NULL, NULL, "-g", NULL, "output gap-based 0/1 mask of non-gap RF len to file <f>", 4 },
59 { "--gmask-all", eslARG_OUTFILE, NULL, NULL, NULL, NULL, "-g", NULL, "output gap-based 0/1 mask of full aln len to file <f>", 4 },
60
61 { "--pfract", eslARG_REAL, "0.95", NULL, "0<=x<=1", NULL, "-p", NULL, "keep cols w/<x> fraction of seqs w/PP >= --pthresh", 5 },
62 { "--pthresh", eslARG_REAL, "0.95", NULL, "0<=x<=1", NULL, "-p", NULL, "set post prob threshold for --pfract as <x>", 5 },
63 { "--pavg", eslARG_REAL, NULL, NULL, "0<=x<=1", NULL, "-p", "--pfract,--pthresh", "keep cols with average post prob >= <x>", 5 },
64 { "--ppcons", eslARG_REAL, NULL, NULL, "0<=x<=1", NULL, "-p", "--keepins,--pavg,--pfract,--pthresh", "keep cols with PP_cons value >= <x>", 5 },
65 { "--pallgapok", eslARG_NONE, NULL, NULL, FALSE, NULL, "-p", NULL, "keep 100% gap columns (by default, they're removed w/-p)", 5 },
66 { "--pmask-rf", eslARG_OUTFILE, NULL, NULL, NULL, NULL, "-p", NULL, "output PP-based 0/1 mask of non-gap RF len to file <f>", 5 },
67 { "--pmask-all", eslARG_OUTFILE, NULL, NULL, NULL, NULL, "-p", NULL, "output PP-based 0/1 mask of full aln len to file <f>", 5 },
68
69 { "--keepins", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "if msa has RF annotation, allow gap-RF columns to possibly survive",6 },
70
71
72 /* undocumented as options, because they're documented as alternative invocations: */
73 { "-t", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-g,-p,--rf-is-mask", "", 99 },
74 { "-g", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "mask based on gap frequency in the alignment", 99 },
75 { "-p", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "mask based on posterior probability annotation in the alignment", 99 },
76 { "--rf-is-mask", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-t,-g,-p,--keepins","remove a column if and only if it is a gap in the RF annotation", 99 },
77 { 0,0,0,0,0,0,0,0,0,0 },
78 };
79
80 int
81 main(int argc, char **argv)
82 {
83 ESL_GETOPTS *go = NULL; /* application configuration */
84 ESL_ALPHABET *abc = NULL; /* biological alphabet */
85 char *alifile = NULL; /* alignment file name */
86 int infmt = eslMSAFILE_UNKNOWN; /* format code for alifile */
87 int outfmt = eslMSAFILE_UNKNOWN; /* format code for output ali */
88 ESL_MSAFILE *afp = NULL; /* open alignment file normal version */
89 ESL_MSAFILE2 *afp2 = NULL; /* open alignment file: legacy small-mem version */
90 FILE *ofp; /* output file (default is stdout) */
91 ESL_MSA *msa = NULL; /* one multiple sequence alignment */
92 int status; /* easel return code */
93 int do_rfonly = FALSE; /* TRUE if we'll automatically remove all gap RF columns */
94 int nseq = 0; /* num seqs in alignment */
95 char errbuf[eslERRBUFSIZE]; /* buffer for error messages */
96 int rflen = 0; /* non-gap RF length */
97 int nkept = 0; /* number of columns not removed for current mask */
98 int nkept_rf = 0; /* number of non-gap RF columns not removed for current mask */
99 int be_verbose = FALSE; /* will we print info on masking to stdout? */
100 int apos = 0; /* alignment position */
101 int *i_am_rf = NULL; /* [0..i..msa->alen-1]: TRUE if pos i is non-gap RF posn, if msa->rf == NULL remains NULL */
102 int *i_am_eligible = NULL; /* [0..i..msa->alen-1]: TRUE if we'll consider keeping posn i in our final masks, FALSE if not,
103 * used to automatically remove all non-gap RF columns if msa->RF != NULL && --keepins NOT enabled */
104 int *rf2a_map = NULL; /* [0..rfpos..rflen-1] = apos,
105 * apos is the alignment position (0..msa->alen-1) that
106 * is non-gap RF position rfpos+1 (for rfpos in 0..rflen-1) */
107 int *useme_final = NULL; /* final mask, [0..i..msa->alen-1] TRUE to keep apos i, FALSE not to */
108 ESL_STOPWATCH *w = NULL; /* for timing the masking, only used if -o enabled */
109 int64_t orig_alen = 0; /* alignment length of input alignment (pre-masked) */
110
111 /* variables related to default mode, reading mask from a maskfile */
112 char *maskfile = NULL; /* mask file name */
113 int do_maskfile; /* TRUE if neither -p nor -g are enabled, and we have 2 command-line args */
114 int file_mlen = 0; /* if do_maskfile, length of mask from maskfile, msa->alen or rflen */
115 double **pp_ct = NULL; /* [0..msa->alen-1][0..11] number of each PP value at each aln position */
116 int *useme_mfile = NULL; /* useme deduced from mask from maskfile,
117 * [0..i..file_mlen-1] TRUE to keep apos or rfpos i, FALSE not to */
118
119 /* variables related to truncation mode (-t) */
120 int do_truncate; /* TRUE if -t enabled */
121 uint32_t tstart, tend; /* with -t, start and end position of aln region to keep, parsed from 2nd cmdline arg (<coords> : <start>..<end>) */
122
123 /* variables related to gap frequency mode (-g) */
124 int do_gapthresh; /* TRUE if -g enabled */
125 double **abc_ct = NULL; /* [0..msa->alen-1][0..abc->K] number of each resiude at each position (abc->K is gap) */
126 double *gap_ct = NULL; /* [0..msa->alen-1] number of gaps at each position */
127 int *useme_g = NULL; /* [0..i..msa->alen-1] TRUE to keep apos i based on gapfreq, FALSE not to */
128
129 /* variables related to postprob mode (-p) */
130 int do_postprob; /* TRUE if -p enabled */
131 int do_pavg; /* TRUE if --pavg enabled */
132 int do_ppcons; /* TRUE if --ppcons enabled */
133 float pavg_min; /* <x> from --pavg <x>, if enabled, 0., otherwise */
134 float ppcons_min; /* <x> from --ppcons <x>, if enabled, 0., otherwise */
135 int *useme_pp = NULL; /* [0..i..msa->alen-1] TRUE to keep apos i based on postprobs, FALSE not to */
136
137 /* variables related to RF mode (--rf-is-mask) */
138 int do_rf_is_mask = FALSE; /* TRUE if --rf-is-mask, RF annotation is the mask, all gap RF columns removed, others kept */
139
140 /* variables related to small memory mode (--small) */
141 int do_small; /* TRUE if --small, operate in special small memory mode, aln seq data is not stored */
142
143 /***********************************************
144 * Parse command line
145 ***********************************************/
146
147 go = esl_getopts_Create(options);
148 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK ||
149 esl_opt_VerifyConfig(go) != eslOK)
150 {
151 printf("Failed to parse command line: %s\n", go->errbuf);
152 esl_usage(stdout, argv[0], usage1);
153 esl_usage(stdout, argv[0], usage2);
154 esl_usage(stdout, argv[0], usage3);
155 esl_usage(stdout, argv[0], usage4);
156 esl_usage(stdout, argv[0], usage5);
157 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
158 exit(1);
159 }
160
161 if (esl_opt_GetBoolean(go, "-h") )
162 {
163 esl_banner(stdout, argv[0], banner);
164 esl_usage (stdout, argv[0], usage1);
165 esl_usage (stdout, argv[0], usage2);
166 esl_usage (stdout, argv[0], usage3);
167 esl_usage (stdout, argv[0], usage4);
168 esl_usage (stdout, argv[0], usage5);
169 puts("\n Only one usage listed above can be used per execution with the exception of");
170 puts(" -p and -g, which can be used in combination with each other.\n");
171 puts(" With -t, <coords> is a string that specifies positive integer start and end");
172 puts(" coordinates seperated by any nonnumeric, nonspace character(s).");
173 puts(" For example, \"23..100\" or \"23/100\" or \"23-100\" all specify that columns");
174 puts(" 23 to 100 be kept and all other columns be removed. Additionally, to retrieve");
175 puts(" all columns from a position to the end, omit the end coord; \"23:\" will work.");
176 puts(" With -t and --t-rf, coordinates are interpreted as non-gap positions in the");
177 puts(" reference (\"#=GC RF\") annotation.\n");
178 puts(" With --rf-is-mask, all columns that are not gaps in the reference annotation");
179 puts(" will be kept and all other columns will be removed.");
180 puts("\n other options are:");
181 esl_opt_DisplayHelp(stdout, go, 1, 2, 80);
182 puts("\n options for specifying alphabet in <msafile>, one is required w/--small:");
183 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
184 puts("\n options related to truncating the alignment (require -t):");
185 esl_opt_DisplayHelp(stdout, go, 3, 2, 80);
186 puts("\n options for masking based on gap frequencies (require -g):");
187 esl_opt_DisplayHelp(stdout, go, 4, 2, 80);
188 puts("\n options for masking based on posterior probabilities (require -p):");
189 esl_opt_DisplayHelp(stdout, go, 5, 2, 80);
190 puts("\n options that modify masking behavior when -g and/or -p are used:");
191 esl_opt_DisplayHelp(stdout, go, 6, 2, 80);
192 exit(0);
193 }
194
195 /* Check that we have the correct number of command line args,
196 * in English: if (NOT 2 cmdline args and none of --rf-is-mask,-p,-g)
197 * AND NOT -p and 1 cmdline arg
198 * AND NOT -g and 1 cmdline arg
199 * AND NOT --rf-is-mask and 1 cmdline arg)
200 * then ERROR due to incorrect usage.
201 */
202 if ((! (((! esl_opt_GetBoolean(go, "--rf-is-mask")) && (! esl_opt_GetBoolean(go, "-p")) && (! esl_opt_GetBoolean(go, "-g"))) && esl_opt_ArgNumber(go) == 2)) && /* it is not the case that (none of --rf-is-mask,-p,-g) and 2 cmdline args */
203 (! ((esl_opt_GetBoolean(go, "-g")) && (esl_opt_ArgNumber(go) == 1))) && /* not -g and 1 arg */
204 (! ((esl_opt_GetBoolean(go, "-p")) && (esl_opt_ArgNumber(go) == 1))) && /* not -p and 1 arg */
205 (! ((esl_opt_GetBoolean(go, "--rf-is-mask")) && (esl_opt_ArgNumber(go) == 1)))) /* not --rf-is-mask and 1 arg */
206 {
207 printf("Incorrect number of command line arguments.\n");
208 esl_usage(stdout, argv[0], usage1);
209 esl_usage(stdout, argv[0], usage2);
210 esl_usage(stdout, argv[0], usage3);
211 esl_usage(stdout, argv[0], usage4);
212 esl_usage(stdout, argv[0], usage5);
213 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
214 exit(1);
215 }
216 else
217
218 alifile = esl_opt_GetArg(go, 1);
219
220 /*******************************************************************************
221 * Determine the type of masking we'll do:
222 * 1. do_maskfile: read mask from file, if none of -p,-g,-t,--rf-is-mask enabled
223 * 2. do_truncate: truncate alignment between coords from 2nd cmdline arg, if -t
224 * 3. do_postprob: use posterior probabilities in aln to create mask, if -p
225 * 4. do_gapthresh: use gap frequency in aln to create mask, if -g
226 * 5. do_rf_is_mask: mask solely based on RF annotation, if --rf-is-mask
227 *
228 * We can combine 3 and 4, but 1 and 2 and 5 are exclusive. Exclusivity of 1 is enforced by
229 * if statement above that checks number of command line args. Exclusivity of 2 and 5
230 * is enforced by esl_getopts.
231 *******************************************************************************/
232
233 do_maskfile = do_truncate = do_postprob = do_gapthresh = do_rf_is_mask = FALSE; /* until proven otherwise */
234 if(esl_opt_ArgNumber(go) == 2) {
235 if(esl_opt_GetBoolean(go, "-t")) {
236 do_truncate = TRUE;
237 /* we parse 2nd cmdline arg later */
238 }
239 else {
240 do_maskfile = TRUE;
241 maskfile = esl_opt_GetArg(go, 2);
242 }
243 }
244 else { /* 1 cmdline arg (when we checked for correct usage above, we verified either 1 or 2 cmdline args)*/
245 do_rf_is_mask = esl_opt_GetBoolean(go, "--rf-is-mask");
246 do_postprob = esl_opt_GetBoolean(go, "-p");
247 do_gapthresh = esl_opt_GetBoolean(go, "-g");
248 }
249
250 /* check for incompatible options that I don't know how to enforce with esl_getopts */
251 /* --keepins only makes sense with -p or -g */
252 if(esl_opt_GetBoolean(go, "--keepins") && (! do_postprob) && (! do_gapthresh))
253 esl_fatal("--keepins only makes sense in combination with -p and/or -g");
254
255 /* will we be verbose? */
256 be_verbose = (esl_opt_IsOn(go, "-o") && (! esl_opt_GetBoolean(go, "-q"))) ? TRUE : FALSE;
257
258 /* will we operate in small memory mode? */
259 do_small = (esl_opt_GetBoolean(go, "--small")) ? TRUE : FALSE;
260
261 /* determine input/output formats */
262 if (esl_opt_IsOn(go, "--informat")) {
263 infmt = esl_msafile_EncodeFormat(esl_opt_GetString(go, "--informat"));
264 if (infmt == eslMSAFILE_UNKNOWN) esl_fatal("%s is not a valid input sequence file format for --informat", esl_opt_GetString(go, "--informat"));
265 if (do_small && infmt != eslMSAFILE_PFAM) esl_fatal("small memory mode requires Pfam formatted alignments");
266 }
267 if (esl_opt_IsOn(go, "--outformat")) {
268 outfmt = esl_msafile_EncodeFormat(esl_opt_GetString(go, "--outformat"));
269 if (outfmt == eslMSAFILE_UNKNOWN) esl_fatal("%s is not a valid input sequence file format for --outformat", esl_opt_GetString(go, "--outformat"));
270 if (do_small && outfmt != eslMSAFILE_PFAM) esl_fatal("we can only output Pfam formatted alignments in small memory mode");
271 }
272 else outfmt = eslMSAFILE_STOCKHOLM;
273
274 if (do_small) { /* defaults change if we're in small memory mode,
275 note we checked --informat and --outformat compatibility with do_small in two if statements above */
276 infmt = eslMSAFILE_PFAM; /* this must be true, else we can't do small memory mode */
277 outfmt = eslMSAFILE_PFAM;
278 }
279
280 /* open output file */
281 if (esl_opt_GetString(go, "-o") != NULL) {
282 if ((ofp = fopen(esl_opt_GetString(go, "-o"), "w")) == NULL)
283 esl_fatal("Failed to open -o output file %s\n", esl_opt_GetString(go, "-o"));
284 /* create and start stopwatch */
285 w = esl_stopwatch_Create();
286 esl_stopwatch_Start(w);
287 } else ofp = stdout;
288
289 /****************************************
290 * Open the MSA file; determine alphabet
291 ****************************************/
292
293 /* abc handling is weird. We only use alphabet to define gap characters in this miniapp
294 * unless do_small is TRUE. msa's are actually read in text mode. Thus if do_small is FALSE,
295 * eslRNA suffices for anything. If do_small is TRUE, we need the alphabet so we
296 * require --amino,--dna, or --rna below.
297 */
298 if (esl_opt_GetBoolean(go, "--amino")) abc = esl_alphabet_Create(eslAMINO);
299 else if (esl_opt_GetBoolean(go, "--dna")) abc = esl_alphabet_Create(eslDNA);
300 else if (esl_opt_GetBoolean(go, "--rna")) abc = esl_alphabet_Create(eslRNA);
301 else if (do_small) esl_fatal("With --small, the alphabet must be specified with --amino, --rna, or --dna.");
302 else abc = esl_alphabet_Create(eslRNA); /* alphabet is only used to define gap characters, so (in this miniapp) we're okay specifying RNA for any alignment (even non-RNA ones) */
303
304 if (do_small)
305 {
306 status = esl_msafile2_Open(alifile, NULL, &afp2);
307 if (status == eslENOTFOUND) esl_fatal("Alignment file %s doesn't exist or is not readable\n", alifile);
308 else if (status != eslOK) esl_fatal("Alignment file open failed with error %d\n", status);
309 }
310 else
311 {
312 status = esl_msafile_Open(NULL, alifile, NULL, infmt, NULL, &afp);
313 if (status != eslOK) esl_msafile_OpenFailure(afp, status);
314 }
315
316 /* If nec, read mask from the mask file */
317 if (do_maskfile) if((status = read_mask_file(maskfile, errbuf, &useme_mfile, &file_mlen)) != eslOK) esl_fatal(errbuf);
318
319 /************************************************************************************
320 * Read the first MSA in the file (we only mask first aln) and verify we can mask it.
321 ************************************************************************************/
322
323 if (do_small)
324 {
325 status = esl_msafile2_ReadInfoPfam(afp2, NULL, abc, -1, NULL, NULL, &msa, &nseq, &orig_alen, NULL, NULL, NULL, NULL, NULL,
326 (do_gapthresh) ? &abc_ct : NULL,
327 (do_postprob) ? &pp_ct : NULL,
328 NULL, NULL, NULL); /* we don't want bp_ct, srfpos_ct nor erfpos_ct */
329 if (status == eslEFORMAT) esl_fatal("Alignment file parse error:\n%s\n", afp2->errbuf);
330 else if (status == eslEINVAL) esl_fatal("Alignment file parse error:\n%s\n", afp2->errbuf);
331 else if (status != eslOK) esl_fatal("Alignment file read failed with error code %d\n%s", status, afp);
332
333 msa->alen = orig_alen; /* for convenience, but be careful, the msa doesn't actually have any aseq or ax */
334 }
335 else
336 {
337 status = esl_msafile_Read(afp, &msa); /* if ! do_small, we read full aln into memory */
338 if (status != eslOK) esl_msafile_ReadFailure(afp, status);
339
340 orig_alen = msa->alen;
341 if(do_postprob && msa->pp == NULL && (! esl_opt_IsOn(go, "--ppcons"))) esl_fatal("-p was enabled, but the MSA has no posterior probability (#=GR PP) annotation.");
342 }
343
344 /* Allocate and initialize i_am_eligible array, which defines which
345 * positions we'll consider keeping. If msa->rf == NULL or --keepins
346 * enabled, this will be all positions, else it will only be non-gap
347 * RF positions.
348 */
349 ESL_ALLOC(i_am_eligible, sizeof(int) * (int) msa->alen);
350 esl_vec_ISet(i_am_eligible, (int) msa->alen, TRUE); /* default to all positions, this is overwritten just below if nec */
351
352 /* if RF exists, get i_am_rf array[0..alen] which tells us which positions are non-gap RF positions
353 * and rf2a_map, a map of non-gap RF positions to overall alignment positions */
354 if(msa->rf != NULL) {
355 if((status = map_rfpos_to_apos(msa, abc, errbuf, &i_am_rf, &rf2a_map, &rflen)) != eslOK) esl_fatal(errbuf);
356 if(! esl_opt_GetBoolean(go, "--keepins")) { /* we'll only consider keeping non-gap RF columns */
357 esl_vec_ICopy(i_am_rf, (int) msa->alen, i_am_eligible);
358 }
359 }
360 else { /* RF doesn't exist, make sure no options that require RF annotation were enabled */
361 if(esl_opt_IsOn(go, "--pmask-rf")) esl_fatal("Error, --pmask-rf enabled, but alignment does not have RF annotation.");
362 if(esl_opt_IsOn(go, "--gmask-rf")) esl_fatal("Error, --gmask-rf enabled, but alignment does not have RF annotation.");
363 if(esl_opt_IsOn(go, "--fmask-rf")) esl_fatal("Error, --fmask-rf enabled, but alignment does not have RF annotation.");
364 if(esl_opt_GetBoolean(go, "--rf-is-mask")) esl_fatal("Error, --rf-is-mask enabled but msa does not have RF annotation.");
365 if(esl_opt_GetBoolean(go, "--keepins")) esl_fatal("Error, --keepins enabled but msa does not have RF annotation.");
366 if(esl_opt_GetBoolean(go, "--t-rmins")) esl_fatal("Error, --t-rmins enabled but msa does not have RF annotation.");
367 }
368
369 /* make sure we have pp_cons if --ppcons enabled */
370 if(esl_opt_IsOn(go, "--ppcons") && msa->pp_cons == NULL) esl_fatal("--ppcons was enabled, but the MSA has no consensus posterior probability (#=GC PP_cons) annotation.");
371
372
373 /* Determine value of do_rfonly, if TRUE, we'll automatically remove all non-gap RF columns,
374 * if(do_maskfile): if mlen (length of mask from file) == rflen, do_rfonly set to TRUE
375 * if(do_truncate): if msa->rf != NULL and --t-rmins enabled, then do_rfonly set to TRUE
376 * else : if msa->rf != NULL and --keepins not enabled, then do_rfonly set to TRUE
377 */
378 do_rfonly = FALSE; /* until proven otherwise */
379 if(do_maskfile) {
380 if(msa->rf == NULL) {
381 if((int) msa->alen != file_mlen) esl_fatal("Error, mask length (%d) not equal to alignment length (%d), and alignment has no #=GC RF annotation.", file_mlen, msa->alen);
382 }
383 else { /* msa->rf != NULL */
384 if(((int) msa->alen != file_mlen) && (rflen != file_mlen)) esl_fatal("Error, mask length (%d) not equal to alignment length (%d), and alignment has no #=GC RF annotation.", file_mlen, msa->alen);
385 if(rflen == file_mlen) do_rfonly = TRUE;
386 }
387 }
388 else if(do_truncate) {
389 if(msa->rf != NULL && esl_opt_GetBoolean(go, "--t-rmins")) do_rfonly = TRUE;
390 /* Note: we verified that --t-rmins was not enabled if msa->rf == NULL immediately after reading the msa above */
391 }
392 else if(do_rf_is_mask) {
393 do_rfonly = TRUE;
394 }
395 else { /* ! do_maskfile && ! do_truncate && ! do_rf_is_mask */
396 if(msa->rf != NULL && (! esl_opt_GetBoolean(go, "--keepins"))) do_rfonly = TRUE;
397 }
398
399 /****************************************************************
400 * Prepare for masking. This is done differently for each mode. *
401 ****************************************************************/
402 ESL_ALLOC(useme_final, sizeof(int) * msa->alen);
403 if(be_verbose) {
404 fprintf(stdout, "# %19s %7s %7s %16s %16s %13s\n", "", "", "", "all columns", "non-gap RF colns","");
405 fprintf(stdout, "# %19s %7s %7s %16s %16s %13s\n", "", "", "", "----------------", "----------------","");
406 fprintf(stdout, "# %19s %7s %7s %7s %7s %7s %7s %13s\n", "", "", "non-gap", "num", "num", "num", "num", "gap RF colns");
407 fprintf(stdout, "# %-19s %7s %7s %7s %7s %7s %7s %13s\n","mask mode", "aln len", "RF len", "kept", "removed", "kept", "removed", "auto removed?");
408 fprintf(stdout, "# %19s %7s %7s %7s %7s %7s %7s %13s\n", "-------------------", "-------", "-------", "-------", "-------", "-------", "-------", "-------------");
409 }
410
411 if(do_maskfile) {
412 if(do_rfonly) {
413 if((status = expand_rf_useme_to_alen(useme_mfile, rf2a_map, rflen, msa->alen, errbuf, useme_final)) != eslOK) esl_fatal(errbuf);
414 }
415 else { /* ! do_rfonly, copy useme_mfile to useme_final (we could do this differently...) */
416 esl_vec_ICopy(useme_mfile, msa->alen, useme_final);
417 }
418 if(be_verbose) {
419 nkept = esl_vec_ISum(useme_final, (int) msa->alen);
420 if(msa->rf == NULL) fprintf(stdout, " %-19s %7" PRId64 " %7s %7d %7d %7s %7s %13s\n", "maskfile", msa->alen, "-", nkept, (int) msa->alen - nkept, "-", "-", "-");
421 else {
422 nkept_rf = (do_rfonly) ? nkept: determine_nkept_rf(useme_final, i_am_rf, msa->alen);
423 fprintf(stdout, " %-19s %7" PRId64 " %7d %7d %7d %7d %7d %13s\n", "maskfile", msa->alen, rflen, nkept, (int) msa->alen - nkept, nkept_rf, rflen - nkept_rf, do_rfonly ? "yes" : "no");
424 }
425 }
426 }
427 if(do_truncate) {
428 parse_coord_string(esl_opt_GetArg(go, 2), &tstart, &tend); /* this dies with esl_fatal() if 2nd cmdline arg is invalid */
429 /* remember: user provided coords are 1..alen or 1..rflen, whereas all internal arrays use 0..alen-1 and 0..rflen-1 */
430 if(esl_opt_GetBoolean(go, "--t-rf")) {
431 /* convert start and end positions read from <coords> 2nd cmdline arg from rf positions to full alignment positions */
432 if(tstart > rflen) esl_fatal("with -t and --t-rf, start coordinate value %d exceeds non-gap RF length of %d", tstart, rflen);
433 if(tend > rflen) esl_fatal("with -t and --t-rf, end coordinate value %d exceeds non-gap RF length of %d", tend, rflen);
434 tstart = rf2a_map[(tstart-1)] + 1;
435 if(tend == 0) tend = (int) msa->alen; /* careful, don't set it to rflen and then convert with the map, you'll lose the inserts after the final non-gap RF posn */
436 else tend = rf2a_map[(tend-1)] + 1;
437 }
438 else {
439 if(tstart > msa->alen) esl_fatal("with -t, start coordinate value %d exceeds alignment length of %" PRId64, tstart, msa->alen);
440 if(tend > msa->alen) esl_fatal("with -t, end coordinate value %d exceeds alignment length of %" PRId64, tend, msa->alen);
441 if(tend == 0) tend = (int) msa->alen;
442 }
443 /* create the truncation mask */
444 for(apos = 0; apos < (tstart-1); apos++) useme_final[apos] = FALSE;
445 for(apos = (tstart-1); apos < tend; apos++) useme_final[apos] = do_rfonly ? i_am_rf[apos] : TRUE; /* only keep non-gap RF positions if do_rfonly */
446 for(apos = tend; apos < msa->alen; apos++) useme_final[apos] = FALSE;
447 if(be_verbose) {
448 nkept = esl_vec_ISum(useme_final, (int) msa->alen);
449 if(msa->rf == NULL) fprintf(stdout, " %-19s %7" PRId64 " %7s %7d %7d %7s %7s %13s\n", "truncation", msa->alen, "-", nkept, (int) msa->alen - nkept, "-", "-", "-");
450 else {
451 nkept_rf = (do_rfonly) ? nkept: determine_nkept_rf(useme_final, i_am_rf, msa->alen);
452 fprintf(stdout, " %-19s %7" PRId64 " %7d %7d %7d %7d %7d %13s\n", "truncation", msa->alen, rflen, nkept, (int) msa->alen - nkept, nkept_rf, rflen - nkept_rf, do_rfonly ? "yes" : "no");
453 }
454 }
455 }
456 if(do_gapthresh) {
457 if(! do_small) {
458 if((status = count_gaps_in_msa(msa, abc, i_am_eligible, errbuf, &gap_ct)) != eslOK) esl_fatal(errbuf);
459 }
460 else {
461 ESL_ALLOC(gap_ct, sizeof(double) * msa->alen);
462 for(apos = 0; apos < msa->alen; apos++) gap_ct[apos] = abc_ct[apos][abc->K];
463 }
464 if((status = mask_based_on_gapfreq(gap_ct, msa->alen, (do_small) ? nseq : msa->nseq, esl_opt_GetReal(go, "--gapthresh"), i_am_eligible, errbuf, &useme_g)) != eslOK) esl_fatal(errbuf);
465 if(be_verbose) {
466 nkept = esl_vec_ISum(useme_g, (int) msa->alen);
467 if(msa->rf == NULL) fprintf(stdout, " %-19s %7" PRId64 " %7s %7d %7d %7s %7s %13s\n", "gapfreq", msa->alen, "-", nkept, (int) msa->alen - nkept, "-", "-", "-");
468 else {
469 nkept_rf = (do_rfonly) ? nkept: determine_nkept_rf(useme_g, i_am_rf, msa->alen);
470 fprintf(stdout, " %-19s %7" PRId64 " %7d %7d %7d %7d %7d %13s\n", "gapfreq", msa->alen, rflen, nkept, (int) msa->alen - nkept, nkept_rf, rflen - nkept_rf, do_rfonly ? "yes" : "no");
471 }
472 }
473 }
474 if(do_postprob) {
475 if(! do_small) {
476 if((status = count_postprobs_in_msa(msa, abc, i_am_eligible, errbuf, &pp_ct)) != eslOK) esl_fatal(errbuf);
477 }
478 do_pavg = esl_opt_IsOn(go, "--pavg");
479 pavg_min = do_pavg ? esl_opt_GetReal(go, "--pavg") : 0.; /* if ! do_pavg, pavg_min is irrelevant */
480 do_ppcons = esl_opt_IsOn(go, "--ppcons");
481 ppcons_min = do_ppcons ? esl_opt_GetReal(go, "--ppcons") : 0.; /* if ! do_ppcons, ppcons_min is irrelevant */
482 if((status = mask_based_on_postprobs(pp_ct, msa->alen, (do_small) ? nseq : msa->nseq, esl_opt_GetReal(go, "--pthresh"), esl_opt_GetReal(go, "--pfract"), do_pavg, pavg_min, do_ppcons, ppcons_min, msa->pp_cons, abc, i_am_eligible, esl_opt_GetBoolean(go, "--pallgapok"), errbuf, &useme_pp)) != eslOK) esl_fatal(errbuf);
483 if(be_verbose) {
484 nkept = esl_vec_ISum(useme_pp, (int) msa->alen);
485 if(msa->rf == NULL) fprintf(stdout, " %-19s %7" PRId64 " %7s %7d %7d %7s %7s %13s\n", "postprobs", msa->alen, "-", nkept, (int) msa->alen - nkept, "-", "-", "-");
486 else {
487 nkept_rf = (do_rfonly) ? nkept: determine_nkept_rf(useme_pp, i_am_rf, msa->alen);
488 fprintf(stdout, " %-19s %7" PRId64 " %7d %7d %7d %7d %7d %13s\n", "postprobs", msa->alen, rflen, nkept, (int) msa->alen - nkept, nkept_rf, rflen - nkept_rf, do_rfonly ? "yes" : "no");
489 }
490 }
491 }
492 if(do_rf_is_mask) {
493 for(apos = 0; apos < msa->alen; apos++) useme_final[apos] = i_am_rf[apos];
494 if(be_verbose) fprintf(stdout, " %-19s %7" PRId64 " %7d %7d %7d %7d %7d %13s\n", "RF", msa->alen, rflen, rflen, (int) msa->alen - rflen, rflen, 0, "yes");
495 }
496
497 /*********************************************************************************
498 * Determine final mask if -p, -g or both were enabled (else we already have it) *
499 *********************************************************************************/
500 /* combine pp and gap mask if -p and -g */
501 if(do_gapthresh && do_postprob) {
502 for(apos = 0; apos < msa->alen; apos++)
503 useme_final[apos] = (useme_g[apos] && useme_pp[apos]) ? TRUE : FALSE;
504 if(be_verbose) {
505 nkept = esl_vec_ISum(useme_final, (int) msa->alen);
506 if(msa->rf == NULL) fprintf(stdout, " %-19s %7" PRId64 " %7s %7d %7d %7s %7s %13s\n", "gapfreq&postprobs", msa->alen, "-", nkept, (int) msa->alen - nkept, "-", "-", "-");
507 else {
508 nkept_rf = (do_rfonly) ? nkept: determine_nkept_rf(useme_final, i_am_rf, msa->alen);
509 fprintf(stdout, " %-19s %7" PRId64 " %7d %7d %7d %7d %7d %13s\n", "gapfreq&postprobs", msa->alen, rflen, nkept, (int) msa->alen - nkept, nkept_rf, rflen - nkept_rf, do_rfonly ? "yes" : "no");
510 }
511 }
512 }
513 else if(do_gapthresh) {
514 esl_vec_ICopy(useme_g, msa->alen, useme_final);
515 }
516 else if(do_postprob) {
517 esl_vec_ICopy(useme_pp, msa->alen, useme_final);
518 }
519 /* else (do_maskfile || do_rf_is_mask || do_truncate) we set useme_final above */
520
521 /************************************************
522 * Unless --small enabled, mask the alignment *
523 ************************************************/
524 if(! do_small) {
525 if (abc && (abc->type == eslRNA || abc->type == eslDNA) &&
526 (status = esl_msa_RemoveBrokenBasepairs(msa, errbuf, useme_final)) != eslOK) esl_fatal(errbuf);
527 if ((status = esl_msa_ColumnSubset (msa, errbuf, useme_final)) != eslOK) esl_fatal(errbuf);
528 } /* else we'll do it as we regurgitate it upon rereading below */
529
530 /************************
531 * Output the alignment *
532 ************************/
533 if (! do_small)
534 {
535 esl_msafile_Write(ofp, msa, outfmt);
536 }
537 else {
538 /* do_small==TRUE, we don't have the full msa stored,
539 * we must regurgitate it, removing unwanted columns as we do.
540 * First, close then reopen alifile so we can reread (first) alignment (no esl_msafile_Position() exists yet)
541 */
542 esl_msafile2_Close(afp2);
543 status = esl_msafile2_OpenDigital(abc, alifile, NULL, &afp2); /* this should work b/c it did on the first pass */
544 if (status == eslENOTFOUND) esl_fatal("Second pass: alignment file %s doesn't exist or is not readable\n", alifile);
545 else if (status == eslEFORMAT) esl_fatal("Second pass: couldn't determine format of alignment %s\n", alifile);
546 else if (status != eslOK) esl_fatal("Second pass: alignment file open failed with error %d\n");
547 status = esl_msafile2_RegurgitatePfam(afp2, ofp,
548 -1, -1, -1, -1, /* max width of seq names, gf,gc,gr tags unknown, we'll use margin length from file */
549 TRUE, /* regurgitate stockholm header ? */
550 TRUE, /* regurgitate // trailer ? */
551 TRUE, /* regurgitate blank lines */
552 TRUE, /* regurgitate comments */
553 TRUE, /* regurgitate GF ? */
554 TRUE, /* regurgitate GS ? */
555 TRUE, /* regurgitate GC ? */
556 TRUE, /* regurgitate GR ? */
557 TRUE, /* regurgitate aseq ? */
558 NULL, /* regurgitate all seqs, not a subset */
559 NULL, /* regurgitate all seqs, not a subset */
560 useme_final, /* which columns to keep */
561 NULL, /* we're not adding any columns */
562 msa->alen, /* expected length, not strictly necessary */
563 '.', /* gapchar, irrelevant in this context */
564 NULL, /* don't return num seqs read */
565 NULL); /* don't return num seqs regurgitated */
566 if(status == eslEOF) esl_fatal("Second pass, unable to reread alignment");
567 if(status != eslOK) esl_fatal("Second pass, error rereading alignment");
568 }
569 if(be_verbose) fprintf(stdout, "#\n");
570
571 /**************************************************************************************************************
572 * Output masks, if nec (we already checked above that msa->rf != NULL If any --*mask-rf options are enabled) *
573 **************************************************************************************************************/
574 if(esl_opt_IsOn(go, "--pmask-rf")) {
575 if((status = output_mask(esl_opt_GetString(go, "--pmask-rf"), useme_pp, i_am_rf, orig_alen, errbuf)) != eslOK) esl_fatal(errbuf);
576 if(be_verbose) fprintf(stdout, "# Posterior probability mask of non-gap RF length (%d) saved to file %s.\n", rflen, esl_opt_GetString(go, "--pmask-rf"));
577 }
578 if(esl_opt_IsOn(go, "--pmask-all")) {
579 if((status = output_mask(esl_opt_GetString(go, "--pmask-all"), useme_pp, NULL, orig_alen, errbuf)) != eslOK) esl_fatal(errbuf);
580 if(be_verbose) fprintf(stdout, "# Posterior probability mask of full alignment length (%d) saved to file %s.\n", (int) orig_alen, esl_opt_GetString(go, "--pmask-all"));
581 }
582 if(esl_opt_IsOn(go, "--gmask-rf")) {
583 if((status = output_mask(esl_opt_GetString(go, "--gmask-rf"), useme_g, i_am_rf, orig_alen, errbuf)) != eslOK) esl_fatal(errbuf);
584 if(be_verbose) fprintf(stdout, "# Gap frequency mask of non-gap RF length (%d) saved to file %s.\n", rflen, esl_opt_GetString(go, "--gmask-rf"));
585 }
586 if(esl_opt_IsOn(go, "--gmask-all")) {
587 if((status = output_mask(esl_opt_GetString(go, "--gmask-all"), useme_g, NULL, orig_alen, errbuf)) != eslOK) esl_fatal(errbuf);
588 if(be_verbose) fprintf(stdout, "# Gap frequency mask of full alignment length (%d) saved to file %s.\n", (int) orig_alen, esl_opt_GetString(go, "--gmask-all"));
589 }
590 if(esl_opt_IsOn(go, "--fmask-rf")) {
591 if((status = output_mask(esl_opt_GetString(go, "--fmask-rf"), useme_final, i_am_rf, orig_alen, errbuf)) != eslOK) esl_fatal(errbuf);
592 if(be_verbose) fprintf(stdout, "# Final mask of non-gap RF length (%d) saved to file %s.\n", rflen, esl_opt_GetString(go, "--fmask-rf"));
593 }
594 if(esl_opt_IsOn(go, "--fmask-all")) {
595 if((status = output_mask(esl_opt_GetString(go, "--fmask-all"), useme_final, NULL, orig_alen, errbuf)) != eslOK) esl_fatal(errbuf);
596 if(be_verbose) fprintf(stdout, "# Final mask of full alignment length (%d) saved to file %s.\n", (int) orig_alen, esl_opt_GetString(go, "--fmask-all"));
597 }
598 if(esl_opt_GetString(go, "-o") != NULL) {
599 fclose(ofp);
600 if(be_verbose) fprintf(stdout, "# Masked alignment saved to file %s.\n", esl_opt_GetString(go, "-o"));
601 esl_stopwatch_Stop(w);
602 esl_stopwatch_Display(stdout, w, "# CPU time: ");
603 }
604
605 /* Clean up, normal return */
606 esl_free(rf2a_map);
607 esl_free(useme_mfile);
608 esl_free(useme_g);
609 esl_free(useme_pp);
610 esl_free(useme_final);
611 esl_free(i_am_rf);
612 esl_free(i_am_eligible);
613 esl_free(gap_ct);
614
615 esl_arr2_Destroy((void **) pp_ct, orig_alen);
616 esl_arr2_Destroy((void **) abc_ct, orig_alen);
617 esl_msa_Destroy(msa);
618 esl_alphabet_Destroy(abc);
619 esl_stopwatch_Destroy(w);
620 esl_msafile_Close(afp);
621 esl_msafile2_Close(afp2);
622 esl_getopts_Destroy(go);
623 return 0;
624
625 ERROR:
626 esl_fatal("Memory allocation error.");
627 return status; /* NEVERREACHED */
628 }
629
630 /* read_mask_file
631 *
632 * Given the name of a mask file with 1 mask in it,
633 * read it, fill <useme> and return.
634 *
635 * mlen length of the mask
636 * useme[0..i..mlen-1]: '1' if we should keep column i, '0' if not.
637 *
638 * useme is allocated here, and must be freed by caller.
639 *
640 * The mask must only contain '0' or '1' characters.
641 * Lines prefixed with '#' are comment lines, and ignored.
642 * All whitespace (including newlines) is ignored.
643 *
644 * Returns: eslOK on success and <ret_useme> is set as <useme>.
645 * <ret_masklen> is set as <masklen>.
646 * eslEINVAL if a non-0/1 character read
647 */
648 int
649 read_mask_file(char *filename, char *errbuf, int **ret_useme, int *ret_mlen)
650 {
651 int status;
652 ESL_FILEPARSER *efp;
653 char *tok;
654 int *useme = NULL;
655 int toklen;
656 int mlen = 0;
657 int i;
658 void *tmp;
659
660 if (esl_fileparser_Open(filename, NULL, &efp) != eslOK) ESL_FAIL(eslFAIL, errbuf, "failed to open %s in read_mask_file\n", filename);
661 esl_fileparser_SetCommentChar(efp, '#');
662
663 while ((status = esl_fileparser_GetToken(efp, &tok, &toklen)) == eslOK) {
664 if(mlen == 0) ESL_ALLOC (useme, sizeof(int) * toklen);
665 else ESL_RALLOC(useme, tmp, sizeof(int) * (mlen+toklen));
666 for(i = 0; i < toklen; i++) {
667 if(tok[i] == '0') useme[mlen+i] = FALSE;
668 else if(tok[i] == '1') useme[mlen+i] = TRUE;
669 else ESL_FAIL(eslEINVAL, errbuf, "Mask character number %d is neither a '0', nor a '1' but a (%c). The mask must be only 1s and 0s.", mlen+i+1, tok[i]);
670 }
671 mlen += toklen;
672 }
673
674 *ret_useme = useme;
675 *ret_mlen = mlen;
676 esl_fileparser_Close(efp);
677 return eslOK;
678
679 ERROR:
680 if(useme != NULL) free(useme);
681 ESL_FAIL(status, errbuf, "Ran out of memory while reading the mask file.");
682 return status; /* NEVERREACHED */
683 }
684
685 /* map_rfpos_to_apos
686 *
687 * Given an MSA, determine the alignment position of each
688 * non-gap RF (reference) position. The abc is only necessary
689 * for defining gap characters.
690 *
691 * rf2a_map[0..rfpos..rflen-1] = apos, apos is the alignment position (0..msa->alen-1) that
692 * is non-gap RF position rfpos+1 (for rfpos in 0..rflen-1)
693 */
694 static int map_rfpos_to_apos(ESL_MSA *msa, ESL_ALPHABET *abc, char *errbuf, int **ret_i_am_rf, int **ret_rf2a_map, int *ret_rflen)
695 {
696 int status;
697 int rflen = 0;
698 int *rf2a_map = NULL;
699 int *i_am_rf = NULL;
700 int rfpos = 0;
701 int apos = 0;
702
703 /* contract check */
704 if(msa->rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "Error, trying to map RF positions to alignment positions, but msa->rf is NULL.");
705
706 /* count non-gap RF columns */
707 for(apos = 0; apos < msa->alen; apos++) {
708 if((! esl_abc_CIsGap(abc, msa->rf[apos])) &&
709 (! esl_abc_CIsMissing(abc, msa->rf[apos])) &&
710 (! esl_abc_CIsNonresidue(abc, msa->rf[apos])))
711 {
712 rflen++;
713 /* I don't use esl_abc_CIsResidue() b/c that would return FALSE for 'x' with RNA and DNA */
714 }
715 }
716 /* build map */
717 ESL_ALLOC(i_am_rf, sizeof(int) * msa->alen);
718 ESL_ALLOC(rf2a_map, sizeof(int) * rflen);
719 for(apos = 0; apos < msa->alen; apos++) {
720 if((! esl_abc_CIsGap(abc, msa->rf[apos])) &&
721 (! esl_abc_CIsMissing(abc, msa->rf[apos])) &&
722 (! esl_abc_CIsNonresidue(abc, msa->rf[apos]))) {
723 i_am_rf[apos] = TRUE;
724 rf2a_map[rfpos++] = apos;
725 }
726 else {
727 i_am_rf[apos] = FALSE;
728 }
729 }
730 *ret_i_am_rf = i_am_rf;
731 *ret_rf2a_map = rf2a_map;
732 *ret_rflen = rflen;
733 return eslOK;
734
735 ERROR:
736 if(i_am_rf != NULL) free(i_am_rf);
737 if(rf2a_map != NULL) free(rf2a_map);
738 ESL_FAIL(status, errbuf, "Error, out of memory while mapping RF positions to alignment positions.");
739 }
740
741 /* expand_rf_useme_to_alen
742 *
743 * Given a <useme_rf> array that corresponds to rflen (non-gap RF)
744 * length of an msa, expand it to msa->alen using the map <rf2a_map>
745 * from RF positions to alignment positions and overwrite the
746 * <useme_a> array as the alen expanded array.
747 *
748 * If we encounter an error, we return non-eslOK status and
749 * and fill errbuf with error message.
750 */
751 static int expand_rf_useme_to_alen(int *useme_rf, int *rf2a_map, int rflen, int alen, char *errbuf, int *useme_a)
752 {
753 int rfpos = 0;
754
755 /* initialize */
756 esl_vec_ISet(useme_a, alen, FALSE);
757
758 for(rfpos = 0; rfpos < rflen; rfpos++) {
759 if(rf2a_map[rfpos] > (alen-1)) ESL_FAIL(eslEINVAL, errbuf, "Error in expand_rf_useme_to_alen(), rf2a_map[rfpos:%d] = %d, but alen is %d.", rfpos, rf2a_map[rfpos], alen);
760 useme_a[rf2a_map[rfpos]] = useme_rf[rfpos];
761 }
762
763 return eslOK;
764 }
765
766 /* count_gaps_in_msa()
767 *
768 * Given an msa, fill gap_ct[apos] with the number of gaps in position
769 * apos, for all positions apos=0..msa->alen-1. Return gap_ct as
770 * <ret_gap_ct>. <countme>[0..apos..msa->alen-1] = TRUE if we should
771 * count for position apos, FALSE if we shouldn't (leave ngap[apos] =
772 * 0). (countme allows us to not waste time counting gaps in columns
773 * that we will automatically remove, for example those that are
774 * gaps in the RF annotation).
775 *
776 * If we encounter an error, we return non-eslOK status and and fill
777 * errbuf with error message.
778 *
779 * Returns eslOK upon success, and points <ret_useme> at useme, caller
780 * must free it.
781 */
782 static int count_gaps_in_msa(ESL_MSA *msa, ESL_ALPHABET *abc, int *countme, char *errbuf, double **ret_gap_ct)
783 {
784 int status;
785 double *gap_ct = NULL;
786 int apos, i;
787
788 /* contract check, msa should be in text mode */
789 if(msa->flags & eslMSA_DIGITAL) ESL_FAIL(eslEINVAL, errbuf, "count_gaps_in_msa() contract violation, MSA is digitized");
790
791 ESL_ALLOC(gap_ct, sizeof(double) * msa->alen);
792 esl_vec_DSet(gap_ct, msa->alen, 0.);
793
794 for(apos = 0; apos < (int) msa->alen; apos++) {
795 if(countme[apos]) {
796 for(i = 0; i < msa->nseq; i++) {
797 if(esl_abc_CIsGap(abc, msa->aseq[i][apos])) gap_ct[apos] += 1.0;
798 }
799 }
800 }
801 *ret_gap_ct = gap_ct;
802 return eslOK;
803
804 ERROR:
805 if(gap_ct != NULL) free(gap_ct);
806 ESL_FAIL(status, errbuf, "Error, out of memory while counting gaps in the msa.");
807 return status; /* NEVERREACHED */
808 }
809
810 /* mask_based_on_gapfreq()
811 *
812 * Determine which columns to include/exclude based on frequency of
813 * gaps. Gap counts per-position are provided in <gap_ct>.
814 * If posn x gap freq is <= <gapthresh>, we set useme[x] to TRUE
815 * (we'll keep x), else we set useme[x] to FALSE (we won't keep x).
816 * <i_am_rf>[0..alen-1] defines which columns are eligible for
817 * being used, if <i_am_rf[x]> useme[x] is set as FALSE,
818 * regardless of gap frequency.
819 *
820 * If we encounter an error, we return non-eslOK status and
821 * and fill errbuf with error message.
822 *
823 * Returns eslOK upon success, and points <ret_useme> at useme,
824 * caller must free it.
825 */
826 static int mask_based_on_gapfreq(double *gap_ct, int64_t alen, int nseq, float gapthresh, int *i_am_eligible, char *errbuf, int **ret_useme)
827 {
828 int status;
829 int *useme = NULL;
830 int apos;
831 float gapfreq;
832
833 /* contract check */
834 if(i_am_eligible == NULL) ESL_FAIL(eslEINVAL, errbuf, "mask_based_on_gapthresh() contract violation, i_am_eligible is NULL");
835
836 /* allocate */
837 ESL_ALLOC(useme, sizeof(int) * alen);
838
839 for(apos = 0; apos < alen; apos++) {
840 if(i_am_eligible[apos]) {
841 gapfreq = gap_ct[apos] / (float) nseq;
842 useme[apos] = gapthresh < gapfreq ? FALSE : TRUE; /* should I be worried about imprecision? 0.5 compared to 0.5? */
843 /* printf("apos: %d gapfreq: %.3f\n", apos, gapfreq); */
844 }
845 else useme[apos] = FALSE;
846 }
847
848 *ret_useme = useme;
849 return eslOK;
850
851 ERROR:
852 if(useme != NULL) free(useme);
853 ESL_FAIL(status, errbuf, "Error, out of memory while masking based on gaps.");
854 return status; /* NEVERREACHED */
855 }
856
857
858 /* get_pp_idx
859 *
860 * Given a #=GR PP or #=GC PP_cons character, return the appropriate index
861 * in a pp_ct[] vector.
862 * '0' return 0;
863 * '1' return 1;
864 * '2' return 2;
865 * '3' return 3;
866 * '4' return 4;
867 * '5' return 5;
868 * '6' return 6;
869 * '7' return 7;
870 * '8' return 8;
871 * '9' return 9;
872 * '*' return 10;
873 * gap return 11;
874 *
875 * Anything else (including missing or nonresidue) return -1;
876 *
877 * This mapping of PP chars to return values should probably be
878 * stored in some internal map structure somewhere, instead of
879 * only existing in this function as used by esl_msafile2_ReadInfoPfam().
880 */
881 static int get_pp_idx(ESL_ALPHABET *abc, char ppchar)
882 {
883 if(esl_abc_CIsGap(abc, ppchar)) return 11;
884 if(ppchar == '*') return 10;
885 if(ppchar == '9') return 9;
886 if(ppchar == '8') return 8;
887 if(ppchar == '7') return 7;
888 if(ppchar == '6') return 6;
889 if(ppchar == '5') return 5;
890 if(ppchar == '4') return 4;
891 if(ppchar == '3') return 3;
892 if(ppchar == '2') return 2;
893 if(ppchar == '1') return 1;
894 if(ppchar == '0') return 0;
895 return -1;
896 }
897
898 /* count_postprobs_in_msa()
899 *
900 * Given an msa, fill nppA[apos] with the number of each possible
901 * posterior probability value in position apos, for all positions
902 * apos=0..msa->alen-1. Return nppA as <ret_nppA>.
903 * <countme>[0..apos..msa->alen-1] = TRUE if we should
904 * count for position apos, FALSE if we shouldn't (leave npp[apos][] =
905 * 0). (countme allows us to not waste time counting pps in columns
906 * that we will automatically remove, for example those that are
907 * gaps in the RF annotation).
908 *
909 * Possible PP values are: '0','1','2','3','4','5','6','7','8','9',
910 * '*','.','-','_'. Final 3 are gaps, and are treated identically.
911 *
912 * If we encounter an error, we return non-eslOK status and and fill
913 * errbuf with error message.
914 *
915 * Returns eslOK upon success, and points <ret_useme> at useme, caller
916 * must free it.
917 */
918 static int count_postprobs_in_msa(ESL_MSA *msa, ESL_ALPHABET *abc, int *countme, char *errbuf, double ***ret_pp_ct)
919 {
920 int status;
921 double **pp_ct = NULL;
922 int apos, i;
923 int nppvals = 12; /* '0-9', '*' and gap */
924 int ppidx;
925
926 /* contract check, msa should be in text mode */
927 if(msa->flags & eslMSA_DIGITAL) ESL_FAIL(eslEINVAL, errbuf, "count_postprobs_in_msa() contract violation, MSA is digitized");
928 if(msa->pp == NULL) ESL_FAIL(eslEINVAL, errbuf, "count_postprobs_in_msa() contract violation, msa->pp is NULL");
929
930 ESL_ALLOC(pp_ct, sizeof(double *) * msa->alen);
931 for(apos = 0; apos < msa->alen; apos++) {
932 ESL_ALLOC(pp_ct[apos], sizeof(double) * nppvals);
933 esl_vec_DSet(pp_ct[apos], nppvals, 0.);
934 }
935
936 for(apos = 0; apos < (int) msa->alen; apos++) {
937 if(countme[apos]) {
938 for(i = 0; i < msa->nseq; i++) {
939 if(msa->pp[i] == NULL) {
940 ESL_FAIL(eslEINVAL, errbuf, "some but not all sequences have PP annotation in msa, seq %d does not.\n", (i+1));
941 }
942 ppidx = get_pp_idx(abc, msa->pp[i][apos]);
943 if(ppidx == 11) { /* special, gap idx */
944 /* make sure the corresponding residue is also a gap */
945 if(! esl_abc_CIsGap(abc, msa->aseq[i][apos])) ESL_FAIL(eslEINVAL, errbuf, "post prob annotation for seq: %d aln column: %d is a gap (%c), but seq res is not: (%c)", i, apos, msa->pp[i][apos], msa->aseq[i][apos]);
946 }
947 pp_ct[apos][ppidx] += 1.;
948 }
949 }
950 }
951 *ret_pp_ct = pp_ct;
952 return eslOK;
953
954 ERROR:
955 if(pp_ct != NULL) {
956 for(apos = 0; apos < msa->alen; apos++) {
957 if(pp_ct[apos] != NULL) free(pp_ct[apos]);
958 }
959 free(pp_ct);
960 }
961 ESL_FAIL(status, errbuf, "Error, out of memory while counting post probs in the msa.");
962 return status; /* NEVERREACHED */
963 }
964
965 /* mask_based_on_postprobs()
966 *
967 * Determine which columns to include/exclude based on frequency of
968 * post probs. Post prob counts per-position are provided in <pp_ct>.
969 *
970 * If (do_pavg == FALSE && do_ppcons == FALSE):
971 * If more than <pfract> fraction of the non-gap residues in posn apos
972 * are annotated with a post prob equal to or better than <pthresh>,
973 * we set useme[apos] to TRUE (we'll keep apos), else we set useme[apos]
974 * to FALSE (we won't keep apos).
975 *
976 * If (do_pavg == TRUE):
977 * If average post prob in posn apos is equal to or better than <pavg_min>
978 * we set useme[apos] to TRUE, else we set useme[apos] to FALSE.
979 *
980 * If (do_ppcons == TRUE):
981 * If PP_cons post prob (from ppcons) in posn apos is equal to or better than
982 * <ppcons_min> we set useme[apos] to TRUE, else we set useme[apos] to FALSE.
983 *
984 * Note: either do_avg OR do_ppcons OR neither must be TRUE. Enforced by contract.
985 *
986 * <i_am_eligible>[0..alen-1] defines which columns are eligible for being
987 * used, if <i_am_eligible[apos]> useme[apos] is set as FALSE, regardless of pp
988 * frequency.
989 *
990 * Finally, unless <allgapok==TRUE> remove any column that contains all gaps,
991 * i.e. that contains 0 aligned residues.
992 *
993 * If we encounter an error, we return non-eslOK status and
994 * and fill errbuf with error message.
995 *
996 * Returns eslOK upon success, and points <ret_useme> at useme,
997 * caller must free it.
998 */
999 static int mask_based_on_postprobs(double **pp_ct, int64_t alen, int nseq, float pthresh, float pfract, int do_pavg, float pavg_min, int do_ppcons, float ppcons_min, char *pp_cons, ESL_ALPHABET *abc, int *i_am_eligible, int allgapok, char *errbuf, int **ret_useme)
1000 {
1001 int status;
1002 int *useme = NULL;
1003 int apos;
1004 float ppfreq;
1005 double nnongap;
1006 int nppvals = 12; /* '0-9', '*' and gap */
1007 int ppidx_thresh;
1008 int ppidx = 0;
1009 double ppcount = 0.;
1010 double ppsum = 0.;
1011 double pavg;
1012 double ppminA[11];
1013 double ppavgA[11];
1014
1015 ppminA[0] = 0.00;
1016 ppminA[1] = 0.05;
1017 ppminA[2] = 0.15;
1018 ppminA[3] = 0.25;
1019 ppminA[4] = 0.35;
1020 ppminA[5] = 0.45;
1021 ppminA[6] = 0.55;
1022 ppminA[7] = 0.65;
1023 ppminA[8] = 0.75;
1024 ppminA[9] = 0.85;
1025 ppminA[10] = 0.95;
1026
1027 ppavgA[0] = 0.025;
1028 ppavgA[1] = 0.10;
1029 ppavgA[2] = 0.20;
1030 ppavgA[3] = 0.30;
1031 ppavgA[4] = 0.40;
1032 ppavgA[5] = 0.50;
1033 ppavgA[6] = 0.60;
1034 ppavgA[7] = 0.70;
1035 ppavgA[8] = 0.80;
1036 ppavgA[9] = 0.90;
1037 ppavgA[10] = 0.975;
1038
1039 /* contract check */
1040 if(i_am_eligible == NULL) ESL_FAIL(eslEINVAL, errbuf, "mask_based_on_postprobs() contract violation, i_am_eligible is NULL");
1041 if(do_pavg == TRUE && do_ppcons == TRUE) ESL_FAIL(eslEINVAL, errbuf, "mask_based_on_postprobs() contract violation, do_pavg and do_ppcons are both TRUE");
1042 if(do_ppcons == TRUE && pp_cons == NULL) ESL_FAIL(eslEINVAL, errbuf, "mask_based_on_postprobs() contract violation, do_ppcons is TRUE, but ppcons string is NULL");
1043
1044 /* allocate */
1045 ESL_ALLOC(useme, sizeof(int) * alen);
1046
1047 if((! do_pavg) && (! do_ppcons)) {
1048 /* determine which pp_ct idx is the minimum we'll accept */
1049 ppidx = 0;
1050 while(ppidx < 10) {
1051 if((esl_FCompare_old(pthresh, ppminA[ppidx], eslSMALLX1) == eslOK) || pthresh < ppminA[ppidx]) break;
1052 ppidx++;
1053 }
1054 ppidx_thresh = ppidx;
1055 }
1056
1057 for(apos = 0; apos < alen; apos++) {
1058 ppcount = 0.;
1059 ppsum = 0.;
1060 if(i_am_eligible[apos]) { /* consider this position */
1061 nnongap = esl_vec_DSum(pp_ct[apos], nppvals) - pp_ct[apos][11];
1062 if(esl_FCompare_old(nnongap, 0., eslSMALLX1) == eslOK) { /* effectively 0.0 */
1063 useme[apos] = allgapok ? TRUE : FALSE;
1064 }
1065 else {
1066 if(do_pavg) {
1067 for(ppidx = 0; ppidx < 11; ppidx++) {
1068 ppsum += pp_ct[apos][ppidx] * ppavgA[ppidx]; /* Note: PP value is considered average of range, not minimum ('9' == 0.90 (0.95-0.85/2) */
1069 /* printf("apos: %d pp_idx: %d ct: %d sum: %.3f\n", apos, ppidx, pp_ct[apos][ppidx], ppsum);*/
1070 }
1071 pavg = ppsum / nnongap;
1072 useme[apos] = pavg < pavg_min? FALSE : TRUE; /* should I be worried about imprecision? 0.5 compared to 0.5? */
1073 /* printf("pavg: %.3f nnongap: %d useme[apos:%d]: %d pavg_min: %.3f\n", pavg, nnongap, apos, useme[apos], pavg_min);*/
1074 }
1075 else if(do_ppcons) {
1076 ppidx = get_pp_idx(abc, pp_cons[apos]);
1077 if(ppidx == -1) ESL_FAIL(eslEFORMAT, errbuf, "bad #=GC PP_cons char: %c at position %d", pp_cons[apos], apos+1);
1078 if(ppidx != 11) {
1079 useme[apos] = ((esl_FCompare_old(ppcons_min, ppminA[ppidx], eslSMALLX1) == eslOK) || ppminA[ppidx] > ppcons_min) ? TRUE : FALSE;
1080 /* printf("ppcons[%4d]: %c ppidx: %2d useme %d ppcons_min: %.3f\n", apos, pp_cons[apos], ppidx, useme[apos], ppcons_min); */
1081 }
1082 else useme[apos] = FALSE; /* ppidx == 11, gap */
1083 }
1084 else { /* ! do_pavg and ! do_ppcons */
1085 for(ppidx = 10; ppidx >= ppidx_thresh; ppidx--) {
1086 ppcount += pp_ct[apos][ppidx];
1087 }
1088 ppfreq = ppcount / nnongap;
1089 useme[apos] = (ppfreq < pfract) ? FALSE : TRUE; /* should I be worried about imprecision? 0.5 compared to 0.5? */
1090 /* printf("apos: %4d nnongap: %6d ppfreq: %.3f pfract %.3f useme: %d ppidx_thresh: %d\n", apos, nnongap, ppfreq, pfract, useme[apos], ppidx_thresh); */
1091 }
1092 }
1093 } /* end of if(i_am_eligible[apos]) */
1094 else useme[apos] = FALSE;
1095 }
1096
1097 *ret_useme = useme;
1098 return eslOK;
1099
1100 ERROR:
1101 if(useme != NULL) free(useme);
1102 ESL_FAIL(status, errbuf, "Error, out of memory while masking based on postprobs.");
1103 return status; /* NEVERREACHED */
1104 }
1105
1106 /* output_mask
1107 *
1108 * Given a useme[0..apos..alen-1] array where useme[apos] = TRUE if we
1109 * should keep apos TRUE, and FALSE if not, output a mask of '1's and
1110 * '0's to the file <filename>. The mask is a string of exactly <alen>
1111 * length with a '1' for each apos to keep, and a '0' for each apos we
1112 * won't keep.
1113 *
1114 * If <i_am_eligible> is non-NULL, only output '1's or '0's for positions
1115 * for which <i_am_eligible>[apos] is TRUE. This allows us to output
1116 * masks that are only the length of the non-gap RF annotation in the file.
1117 *
1118 * If we encounter an error, we return non-eslOK status and and fill
1119 * errbuf with error message.
1120 *
1121 * Returns eslOK upon success.
1122 */
1123 static int
1124 output_mask(char *filename, int *useme, int *i_am_eligible, int64_t alen, char *errbuf)
1125 {
1126 int status;
1127 FILE *ofp;
1128 int apos;
1129 char *mask = NULL;
1130 int64_t mlen;
1131 int mpos;
1132
1133 if(useme == NULL) ESL_FAIL(eslEINVAL, errbuf, "Error, trying to output a mask but useme is NULL.");
1134
1135 /* determine length of mask */
1136 if(i_am_eligible == NULL) mlen = alen;
1137 else mlen = esl_vec_ISum(i_am_eligible, (int) alen); /* relies on TRUE being equal to 1 */
1138
1139 ESL_ALLOC(mask, sizeof(char) * (mlen+1));
1140
1141 mpos = 0;
1142 for (apos = 0; apos < alen; apos++) {
1143 if(i_am_eligible == NULL) {
1144 mask[mpos++] = useme[apos] ? '1' : '0';
1145 }
1146 else if(i_am_eligible[apos]) {
1147 mask[mpos++] = useme[apos] ? '1' : '0';
1148 }
1149 }
1150 mask[mlen] = '\0';
1151
1152 if ((ofp = fopen(filename, "w")) == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to open output file %s\n", filename);
1153 fprintf(ofp, "%s\n", mask);
1154
1155 free(mask);
1156 fclose(ofp);
1157 return eslOK;
1158
1159 ERROR:
1160 ESL_FAIL(status, errbuf, "Memory allocation error while outputting mask.");
1161 return status; /* NEVERREACHED */
1162 }
1163
1164 /* determine_nkept_rf()
1165 *
1166 * Determine number of alignment positions to be kept (useme[apos]==TRUE)
1167 * are non-gap RF positions using useme[] and i_am_rf[], both of length
1168 * <alen>. Return that number.
1169 */
1170 static int
1171 determine_nkept_rf(int *useme, int *i_am_rf, int64_t len)
1172 {
1173 int nkept_rf = 0;
1174 int apos;
1175 for(apos = 0; apos < len; apos++) {
1176 if(useme[apos] && i_am_rf[apos]) nkept_rf++;
1177 }
1178 return nkept_rf;
1179 }
1180
1181 static int
1182 parse_coord_string(const char *cstring, uint32_t *ret_start, uint32_t *ret_end)
1183 {
1184 ESL_REGEXP *re = esl_regexp_Create();
1185 char tok1[32];
1186 char tok2[32];
1187 uint32_t start, end;
1188
1189 if (esl_regexp_Match(re, "^(\\d+)\\D+(\\d*)$", cstring) != eslOK) esl_fatal("with -t, 2nd cmdline arg must be coords <from>..<to>; %s not recognized", cstring);
1190 if (esl_regexp_SubmatchCopy(re, 1, tok1, 32) != eslOK) esl_fatal("Failed to find <from> coord in %s", cstring);
1191 if (esl_regexp_SubmatchCopy(re, 2, tok2, 32) != eslOK) esl_fatal("Failed to find <to> coord in %s", cstring);
1192
1193 /* Check for invalid values for start and end. Note that regexp matching enforced that tok1 and tok2 are both >= 0 */
1194 start = atol(tok1);
1195 if(start == 0) esl_fatal("with -t, coordinates must be positive integers <from>..<to>, <from> coordinate read as '0'");
1196 if(tok2[0] == '\0') { /* special case: user provided something like "100:", keep positions 100 until end of alignment */
1197 end = 0;
1198 }
1199 else {
1200 end = atol(tok2);
1201 if(end <= 0) esl_fatal("with -t, coordinates must be positive integers <from>..<to>, <to> coordinate read as '0'");
1202 if(start > end) esl_fatal("with -t, 2nd cmdline arg <coords> must equal <from>..<to>, with <from> <= <to>");
1203 }
1204
1205 *ret_start = start;
1206 *ret_end = end;
1207
1208 esl_regexp_Destroy(re);
1209 return eslOK;
1210 }
1211
1212