Debian Codegraph @

hmmer/easel/miniapps/esl-alimanip.c

raw symbols SCIP
1 /* Manipulate a multiple sequence alignment in various ways.
2 */
3 #include <esl_config.h>
4
5 #include <stdlib.h>
6 #include <stdio.h>
7 #include <string.h>
8 #include <assert.h>
9 #include <math.h>
10 #include <limits.h>
11
12 #include "easel.h"
13 #include "esl_arr2.h"
14 #include "esl_distance.h"
15 #include "esl_dmatrix.h"
16 #include "esl_fileparser.h"
17 #include "esl_getopts.h"
18 #include "esl_keyhash.h"
19 #include "esl_msa.h"
20 #include "esl_msafile.h"
21 #include "esl_msafile2.h"
22 #include "esl_sq.h"
23 #include "esl_sqio.h"
24 #include "esl_stack.h"
25 #include "esl_tree.h"
26 #include "esl_vectorops.h"
27 #include "esl_wuss.h"
28
29 static char banner[] = "manipulate a multiple sequence alignment";
30 static char usage[] = "[options] <msafile>";
31
32 #define CLUSTOPTS "--cn-id,--cs-id,--cx-id,--cn-ins,--cs-ins,--cx-ins" /* Exclusive choice for clustering */
33 #define CHOOSESEQOPTS "--seq-k,--seq-r,--seq-ins,--reorder" /* Exclusive choice for choosing which seqs to keep/remove */
34 #define INCOMPATWITHSMALLOPTS "--rffract,--lnfract,--lxfract,--lmin,--lmax,--detrunc,--k-reorder,--seq-ins,--seq-ni,--seq-xi,--trim,--minpp,--t-keeprf,--tree,--reorder,--mask2rf,--m-keeprf,--num-all,--num-rf,--rm-gc,--sindi,--post2pp" /* Options incompatible with --small (all opts except --seq-k,--seq-r,--informat,--outformat,--rna,--dna,--amino */
35
36 static int write_rf_gapthresh(const ESL_GETOPTS *go, char *errbuf, ESL_MSA *msa, float gapthresh);
37 static int write_rf_given_alen(ESL_MSA *msa, char *errbuf, int *i_am_rf, int do_keep_rf_chars, char *amask, int amask_len);
38 static int write_rf_given_rflen(ESL_MSA *msa, char *errbuf, int *i_am_rf, int do_keep_rf_chars, char *mask_for_rf, int mask_for_rf_len);
39 static int individualize_consensus(const ESL_GETOPTS *go, char *errbuf, ESL_MSA *msa);
40 static int read_sqfile(ESL_SQFILE *sqfp, const ESL_ALPHABET *abc, int nseq, ESL_SQ ***ret_sq);
41 static int trim_msa(ESL_MSA *msa, ESL_SQ **sq, int do_keeprf, char *errbuf);
42 static int prune_msa_based_on_posteriors(ESL_MSA *msa, float min_pp, char *errbuf);
43 static int get_pp_idx(ESL_ALPHABET *abc, char ppchar);
44 static int get_tree_order(ESL_TREE *T, char *errbuf, int **ret_order);
45 static int reorder_msa(ESL_MSA *msa, int *order, char *errbuf);
46 static int read_mask_file(char *filename, char *errbuf, char **ret_mask, int *ret_mask_len);
47 static int expand_msa2mask(char *errbuf, ESL_MSA *msa1, char *xmask, ESL_MSA **newmsa1);
48 static int add_gap_columns_to_msa(char *errbuf, ESL_MSA *msa, int *toadd, ESL_MSA **ret_msa, int do_treat_as_rf_gap);
49 static int msa_median_length(ESL_MSA *msa);
50 static int msa_remove_seqs_below_minlen(ESL_MSA *msa, float minlen, int *i_am_rf, ESL_MSA **ret_new_msa);
51 static int msa_remove_seqs_above_maxlen(ESL_MSA *msa, float maxlen, ESL_MSA **ret_new_msa);
52 static int msa_remove_truncated_seqs(ESL_MSA *msa, char *errbuf, int ntrunc, int *i_am_rf, ESL_MSA **ret_new_msa);
53 static int msa_remove_seqs_with_ambiguities(ESL_MSA *msa, int max_nambig, ESL_MSA **ret_new_msa);
54 static int number_columns(ESL_MSA *msa, int do_all, int *i_am_rf, char *errbuf);
55 static char digit_to_char(int digit);
56 static int int_ndigits(int i);
57 static char get_char_digit_x_from_int(int i, int place);
58 static int read_seq_name_file(char *filename, char *errbuf, char ***ret_seqlist, int *ret_seqlist_n);
59 static int msa_keep_or_remove_seqs(ESL_MSA *msa, char *errbuf, char **seqlist, int seqlist_n, int do_keep, int do_reorder, int nali, ESL_MSA **ret_new_msa);
60 static int insert_x_pair_shared(ESL_MSA *msa, int *i_am_rf, int i, int j, int cfirst, int clast, double *opt_pshared, int *opt_nshared, int *opt_nins);
61 static int insert_x_pair_shared_length(ESL_MSA *msa, int *i_am_rf, int i, int j, int cfirst, int clast, double *opt_pshared, double *opt_nshared, int *opt_nins);
62 static int insert_x_diffmx(const ESL_GETOPTS *go, char *errbuf, ESL_MSA *msa, int rflen, int *i_am_rf, int do_length_weight, int do_only_internal_inserts, ESL_DMATRIX **ret_D);
63 static int MSADivide(ESL_MSA *mmsa, ESL_DMATRIX *D, int do_mindiff, int do_nc, int do_nsize, float mindiff, int target_nc, int target_nsize, int *ret_num_msa, ESL_MSA ***ret_cmsa, int *ret_xsize, char *errbuf);
64 static int select_node(ESL_TREE *T, double *diff, double mindiff, int **ret_clust, int *ret_nc, int *ret_xsize, int *ret_best, char *errbuf);
65 static float find_mindiff(ESL_TREE *T, double *diff, int do_nsize, int target, int **ret_clust, int *ret_nc, int *ret_xsize, int *ret_best, float *ret_mindiff, char *errbuf);
66 static int determine_first_last_consensus_columns(ESL_MSA *msa, char *errbuf, int *i_am_rf, int rflen, int **ret_fA, int **ret_lA);
67 static int dst_nongap_XPairId(const ESL_ALPHABET *abc, const ESL_DSQ *ax1, const ESL_DSQ *ax2, double *opt_distance, int *opt_nid, int *opt_n);
68 static int dst_nongap_XDiffMx(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, ESL_DMATRIX **ret_D);
69 static int find_seqs_with_given_insert(ESL_MSA *msa, int *i_am_rf, char *errbuf, int target, int min, int max, int **ret_useme);
70 static int minorize_msa(const ESL_GETOPTS *go, ESL_MSA *msa, char *errbuf, FILE *fp, char *tag, int outfmt);
71 static int remove_gc_markup(ESL_MSA *msa, char *errbuf, char *tag);
72 static int cp_and_add_gaps_to_aseq(char *new_aseq, char *orig_aseq, int alen, int *toadd, int nnew, char gapchar);
73 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);
74 static int convert_post_to_pp(ESL_MSA *msa, char *errbuf, int nali);
75 static int compare_ints(const void *el1, const void *el2);
76
77 static ESL_OPTIONS options[] = {
78 /* name type default env range togs reqs incomp help docgroup */
79 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "help; show brief info on version and usage", 1 },
80 { "-o", eslARG_OUTFILE,NULL, NULL, NULL, NULL,NULL, NULL, "output the alignment to file <f>, not stdout", 1 },
81 { "--informat", eslARG_STRING,NULL, NULL, NULL, NULL,NULL, NULL, "specify that input file is in format <s>", 1 },
82 { "--outformat", eslARG_STRING,NULL, NULL, NULL, NULL,NULL,NULL, "specify that output format be <s>", 1 },
83 { "--devhelp", eslARG_NONE, NULL, NULL, NULL, NULL,NULL, NULL, "show list of undocumented developer options", 1 },
84 /* options for removing/trimming/reordering sequences */
85 { "--lnfract", eslARG_REAL, NULL, NULL, "0<=x<=2", NULL,NULL, CHOOSESEQOPTS, "remove sequences w/length < <x> fraction of median length", 2 },
86 { "--lxfract", eslARG_REAL, NULL, NULL, "0<=x<=3", NULL,NULL, CHOOSESEQOPTS, "remove sequences w/length > <x> fraction of median length", 2 },
87 { "--lmin", eslARG_INT, NULL, NULL, "n>0", NULL,NULL, CHOOSESEQOPTS, "remove sequences w/length < <n> residues", 2 },
88 { "--lmax", eslARG_INT, NULL, NULL, "n>0", NULL,NULL, CHOOSESEQOPTS, "remove sequences w/length > <n> residues", 2 },
89 { "--rffract", eslARG_REAL, NULL, NULL, "0<=x<=1", NULL,NULL, CHOOSESEQOPTS, "remove seqs w/nongap RF len < <x> fraction of aln nongap RF len", 2 },
90 { "--detrunc", eslARG_INT, NULL, NULL, "n>0", NULL,NULL, CHOOSESEQOPTS, "remove seqs w/gaps in >= <n> 5' or 3'-most nongap #=GC RF cols", 2 },
91 { "--xambig", eslARG_INT, NULL, NULL, "n>=0", NULL,NULL, CHOOSESEQOPTS, "remove sequences with >= <n> ambiguous residues", 2 },
92 { "--seq-r", eslARG_INFILE,NULL, NULL, NULL, NULL,NULL, CHOOSESEQOPTS, "remove sequences with names listed in file <f>", 2 },
93 { "--seq-k", eslARG_INFILE,NULL, NULL, NULL, NULL,NULL, CHOOSESEQOPTS, "remove all seqs *except* those listed in <f>", 2 },
94 { "--small", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, INCOMPATWITHSMALLOPTS, "w/--seq-r or --seq-k use minimal RAM (no seq reordering)", 2 },
95 { "--k-reorder", eslARG_NONE, NULL, NULL, NULL, NULL,"--seq-k", INCOMPATWITHSMALLOPTS, "with --seq-k <f>, reorder sequences to order in <f>", 2 },
96 { "--seq-ins", eslARG_INT, NULL, NULL, NULL, NULL,NULL, CHOOSESEQOPTS, "keep only seqs w/an insert after nongap RF col <n>", 2 },
97 { "--seq-ni", eslARG_INT, "1", NULL, "n>0", NULL,"--seq-ins", NULL, "w/--seq-ins require at least <n> residue insertions", 2 },
98 { "--seq-xi", eslARG_INT,"1000000",NULL, "n>0", NULL,"--seq-ins", NULL, "w/--seq-ins require at most <n> residue insertions", 2 },
99 { "--trim", eslARG_INFILE, NULL, NULL, NULL, NULL,NULL, NULL, "trim aligned seqs in <msafile> to subseqs in <f>", 2 },
100 { "--t-keeprf", eslARG_NONE, NULL, NULL, NULL, NULL,"--trim", NULL, "w/--trim keep GC RF annotation in msa, if it exists", 2 },
101 { "--minpp", eslARG_REAL, NULL, NULL, "0<x<=0.95",NULL,NULL,NULL, "replace residues with posterior probabilities < <x> with gaps", 2 },
102 { "--tree", eslARG_OUTFILE,NULL, NULL, NULL, NULL,NULL, CHOOSESEQOPTS, "reorder MSA to tree order following SLC, save Newick tree to <f>", 2 },
103 { "--reorder", eslARG_INFILE, NULL, NULL, NULL, NULL,NULL, CHOOSESEQOPTS, "reorder seqs to the order listed in <f>, all seqs must be listed", 2 },
104 /* options for adding/removing alignment annotation */
105 { "--mask2rf", eslARG_INFILE, FALSE,NULL, NULL, NULL,NULL, NULL, "set #=GC RF as x=1, gap=0 from 1/0s in 1-line <f>", 3 },
106 { "--m-keeprf", eslARG_NONE, FALSE, NULL, NULL, NULL,"--mask2rf", NULL, "with --mask2rf, do not overwrite nongap RF characters with 'x'", 3 },
107 { "--num-all", eslARG_NONE, NULL, NULL, NULL, NULL,NULL, NULL, "add annotation numbering all columns", 3 },
108 { "--num-rf", eslARG_NONE, NULL, NULL, NULL, NULL,NULL, NULL, "add annotation numbering the nongap RF columns", 3 },
109 { "--rm-gc", eslARG_STRING,NULL, NULL, NULL, NULL,NULL, "--mask2rf", "remove GC <s> markup, <s> must be RF|SS_cons|SA_cons|PP_cons", 3 },
110 { "--sindi", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "add per-sequence SS based on SS_cons, omitting bps with gaps", 3 },
111 { "--cindi", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, "--sindi", "add per-sequence SS based on SS_cons, keeping bps with gaps", 3 },
112 { "--post2pp", eslARG_NONE, NULL, NULL, NULL, NULL,NULL, NULL, "convert infernal 0.72-1.0.2 POST posterior prob annotation to PP", 3 },
113 /* options for specifying the alphabet */
114 { "--amino", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL,"--dna,--rna", "<msafile> contains protein alignments", 4 },
115 { "--dna", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL,"--amino,--rna", "<msafile> contains DNA alignments", 4 },
116 { "--rna", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL,"--amino,--dna", "<msafile> contains RNA alignments", 4 },
117
118 /* All options below are developer options, only shown if --devhelp invoked */
119 { "--xmask", eslARG_INFILE, NULL, NULL, NULL, NULL,NULL, NULL, "for each 0 column in <f>, add a 100% gap column to <msafile>", 101 },
120 { "--cn-id", eslARG_INT, NULL, NULL, "n>0", NULL,NULL, CLUSTOPTS, "split MSA into <n> clusters based on sequence identity", 101 },
121 { "--cs-id", eslARG_INT, NULL, NULL, "n>0", NULL,NULL, CLUSTOPTS, "split MSA into clusters on id s.t max cluster has <n> seqs", 101 },
122 { "--cx-id", eslARG_REAL, NULL, NULL, "0.<x<1.",NULL,NULL, CLUSTOPTS, "split MSA into clusters s.t. no seq b/t 2 clusters > <x> seq id", 101 },
123 { "--cn-ins", eslARG_INT, NULL, NULL, "n>0", NULL,NULL, CLUSTOPTS, "split MSA into <n> clusters based on insert similarity", 101 },
124 { "--cs-ins", eslARG_INT, NULL, NULL, "n>0", NULL,NULL, CLUSTOPTS, "split MSA into clusters on inserts s.t. max cluster has <n> seqs", 101 },
125 { "--cx-ins", eslARG_REAL, NULL, NULL, "0.<x<1.",NULL,NULL, CLUSTOPTS, "split MSA into clusters s.t. no seq b/t 2 clusters > <x> ins id", 101 },
126 { "--c-nmin", eslARG_INT, NULL, NULL, "n>0", NULL,NULL, NULL, "only keep the cluster(s) with number of seqs > <n>", 101 },
127 { "--c-mx", eslARG_OUTFILE,NULL, NULL, NULL, NULL,NULL, NULL, "output identity matrix to file <f>", 101 },
128 { "-M", eslARG_STRING,NULL, NULL, NULL, NULL,NULL, "--seq-r,--seq-k", "use #=GS tag <s> to define minor alignments, and output them", 101 },
129 { "--M-rf", eslARG_NONE, NULL, NULL, NULL, NULL,"-M", NULL, "w/-M, impose major #=GC RF onto all minor alns", 101 },
130 { "--M-gapt", eslARG_REAL, "0.5", NULL, "0<=x<=1", NULL,"-M", NULL, "w/-M, fraction of gaps allowed in nongap RF columns", 101 },
131
132 { 0,0,0,0,0,0,0,0,0,0 },
133 };
134
135 int
136 main(int argc, char **argv)
137 {
138 ESL_GETOPTS *go = NULL; /* application configuration */
139 ESL_ALPHABET *abc = NULL; /* biological alphabet */
140 char *alifile = NULL; /* alignment file name */
141 int infmt = eslMSAFILE_UNKNOWN; /* format code for alifile */
142 int outfmt = eslMSAFILE_UNKNOWN; /* format code for output ali */
143 int i; /* counter */
144 ESL_MSAFILE *afp = NULL; /* open ali file, normal interface */
145 ESL_MSAFILE2 *afp2 = NULL; /* open ali file, legacy small-mem interface */
146 ESL_MSA *msa = NULL; /* one multiple sequence alignment */
147 int status; /* easel return code */
148 int nali; /* number of alignments read */
149 FILE *ofp; /* output file (default is stdout) */
150 char errbuf[eslERRBUFSIZE];
151 int median; /* median length seq in msa */
152 float minlen; /* min length seq we'll keep */
153 float maxlen; /* max length seq we'll keep */
154 ESL_MSA *new_msa; /* a new MSA object created from the msa we read from a file */
155
156 /* variables related to --seq-k and --seq-r and --reorder */
157 char **seqlist = NULL; /* list of sequences to keep in msa */
158 int seqlist_n; /* number of sequences in seqlist */
159 int n; /* counter over seqnames */
160 int *useme = NULL; /* useme[0..n..msa->nseq-1] TRUE to keep seq n, FALSE not to */
161
162 /* variables related to --trim */
163 ESL_SQ **trim_sq = NULL; /* unaligned sequences read from a file */
164
165 /* --trim related vars */
166 ESL_SQFILE *trimfp = NULL; /* sequence file with subsequences for --trim */
167
168 /* --mask2rf */
169 char *mask_for_rf = NULL;
170 int mask_for_rf_len = -1;
171 /* --xmask */
172 char *xmask = NULL;
173 int xmask_len = -1;
174 /* RF related variables */
175 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 */
176 int *rf2a_map = NULL; /* [0..rfpos..rflen-1] = apos,
177 * apos is the alignment position (0..msa->alen-1) that
178 * is non-gap RF position rfpos+1 (for rfpos in 0..rflen-1) */
179 int rflen = -1; /* nongap RF length */
180
181 /* options related to --tree */
182 ESL_TREE *T = NULL; /* the tree, created by Single-Linkage Clustering */
183 ESL_DMATRIX *D = NULL; /* the distance matrix */
184 int *order; /* order of sequences in new, reordered msa */
185
186 /* options related the 'in development '--c*' options */
187 int do_id_cluster = FALSE; /* TRUE if --cn-id, --cs-id, or --cx-id */
188 int do_insert_cluster = FALSE; /* TRUE if --cn-ins, --cs-ins, or --cx-ins */
189 int do_ctarget_nc, do_ctarget_nsize, do_cmindiff, nmsa, m, nc, nsize, xsize, nmin;
190 float mindiff;
191 ESL_MSA **cmsa; /* the new msa's created by clustering seqs in the main msa */
192 ESL_MSA *rfmsa; /* the new msa, but with gap RF columns removed */
193 FILE *mxfp = NULL;
194 int j;
195
196 /* --iinfo, --iplot, --gplot --rinfo, --dinfo related vars */
197 double **abc_ct = NULL; /* [0..msa->alen-1][0..abc->K], count of each residue at each position, over all sequences, missing and nonresidues are *not counted* */
198 int **pp_ct = NULL; /* [0..msa->alen-1][0..11], count of reach posterior probability (PP) code, over all sequences, gap is 11 */
199 FILE *treefp = NULL; /* output file for --tree */
200
201 /* options related to --small */
202 ESL_KEYHASH *seqname_keyhash=NULL; /* keyhash of sequence names listed in list file <f>, with <f> from --seq-k <f> --seq-r <f> */
203 int nseq_read = 0; /* number of sequences read from current alignment */
204 int nseq_regurged = 0; /* number of sequences regurgitated from current alignment */
205
206
207 /***********************************************
208 * Parse command line
209 ***********************************************/
210
211 go = esl_getopts_Create(options);
212 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK ||
213 esl_opt_VerifyConfig(go) != eslOK)
214 {
215 printf("Failed to parse command line: %s\n", go->errbuf);
216 esl_usage(stdout, argv[0], usage);
217 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
218 exit(1);
219 }
220
221 if (esl_opt_GetBoolean(go, "--devhelp") )
222 {
223 esl_banner(stdout, argv[0], banner);
224 esl_usage (stdout, argv[0], usage);
225 puts("\nwhere basic options are:");
226 esl_opt_DisplayHelp(stdout, go, 1, 2, 80);
227 puts("\noptions for removing/reordering/trimming sequences:");
228 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
229 puts("\noptions for adding/removing alignment annotation:");
230 esl_opt_DisplayHelp(stdout, go, 3, 2, 80);
231 puts("\noptions for specifying bio alphabet:");
232 esl_opt_DisplayHelp(stdout, go, 4, 2, 80);
233 puts("\nundocumented, experimental developer options:");
234 esl_opt_DisplayHelp(stdout, go, 101, 2, 80);
235 exit(0);
236 }
237 if (esl_opt_GetBoolean(go, "-h") )
238 {
239 esl_banner(stdout, argv[0], banner);
240 esl_usage (stdout, argv[0], usage);
241 puts("\nwhere basic options are:");
242 esl_opt_DisplayHelp(stdout, go, 1, 2, 80);
243 puts("\noptions for removing/reordering/trimming sequences:");
244 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
245 puts("\noptions for adding/removing alignment annotation:");
246 esl_opt_DisplayHelp(stdout, go, 3, 2, 80);
247 puts("\noptions for specifying bio alphabet:");
248 esl_opt_DisplayHelp(stdout, go, 4, 2, 80);
249 exit(0);
250 }
251
252 if (esl_opt_ArgNumber(go) != 1)
253 {
254 printf("Incorrect number of command line arguments.\n");
255 esl_usage(stdout, argv[0], usage);
256 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
257 exit(1);
258 }
259
260 /* Check for incompatible options that aren't simple to check with esl_getopts */
261 /* --small requires either --seq-k or --seq-r */
262 if (esl_opt_GetBoolean(go, "--small") && (! esl_opt_IsOn(go, "--seq-k")) && (! esl_opt_IsOn(go, "--seq-r"))) {
263 esl_fatal("--small requires either --seq-k or --seq-r");
264 }
265
266 alifile = esl_opt_GetArg(go, 1);
267
268 /* get informat and outformat */
269 if (esl_opt_GetBoolean(go, "--small"))
270 {
271 infmt = eslMSAFILE_PFAM;
272 outfmt = eslMSAFILE_PFAM;
273 }
274 else
275 {
276 outfmt = eslMSAFILE_STOCKHOLM;
277 }
278
279 if (esl_opt_IsOn(go, "--informat"))
280 {
281 infmt = esl_msafile_EncodeFormat(esl_opt_GetString(go, "--informat"));
282 if (infmt == eslMSAFILE_UNKNOWN)
283 esl_fatal("%s is not a valid input sequence file format for --informat", esl_opt_GetString(go, "--informat"));
284 if (esl_opt_GetBoolean(go, "--small") && infmt != eslMSAFILE_PFAM)
285 esl_fatal("--small requires (and defaults to) pfam format\ncan't set --informat %s\n", esl_opt_GetString(go, "--informat"));
286 }
287
288 if (esl_opt_IsOn(go, "--outformat"))
289 {
290 outfmt = esl_msafile_EncodeFormat(esl_opt_GetString(go, "--outformat"));
291 if (outfmt == eslMSAFILE_UNKNOWN)
292 esl_fatal("%s is not a valid input sequence file format for --outformat", esl_opt_GetString(go, "--outformat"));
293 if (esl_opt_GetBoolean(go, "--small") && outfmt != eslMSAFILE_PFAM)
294 esl_fatal("--small requires (and defaults to) pfam format\ncan't set --outformat %s\n", esl_opt_GetString(go, "--outformat"));
295 }
296
297 /***************************************************************
298 * Open the MSA file; determine alphabet; set for digital input
299 ****************************************************************/
300
301 if (esl_opt_GetBoolean(go, "--amino")) abc = esl_alphabet_Create(eslAMINO);
302 else if (esl_opt_GetBoolean(go, "--dna")) abc = esl_alphabet_Create(eslDNA);
303 else if (esl_opt_GetBoolean(go, "--rna")) abc = esl_alphabet_Create(eslRNA);
304 else if (esl_opt_GetBoolean(go, "--small")) esl_fatal("Must specify an alphabet (--amino, --dna, --rna) to use --small");
305
306 if (esl_opt_GetBoolean(go, "--small"))
307 {
308 status = esl_msafile2_OpenDigital(abc, alifile, NULL, &afp2);
309 if (status == eslENOTFOUND) esl_fatal("Alignment file %s doesn't exist or is not readable\n", alifile);
310 else if (status != eslOK) esl_fatal("Alignment file %s open failed with error %d\n", alifile, status);
311 }
312 else
313 {
314 if ( (status = esl_msafile_Open(&abc, alifile, NULL, infmt, NULL, &afp)) != eslOK)
315 esl_msafile_OpenFailure(afp, status);
316 infmt = afp->format;
317 }
318
319 /* Check for incompatible options that require Stockholm/Pfam as input or output format */
320 if((esl_opt_IsOn(go, "--mask2rf")) && (outfmt != eslMSAFILE_STOCKHOLM) && (outfmt != eslMSAFILE_PFAM)) esl_fatal("with --mask2rf, the the output format must be stockholm/pfam format");
321 if((esl_opt_IsOn(go, "--rm-gc")) && (outfmt != eslMSAFILE_STOCKHOLM) && (outfmt != eslMSAFILE_PFAM)) esl_fatal("with --rm-gc, the the output format must be stockholm/pfam format");
322 if((esl_opt_IsOn(go, "--post2pp")) && (outfmt != eslMSAFILE_STOCKHOLM) && (outfmt != eslMSAFILE_PFAM)) esl_fatal("with --post2pp, the the output format must be stockholm/pfam format");
323 if((esl_opt_IsOn(go, "--num-all")) && (outfmt != eslMSAFILE_STOCKHOLM) && (outfmt != eslMSAFILE_PFAM)) esl_fatal("with --num-all, the the output format must be stockholm/pfam format");
324 if((esl_opt_IsOn(go, "--num-rf")) && (outfmt != eslMSAFILE_STOCKHOLM) && (outfmt != eslMSAFILE_PFAM)) esl_fatal("with --num-rf, the the output format must be stockholm/pfam format");
325
326 if((esl_opt_IsOn(go, "--seq-ins")) && (infmt != eslMSAFILE_STOCKHOLM) && (infmt != eslMSAFILE_PFAM)) esl_fatal("with --seq-ins, the alignment file must be in stockholm/pfam format");
327 if((esl_opt_IsOn(go, "--cn-id")) && (infmt != eslMSAFILE_STOCKHOLM) && (infmt != eslMSAFILE_PFAM)) esl_fatal("with --cn-id, the alignment file must be in stockholm/pfam format");
328 if((esl_opt_IsOn(go, "--cs-id")) && (infmt != eslMSAFILE_STOCKHOLM) && (infmt != eslMSAFILE_PFAM)) esl_fatal("with --cs-id, the alignment file must be in stockholm/pfam format");
329 if((esl_opt_IsOn(go, "--cx-id")) && (infmt != eslMSAFILE_STOCKHOLM) && (infmt != eslMSAFILE_PFAM)) esl_fatal("with --cx-id, the alignment file must be in stockholm/pfam format");
330 if((esl_opt_IsOn(go, "--cn-ins")) && (infmt != eslMSAFILE_STOCKHOLM) && (infmt != eslMSAFILE_PFAM)) esl_fatal("with --cn-ins, the alignment file must be in stockholm/pfam format");
331 if((esl_opt_IsOn(go, "--cs-ins")) && (infmt != eslMSAFILE_STOCKHOLM) && (infmt != eslMSAFILE_PFAM)) esl_fatal("with --cs-ins, the alignment file must be in stockholm/pfam format");
332 if((esl_opt_IsOn(go, "--cx-ins")) && (infmt != eslMSAFILE_STOCKHOLM) && (infmt != eslMSAFILE_PFAM)) esl_fatal("with --cx-ins, the alignment file must be in stockholm/pfam format");
333
334 /* open output file */
335 if (esl_opt_GetString(go, "-o") != NULL) {
336 if ((ofp = fopen(esl_opt_GetString(go, "-o"), "w")) == NULL)
337 esl_fatal("Failed to open -o output file %s\n", esl_opt_GetString(go, "-o"));
338 } else ofp = stdout;
339
340 do_id_cluster = ((esl_opt_IsOn(go, "--cn-id")) || (esl_opt_IsOn(go, "--cs-id")) || (esl_opt_IsOn(go, "--cx-id"))) ? TRUE : FALSE;
341 do_insert_cluster = ((esl_opt_IsOn(go, "--cn-ins")) || (esl_opt_IsOn(go, "--cs-ins")) || (esl_opt_IsOn(go, "--cx-ins")))? TRUE : FALSE;
342
343 /****************************
344 * Read optional input files
345 ****************************/
346 /* read --mask2rf file, if nec */
347 if(esl_opt_GetString(go, "--mask2rf") != NULL) {
348 if((status = read_mask_file(esl_opt_GetString(go, "--mask2rf"), errbuf, &mask_for_rf, &mask_for_rf_len)) != eslOK)
349 esl_fatal(errbuf);
350 }
351 /* read --xmask file, if nec */
352 if(esl_opt_GetString(go, "--xmask") != NULL) {
353 if((status = read_mask_file(esl_opt_GetString(go, "--xmask"), errbuf, &xmask, &xmask_len)) != eslOK)
354 esl_fatal(errbuf);
355 }
356
357 /****************************
358 * Open optional output files
359 ****************************/
360
361 if( esl_opt_IsOn(go, "--tree")) {
362 if ((treefp = fopen(esl_opt_GetString(go, "--tree"), "w")) == NULL)
363 esl_fatal("Failed to open --tree output file %s\n", esl_opt_GetString(go, "--tree"));
364 }
365 if( esl_opt_IsOn(go, "--c-mx")) {
366 if ((mxfp = fopen(esl_opt_GetString(go, "--c-mx"), "w")) == NULL)
367 esl_fatal("Failed to open --c-mx output file %s\n", esl_opt_GetString(go, "--c-mx"));
368 }
369
370 /*******************************************************************
371 * Open and read list file, if nec (--seq-k, --seq-r or --reorder) *
372 *******************************************************************/
373 if ( esl_opt_IsOn(go, "--seq-k") || esl_opt_IsOn(go, "--seq-r") || esl_opt_IsOn(go, "--reorder")) {
374 if( esl_opt_IsOn(go, "--seq-k")) {
375 if((status = read_seq_name_file(esl_opt_GetString(go, "--seq-k"), errbuf, &seqlist, &seqlist_n)) != eslOK) esl_fatal(errbuf);
376 }
377 else if( esl_opt_IsOn(go, "--reorder")) {
378 if((status = read_seq_name_file(esl_opt_GetString(go, "--reorder"), errbuf, &seqlist, &seqlist_n)) != eslOK) esl_fatal(errbuf);
379 }
380 else { /* --seq-r enabled */
381 if((status = read_seq_name_file(esl_opt_GetString(go, "--seq-r"), errbuf, &seqlist, &seqlist_n)) != eslOK) esl_fatal(errbuf);
382 }
383 }
384
385 /*************************************************************
386 * Read MSAs one at a time, manipulate them, then output them
387 *************************************************************/
388
389 nali = 0;
390 if (! esl_opt_GetBoolean(go, "--small")) {
391 while ((status = esl_msafile_Read(afp, &msa)) != eslEOF){
392 if (status != eslOK) esl_msafile_ReadFailure(afp, status);
393 nali++;
394
395 /* if RF exists, get i_am_rf array[0..alen] which tells us which positions are non-gap RF positions
396 * and rf2a_map, a map of non-gap RF positions to overall alignment positions */
397 if(msa->rf != NULL) {
398 if((status = map_rfpos_to_apos(msa, abc, errbuf, &i_am_rf, &rf2a_map, &rflen)) != eslOK) esl_fatal(errbuf);
399 }
400
401 /********************************************************************
402 * Remove sequences based on an input list file (--seq-k or --seq-r)
403 ********************************************************************/
404 /* Handle the --seq-k and --seq-r options if enabled, all subsequent manipulations will omit any seqs removed here.
405 * We've already read list file <f>, seqlist holds the seqlist_n sequences read from <f>
406 * (<f> from either --seq-k <f>, --seq-r <f>, --reorder <f>)
407 */
408 if ( esl_opt_IsOn(go, "--seq-k") || esl_opt_IsOn(go, "--seq-r") || esl_opt_IsOn(go, "--reorder")) {
409 if((afp->format != eslMSAFILE_STOCKHOLM) && (afp->format != eslMSAFILE_PFAM)) {
410 esl_fatal("--seq-k, --seq-r, --reorder only work on Stockholm formatted alignments");
411 }
412 if( esl_opt_IsOn(go, "--seq-k")) {
413 if((status = msa_keep_or_remove_seqs(msa, errbuf, seqlist, seqlist_n, TRUE, (esl_opt_GetBoolean(go, "--k-reorder")), nali, &new_msa)) != eslOK) esl_fatal(errbuf);
414 /* new_msa is msa but only with seqs listed in --seq-k <f> file */
415 }
416 else if( esl_opt_IsOn(go, "--reorder")) {
417 if(seqlist_n != msa->nseq) esl_fatal("With --reorder <f>, <f> contains %d names, but alignment %d has %d seqs (all seqs must be listed in <f>)", seqlist_n, nali, msa->nseq);
418 if((status = msa_keep_or_remove_seqs(msa, errbuf, seqlist, seqlist_n, TRUE, TRUE, nali, &new_msa)) != eslOK) esl_fatal(errbuf);
419 /* new_msa is msa but only with seqs listed in --seq-k <f> file */
420 }
421 else { /* --seq-r enabled */
422 if((status = msa_keep_or_remove_seqs(msa, errbuf, seqlist, seqlist_n, FALSE, TRUE, nali, &new_msa)) != eslOK) esl_fatal(errbuf);
423 /* new_msa is msa but without seqs listed in --seq-r <f> file */
424 }
425 esl_msa_Destroy(msa);
426 msa = new_msa;
427 }
428
429 /*************************************************************
430 * Remove sequences based on length or number of ambiguities *
431 *************************************************************/
432 /* The --lnfract,--lxfract,--lmin,--lmax,--detrunc,--xambig options.
433 * we do each separately, removing seqs for each as we go.
434 * They can be used in combination.
435 */
436 if (esl_opt_IsOn(go, "--lnfract")) {
437 median = msa_median_length(msa);
438 minlen = esl_opt_GetReal(go, "--lnfract") * (float) median;
439 msa_remove_seqs_below_minlen(msa, minlen, NULL, &new_msa); /* NULL: do not consider only nongap RF positions */
440 /* new_msa is msa without seqs below minlen, swap ptrs */
441 esl_msa_Destroy(msa);
442 msa = new_msa;
443 new_msa = NULL;
444 }
445 if (esl_opt_IsOn(go, "--lxfract")) {
446 median = msa_median_length(msa);
447 maxlen = esl_opt_GetReal(go, "--lxfract") * (float) median;
448 msa_remove_seqs_above_maxlen(msa, maxlen, &new_msa);
449 /* new_msa is msa without seqs above maxlen, swap ptrs */
450 esl_msa_Destroy(msa);
451 msa = new_msa;
452 new_msa = NULL;
453 }
454 if (esl_opt_IsOn(go, "--lmin")) {
455 minlen = esl_opt_GetInteger(go, "--lmin");
456 msa_remove_seqs_below_minlen(msa, minlen, NULL, &new_msa); /* NULL: do not consider only nongap RF positions */
457 /* new_msa is msa without seqs below minlen, swap ptrs */
458 esl_msa_Destroy(msa);
459 msa = new_msa;
460 new_msa = NULL;
461 }
462 if (esl_opt_IsOn(go, "--lmax")) {
463 maxlen = esl_opt_GetInteger(go, "--lmax");
464 msa_remove_seqs_above_maxlen(msa, maxlen, &new_msa);
465 /* new_msa is msa without seqs below maxlen, swap ptrs */
466 esl_msa_Destroy(msa);
467 msa = new_msa;
468 new_msa = NULL;
469 }
470 if (esl_opt_IsOn(go, "--rffract")) {
471 /* determine nongap RF length */
472 if(msa->rf == NULL) esl_fatal("with --rffract, alignment(s) must have RF annotation, alignment %d does not", nali);
473 minlen = rflen * esl_opt_GetReal(go, "--rffract");
474 msa_remove_seqs_below_minlen(msa, minlen, i_am_rf, &new_msa);
475 /* new_msa is msa without seqs below minlen, swap ptrs */
476 esl_msa_Destroy(msa);
477 msa = new_msa;
478 new_msa = NULL;
479 }
480 if( esl_opt_IsOn(go, "--detrunc")) {
481 if((status = msa_remove_truncated_seqs(msa, errbuf, esl_opt_GetInteger(go, "--detrunc"), i_am_rf, &new_msa)) != eslOK) esl_fatal(errbuf);
482 /* new_msa is msa without seqs below minlen, swap ptrs */
483 esl_msa_Destroy(msa);
484 msa = new_msa;
485 new_msa = NULL;
486 }
487 if( esl_opt_IsOn(go, "--xambig")) {
488 if((status = msa_remove_seqs_with_ambiguities(msa, esl_opt_GetInteger(go, "--xambig"), &new_msa)) != eslOK) esl_fatal(errbuf);
489 /* new_msa is msa without seqs with > <n> (from --xambig <n>) ambiguities, swap ptrs */
490 esl_msa_Destroy(msa);
491 msa = new_msa;
492 new_msa = NULL;
493 }
494
495 /*********************************************************
496 * Remove sequences based on a specific insert (--seq-ins)
497 *********************************************************/
498 if( esl_opt_IsOn(go, "--seq-ins")) {
499 if((status = find_seqs_with_given_insert(msa, i_am_rf, errbuf, esl_opt_GetInteger(go, "--seq-ins"), esl_opt_GetInteger(go, "--seq-ni"), esl_opt_GetInteger(go, "--seq-xi"), &useme)) != eslOK) esl_fatal(errbuf);
500 if(esl_vec_ISum(useme, msa->nseq) == 0) esl_fatal("No sequences satisfy the --seq-ins option.");
501 if((status = esl_msa_SequenceSubset(msa, useme, &new_msa)) != eslOK) esl_fatal(errbuf);
502 /* new_msa is msa but without seqs that do not have an insert of length <a>..<b> (from --seq-ni <a> and --seq-xi <b>) after consensus column <n> from --seq-ins <n> file */
503 esl_msa_Destroy(msa);
504 msa = new_msa;
505 new_msa = NULL;
506 if(useme != NULL){
507 free(useme); // not needed any more
508 }
509 }
510
511 /******************
512 * Trim sequences *
513 ******************/
514 if(esl_opt_GetString(go, "--trim") != NULL) {
515 if(nali > 1) { esl_fatal("--trim only works if the alignment file has a single alignment"); }
516 status = esl_sqfile_Open(esl_opt_GetString(go, "--trim"), eslSQFILE_UNKNOWN, NULL, &(trimfp));
517 if (status == eslENOTFOUND) esl_fatal("File %s doesn't exist or is not readable\n", esl_opt_GetString(go, "--trim"));
518 else if (status == eslEFORMAT) esl_fatal("Couldn't determine format of sequence file %s\n", esl_opt_GetString(go, "--trim"));
519 else if (status == eslEINVAL) esl_fatal("Can't autodetect stdin or .gz.");
520 else if (status != eslOK) esl_fatal("Sequence file open failed with error %d\n", status);
521 /* read the sequences */
522 read_sqfile(trimfp, msa->abc, msa->nseq, &trim_sq); /* dies on failure */
523 /* trim the msa */
524 if((status = trim_msa(msa, trim_sq, esl_opt_GetBoolean(go, "--t-keeprf"), errbuf)) != eslOK) esl_fatal(errbuf);
525 for(i = 0; i < msa->nseq; i++) esl_sq_Destroy(trim_sq[i]);
526 free(trim_sq);
527 trim_sq = NULL;
528 }
529
530 /*****************************************************
531 * Replace residues with PP values less than minimum *
532 *****************************************************/
533 if(esl_opt_IsOn(go, "--minpp")) {
534 if(msa->pp == NULL) esl_fatal("--minpp requires all alignments have posterior probability annotation, %d does not\n", nali);
535 if((status = prune_msa_based_on_posteriors(msa, esl_opt_GetReal(go, "--minpp"), errbuf)) != eslOK) esl_fatal(errbuf);
536 }
537
538 /**********************************************
539 * Reorder sequences to tree order, if --tree *
540 **********************************************/
541 /* handle the --tree option, if enabled */
542 if( esl_opt_IsOn(go, "--tree")) {
543 /* Create distance matrix and infer tree by single linkage clustering */
544 esl_dst_XDiffMx(msa->abc, msa->ax, msa->nseq, &D);
545 esl_tree_SingleLinkage(D, &T);
546 esl_tree_SetTaxaParents(T);
547 esl_tree_SetTaxonlabels(T, msa->sqname);
548 if((status = esl_tree_Validate(T, errbuf)) != eslOK) esl_fatal(errbuf);
549
550 esl_tree_WriteNewick(treefp, T);
551
552 /* Get new order for seqs in the MSA based on the tree */
553 if((status = get_tree_order(T, errbuf, &order)) != eslOK) esl_fatal(errbuf);
554
555 /*for(i = 0; i < msa->nseq; i++) printf("new MSA idx: %3d | orig MSA idx: %3d\n", i, order[i]);*/
556 esl_tree_Destroy(T);
557 esl_dmatrix_Destroy(D);
558 T = NULL;
559 D = NULL;
560 if((status = reorder_msa(msa, order, errbuf)) != eslOK) esl_fatal(errbuf);
561 free(order);
562 }
563
564 /******************************************
565 * Modify/add annotation in the alignment *
566 ******************************************/
567 /* Convert POST annotation (infernal 0.72-1.0) to PP, if nec */
568 /* Remove GC annotation, if nec */
569
570 if( esl_opt_IsOn(go, "--rm-gc")) {
571 if((status = remove_gc_markup(msa, errbuf, esl_opt_GetString(go, "--rm-gc")) != eslOK)) esl_fatal(errbuf);
572 }
573 /* Rewrite RF annotation based on a mask, if nec */
574 if(mask_for_rf != NULL) { /* --mask2rf enabled */
575 if(msa->rf != NULL && mask_for_rf_len == rflen) { /* mask corresponds to RF len */
576 if((status = write_rf_given_rflen(msa, errbuf, i_am_rf, esl_opt_GetBoolean(go, "--m-keeprf"), mask_for_rf, mask_for_rf_len)) != eslOK) esl_fatal(errbuf);
577 }
578 else if(mask_for_rf_len == msa->alen) {
579 if((status = write_rf_given_alen(msa, errbuf, i_am_rf, esl_opt_GetBoolean(go, "--m-keeprf"), mask_for_rf, mask_for_rf_len)) != eslOK) esl_fatal(errbuf);
580 }
581 else {
582 if(msa->rf != NULL) esl_fatal("msa %d, alignment length is %d, nongap RF length is %d, --mask2rf mask length is neither (%d)", msa->alen, rflen);
583 else esl_fatal("msa %d, alignment length is %d (no RF annotation), --mask2rf mask length is neither (%d)", msa->alen, rflen);
584 }
585 }
586 /* Add annotation numbering the nongap RF columns, if nec */
587 if( esl_opt_IsOn(go, "--num-rf")) {
588 if(msa->rf == NULL) esl_fatal("--num-rf requires all alignments have #=GC RF annotation, but alignment %d does not", nali);
589 if((status = number_columns(msa, FALSE, i_am_rf, errbuf) != eslOK)) esl_fatal(errbuf);
590 }
591 /* Add annotation numbering all columns, if nec */
592 if( esl_opt_IsOn(go, "--num-all")) {
593 if((status = number_columns(msa, TRUE, i_am_rf, errbuf) != eslOK)) esl_fatal(errbuf);
594 }
595 /* Convert POST to PP annotation, if nec */
596 if(esl_opt_GetBoolean(go, "--post2pp")) {
597 if(msa->pp != NULL) esl_fatal("--post2pp enabled but alignment %d already has PP annotation.\n", nali);
598 if((status = convert_post_to_pp(msa, errbuf, nali)) != eslOK) esl_fatal(errbuf);
599 }
600 /* Impose consensus structure to get individual secondary structures, if nec */
601 if((esl_opt_GetBoolean(go, "--sindi")) || (esl_opt_GetBoolean(go, "--cindi"))) {
602 if((status = individualize_consensus(go, errbuf, msa) != eslOK)) esl_fatal(errbuf);
603 }
604
605 /****************************************************
606 * Handle 'in development' options, that are undocumented
607 * (only visible from the command line with --devhelp)
608 * These are even less stable than the other options.
609 ***************************************************/
610 /* --xmask option: expand the alignment to fit lanemask in xmask <f>, number of TOTAL msa columns must equal number of 1s in <f>. */
611 if(xmask != NULL) {
612 if((status = expand_msa2mask(errbuf, msa, xmask, &new_msa)) != eslOK) esl_fatal(errbuf);
613 esl_msa_Destroy(msa);
614 msa = new_msa;
615 }
616
617 /*******************************************************
618 * Handle the 'in development' cluster options. (--c-*)
619 * (these should probably go into a different miniapp eventually)
620 *******************************************************/
621 if(do_id_cluster || do_insert_cluster) {
622 if(msa->rf == NULL) esl_fatal("--c* options require #=GC RF annotation marking consensus columns.");
623 if(do_id_cluster) {
624 if(msa->rf == NULL) esl_fatal("Error, --cn-id, --cs-id and --cx-id require all alignments have #=GC RF anntotation, aln %d does not.", nali);
625 /* create distance matrix and infer tree by single linkage clustering */
626 /* first, remove all non-consensus columns */
627 rfmsa = esl_msa_Clone(msa);
628 if((status = esl_msa_ColumnSubset(rfmsa, errbuf, i_am_rf)) != eslOK) esl_fatal(errbuf);
629 dst_nongap_XDiffMx(rfmsa->abc, rfmsa->ax, rfmsa->nseq, &D);
630 esl_msa_Destroy(rfmsa);
631 rfmsa = NULL;
632 do_ctarget_nc = esl_opt_IsOn(go, "--cn-id");
633 do_ctarget_nsize = esl_opt_IsOn(go, "--cs-id");
634 do_cmindiff = esl_opt_IsOn(go, "--cx-id");
635 nc = esl_opt_IsOn(go, "--cn-id") ? esl_opt_GetInteger(go, "--cn-id") : 0;
636 nsize = esl_opt_IsOn(go, "--cs-id") ? esl_opt_GetInteger(go, "--cs-id") : 0;
637 mindiff = esl_opt_IsOn(go, "--cx-id") ? 1. - esl_opt_GetReal(go, "--cx-id") : 0;
638 }
639 else { /* do_insert_cluster, create insert distance matrix and infer tree by SLC */
640 if(msa->rf == NULL) esl_fatal("Error, --cn-ins, --cs-ins and --cx-ins require all alignments have #=GC RF anntotation, aln %d does not.", nali);
641 if((status = insert_x_diffmx(go, errbuf, msa, rflen, i_am_rf, TRUE, TRUE, &D)) != eslOK) esl_fatal(errbuf);
642 do_ctarget_nc = esl_opt_IsOn(go, "--cn-ins");
643 do_ctarget_nsize = esl_opt_IsOn(go, "--cs-ins");
644 do_cmindiff = esl_opt_IsOn(go, "--cx-ins");
645 nc = esl_opt_IsOn(go, "--cn-ins") ? esl_opt_GetInteger(go, "--cn-ins") : 0;
646 nsize = esl_opt_IsOn(go, "--cs-ins") ? esl_opt_GetInteger(go, "--cs-ins") : 0;
647 mindiff = esl_opt_IsOn(go, "--cx-ins") ? 1. - esl_opt_GetReal(go, "--cx-ins") : 0;
648 }
649 /* print out the id matrix if nec */
650 if( esl_opt_IsOn(go, "--c-mx")) {
651 for(i = 0; i < msa->nseq; i++) {
652 for(j = 0; j < msa->nseq; j++) {
653 fprintf(mxfp, "%5d %5d %-30s %-30s %.5f\n", i, j, msa->sqname[i], msa->sqname[j], 1. - D->mx[i][j]);
654 }
655 }
656 fclose(mxfp);
657 }
658 if((status = MSADivide(msa, D, do_cmindiff, do_ctarget_nc, do_ctarget_nsize, mindiff, nc, nsize, &nmsa, &cmsa, &xsize, errbuf)) != eslOK) esl_fatal(errbuf);
659 esl_msa_Destroy(msa);
660 msa = NULL;
661 nmin = esl_opt_IsOn(go, "--c-nmin") ? esl_opt_GetInteger(go, "--c-nmin") : 1;
662 for(m = 0; m < nmsa; m++) {
663 if(cmsa[m]->nseq >= nmin) {
664 status = esl_msafile_Write(ofp, cmsa[m], outfmt);
665 if (status == eslEMEM) esl_fatal("Memory error when outputting alignment\n");
666 else if (status != eslOK) esl_fatal("Writing alignment file failed with error %d\n", status);
667 }
668 esl_msa_Destroy(cmsa[m]);
669 }
670 free(cmsa);
671 }
672 else if ( esl_opt_IsOn(go, "--c-mx")) esl_fatal("--c-mx option requires at least one of: --cn-id, --cs-id, --cx-id, --cn-ins, --cs-ins, --cx-ins");
673 /*******************************
674 * End of cluster option block
675 *******************************/
676
677 /* handle the *in development* -M option, if enabled */
678 if( esl_opt_IsOn(go, "-M")) {
679 if((status = minorize_msa(go, msa, errbuf, ofp, esl_opt_GetString(go, "-M"), outfmt) != eslOK)) esl_fatal(errbuf);
680 }
681
682 /********************
683 * Output alignment *
684 ********************/
685 if(! esl_opt_IsOn(go, "-M")) { /* if -M, we already output the alignments in minorize_msa() */
686 status = esl_msafile_Write(ofp, msa, outfmt);
687 if (status == eslEMEM) esl_fatal("Memory error when outputting alignment\n");
688 else if (status != eslOK) esl_fatal("Writing alignment file failed with error %d\n", status);
689 }
690
691 /* Clean up for this msa */
692 esl_arr2_Destroy((void **) abc_ct, msa? msa->alen:0); abc_ct = NULL;
693 esl_arr2_Destroy((void **) pp_ct, msa? msa->alen:0); pp_ct = NULL;
694 esl_msa_Destroy(msa); msa = NULL;
695 esl_free(i_am_rf); i_am_rf = NULL;
696 esl_free(rf2a_map); rf2a_map = NULL;
697 } /* end loop over msa's */
698 if (nali == 0) esl_fatal("No alignments found in file %s\n", alifile);
699 } /* end of 'if (! esl_opt_IsOn(go, "--small"))' */
700
701 else
702 { /* --small enabled */
703 /* First, a paranoid check first, the following should never be false based on earlier checks */
704 if((! esl_opt_IsOn(go, "--seq-r")) && (! esl_opt_IsOn(go, "--seq-k"))) esl_fatal("--small requires either --seq-r or --seq-k");
705 /* We've already read list file <f>, seqlist holds the seqlist_n sequences read from <f> (<f> from either --seq-k <f> or --seq-r <f>) */
706 seqname_keyhash = esl_keyhash_Create();
707 for (n = 0; n < seqlist_n; n++)
708 {
709 status = esl_keyhash_Store(seqname_keyhash, seqlist[n], -1, NULL);
710 if(status == eslEDUP) { esl_fatal("Error sequence %s listed twice in a input list file.", seqlist[n]); }
711 else if (status != eslOK) { esl_fatal("Error adding sequence %s to keyhash", seqlist[n]); }
712 }
713
714 while ((status = esl_msafile2_RegurgitatePfam(afp2, ofp,
715 -1, -1, -1, -1, /* don't care about max width of fields */
716 TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, /* regurgitate all non-seq info */
717 esl_opt_IsOn(go, "--seq-k") ? seqname_keyhash : NULL, /* if --seq-k <f> keep seqs from list file <f> */
718 esl_opt_IsOn(go, "--seq-r") ? seqname_keyhash : NULL, /* if --seq-r <f> remove seqs from list file <f> */
719 NULL, NULL, -1, '.', &nseq_read, &nseq_regurged)) == eslOK)
720 {
721 nali++;
722 if (esl_opt_IsOn(go, "--seq-k") && (nseq_regurged != seqlist_n))
723 esl_fatal("Error, in alignment %d, did not find %d of the sequences listed in %s", nali, (seqlist_n - nseq_regurged), esl_opt_GetString(go, "--seq-k"));
724 else if (esl_opt_IsOn(go, "--seq-r") && ((nseq_read - nseq_regurged) != seqlist_n))
725 esl_fatal("Error, in alignment %d, did not find %d of the sequences listed in %s", nali, (seqlist_n - (nseq_read - nseq_regurged)), esl_opt_GetString(go, "--seq-r"));
726 }
727 }
728
729 /* Cleanup, normal return
730 */
731 if(seqlist != NULL) {
732 for(n = 0; n < seqlist_n; n++) if(seqlist[n] != NULL) free(seqlist[n]);
733 free(seqlist);
734 }
735
736 if(esl_opt_IsOn(go, "-o")) {
737 fclose(ofp);
738 if(nali > 1) printf("# %d alignments saved to file %s.\n", nali, esl_opt_GetString(go, "-o"));
739 else printf("# Alignment saved to file %s.\n", esl_opt_GetString(go, "-o"));
740 }
741 if(treefp != NULL) {
742 fclose(treefp);
743 printf("# Tree(s) saved in Newick format to file %s.\n", esl_opt_GetString(go, "--tree"));
744 }
745 if(mxfp != NULL) {
746 fclose(mxfp);
747 printf("# Distance matri{x,ces} saved to file %s.\n", esl_opt_GetString(go, "--c-mx"));
748 }
749 if(mask_for_rf != NULL){
750 free(mask_for_rf);
751 }
752 if(seqname_keyhash != NULL){
753 esl_keyhash_Destroy(seqname_keyhash);
754 }
755 if (esl_opt_GetBoolean(go, "--small")) esl_msafile2_Close(afp2);
756 else esl_msafile_Close(afp);
757 esl_alphabet_Destroy(abc);
758 esl_getopts_Destroy(go);
759
760 return 0;
761 }
762
763
764 /* write_rf_given_alen
765 *
766 * Given an MSA and a char string of 1s and 0s (a lanemask) of length
767 * msa->alen, write/rewrite RF positions as 'x' (non-gap) for 1, '.' (gap) for 0.
768 * If RF already exists AND do_keep_rf_chars == TRUE, do not modify non-gap RF columns
769 * if they are within mask ('1').
770 */
771 static int
772 write_rf_given_alen(ESL_MSA *msa, char *errbuf, int *i_am_rf, int do_keep_rf_chars, char *amask, int amask_len)
773 {
774 int status;
775 int64_t apos;
776
777 /* contract check, rfgiven_mask must be exact length of msa */
778 if(amask == NULL) ESL_FAIL(eslEINVAL, errbuf, "--mask2rf mask is NULL in write_rf_given, this shouldn't happen.\n");
779 if(amask_len != (int) strlen(amask)) { ESL_FAIL(eslEINVAL, errbuf, "write_rf_given_alen(), passed in mask len (%d) is not equal to actual mask length (%d)\n", amask_len, (int) strlen(amask)); }
780 if(amask_len != msa->alen)
781 ESL_FAIL(eslEINVAL, errbuf, "--mask2rf mask length: %d is not equal to the MSA length (%" PRId64 ")\n",
782 amask_len, msa->alen);
783 if(msa->rf == NULL) {
784 ESL_ALLOC(msa->rf, sizeof(char) * (msa->alen+1));
785 for (apos = 1; apos <= msa->alen; apos++) msa->rf[(apos-1)] = '.';
786 }
787
788 for (apos = 1; apos <= msa->alen; apos++) {
789 if (amask[(apos-1)] == '0') msa->rf[(apos-1)] = '.';
790 else if(amask[(apos-1)] == '1') {
791 if((! do_keep_rf_chars) || (i_am_rf == NULL) || (! i_am_rf[(apos-1)])) msa->rf[(apos-1)] = 'x'; /* else, msa has RF nongap char there already, leave it alone */
792 }
793 else ESL_FAIL(eslEINVAL, errbuf, "--mask2rf mask char number %" PRId64 " is not a 1 nor a 0, but a %c\n", apos, amask[(apos-1)]);
794 }
795
796 msa->rf[msa->alen] = '\0';
797 return eslOK;
798 ERROR:
799 return status;
800 }
801
802 /* write_rf_given_rflen
803 *
804 * Given an MSA and a char string of 1s and 0s (a lanemask) that is
805 * the same length as the non-gap RF annotation in msa, rewrite msa
806 * RF based as 'x' (non-gap) for 1, '.' (gap) for 0. 1s indicate which
807 * non-gap RF columns to keep as 'x', and 0s indicate which non-gap
808 * RF columns to make gaps '.'.
809 * If RF already exists, do not modify non-gap RF columns if they are
810 * within mask ('1').
811 */
812 static int
813 write_rf_given_rflen(ESL_MSA *msa, char *errbuf, int *i_am_rf, int do_keep_rf_chars, char *mask_for_rf, int mask_for_rf_len)
814 {
815 int64_t apos, rfpos;
816
817 /* contract check, mask must be exact length of msa */
818 if(mask_for_rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "--mask2rf mask is NULL in write_rf_given, this shouldn't happen.\n");
819 if(msa->rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "--mask2rf mask requires RF annotation in MSA (try -g)\n");
820 if(mask_for_rf_len != (int) strlen(mask_for_rf)) { ESL_FAIL(eslEINVAL, errbuf, "write_rf_given_rflen(), passed in mask len (%d) is not equal to actual mask length (%d).\n", mask_for_rf_len, (int) strlen(mask_for_rf)); }
821
822 rfpos = 0;
823 for (apos = 1; apos <= msa->alen; apos++) {
824 if(! esl_abc_CIsGap(msa->abc, msa->rf[(apos-1)])) {
825 rfpos++;
826 if (mask_for_rf[(rfpos-1)] == '0') msa->rf[(apos-1)] = '.';
827 else if(mask_for_rf[(rfpos-1)] == '1') {
828 if((! do_keep_rf_chars) || (i_am_rf == NULL) || (! i_am_rf[(apos-1)])) msa->rf[(apos-1)] = 'x'; /* else, msa has RF nongap char there already, leave it alone */
829 }
830 }
831 else msa->rf[(apos-1)] = '.';
832 }
833 if(rfpos != mask_for_rf_len) { ESL_FAIL(eslEINVAL, errbuf, "write_rf_given_rflen(), RF non-gap length (consensus length) (%" PRId64 ") is not equal to mask length (%d)\n", rfpos, mask_for_rf_len); }
834
835 msa->rf[msa->alen] = '\0';
836 return eslOK;
837 }
838
839 /* individualize_consensus
840 *
841 * Given an MSA with a consensus structure impose it to create
842 * individual secondary structures.
843 * If --cindi: copy all SS_cons basepairs
844 * If --sindi: omit and bp i,j if seq positions i and/or j is a gap in the seq
845 * with --sindi, dealigned seqs are still guaranteed to have valid consistent SS
846 */
847 static int
848 individualize_consensus(const ESL_GETOPTS *go, char *errbuf, ESL_MSA *msa)
849 {
850 int *ct = NULL; // 0..alen-1 base pair partners array SS_cons
851 int *sct = NULL; // 0..alen-1 base pair partners array for current sequence, used only for sanity check
852 int *removeme = NULL; // 0..alen TRUE/FALSE: do we keep this posn of SS_cons in cur seq SS (only used if --sindi)
853 int do_sindi;
854 int64_t apos;
855 int i;
856 int status;
857
858 if (msa->ss_cons == NULL) ESL_FAIL(eslEINVAL, errbuf, "--sindi requires MSA to have consensus structure annotation.\n");
859 if (! (msa->flags & eslMSA_DIGITAL)) ESL_FAIL(eslEINVAL, errbuf, "individualize_consensus() MSA is not digitized.\n");
860
861 do_sindi = esl_opt_GetBoolean(go, "--sindi") ? TRUE : FALSE;
862
863 ESL_ALLOC(ct, sizeof(int) * (msa->alen+1));
864 ESL_ALLOC(sct, sizeof(int) * (msa->alen+1));
865 ESL_ALLOC(removeme, sizeof(int) * (msa->alen+1));
866
867 /* All individual seqs will get a SS annotation.
868 * None, some, or all of them may already have one allocated.
869 * Fill out the allocation of msa->ss accordingly.
870 */
871 if (! msa->ss)
872 {
873 ESL_ALLOC(msa->ss, sizeof(char *) * msa->nseq);
874 for (i = 0; i < msa->nseq; i++) msa->ss[i] = NULL;
875 }
876 for (i = 0; i < msa->nseq; i++)
877 if (msa->ss[i] == NULL)
878 ESL_ALLOC(msa->ss[i], sizeof(char) * (msa->alen+1));
879
880
881 /* create the SS from each sequence but just copying the SS_cons
882 * annotation if --sindi, then remove basepair for which either
883 * position is a gap in the sequence (set the two paired positions
884 * in SS_cons to '.'). With --sindi, dealigned sequences/SS strings
885 * will still be guaranteed to be consistent, but that is not true
886 * with --cindi (basepairs with that are a gap in one but not both
887 * positions will introduce an inconsistency in the dealigned SS
888 * string).
889 *
890 * With --sindi, we could try to rebuild the SS using ct2wuss with
891 * ct from SS_cons after removing any basepairs with a gap, so that
892 * we get full WUSS notation for the SS strings no matter what, but
893 * if we did that the WUSS notation could change relative to the
894 * SS_cons, e.g. '(<><>)' would go to '<....>' if middle 4 bps are
895 * gaps (the way it is implemented here it will become '(....)').
896 * And that alternative ct2wuss strategy is more problematic in that
897 * pknot letters can change and even go from pknots to nested
898 * (e.g. A..a could go to <..>) depending on which other bps get
899 * removed. Note that with the current implementation, a subsequent
900 * esl-reformat --fullwuss call will reformat the individual SS
901 * lines output here to full wuss.
902 */
903 if (do_sindi) { /* only need the ct array if --sindi */
904 if (esl_wuss2ct(msa->ss_cons, msa->alen, ct) != eslOK)
905 ESL_FAIL(eslEINVAL, errbuf, "Consensus structure string is inconsistent or has too many pseudoknots.");
906 }
907
908 for (i = 0; i < msa->nseq; i++)
909 {
910 if (do_sindi)
911 {
912 esl_vec_ISet(removeme, (msa->alen+1), FALSE);
913 for (apos = 1; apos <= msa->alen; apos++)
914 {
915 if (esl_abc_XIsGap(msa->abc, msa->ax[i][apos]))
916 {
917 if (ct[apos] != 0)
918 {
919 removeme[apos] = TRUE;
920 removeme[ct[apos]] = TRUE;
921 }
922 }
923 }
924 for (apos = 1; apos <= msa->alen; apos++)
925 msa->ss[i][apos-1] = removeme[apos] ? '.' : msa->ss_cons[apos-1];
926 msa->ss[i][msa->alen] = '\0';
927
928 if (esl_wuss2ct(msa->ss[i], msa->alen, sct) != eslOK)
929 ESL_FAIL(eslEINVAL, errbuf, "Inconsistent SS after removing bps from SS_cons");
930 }
931 else // do_sindi is false, just copy the SS_cons
932 strcpy(msa->ss[i], msa->ss_cons);
933 }
934 free(ct);
935 free(sct);
936 free(removeme);
937 return eslOK;
938
939 ERROR:
940 if (ct) free(ct);
941 if (sct) free(sct);
942 if (removeme) free(removeme);
943 return status;
944 }
945
946
947 /* map_rfpos_to_apos
948 *
949 * Given an MSA, determine the alignment position of each
950 * non-gap RF (reference) position. The abc is only necessary
951 * for defining gap characters.
952 *
953 * rf2a_map[0..rfpos..rflen-1] = apos, apos is the alignment position (0..msa->alen-1) that
954 * is non-gap RF position rfpos+1 (for rfpos in 0..rflen-1)
955 */
956 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)
957 {
958 int status;
959 int rflen = 0;
960 int *rf2a_map = NULL;
961 int *i_am_rf = NULL;
962 int rfpos = 0;
963 int apos = 0;
964
965 /* contract check */
966 if(msa->rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "Error, trying to map RF positions to alignment positions, but msa->rf is NULL.");
967
968 /* count non-gap RF columns */
969 for(apos = 0; apos < msa->alen; apos++) {
970 if((! esl_abc_CIsGap(abc, msa->rf[apos])) &&
971 (! esl_abc_CIsMissing(abc, msa->rf[apos])) &&
972 (! esl_abc_CIsNonresidue(abc, msa->rf[apos])))
973 {
974 rflen++;
975 /* I don't use esl_abc_CIsResidue() b/c that would return FALSE for 'x' with RNA and DNA */
976 }
977 }
978 /* build map */
979 ESL_ALLOC(i_am_rf, sizeof(int) * msa->alen);
980 ESL_ALLOC(rf2a_map, sizeof(int) * rflen);
981 for(apos = 0; apos < msa->alen; apos++) {
982 if((! esl_abc_CIsGap(abc, msa->rf[apos])) &&
983 (! esl_abc_CIsMissing(abc, msa->rf[apos])) &&
984 (! esl_abc_CIsNonresidue(abc, msa->rf[apos]))) {
985 i_am_rf[apos] = TRUE;
986 rf2a_map[rfpos++] = apos;
987 }
988 else {
989 i_am_rf[apos] = FALSE;
990 }
991 }
992 *ret_i_am_rf = i_am_rf;
993 *ret_rf2a_map = rf2a_map;
994 *ret_rflen = rflen;
995 return eslOK;
996
997 ERROR:
998 if(i_am_rf != NULL) free(i_am_rf);
999 if(rf2a_map != NULL) free(rf2a_map);
1000 ESL_FAIL(status, errbuf, "Error, out of memory while mapping RF positions to alignment positions.");
1001 }
1002
1003
1004 /* read_sqfile
1005 *
1006 * Read all seqs in a sequence file and return them. Originally
1007 * written for --trim option.
1008 */
1009 static int read_sqfile(ESL_SQFILE *sqfp, const ESL_ALPHABET *abc, int nseq, ESL_SQ ***ret_sq)
1010 {
1011 int status;
1012 ESL_SQ **sq;
1013 int i;
1014
1015 /* get seqs from sqfile */
1016 ESL_ALLOC(sq, sizeof(ESL_SQ *) * (nseq + 1)); /* +1 for the last guy we allocate but don't use */
1017 i = 0;
1018 sq[i] = esl_sq_CreateDigital(abc);
1019 while ((status = esl_sqio_Read(sqfp, sq[i])) == eslOK) {
1020 i++;
1021 if(i > nseq) esl_fatal("With --trim, sequence file must have same number seqs as in <msafile>\n");
1022 sq[i] = esl_sq_CreateDigital(abc);
1023 }
1024 if (i != nseq) esl_fatal("With --trim, sequence file must have same number seqs as in <msafile>\n");
1025 /* status should be eslEOF on normal end; if it isn't, deal w/ error */
1026 esl_sq_Destroy(sq[i]); /* destroy final allocated but unused seq */
1027
1028 if (status == eslEFORMAT) esl_fatal("Parse failed (sequence file %s):\n%s\n",
1029 sqfp->filename, esl_sqfile_GetErrorBuf(sqfp));
1030 else if (status != eslEOF) esl_fatal("Unexpected error %d reading sequence file %s",
1031 status, sqfp->filename);
1032 esl_sqfile_Close(sqfp);
1033 *ret_sq = sq;
1034
1035 return eslOK;
1036
1037 ERROR:
1038 esl_fatal("Memory allocation error.");
1039 return status; /* NEVERREACHED */
1040 }
1041
1042
1043 /* trim_msa
1044 *
1045 * Given an MSA and unaligned 'trimmed' versions (subsequences) of all seqs in that MSA,
1046 * replace all chars that have been trimmed away (not in subsequences) with gaps in the MSA.
1047 *
1048 * We remove all GR and GC markup from the msa, except for possibly #=GC RF if <do_keeprf>
1049 * is TRUE, else we remove that too.
1050 */
1051 static int trim_msa(ESL_MSA *msa, ESL_SQ **sq, int do_keeprf, char *errbuf)
1052 {
1053 int status;
1054 int i, r;
1055 int apos, uapos;
1056 int astart, aend;
1057 int uastart, uaend;
1058 char *offset;
1059 char *aseq;
1060 char *uaseq;
1061 char *uasubseq;
1062 int *a2ua_map;
1063 int *ua2a_map;
1064 int ualen;
1065
1066 if(! (msa->flags & eslMSA_DIGITAL))
1067 ESL_FAIL(eslEINVAL, errbuf, "in trim_msa(), msa must be digitized.");
1068
1069 ESL_ALLOC(aseq, sizeof(char) * (msa->alen+1));
1070
1071 for(i = 0; i < msa->nseq; i++)
1072 {
1073 if (sq[i]->dsq == NULL) ESL_FAIL(eslEINVAL, errbuf, "in trim_msa(), sq's must be digitized.");
1074 if (sq[i]->n == 0) ESL_FAIL(eslEINVAL, errbuf, "in trim_msa(), sq[%d] is zero-length\n", i);
1075
1076 ESL_ALLOC(a2ua_map, sizeof(int) * (msa->alen+1));
1077 esl_vec_ISet(a2ua_map, (msa->alen+1), -1);
1078 uapos = apos = 1;
1079 while(apos <= msa->alen)
1080 {
1081 while(apos <= msa->alen && esl_abc_XIsGap(msa->abc, msa->ax[i][apos])) apos++;
1082 if(apos <= msa->alen) a2ua_map[apos] = uapos++;
1083 apos++;
1084 }
1085 ualen = uapos;
1086 ESL_ALLOC(ua2a_map, sizeof(int) * (ualen+1));
1087 ua2a_map[0] = -1;
1088 for(apos = 1; apos <= msa->alen; apos++)
1089 if(a2ua_map[apos] != -1)
1090 ua2a_map[a2ua_map[apos]] = apos;
1091
1092 ESL_ALLOC(uasubseq, sizeof(char) * (sq[i]->n+1));
1093 esl_abc_Textize(msa->abc, sq[i]->dsq, sq[i]->n, uasubseq);
1094 esl_abc_Textize(msa->abc, msa->ax[i], msa->alen, aseq);
1095
1096 esl_strdup(aseq, -1, &(uaseq));
1097 esl_strdealign(uaseq, uaseq, "-_.~", NULL);
1098 offset = strstr(uaseq, uasubseq); /* we'll replace the first occurence of uasubseq in uaseq */
1099 if(offset == NULL) ESL_FAIL(eslEINVAL, errbuf, "in trim_msa(), sq[%d] is not a subseq of msa seq %d\n", i, i);
1100 uastart = offset - uaseq + 1;
1101 uaend = uastart + strlen(uasubseq) - 1;
1102 astart = ua2a_map[uastart];
1103 aend = ua2a_map[uaend];
1104 free(ua2a_map);
1105 free(a2ua_map);
1106
1107 for(apos = 1; apos < astart; apos++) msa->ax[i][apos] = msa->abc->K; /* make it a gap */
1108 for(apos = aend + 1; apos <= msa->alen; apos++) msa->ax[i][apos] = msa->abc->K; /* make it a gap */
1109 free(uaseq);
1110 free(uasubseq);
1111 }
1112
1113 /* Free all per-column annotation that might now be invalid */
1114 if(! do_keeprf && msa->rf != NULL) { free(msa->rf); msa->rf = NULL; }
1115 if(msa->ss_cons != NULL) { free(msa->ss_cons); msa->ss_cons = NULL; }
1116 if(msa->sa_cons != NULL) { free(msa->sa_cons); msa->sa_cons = NULL; }
1117 if(msa->pp_cons != NULL) { free(msa->pp_cons); msa->pp_cons = NULL; }
1118
1119 /* Free all per-residue annotation (alternatively, we could just add gaps to the gaps we've created by
1120 * trimming, but this would cause problems for SS annotation, for example. */
1121 if(msa->ss != NULL) {
1122 for(i = 0; i < msa->nseq; i++) if(msa->ss[i] != NULL) { free(msa->ss[i]); }
1123 free(msa->ss);
1124 msa->ss = NULL;
1125 }
1126 if(msa->sa != NULL) {
1127 for(i = 0; i < msa->nseq; i++) if(msa->sa[i] != NULL) { free(msa->sa[i]); }
1128 free(msa->sa);
1129 msa->sa = NULL;
1130 }
1131 if(msa->pp != NULL) {
1132 for(i = 0; i < msa->nseq; i++) if(msa->pp[i] != NULL) { free(msa->pp[i]); }
1133 free(msa->pp);
1134 msa->pp = NULL;
1135 }
1136 if(msa->ngr > 0) {
1137 for(r = 0; r < msa->ngr; r++) {
1138 for(i = 0; i < msa->nseq; i++) if(msa->gr[r][i] != NULL) { free(msa->gr[r][i]); }
1139 free(msa->gr[r]);
1140 }
1141 if(msa->gr_idx != NULL) { esl_keyhash_Destroy(msa->gr_idx); msa->gr_idx = NULL; }
1142 msa->gr_idx = NULL;
1143 free(msa->gr);
1144 msa->gr = NULL;
1145 msa->ngr = 0;
1146 }
1147
1148 free(aseq);
1149 return eslOK;
1150
1151 ERROR:
1152 return status;
1153 }
1154
1155
1156 /* prune_msa_based_on_posteriors
1157 *
1158 * Given an MSA and a minimum posterior probability (PP) <min_pp>
1159 * value to keep, replace all residues that have posterior
1160 * probabilities < <min_pp> with gaps. The PP values for these
1161 * residues are replaced with gaps as well.
1162 *
1163 * We remove all GF, GS, GR and GC markup from the msa, except for GR
1164 * PP annotation and parsed GC annotation, like SS_cons, RF, SA_cons
1165 * and PP_cons.
1166 */
1167 static int prune_msa_based_on_posteriors(ESL_MSA *msa, float min_pp, char *errbuf)
1168 {
1169 double ppminA[11]; /* values of the 11 possible nongap PP values, '0'-'9' and '*', hardcoded here */
1170 float max_pp; /* max allowable min_pp value */
1171 int i, r; /* counters */
1172 int min_ppidx; /* index in ppminA[] corresponding to minimum allowed PP */
1173 int apos;
1174 int ppidx;
1175
1176 ppminA[0] = 0.00;
1177 ppminA[1] = 0.05;
1178 ppminA[2] = 0.15;
1179 ppminA[3] = 0.25;
1180 ppminA[4] = 0.35;
1181 ppminA[5] = 0.45;
1182 ppminA[6] = 0.55;
1183 ppminA[7] = 0.65;
1184 ppminA[8] = 0.75;
1185 ppminA[9] = 0.85;
1186 ppminA[10] = 0.95;
1187 max_pp = 0.95;
1188
1189 if(! (msa->flags & eslMSA_DIGITAL))
1190 ESL_FAIL(eslEINVAL, errbuf, "in prune_msa_based_on_posteriors(), msa must be digitized.");
1191 if(msa->pp == NULL)
1192 ESL_FAIL(eslEINVAL, errbuf, "in prune_msa_based_on_posteriors(), msa has no PP annotation.");
1193
1194 /* determine the index in ppminA of the minimum allowed PP */
1195 min_ppidx = 0;
1196 /* special case, check to see if max possible min_pp was passed in, this is 0.95 */
1197 if(esl_FCompare_old(min_pp, max_pp, eslSMALLX1) == eslOK) {
1198 min_ppidx = 10;
1199 }
1200 else if(min_pp > max_pp) {
1201 ESL_FAIL(eslERANGE, errbuf, "in prune_msa_based_on_posteriors(), min_pp (%f) is too large (max allowed is %f)\n", min_pp, max_pp);
1202 }
1203 else {
1204 while((min_ppidx < 10) && (min_pp > ppminA[min_ppidx])) {
1205 min_ppidx++;
1206 }
1207 }
1208
1209 /* replace all PP values less than our minimum, and their associated residues, with gaps */
1210 for(i = 0; i < msa->nseq; i++) {
1211 /* rename the sequence */
1212 if(msa->pp[i] != NULL) {
1213 for(apos = 1; apos <= msa->alen; apos++) {
1214 /* be wary off the off-by-one b/t msa->ax and msa->pp */
1215 if(! esl_abc_CIsGap(msa->abc, msa->pp[i][apos-1])) {
1216 ppidx = get_pp_idx(msa->abc, msa->pp[i][apos-1]);
1217 if(ppidx < min_ppidx) { /* not a gap, and less than our minimum */
1218 msa->ax[i][apos] = msa->abc->K; /* make this residue a gap */
1219 msa->pp[i][apos-1] = '.'; /* make the PP for this residue a gap */
1220 }
1221 }
1222 }
1223 }
1224 }
1225
1226 /* Free annotation in MSA because we can't be sure any of it is
1227 * valid anymore -- we've removed residues from the sequences (!)
1228 */
1229
1230 /* Free all per-file (GF) annotation */
1231 for(r = 0; r < msa->ngf; r++) {
1232 if(msa->gf[r] != NULL) free(msa->gf[r]);
1233 if(msa->gf_tag[r] != NULL) free(msa->gf_tag[r]);
1234 }
1235 if(msa->gf != NULL) { free(msa->gf); msa->gf = NULL; }
1236 if(msa->gf_tag != NULL) { free(msa->gf_tag); msa->gf_tag = NULL; }
1237 msa->ngf = 0;
1238
1239 /* Free all per-column (GC) annotation that might now be invalid,
1240 * we leave the parsed GC annotation, like SS_cons
1241 */
1242 for(r = 0; r < msa->ngc; r++) {
1243 if(msa->gc[r] != NULL) free(msa->gc[r]);
1244 if(msa->gc_tag[r] != NULL) free(msa->gc_tag[r]);
1245 }
1246 if(msa->gc != NULL) { free(msa->gc); msa->gc = NULL; }
1247 if(msa->gc_tag != NULL) { free(msa->gc_tag); msa->gc_tag = NULL; }
1248 if(msa->gc_idx != NULL) { esl_keyhash_Destroy(msa->gc_idx); msa->gc_idx = NULL; }
1249 msa->ngc = 0;
1250
1251 /* Free all per-sequence (GS) annotation */
1252 for(r = 0; r < msa->ngc; i++) {
1253 if(msa->gs[r] != NULL) {
1254 for(i = 0; i < msa->nseq; i++) {
1255 free(msa->gs[r][i]);
1256 }
1257 free(msa->gs[r]);
1258 }
1259 if(msa->gc_tag[r] != NULL) free(msa->gc_tag[r]);
1260 }
1261 if(msa->gs != NULL) { free(msa->gs); msa->gs = NULL; }
1262 if(msa->gs_tag != NULL) { free(msa->gs_tag); msa->gs_tag = NULL; }
1263 if(msa->gs_idx != NULL) { esl_keyhash_Destroy(msa->gs_idx); msa->gs_idx = NULL; }
1264 msa->ngs = 0;
1265
1266 /* Free all per-residue (GR) annotation (except PP) */
1267 if(msa->ss != NULL) {
1268 for(i = 0; i < msa->nseq; i++) if(msa->ss[i] != NULL) { free(msa->ss[i]); }
1269 free(msa->ss);
1270 msa->ss = NULL;
1271 }
1272 if(msa->sa != NULL) {
1273 for(i = 0; i < msa->nseq; i++) if(msa->sa[i] != NULL) { free(msa->sa[i]); }
1274 free(msa->sa);
1275 msa->sa = NULL;
1276 }
1277 if(msa->ngr > 0) {
1278 for(r = 0; r < msa->ngr; r++) {
1279 for(i = 0; i < msa->nseq; i++) if(msa->gr[r][i] != NULL) { free(msa->gr[r][i]); }
1280 free(msa->gr[r]);
1281 }
1282 if(msa->gr_idx != NULL) { esl_keyhash_Destroy(msa->gr_idx); msa->gr_idx = NULL; }
1283 msa->gr_idx = NULL;
1284 free(msa->gr);
1285 msa->gr = NULL;
1286 msa->ngr = 0;
1287 }
1288
1289 return eslOK;
1290 }
1291
1292 /* get_pp_idx
1293 *
1294 * Given a #=GR PP or #=GC PP_cons character, return the appropriate index
1295 * in a pp_ct[] vector.
1296 * '0' return 0;
1297 * '1' return 1;
1298 * '2' return 2;
1299 * '3' return 3;
1300 * '4' return 4;
1301 * '5' return 5;
1302 * '6' return 6;
1303 * '7' return 7;
1304 * '8' return 8;
1305 * '9' return 9;
1306 * '*' return 10;
1307 * gap return 11;
1308 *
1309 * Anything else (including missing or nonresidue) return -1;
1310 *
1311 * This mapping of PP chars to return values should probably be
1312 * stored in some internal map structure somewhere.
1313 */
1314 static int get_pp_idx(ESL_ALPHABET *abc, char ppchar)
1315 {
1316 if(esl_abc_CIsGap(abc, ppchar)) return 11;
1317 if(ppchar == '*') return 10;
1318 if(ppchar == '9') return 9;
1319 if(ppchar == '8') return 8;
1320 if(ppchar == '7') return 7;
1321 if(ppchar == '6') return 6;
1322 if(ppchar == '5') return 5;
1323 if(ppchar == '4') return 4;
1324 if(ppchar == '3') return 3;
1325 if(ppchar == '2') return 2;
1326 if(ppchar == '1') return 1;
1327 if(ppchar == '0') return 0;
1328 return -1;
1329 }
1330
1331 /* get_tree_order
1332 *
1333 * Given a tree, determine the branching order of the sequences
1334 * it represents by traversing it preorder.
1335 */
1336 static int get_tree_order(ESL_TREE *T, char *errbuf, int **ret_order)
1337 {
1338 int status;
1339 int opos = 0;
1340 int nd;
1341 int *order;
1342 ESL_STACK *pda;
1343 ESL_ALLOC(order, sizeof(int) * T->N);
1344
1345 opos = 0;
1346 pda = esl_stack_ICreate();
1347 esl_stack_IPush(pda, T->right[0]);
1348 esl_stack_IPush(pda, T->left[0]);
1349 while (esl_stack_IPop(pda, &nd) != eslEOD)
1350 {
1351 if (nd > 0) { /* a node */
1352 esl_stack_IPush(pda, T->right[nd]); /* index for right child */
1353 esl_stack_IPush(pda, T->left[nd]); /* index for left child */
1354 }
1355 else /* nd <= 0, a child */
1356 order[opos++] = nd * -1;
1357 }
1358 *ret_order = order;
1359 esl_stack_Destroy(pda);
1360 return eslOK;
1361
1362 ERROR:
1363 return status;
1364 }
1365
1366 /* reorder_msa
1367 *
1368 * Given an array specifying a new order for the sequences in
1369 * the MSA, reorder it by swapping pointers.
1370 */
1371 static int
1372 reorder_msa(ESL_MSA *msa, int *order, char *errbuf)
1373 {
1374 int status;
1375 char **tmp;
1376 ESL_ALLOC(tmp, sizeof(char *) * msa->nseq);
1377 int i, a;
1378
1379 /* contract check */
1380 /* 'order' must be have nseq elements, elements must be in range [0..nseq-1], no duplicates */
1381 int *covered;
1382 ESL_ALLOC(covered, sizeof(int) * msa->nseq);
1383 esl_vec_ISet(covered, msa->nseq, 0);
1384 for(i = 0; i < msa->nseq; i++) {
1385 /* printf("order[i:%4d]: %4d\n", i, order[i]);
1386 printf("covered[order[i:%4d]]: %4d\n", i, covered[order[i]]);
1387 */
1388 if(covered[order[i]]) ESL_FAIL(eslEINVAL, errbuf, "reorder_msa() order array has duplicate entries for i: %d\n", i);
1389 covered[order[i]] = 1;
1390 }
1391 free(covered);
1392
1393 /* swap aseq or ax (one or the other must be non-NULL) */
1394 if(msa->flags & eslMSA_DIGITAL) { /* digital MSA */
1395 ESL_DSQ **tmp_dsq;
1396 ESL_ALLOC(tmp_dsq, sizeof(ESL_DSQ *) * msa->nseq);
1397 for(i = 0; i < msa->nseq; i++) tmp_dsq[i] = msa->ax[i];
1398 for(i = 0; i < msa->nseq; i++) msa->ax[i] = tmp_dsq[order[i]];
1399 free(tmp_dsq);
1400 }
1401 else { /* text MSA */
1402 for(i = 0; i < msa->nseq; i++) tmp[i] = msa->aseq[i];
1403 for(i = 0; i < msa->nseq; i++) msa->aseq[i] = tmp[order[i]];
1404 }
1405
1406 /* swap sqnames (mandatory) */
1407 for(i = 0; i < msa->nseq; i++) tmp[i] = msa->sqname[i];
1408 for(i = 0; i < msa->nseq; i++) msa->sqname[i] = tmp[order[i]];
1409
1410 /* swap sqacc, if they exist */
1411 if(msa->sqacc != NULL) {
1412 for(i = 0; i < msa->nseq; i++) tmp[i] = msa->sqacc[i];
1413 for(i = 0; i < msa->nseq; i++) msa->sqacc[i] = tmp[order[i]];
1414 }
1415
1416 /* swap sqdesc, if they exist */
1417 if(msa->sqdesc != NULL) {
1418 for(i = 0; i < msa->nseq; i++) tmp[i] = msa->sqdesc[i];
1419 for(i = 0; i < msa->nseq; i++) msa->sqdesc[i] = tmp[order[i]];
1420 }
1421
1422 /* swap ss, if they exist */
1423 if(msa->ss != NULL) {
1424 for(i = 0; i < msa->nseq; i++) tmp[i] = msa->ss[i];
1425 for(i = 0; i < msa->nseq; i++) msa->ss[i] = tmp[order[i]];
1426 }
1427
1428 /* swap sa, if they exist */
1429 if(msa->sa != NULL) {
1430 for(i = 0; i < msa->nseq; i++) tmp[i] = msa->sa[i];
1431 for(i = 0; i < msa->nseq; i++) msa->sa[i] = tmp[order[i]];
1432 }
1433
1434 /* swap pp, if they exist */
1435 if(msa->pp != NULL) {
1436 for(i = 0; i < msa->nseq; i++) tmp[i] = msa->pp[i];
1437 for(i = 0; i < msa->nseq; i++) msa->pp[i] = tmp[order[i]];
1438 }
1439
1440 /* swap gs annotation, if it exists */
1441 for(a = 0; a < msa->ngs; a++) {
1442 for(i = 0; i < msa->nseq; i++) tmp[i] = msa->gs[a][i];
1443 for(i = 0; i < msa->nseq; i++) msa->gs[a][i] = tmp[order[i]];
1444 }
1445
1446 /* swap gr annotation, if it exists */
1447 for(a = 0; a < msa->ngr; a++) {
1448 for(i = 0; i < msa->nseq; i++) tmp[i] = msa->gr[a][i];
1449 for(i = 0; i < msa->nseq; i++) msa->gr[a][i] = tmp[order[i]];
1450 }
1451 free(tmp);
1452 return eslOK;
1453
1454 ERROR:
1455 return status;
1456 }
1457
1458 /* read_mask_file
1459 *
1460 * Given an open file pointer, read the first token of the
1461 * file and return it as *ret_mask. It must contain only
1462 * '0' or '1' characters.
1463 *
1464 * Returns: eslOK on success.
1465 */
1466 int
1467 read_mask_file(char *filename, char *errbuf, char **ret_mask, int *ret_mask_len)
1468 {
1469 int status;
1470 ESL_FILEPARSER *efp;
1471 char *tok;
1472 char *mask;
1473 int toklen;
1474 int n;
1475
1476 if (esl_fileparser_Open(filename, NULL, &efp) != eslOK) ESL_FAIL(eslFAIL, errbuf, "failed to open %s in read_mask_file\n", filename);
1477 esl_fileparser_SetCommentChar(efp, '#');
1478
1479 if((status = esl_fileparser_GetToken(efp, &tok, &toklen)) != eslOK) ESL_FAIL(eslFAIL, errbuf, "failed to read a single token from %s\n", filename);
1480
1481 ESL_ALLOC(mask, sizeof(char) * (toklen+1));
1482 for(n = 0; n < toklen; n++) {
1483 if((tok[n] == '0') || (tok[n] == '1')) {
1484 mask[n] = tok[n];
1485 }
1486 else { ESL_FAIL(eslFAIL, errbuf, "read a non-0 and non-1 character (%c) in the mask file %s\n", tok[n], filename); }
1487 }
1488 mask[n] = '\0';
1489
1490 *ret_mask = mask;
1491 *ret_mask_len = n;
1492 esl_fileparser_Close(efp);
1493 return eslOK;
1494
1495 ERROR:
1496 return eslEMEM;
1497 }
1498
1499
1500 /* expand_msa2mask
1501 *
1502 * Given an MSA <msa> and a lanemask <xmask> with exactly msa->alen 1s in it.
1503 * Add 100% gap columns in between each column as dictated by <xmask>.
1504 *
1505 * For example if lanemask is 100101, msa->alen is 3, we add 2 100% gap
1506 * columns after column 1, and 1 100% gap column after column 2, to make
1507 * the msa length = length(xmask) = 6.
1508 */
1509 static int
1510 expand_msa2mask(char *errbuf, ESL_MSA *msa, char *xmask, ESL_MSA **newmsa)
1511 {
1512 int status;
1513 int mpos;
1514 int masklen;
1515 int *nzeroesA;
1516 int nones = 0;
1517
1518 if(xmask == NULL) ESL_FAIL(eslEINVAL, errbuf, "expand_msa2mask(), xmask is NULL.");
1519
1520 masklen = strlen(xmask);
1521 /* count 1s in xmask */
1522 for (mpos = 0; mpos < masklen; mpos++) {
1523 if (xmask[mpos] == '1') nones++;
1524 else if(xmask[mpos] == '0') ; /* do nothing */
1525 else ESL_FAIL(eslEINVAL, errbuf, "--xmask mask char number %d is not a 1 nor a 0, but a %c\n", mpos+1, xmask[mpos]);
1526 }
1527 if(nones != msa->alen) ESL_FAIL(eslEINVAL, errbuf, "expand_msa2mask(), number of 1s in --xmask file: %d != msa->alen: %" PRId64 ", they must be equal.", nones, msa->alen);
1528
1529 /* determine number of 0s after each consensus column */
1530 nones = 0;
1531 ESL_ALLOC(nzeroesA, sizeof(int) * (masklen+1));
1532 esl_vec_ISet(nzeroesA, (masklen+1), 0);
1533 for (mpos = 0; mpos < masklen; mpos++) {
1534 if (xmask[mpos] == '1') nones++;
1535 else if(xmask[mpos] == '0') nzeroesA[nones]++;
1536 else ESL_FAIL(eslEINVAL, errbuf, "--xmask mask char number %d is not a 1 nor a 0, but a %c\n", mpos+1, xmask[mpos]);
1537 }
1538
1539 /*int i;
1540 for (i = 0; i <= nones; i++) {
1541 printf("nzeroes[%3d]: %3d\n", i, nzeroesA[i]);
1542 }*/
1543
1544 /* add the 100% gap columns */
1545 if((status = add_gap_columns_to_msa(errbuf, msa, nzeroesA, newmsa, TRUE)) != eslOK) return status ;
1546 /* new alen should equal masklen */
1547 if((*newmsa)->alen != masklen) ESL_FAIL(eslEINVAL, errbuf, "expand_msa2mask(), new msa->alen: (%" PRId64 ") != length of mask (%d), this shouldn't happen.", (*newmsa)->alen, masklen);
1548 free(nzeroesA);
1549
1550 return eslOK;
1551
1552 ERROR:
1553 return status;
1554 }
1555
1556 /* Function: msa_median_length()
1557 *
1558 * Purpose: Returns the median (unaligned) length of
1559 * the sequences in an alignment.
1560 */
1561 static int
1562 msa_median_length(ESL_MSA *msa)
1563 {
1564 int status;
1565 int *len;
1566 int i;
1567 int median;
1568 ESL_SQ *sq;
1569 sq = esl_sq_CreateDigital(msa->abc);
1570
1571 ESL_ALLOC(len, sizeof(int) * msa->nseq);
1572 for (i = 0; i < msa->nseq; i++) {
1573 esl_sq_GetFromMSA(msa, i, sq);
1574 len[i] = sq->n;
1575 esl_sq_Reuse(sq);
1576 }
1577
1578 qsort(len, msa->nseq, sizeof(int), compare_ints);
1579
1580 median = len[msa->nseq / 2];
1581 free(len);
1582
1583 esl_sq_Destroy(sq);
1584 return median;
1585
1586 ERROR:
1587 esl_fatal("msa_median_length() memory allocation error.");
1588 return 0.; /*NOTREACHED*/
1589 }
1590
1591
1592 /* Function: msa_remove_seqs_below_minlen()
1593 *
1594 * Purpose: Remove sequences in MSA whose dealigned length is less than a minimum length.
1595 * If <i_am_rf> is non-NULL, only consider positions that are nongap RF.
1596 */
1597 static int
1598 msa_remove_seqs_below_minlen(ESL_MSA *msa, float minlen, int *i_am_rf, ESL_MSA **ret_new_msa)
1599 {
1600 int status;
1601 int *useme; /* [0..msa->nseq-1]: 1 to keep sequence, 0 to remove it */
1602 int i, apos; /* sequence index, alignment position */
1603 int64_t len; /* length of current sequence, either nongap length (if i_am_rf == NULL) or nongap RF length (if i_am_rf != NULL) */
1604
1605 ESL_MSA *new_msa;
1606 ESL_SQ *sq;
1607 sq = esl_sq_CreateDigital(msa->abc);
1608
1609 ESL_ALLOC(useme, sizeof(int) * msa->nseq);
1610 for (i = 0; i < msa->nseq; i++) {
1611 if(i_am_rf != NULL) {
1612 len = 0;
1613 for(apos = 1; apos <= msa->alen; apos++) {
1614 if(i_am_rf[(apos-1)] && (! esl_abc_XIsGap(msa->abc, msa->ax[i][apos]))) len++;
1615 }
1616 }
1617 else { /* i_am_rf is NULL, consider the entire sequence */
1618 esl_sq_GetFromMSA(msa, i, sq);
1619 len = sq->n;
1620 esl_sq_Reuse(sq);
1621 }
1622 useme[i] = ((float) len >= minlen) ? TRUE : FALSE;
1623 /*printf("useme[i:%d]: %d (len: %" PRId64 ", minlen: %.2f)\n", i, useme[i], len, minlen);*/
1624 }
1625
1626 if(esl_vec_ISum(useme, msa->nseq) == 0) esl_fatal("No sequences at or above minimum allowed length.");
1627 if((status = esl_msa_SequenceSubset(msa, useme, &new_msa)) != eslOK) esl_fatal("esl_msa_SequenceSubset() had a problem.");
1628 free(useme);
1629 esl_sq_Destroy(sq);
1630 *ret_new_msa = new_msa;
1631 return eslOK;
1632
1633 ERROR:
1634 esl_fatal("msa_remove_seqs_below_minlen() memory allocation error.");
1635 return eslOK; /* NEVERREACHED */
1636 }
1637
1638
1639 /* Function: msa_remove_seqs_above_maxlen()
1640 *
1641 * Purpose: Remove sequences in MSA whose dealigned length is more than a maximum length.
1642 */
1643 static int
1644 msa_remove_seqs_above_maxlen(ESL_MSA *msa, float maxlen, ESL_MSA **ret_new_msa)
1645 {
1646 int status;
1647 int *useme;
1648 int i;
1649
1650 ESL_MSA *new_msa;
1651 ESL_SQ *sq;
1652 sq = esl_sq_CreateDigital(msa->abc);
1653
1654 ESL_ALLOC(useme, sizeof(int) * msa->nseq);
1655 for (i = 0; i < msa->nseq; i++) {
1656 esl_sq_GetFromMSA(msa, i, sq);
1657 useme[i] = ((float) sq->n <= maxlen) ? TRUE : FALSE;
1658 /*printf("useme[i:%d]: %d\n", i, useme[i]);*/
1659 esl_sq_Reuse(sq);
1660 }
1661
1662 if(esl_vec_ISum(useme, msa->nseq) == 0) esl_fatal("No sequences are less than maximum allowed length.");
1663 if((status = esl_msa_SequenceSubset(msa, useme, &new_msa)) != eslOK) esl_fatal("esl_msa_SequenceSubset() had a problem.");
1664 free(useme);
1665 esl_sq_Destroy(sq);
1666 *ret_new_msa = new_msa;
1667 return eslOK;
1668
1669 ERROR:
1670 esl_fatal("msa_remove_seqs_above_maxlen() memory allocation error.");
1671 return eslOK; /* NEVERREACHED */
1672 }
1673
1674 /* Function: msa_remove_truncated_seqs()
1675 *
1676 * Purpose: Remove sequences in MSA that have all gaps in the first <ntrunc> 5' leading
1677 * non-gap RF columns OR the last <ntrunc> 3' leading non-gap RF columns
1678 */
1679 static int
1680 msa_remove_truncated_seqs(ESL_MSA *msa, char *errbuf, int ntrunc, int *i_am_rf, ESL_MSA **ret_new_msa)
1681 {
1682 int status;
1683 int *useme;
1684 int i;
1685 int leading_okay, trailing_okay;
1686 int apos, rfpos_ct;
1687 int nused = 0;
1688 ESL_MSA *new_msa;
1689
1690 /* contract check */
1691 if(! (msa->flags & eslMSA_DIGITAL)) ESL_FAIL(eslEINVAL, errbuf, "in msa_remove_truncated_seqs(), msa must be digitized.");
1692 if(msa->rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "No #=GC RF markup in alignment, it is needed for --detrunc.");
1693 if(i_am_rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "internal error, msa_remove_truncated_seq() i_am_rf is NULL.");
1694
1695 ESL_ALLOC(useme, sizeof(int) * msa->nseq);
1696
1697 for(i = 0; i < msa->nseq; i++) {
1698 /* if ALL of the first 5' <ntrunc> non-gap RF columns are gaps in this seq, we'll remove it */
1699 leading_okay = FALSE;
1700 rfpos_ct = 0;
1701 apos = 1;
1702 while(!leading_okay && (rfpos_ct < ntrunc) && (apos <= msa->alen)) {
1703 if(i_am_rf[(apos-1)]) {
1704 rfpos_ct++;
1705 if(! esl_abc_XIsGap(msa->abc, msa->ax[i][apos])) leading_okay = TRUE;
1706 }
1707 apos++;
1708 }
1709
1710 trailing_okay = FALSE;
1711 rfpos_ct = 0;
1712 apos = msa->alen;
1713 while(!trailing_okay && (rfpos_ct < ntrunc) && (apos >= 1)) {
1714 if(i_am_rf[(apos-1)]) {
1715 rfpos_ct++;
1716 if(! esl_abc_XIsGap(msa->abc, msa->ax[i][apos])) trailing_okay = TRUE;
1717 }
1718 apos--;
1719 }
1720 useme[i] = (leading_okay && trailing_okay) ? TRUE : FALSE;
1721 if(useme[i]) nused++;
1722 }
1723 if(nused == 0) ESL_FAIL(eslEINVAL, errbuf, "--detrunc removed ALL sequences!");
1724 if((status = esl_msa_SequenceSubset(msa, useme, &new_msa)) != eslOK) esl_fatal("esl_msa_SequenceSubset() had a problem.");
1725 free(useme);
1726 *ret_new_msa = new_msa;
1727 return eslOK;
1728
1729 ERROR:
1730 ESL_FAIL(status, errbuf, "msa_remove_truncated_seqs(): memory allocation error.");
1731 return eslOK; /* NEVERREACHED */
1732 }
1733
1734
1735 /* Function: msa_remove_seqs_with_ambiguities()
1736 *
1737 * Purpose: Remove sequences in MSA that have more than <max_nambig> ambiguous residues.
1738 */
1739 static int
1740 msa_remove_seqs_with_ambiguities(ESL_MSA *msa, int max_nambig, ESL_MSA **ret_new_msa)
1741 {
1742 int status;
1743 int *useme;
1744 int i, j;
1745 int nambig;
1746
1747 ESL_MSA *new_msa;
1748 ESL_SQ *sq;
1749 sq = esl_sq_CreateDigital(msa->abc);
1750
1751 ESL_ALLOC(useme, sizeof(int) * msa->nseq);
1752 for (i = 0; i < msa->nseq; i++) {
1753 esl_sq_GetFromMSA(msa, i, sq);
1754 nambig = 0;
1755 for (j = 1; sq->dsq[j] != eslDSQ_SENTINEL; j++) {
1756 if (esl_abc_XIsDegenerate(sq->abc, sq->dsq[j])) nambig++;
1757 }
1758 useme[i] = (nambig > max_nambig) ? FALSE : TRUE;
1759 esl_sq_Reuse(sq);
1760 }
1761
1762 if((status = esl_msa_SequenceSubset(msa, useme, &new_msa)) != eslOK) esl_fatal("esl_msa_SequenceSubset() had a problem.");
1763 free(useme);
1764 esl_sq_Destroy(sq);
1765 *ret_new_msa = new_msa;
1766 return eslOK;
1767
1768 ERROR:
1769 esl_fatal("msa_remove_seqs_above_maxlen() memory allocation error.");
1770 return eslOK; /* NEVERREACHED */
1771 }
1772
1773 /* number_columns
1774 *
1775 * Add annotation to an MSA numbering the columns, either all
1776 * the columns (if <do_all>) or just non-gap #=GC RF columns.
1777 * If do_all is FALSE, i_am_rf must be non-NULL.
1778 */
1779 static int
1780 number_columns(ESL_MSA *msa, int do_all, int *i_am_rf, char *errbuf)
1781 {
1782 int status;
1783 int i;
1784 char *numstring;
1785 char *tag;
1786 int alen_ndigits;
1787 int tagwidth;
1788 int a,b,apos;
1789 int bmin;
1790 int pos2print;
1791 int tagidx;
1792
1793 /* contract check */
1794 if(!do_all && i_am_rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "number_columns() called but MSA has no #=GC RF annotation.");
1795
1796 alen_ndigits = int_ndigits(msa->alen);
1797 tagwidth = do_all ? (3+alen_ndigits) : (5+alen_ndigits); /* "COL.X" or RFCOL.X" */
1798
1799 ESL_ALLOC(tag, sizeof(char) * (tagwidth+1));
1800 ESL_ALLOC(numstring, sizeof(char) * (msa->alen+1));
1801 numstring[msa->alen] = '\0';
1802 tag[tagwidth] = '\0';
1803 if(do_all) {
1804 bmin = 3;
1805 tag[0] = 'C';
1806 tag[1] = 'O';
1807 tag[2] = 'L';
1808 }
1809 else {
1810 bmin = 5;
1811 tag[0] = 'R';
1812 tag[1] = 'F';
1813 tag[2] = 'C';
1814 tag[3] = 'O';
1815 tag[4] = 'L';
1816 }
1817
1818 for(a = 0; a < alen_ndigits; a++) {
1819 for(b = 0; b < alen_ndigits; b++) tag[b+bmin] = (a == b) ? 'X' : '.';
1820 pos2print = 1;
1821 for(apos = 1; apos <= msa->alen; apos++) {
1822 if(!do_all && (! i_am_rf[(apos-1)])) numstring[(apos-1)] = '.';
1823 else numstring[(apos-1)] = get_char_digit_x_from_int(pos2print++, (alen_ndigits-a));
1824 /*printf("called get_char_digit_x_from_int(%d, %d)\n",apos, (alen_ndigits-a));*/
1825 }
1826 /* If the tag already exists, free it's associated markup string. This is an awful hack. */
1827 for (tagidx = 0; tagidx < msa->ngc; tagidx++)
1828 if (strcmp(msa->gc_tag[tagidx], tag) == 0) break;
1829 if(tagidx != msa->ngc) { /* tag exists */
1830 free(msa->gc[tagidx]);
1831 msa->gc[tagidx] = NULL;
1832 }
1833
1834 esl_msa_AppendGC(msa, tag, numstring);
1835 }
1836 free(numstring); // Free this before we overwrite it on next line
1837 ESL_ALLOC(numstring, sizeof(char) * (msa->alen + 1));
1838 for(i = 0; i < msa->alen; i++) {
1839 numstring[i] = digit_to_char(i);
1840 }
1841 numstring[msa->alen] = '\0';
1842 free(tag);
1843 free(numstring);
1844 return eslOK;
1845
1846 ERROR:
1847 return eslEMEM;
1848 }
1849
1850
1851 /* digit_to_char
1852 *
1853 * Given a digit (0-9) return the character reprentation of it.
1854 * There must be a better way to do this; oh well.
1855 */
1856 static char
1857 digit_to_char(int digit)
1858 {
1859 if(digit == 0) return '0';
1860 if(digit == 1) return '1';
1861 if(digit == 2) return '2';
1862 if(digit == 3) return '3';
1863 if(digit == 4) return '4';
1864 if(digit == 5) return '5';
1865 if(digit == 6) return '6';
1866 if(digit == 7) return '7';
1867 if(digit == 8) return '8';
1868 if(digit == 9) return '9';
1869 else return '?';
1870 }
1871
1872 /* Function: int_ndigits
1873 * Returns: The number of digits in <i>.
1874 */
1875 static int
1876 int_ndigits(int i)
1877 {
1878 int n = 0;
1879 while(i > 0) { i/=10; n++; }
1880 return n;
1881 }
1882
1883 /* get_char_digit_x_from_int
1884 *
1885 * Given two integers <i> and <place> return the
1886 * character version of the <place>'th digit in <i>.
1887 * Example <i> = 14378 <place> = 4 would return 7.
1888 */
1889 static char
1890 get_char_digit_x_from_int(int i, int place)
1891 {
1892 int n,a,divisor;
1893 n = int_ndigits(i);
1894
1895 if(n < place) return digit_to_char(0);
1896
1897 divisor = 1;
1898 for(a = 0; a < (place-1); a++) divisor *= 10;
1899 /* subtract leading digits before the one we care about */
1900 i %= (divisor*10);
1901 return digit_to_char (i / divisor);
1902 }
1903
1904 /* Function: read_seq_name_file
1905 * Date: EPN, Thu Jun 5 13:21:36 2008
1906 *
1907 * Read a file listing sequence names to remove or keep.
1908 * Store sequences in *ret_seqlist and return it.
1909 * Each white-space delimited token is considered a
1910 * different sequence name. No checking is done in this
1911 * function, but rather in subsequent functions.
1912 *
1913 * Returns eslOK on success.
1914 */
1915 int
1916 read_seq_name_file(char *filename, char *errbuf, char ***ret_seqlist, int *ret_seqlist_n)
1917 {
1918 int status;
1919 ESL_FILEPARSER *efp;
1920 char *tok;
1921 int toklen;
1922 int nalloc = 10;
1923 int chunksize = 10;
1924 char **seqlist = NULL;
1925 int n = 0;
1926 int i;
1927 void *tmp;
1928
1929 ESL_ALLOC(seqlist, sizeof(char *) * nalloc);
1930 if (esl_fileparser_Open(filename, NULL, &efp) != eslOK) ESL_FAIL(eslEINVAL, errbuf, "failed to open %s in read_seq_name_file\n", filename);
1931
1932 while((status = esl_fileparser_GetToken(efp, &tok, &toklen)) != eslEOF) {
1933 if(n == nalloc) { nalloc += chunksize; ESL_RALLOC(seqlist, tmp, sizeof(char *) * nalloc); }
1934 if((status = esl_strdup(tok, -1, &(seqlist[n++]))) != eslOK) ESL_FAIL(status, errbuf, "error in esl_strdup.");
1935 }
1936 esl_fileparser_Close(efp);
1937 *ret_seqlist = seqlist;
1938 *ret_seqlist_n = n;
1939 return eslOK;
1940
1941 ERROR:
1942 if(seqlist != NULL) {
1943 for(i = 0; i < n; i++) free(seqlist[i]);
1944 free(seqlist);
1945 }
1946 return status;
1947 }
1948
1949
1950 /* Function: msa_keep_or_remove_seqs()
1951 *
1952 * Purpose: Given a list of <seqlist_n> sequences in <seqlist>, either remove those
1953 * sequences from msa, or remove all other sequences besides those from msa.
1954 * Create and return the new msa with only the specified seqs in <ret_new_msa>.
1955 *
1956 * Returns: eslOK on success, eslEINVAL if a sequence name in seqlist does not exist in the msa.
1957 *
1958 */
1959 static int
1960 msa_keep_or_remove_seqs(ESL_MSA *msa, char *errbuf, char **seqlist, int seqlist_n, int do_keep, int do_reorder, int nali, ESL_MSA **ret_new_msa)
1961 {
1962 int status;
1963 int *useme;
1964 int i, ip, n;
1965 int *order_all, *order_new;
1966
1967 ESL_MSA *new_msa;
1968 if(msa->index == NULL) ESL_FAIL(eslEINVAL, errbuf, "ERROR, msa->index is NULL!");
1969
1970 ESL_ALLOC(useme, sizeof(int) * msa->nseq);
1971 ESL_ALLOC(order_all, sizeof(int) * msa->nseq);
1972 ESL_ALLOC(order_new, sizeof(int) * seqlist_n);
1973 esl_vec_ISet(order_all, msa->nseq, -1);
1974
1975 if(do_keep) esl_vec_ISet(useme, msa->nseq, FALSE);
1976 else esl_vec_ISet(useme, msa->nseq, TRUE);
1977
1978 for(n = 0; n < seqlist_n; n++) {
1979 if((status = esl_keyhash_Lookup(msa->index, seqlist[n], -1, &i)) == eslENOTFOUND)
1980 ESL_FAIL(status, errbuf, "Error sequence %s does not exist in alignment %d", seqlist[n], nali);
1981 useme[i] = do_keep ? TRUE : FALSE;
1982 if(order_all[i] != -1) ESL_FAIL(eslEINVAL, errbuf, "ERROR sequence %s listed twice in a input list file.", seqlist[n]);
1983 order_all[i] = n;
1984 }
1985
1986 if(esl_vec_ISum(useme, msa->nseq) == 0) esl_fatal("No sequences remaining in the alignment!.");
1987 if((status = esl_msa_SequenceSubset(msa, useme, &new_msa)) != eslOK) esl_fatal("esl_msa_SequenceSubset() had a problem.");
1988 /* if do_keep, reorder to order of names in the list file */
1989 if(do_keep && do_reorder) {
1990 ip = 0;
1991 for(i = 0; i < msa->nseq; i++) {
1992 if(order_all[i] != -1) order_new[order_all[i]] = ip++;
1993 }
1994 if((status = reorder_msa(new_msa, order_new, errbuf)) != eslOK) return status;
1995 }
1996
1997 free(useme);
1998 free(order_all);
1999 free(order_new);
2000 *ret_new_msa = new_msa;
2001 return eslOK;
2002
2003 ERROR:
2004 esl_fatal("msa_keep_or_remove_seqs() memory allocation error.");
2005 return eslOK; /* NEVERREACHED */
2006 }
2007
2008 /* Function: insert_x_pair_shared()
2009 * Synopsis: Calculate the fraction of inserts shared between of two aligned digital seqs.
2010 * Incept: EPN, Wed Jun 25 10:33:23 2008
2011 *
2012 * Purpose: Returns the fraction of the total
2013 * number of inserts in both sequences that are shared.
2014 * An 'insert' is present in sequence s for consensus column
2015 * (non-gap RF column) c if at least 1 residue exists between
2016 * consensus column c and c+1. If sequence t also has an insert
2017 * between c and c+1, they share that insert. If that were the
2018 * only insert in either of the two sequences, then they would
2019 * share 1.0 fraction of inserts.
2020 *
2021 * Args: msa - MSA, digitized, with RF annotation
2022 * i_am_rf - [0..msa->alen-1], TRUE if apos is a nongap RF column, FALSE if not
2023 * i - index of seq 1
2024 * j - indes of seq 2
2025 * cfirst - first consensus position to consider
2026 * clast - last consensus position to consider
2027 * opt_pshared - optRETURN: pairwise insert identity, 0<=x<=1
2028 * opt_nshared - optRETURN: # of inserts shared
2029 * opt_nins - optRETURN: nins
2030 *
2031 * Returns: <eslOK> on success. <opt_distance>, <opt_nid>, <opt_n>
2032 * contain the answers, for any of these that were passed
2033 * non-<NULL> pointers.
2034 *
2035 * Throws: <eslEINVAL> if the strings are different lengths (not aligned).
2036 */
2037 int
2038 insert_x_pair_shared(ESL_MSA *msa, int *i_am_rf, int i, int j, int cfirst, int clast, double *opt_pshared, int *opt_nshared, int *opt_nins)
2039 {
2040 int shared; /* total shared inserts */
2041 int nins; /* number of inserts in either sequence */
2042 int apos; /* position in aligned seqs */
2043 int rfpos;
2044 int insi, insj;
2045 int seen_insert = FALSE;
2046 shared = nins = 0;
2047
2048 rfpos = 0;
2049 for(apos = 1; apos <= msa->alen; apos++)
2050 {
2051 if(! esl_abc_CIsGap(msa->abc, msa->rf[(apos-1)])) {
2052 rfpos++;
2053 seen_insert = FALSE;
2054 }
2055 else { /* not a consensus column, an insert column */
2056 insi = (! esl_abc_XIsGap(msa->abc, msa->ax[i][apos]));
2057 insj = (! esl_abc_XIsGap(msa->abc, msa->ax[j][apos]));
2058 if(rfpos >= cfirst && rfpos <= clast) {
2059 if(insi && insj && !seen_insert) shared++;
2060 if((insi || insj) && !seen_insert) { nins++; seen_insert = TRUE; }
2061 }
2062 }
2063 }
2064 /*if (opt_pshared != NULL) *opt_pshared = ( nins==0 ? 0. : (double) shared / (double) nins );*/
2065 if (opt_pshared != NULL) *opt_pshared = ( nins==0 ? 1. : (double) shared / (double) nins );
2066 if (opt_nshared != NULL) *opt_nshared = shared;
2067 if (opt_nins != NULL) *opt_nins = nins;
2068 return eslOK;
2069 }
2070
2071
2072 /* Function: insert_x_pair_shared_length()
2073 * Synopsis: Calculate the fraction of inserts shared between of two aligned digital seqs,
2074 * weighted by the length of the inserts.
2075 * Incept: EPN, Wed Jun 25 10:33:23 2008
2076 *
2077 * Purpose: Returns the weighted fraction of the total
2078 * number of inserts in both sequences that are shared.
2079 *
2080 * Args: msa - MSA, digitized, with RF annotation
2081 * i - index of seq 1
2082 * j - indes of seq 2
2083 * cfirst - first consensus position to consider
2084 * clast - last consensus position to consider
2085 * opt_pshared - optRETURN: pairwise insert identity, 0<=x<=1
2086 * opt_nshared - optRETURN: weighted # inserts shared
2087 * opt_nins - optRETURN: nins, number of columns with an insert
2088 *
2089 * Returns: <eslOK> on success. <opt_distance>, <opt_nid>, <opt_n>
2090 * contain the answers, for any of these that were passed
2091 * non-<NULL> pointers.
2092 *
2093 * Throws: <eslEINVAL> if the strings are different lengths (not aligned).
2094 */
2095 int
2096 insert_x_pair_shared_length(ESL_MSA *msa, int *i_am_rf, int i, int j, int cfirst, int clast, double *opt_pshared, double *opt_nshared, int *opt_nins)
2097 {
2098 double shared; /* weighted shared inserts */
2099 int nins; /* number of inserts in either sequence */
2100 int apos; /* position in aligned seqs */
2101 int rfpos;
2102 int leni, lenj;
2103 shared = nins = leni = lenj = 0;
2104
2105 rfpos = 0;
2106 for(apos = 1; apos <= msa->alen; apos++)
2107 {
2108 if(i_am_rf[(apos-1)]) {
2109 rfpos++;
2110 if(rfpos >= cfirst && rfpos <= clast) {
2111 if((leni + lenj) > 0) {
2112 nins++;
2113 if(leni >= lenj) shared += (double) lenj / (double) leni;
2114 else shared += (double) leni / (double) lenj;
2115 }
2116 leni = lenj = 0;
2117 }
2118 }
2119 else { /* not a consensus column, an insert column */
2120 if(! esl_abc_XIsGap(msa->abc, msa->ax[i][apos])) leni++;
2121 if(! esl_abc_XIsGap(msa->abc, msa->ax[j][apos])) lenj++;
2122 }
2123 }
2124 /*if (opt_pshared != NULL) *opt_pshared = ( nins==0 ? 0. : (double) shared / (double) nins );*/
2125 if (opt_pshared != NULL) *opt_pshared = ( nins==0 ? 1. : (double) shared / (double) nins );
2126 if (opt_nshared != NULL) *opt_nshared = shared;
2127 if (opt_nins != NULL) *opt_nins = nins;
2128 return eslOK;
2129 }
2130
2131 /* Function: insert_x_diffmx()
2132 * Synopsis: NxN insert difference matrix for N aligned digital seqs.
2133 * Incept: EPN, Wed Jun 25 10:25:01 2008
2134 *
2135 * Purpose: For each pair of sequences calculates the fraction of number
2136 * of inserts that are different between the two sequences.
2137 * An 'insert' is present in sequence s for consensus column
2138 * (non-gap RF column) c if at least 1 residue exists between
2139 * consensus column c and c+1. If sequence t also has an insert
2140 * between c and c+1, they share that insert. If that were the
2141 * only insert in either of the two sequences, then they would
2142 * share 1.0 fractional insert id, and 1.0 - 1.0 = 0.0 fractional
2143 * insert difference, thus the insert diff mx entry between
2144 * seq s and t would be 0.0.
2145 *
2146 * Args: go - command-line options
2147 * errbuf - for printing error messages
2148 * msa - aligned dsq's, [0..N-1][1..alen]
2149 * do_length_weight - weight insert similarity by length of inserts
2150 * do_only_internal_inserts - TRUE to only count inserts that are at positions
2151 * internal to both seq i, j (don't count those truncated off in either seq)
2152 * ret_D - RETURN: NxN matrix of fractional differences
2153 *
2154 * Returns: <eslOK> on success, and <ret_D> contains the difference
2155 * matrix; caller is obligated to free <D> with
2156 * <esl_dmatrix_Destroy()>.
2157 *
2158 * Throws: <eslEINVAL> if a seq has a different
2159 * length than others. On failure, <ret_D> is returned <NULL>
2160 * and state of inputs is unchanged.
2161 */
2162 int
2163 insert_x_diffmx(const ESL_GETOPTS *go, char *errbuf, ESL_MSA *msa, int rflen, int *i_am_rf, int do_length_weight, int do_only_internal_inserts, ESL_DMATRIX **ret_D)
2164 {
2165 int status;
2166 ESL_DMATRIX *D = NULL;
2167 int i,j;
2168 int N = msa->nseq;
2169 int nshared;
2170 double nshared_len;
2171 int nins;
2172 int *firstA, *lastA; /* [0..i..nseq-1] first and last consensus column occupied by seq i, only used if do_only_internal_inserts == TRUE */
2173 int ifirst, ilast, jfirst, jlast;
2174
2175 if(msa->rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "No #=GC RF markup in alignment.");
2176 if(! (msa->flags & eslMSA_DIGITAL)) ESL_FAIL(eslEINVAL, errbuf, "insert_x_diffmx() MSA is not digitized.\n");
2177
2178 if (( D = esl_dmatrix_Create(N,N) ) == NULL) esl_fatal(errbuf);
2179 if ((status = determine_first_last_consensus_columns(msa, errbuf, i_am_rf, rflen, &firstA, &lastA)) != eslOK) return status;
2180
2181 /* TEMP for (i = 0; i < N; i++) printf("i: %4d %4d %4d\n", i, firstA[i], lastA[i]); */
2182
2183 for (i = 0; i < N; i++)
2184 {
2185 D->mx[i][i] = 0.;
2186 ifirst = do_only_internal_inserts ? firstA[i] : 0;
2187 ilast = do_only_internal_inserts ? lastA[i] : rflen;
2188 for (j = i+1; j < N; j++)
2189 {
2190 jfirst = do_only_internal_inserts ? firstA[j] : 0;
2191 jlast = do_only_internal_inserts ? lastA[j] : rflen;
2192 if(do_length_weight) {
2193 status = insert_x_pair_shared_length(msa, i_am_rf, i, j, ESL_MAX(ifirst, jfirst), ESL_MIN(ilast, jlast), &(D->mx[i][j]), &nshared_len, &nins);
2194 /* if(esl_opt_GetBoolean(go, "--verbose")) printf("D %4d %4d %.3f %8.3f of %4d\n", i, j, 1. - D->mx[i][j], nshared_len, nins); */
2195 }
2196 else {
2197 status = insert_x_pair_shared(msa, i_am_rf, i, j, ESL_MAX(ifirst, jfirst), ESL_MIN(ilast, jlast), &(D->mx[i][j]), &nshared, &nins);
2198 /* if(esl_opt_GetBoolean(go, "--verbose")) printf("D %4d %4d %.3f %4d of %4d\n", i, j, 1. - D->mx[i][j], nshared, nins); */
2199 }
2200 D->mx[i][j] = 1. - D->mx[i][j]; /* convert from id to distance */
2201 if (status != eslOK) ESL_XEXCEPTION(status, "Pairwise insert identity calculation failed at seqs %d,%d\n", i,j);
2202 D->mx[j][i] = D->mx[i][j];
2203 }
2204 /* if(esl_opt_GetBoolean(go, "--verbose")) printf("\n"); */
2205 }
2206 if (ret_D != NULL) *ret_D = D; else esl_dmatrix_Destroy(D);
2207 return eslOK;
2208
2209 ERROR:
2210 if (D != NULL) esl_dmatrix_Destroy(D);
2211 if (ret_D != NULL) *ret_D = NULL;
2212 return status;
2213 }
2214
2215 /* Function: MSADivide()
2216 * From Infernal's cmbuild.c
2217 * EPN, Wed Mar 21 17:26:39 2007
2218 *
2219 * Purpose: Given an MSA and a distance matrix, divide the MSA it into
2220 * multiple MSAs, each with a different cluster of the original
2221 * sequences. Where clusters are defined by single linkage
2222 * clustering based on the distance matrix.
2223 *
2224 * Different modes:
2225 *
2226 * 1. if(do_mindiff): define clusters
2227 * such that we maximize the number of clusters while
2228 * satisfying: minimum fractional difference b/t any
2229 * 2 seqs in different clusters >= 'mindiff'.
2230 * The contract states that mindiff > 0. in this case.
2231 *
2232 * 2. if(do_nc): define clusters
2233 * such that we have exactly 'target_nc' clusters by
2234 * searching for the 'mindiff' that gives exactly
2235 * 'target_nc' clusters. (We guarantee we can do this
2236 * by rounding 'diff' fractional difference values b/t
2237 * seqs to nearest 0.001).
2238 *
2239 * 3. if(do_nsize): define clusters
2240 * such that we have 1 cluster that has at least nsize
2241 * sequences in it by searching for the 'mindiff' that
2242 * achieves that.
2243 *
2244 * Args:
2245 * ESL_MSA *mmsa - the master MSA, we cluster the seqs in this guy
2246 * and build a new MSA from each cluster
2247 * ESL_DMATRIX *D; - the distance matrix
2248 * int do_mindiff - TRUE (mode 1): satisfy clusters are at least mindiff different
2249 * int do_nc - TRUE (mode 2): set mindiff such that we get exactly target_nc clusters
2250 * int do_nsize - TRUE (mode 3): set mindiff such that we get 1 cluster with nsize seqs
2251 * float mindiff - the minimum fractional difference allowed between 2 seqs of different clusters
2252 * (0. indicates mode 2 or 3)
2253 * int target_nc - if(do_nc) number of clusters to define, else irrelevant
2254 * int target_nsize - if(do_nsize) min size of largets cluster, else irrelevant
2255 * int *ret_num_msa - number of MSAs in ret_MSA
2256 * ESL_MSA ***ret_cmsa - new MSAs, one for each cluster
2257 * ESL_MSA *ret_xsize - max size of a cluster
2258 * char *errbuf - buffer for error messages
2259 *
2260 * Return: ret_cmsa (alloc'ed here) and ret_num_msa
2261 */
2262 int
2263 MSADivide(ESL_MSA *mmsa, ESL_DMATRIX *D, int do_mindiff, int do_nc, int do_nsize, float mindiff, int target_nc,
2264 int target_nsize, int *ret_num_msa, ESL_MSA ***ret_cmsa, int *ret_xsize, char *errbuf)
2265 {
2266 int status; /* Easel status code */
2267 ESL_MSA **cmsa = NULL;/* the new MSAs we're creating from clusters of seqs in mmsa */
2268 int i; /* counter over sequences */
2269 int m; /* counter over new MSAs */
2270 int n; /* counter over tree nodes */
2271 ESL_TREE *T = NULL;/* the tree, created by Single-Linkage Clustering */
2272 double *diff = NULL; /* [0..T->N-2], diff[n]= min distance between any leaf in right and
2273 * left subtree of node n of tree T */
2274 double *minld = NULL;/* [0..T->N-2], min dist from node to any taxa in left subtree */
2275 double *minrd = NULL;/* [0..T->N-2], min dist from node to any taxa in right subtree */
2276 int nc; /* number of clusters/MSAs */
2277 int *clust = NULL;/* [0..T->N-1], cluster number (0..nc-1) this seq is in */
2278 int *csize = NULL;/* [0..nc-1], size of each cluster */
2279 int **useme = NULL;/* [0.m.nc-1][0.i.N] TRUE to use seq i in new MSA m, FALSE not to */
2280 int best; /* 'best' node, returned by select_node() */
2281 int xsize; /* size of cluster under 'best' node (largest cluster) */
2282
2283 /* Contract check */
2284 if((do_nc + do_mindiff + do_nsize) != 1) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() exactly 1 of do_nc, do_mindiff, do_nsize must be TRUE.");
2285 if( do_nc && target_nc == 0) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() target_nc is 0 but do_nc is TRUE!");
2286 if( do_nsize && target_nsize == 0) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() target_nsize is 0 but do_nsize is TRUE!");
2287 if( do_mindiff && mindiff <= 0.) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() mindiff is <= 0. but do_mindiff is TRUE!");
2288 if( do_mindiff && target_nc != 0) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() do_mindiff is TRUE, but target_nc != 0");
2289 if( do_mindiff && target_nsize != 0) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() do_mindiff is TRUE, but target_nsize != 0");
2290 /* mmsa must be digital */
2291 if(!(mmsa->flags & eslMSA_DIGITAL)) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() MSA is not digital.");
2292
2293 if(do_nc || do_nsize) mindiff = 0.;
2294
2295 /* Infer tree by single linkage clustering given the distance matrix */
2296 if((status = esl_tree_SingleLinkage(D, &T)) != eslOK) ESL_FAIL(status, errbuf, "esl_tree_SingleLinkage() error, status: %d", status);
2297 if((status = esl_tree_SetTaxaParents(T)) != eslOK) ESL_FAIL(status, errbuf, "esl_tree_SetTaxaParentse() error, status: %d", status);
2298 /*esl_tree_WriteNewick(stdout, T);*/
2299 if((status = esl_tree_Validate(T, errbuf) != eslOK)) return status;
2300
2301 /* determine the diff values:
2302 * (use: n_child > n, unless n's children are taxa)
2303 * diff[n] is minimum distance between any taxa (leaf) in left subtree of
2304 * n to any taxa in right subtree of n.
2305 */
2306 ESL_ALLOC(diff, (sizeof(double) * (T->N - 1))); /* one for each node */
2307 ESL_ALLOC(minld, (sizeof(double) * (T->N - 1)));
2308 ESL_ALLOC(minrd, (sizeof(double) * (T->N - 1)));
2309 for (n = (T->N-2); n >= 0; n--) {
2310 minld[n] = T->ld[n] + ((T->left[n] > 0) ? (minld[T->left[n]]) : 0);
2311 minrd[n] = T->rd[n] + ((T->right[n] > 0) ? (minrd[T->right[n]]) : 0);
2312 diff[n] = minld[n] + minrd[n];
2313 diff[n] *= 1000.;
2314 diff[n] = (float) ((int) diff[n]);
2315 diff[n] /= 1000.;
2316 /*printf("diff[n:%d]: %f\n", n, diff[n]);*/
2317 }
2318 free(minld); minld = NULL;
2319 free(minrd); minrd = NULL;
2320 /*for (n = 0; n < (T->N-1); n++)
2321 printf("diff[n:%d]: %f\n", n, diff[n]);
2322 for (n = 0; n < (T->N-1); n++)
2323 printf("left[n:%d]: %d right[n:%d]: %d\n", n, T->left[n], n, T->right[n]);*/
2324
2325 if(do_mindiff) { /* Mode 1 */
2326 /* Define clusters that are at least mindiff different
2327 * from each other. */
2328 if((status = select_node(T, diff, mindiff, &clust, &nc, &xsize, &best, errbuf)) != eslOK) return status;
2329 printf("# Alignment split into %d clusters\n", nc);
2330 printf("# Maximum identity b/t any 2 seqs in different clusters: %.2f\n", (1.-mindiff));
2331 printf("# Largest cluster contains %d sequences.\n", xsize);
2332 printf("#\n");
2333 }
2334 else if (do_nc) { /* Mode 2, do_nc == TRUE, mindiff was set to 0.0 above */
2335 /* Find the minimum fractional difference (mindiff) that
2336 * gives exactly target_nc clusters, also define clusters
2337 * based on that mindiff, this is all done with find_mindiff(),
2338 * which does a binary search for mindiff, we're guaranteed to
2339 * find exactly target_nc clusters b/c diff values are rounded
2340 * to nearest 0.001. */
2341 if(target_nc > (T->N)) target_nc = T->N; /* max num clusters is num seqs */
2342 if((status = find_mindiff(T, diff, FALSE, target_nc, &clust, &nc, &xsize, &best, &mindiff, errbuf)) != eslOK) return status;
2343 printf("# Alignment split into %d clusters.\n", nc);
2344 printf("# Maximum identity b/t any 2 seqs in different clusters: %.2f\n", (1.-mindiff));
2345 printf("# Largest cluster contains %d sequences.\n", xsize);
2346 printf("#\n");
2347 }
2348 else { /* Mode 3, do_nsize == TRUE, mindiff was set to 0.0 above */
2349 /* Find the minimum fractional difference (mindiff) that
2350 * gives 1 cluster with size of at least <target_nsize> sequences
2351 * based on that mindiff, this is all done with find_mindiff(),
2352 * which does a binary search for mindiff.
2353 */
2354 if(target_nsize > (T->N)) target_nsize = T->N; /* max num clusters is num seqs */
2355 if((status = find_mindiff(T, diff, TRUE, target_nsize, &clust, &nc, &xsize, &best, &mindiff, errbuf)) != eslOK) return status;
2356 printf("# Alignment split into %d clusters.\n", nc);
2357 printf("# Largets cluster contains %d sequences.\n", xsize);
2358 printf("# Maximum identity b/t any 2 seqs in different clusters: %.2f\n", (1.-mindiff));
2359 printf("#\n");
2360 }
2361 /* Determine the size of each cluster */
2362 ESL_ALLOC(csize, (sizeof(int) * (nc)));
2363 esl_vec_ISet(csize, nc, 0);
2364 for(i = 0; i < mmsa->nseq; i++)
2365 csize[clust[i]]++;
2366
2367 /* Create one new MSA for each cluster,
2368 * if(do_orig): keep the original MSA as cmsa[nc] */
2369 ESL_ALLOC(cmsa, (sizeof(ESL_MSA *) * (nc)));
2370 for(m = 0; m < nc; m++) cmsa[m] = NULL;
2371
2372 ESL_ALLOC(useme, (sizeof(int *) * (nc+1)));
2373 for(m = 0; m <= nc; m++) {
2374 ESL_ALLOC(useme[m], (sizeof(int)) * mmsa->nseq);
2375 if(m < nc) esl_vec_ISet(useme[m], mmsa->nseq, FALSE);
2376 else esl_vec_ISet(useme[m], mmsa->nseq, TRUE); /* keep all seqs in cmsa[nc]*/
2377 }
2378
2379 for(i = 0; i < mmsa->nseq; i++)
2380 if(clust[i] != -1)
2381 useme[clust[i]][i] = TRUE;
2382 printf("# idx nseq\n");
2383 printf("# ---- ------\n");
2384 for(m = 0; m < nc; m++) {
2385 if(esl_vec_ISum(useme[m], mmsa->nseq) == 0) esl_fatal("No sequences in cluster %d\n");
2386 if((status = esl_msa_SequenceSubset(mmsa, useme[m], &(cmsa[m]))) != eslOK) ESL_FAIL(status, errbuf, "MSADivide(), esl_msa_SequenceSubset error, status: %d.", status);
2387 printf(" %4d %6d\n", m+1, cmsa[m]->nseq);
2388 free(useme[m]);
2389 }
2390 printf("\n");
2391
2392 free(useme[nc]);
2393 free(useme);
2394
2395 *ret_num_msa = nc;
2396 *ret_cmsa = cmsa;
2397 *ret_xsize = xsize;
2398
2399 esl_tree_Destroy(T);
2400 free(diff);
2401 diff = NULL;
2402
2403 if(clust != NULL) free(clust);
2404 if(csize != NULL) free(csize);
2405 return eslOK;
2406
2407 ERROR:
2408 if(diff != NULL) free(diff);
2409 if(minld != NULL) free(minld);
2410 if(minrd != NULL) free(minrd);
2411 if(clust != NULL) free(clust);
2412 if(csize != NULL) free(csize);
2413 if(cmsa != NULL) {
2414 for(m = 0; m < nc; m++)
2415 if(cmsa[m] != NULL) esl_msa_Destroy(cmsa[m]);
2416 free(cmsa);
2417 }
2418 return status;
2419 }
2420
2421 /* Function: select_node()
2422 * EPN, Fri Mar 23 08:48:37 2007
2423 * Adapted from SRE's select_node() in maketestset.c originally written
2424 * for the PROFMARK HMMER benchmark.
2425 *
2426 *
2427 * Purpose: Define clusters of the taxa (seqs) in the tree such
2428 * that minimum disparity b/t any 2 seqs in different
2429 * clusters is greater than <mindiff> and the number of
2430 * clusters is maximized. <ret_best> is the index of the node
2431 * of the tree under which the largest cluster belongs.
2432 * <ret_nc> is the number of clusters after clustering,
2433 * <ret_clust> is an array [0..T->N-1] specifying which
2434 * cluster each taxa belongs to.
2435 *
2436 * For high disparities, this cluster may contain all
2437 * the sequences, and we'll return the root node (0).
2438 *
2439 * Args:
2440 * ESL_TREE *T - the tree
2441 * double *diff - [0..T->N-2]: for each node of the tree, the minimum
2442 * distance (sum of branch lengths) from any taxa (leaf)
2443 * in left subtree to any taxa in right subtree.
2444 * double mindiff - (see description above)
2445 * int **ret_clust- [0..T->N-1] cluster number this seq is in, alloc'ed, filled here
2446 * int *ret_nc - number of clusters
2447 * int *ret_xsize- size of largest cluster
2448 * int *ret_best - RETURN: index of node of tree under which largest cluster belongs (see Purpose).
2449 * char *errbuf - buffer for error messages
2450 *
2451 * Returns: node index (as explained in Purpose)
2452 */
2453 static int
2454 select_node(ESL_TREE *T, double *diff, double mindiff, int **ret_clust, int *ret_nc, int *ret_xsize, int *ret_best, char *errbuf)
2455 {
2456 int status; /* Easel status code */
2457 ESL_STACK *ns1; /* stack for traversing tree */
2458 ESL_STACK *ns2; /* another stack for traversing tree */
2459 int c; /* counter for clusters */
2460 int best; /* index of current best node */
2461 int maxsize; /* size of cluster for best node */
2462 int n, np; /* counters over tree nodes */
2463 int *clust; /* [1..T->N-1] cluster number this seq is in */
2464
2465 /*printf("in selec_node mindiff: %f T->N: %d\n", mindiff, T->N);*/
2466 /* set tree cladesizes if not already set */
2467 if(T->cladesize == NULL)
2468 if((status = esl_tree_SetCladesizes(T)) != eslOK) ESL_FAIL(status, errbuf, "select_node(), esl_tree_SetCladeSizes error, status: %d.", status);
2469
2470 ESL_ALLOC(clust, (sizeof(int) * T->N));
2471 esl_vec_ISet(clust, T->N, 0);
2472
2473 if((ns1 = esl_stack_ICreate()) == NULL) ESL_FAIL(status, errbuf, "select_node(), failed to create a stack, probably out of memory, status: %d.", status);
2474 if((ns2 = esl_stack_ICreate()) == NULL) ESL_FAIL(status, errbuf, "select_node(), failed to create a stack, probably out of memory, status: %d.", status);
2475
2476 /* push root on stack to start */
2477 if((status = esl_stack_IPush(ns1, 0)) != eslOK) ESL_FAIL(status, errbuf, "select_node(), failed to push onto a stack, probably out of memory, status: %d.", status);
2478 maxsize = 0;
2479 best = 0;
2480 c = 0;
2481 while (esl_stack_IPop(ns1, &n) != eslEOD) {
2482 if ((n == 0 || diff[T->parent[n]] > mindiff) &&
2483 diff[n] <= mindiff) { /* we're at a cluster */
2484 if (T->cladesize[n] > maxsize) {
2485 maxsize = T->cladesize[n];
2486 best = n;
2487 }
2488 /* determine all taxa in the clade rooted at n*/
2489 esl_stack_IPush(ns2, n);
2490 while (esl_stack_IPop(ns2, &np) != eslEOD) {
2491 /*printf("np: %d T->left[np]: %d\n", np, T->left[np]);*/
2492 if(T->left[np] <= 0) clust[(-1*T->left[np])] = c;
2493 else { if((status = esl_stack_IPush(ns2, T->left[np])) != eslOK) ESL_FAIL(status, errbuf, "select_node(), failed to push onto a stack, probably out of memory, status: %d.", status); }
2494 if(T->right[np] <= 0) clust[(-1*T->right[np])] = c;
2495 else { if((status = esl_stack_IPush(ns2, T->right[np])) != eslOK) ESL_FAIL(status, errbuf, "select_node(), failed to push onto a stack, probably out of memory, status: %d.", status); }
2496 }
2497 c++;
2498 }
2499 else { /* we're not a cluster, keep traversing */
2500 /*printf("n: %d T->left[n]: %d\n", n, T->left[n]);*/
2501 if(T->left[n] <= 0) clust[(-1*T->left[n])] = c++; /* single seq with its own cluster */
2502 else { if((status = esl_stack_IPush(ns1, T->left[n])) != eslOK) ESL_FAIL(status, errbuf, "select_node(), failed to push onto a stack, probably out of memory, status: %d.", status); }
2503 if(T->right[n] <= 0) clust[(-1*T->right[n])] = c++; /* single seq with its own cluster */
2504 else { if((status = esl_stack_IPush(ns1, T->right[n])) != eslOK) ESL_FAIL(status, errbuf, "select_node(), failed to push onto a stack, probably out of memory, status: %d.", status); }
2505 }
2506 }
2507 esl_stack_Destroy(ns1);
2508 esl_stack_Destroy(ns2);
2509 *ret_nc = c;
2510 *ret_clust = clust;
2511 *ret_xsize = maxsize;
2512 *ret_best = best;
2513 /*printf("nc: %d(%d) best: %d maxsize: %d nc: %d mindiff: %.3f\n\n", *ret_nc, c, best, maxsize, c, mindiff);
2514 for(n = 0; n < T->N; n++) printf("clust[%d]: %d\n", n, clust[n]);*/
2515 return eslOK;
2516
2517 ERROR:
2518 if(clust != NULL) free(clust);
2519 ESL_FAIL(status, errbuf, "select_node(), memory allocation error, status: %d.", status);
2520 }
2521
2522
2523 /* Function: find_mindiff()
2524 * EPN, Fri Mar 23 18:59:42 2007
2525 *
2526 * Purpose: Given a tree resulting from single linkage clustering,
2527 * find the min fractional difference (mindiff) that when used to
2528 * define clusters (such that no seq in cluster A is less
2529 * than mindiff different than any seq in cluster B),
2530 * gives either (A) (if(do_nc)) number of clusters >= target or
2531 * (B) (if(do_nsize)) >= 1 cluster with >= target sequences
2532 *
2533 * Args:
2534 * ESL_TREE *T - the tree
2535 * double *diff - [0..T->N-2]: for each node of the tree, the minimum
2536 * distance (sum of branch lengths) from any taxa (leaf)
2537 * in left subtree to any taxa in right subtree.
2538 * int do_nsize - TRUE to find mindiff that gives >= 1 cluster with <target> seqs
2539 * FALSE to find mindiff that gives <target> clusters
2540 * int target - number of clusters (! if(do_nsize)) we want, or min size of
2541 * biggest cluster (if(do_nsize))
2542 * int **ret_clust- [0..T->N-1] cluster number this seq is in, alloc'ed, filled here
2543 * int *ret_nc - number of clusters
2544 * int *ret_xsize- size of largest cluster
2545 * int *ret_best - cluster idx of largest cluster
2546 * int *ret_mindiff - mindiff that achieves target
2547 * char *errbuf - buffer for error messages
2548 *
2549 * Returns: fractional difference (as explained in Purpose)
2550 */
2551 static float
2552 find_mindiff(ESL_TREE *T, double *diff, int do_nsize, int target, int **ret_clust, int *ret_nc, int *ret_xsize, int *ret_best, float *ret_mindiff, char *errbuf)
2553 {
2554 int status;
2555 float high_diff = 1.0;
2556 float low_diff = 0.0;
2557 int high = 0;
2558 int low = 0;
2559 float mindiff = 0.5;
2560 int curr_nc = -1;
2561 int curr_xsize = -1;
2562 int curr = -1;
2563 int curr_best = -1;
2564 int keep_going = TRUE;
2565 float thresh = 0.001;
2566 int *clust = NULL;
2567
2568 /* Contract check */
2569 if(target > T->N) ESL_FAIL(eslEINCOMPAT, errbuf, "find_mindiff(), desired target is greater than number of seqs in the tree");
2570
2571 while(keep_going) {
2572 if(clust != NULL) free(clust);
2573 if((status = select_node(T, diff, mindiff, &clust, &curr_nc, &curr_xsize, &curr_best, errbuf)) != eslOK) return status;
2574 curr = do_nsize ? curr_xsize : curr_nc;
2575 if(((!do_nsize) && (curr < target)) || ((do_nsize) && (curr >= target))) {
2576 high_diff = mindiff;
2577 high = curr;
2578 /*printf("LOWER curr: %d mindiff: %f low: %f (%d) high: %f (%d)\n", curr, mindiff, low_diff, low, high_diff, high);*/
2579 mindiff -= (mindiff - low_diff) / 2.;
2580 if((fabs(high_diff-0.) < thresh) && (fabs(low-0.) < thresh)) keep_going = FALSE;
2581 /* stop, high and low have converged at 0. */
2582 }
2583 else {/* if(do_nsize) curr_nc > target_nc, else if(!do_nsize) curr_nc >= target_nc */
2584 low_diff = mindiff;
2585 low = curr;
2586 /*printf("GREATER curr: %d mindiff: %f low: %f (%d) high: %f (%d)\n", curr, mindiff, low_diff, low, high_diff, high);*/
2587 mindiff += (high_diff - mindiff) / 2.;
2588 if(fabs(high_diff-low_diff) < thresh) keep_going = FALSE; /* stop, high and low have converged */
2589 }
2590 }
2591 if(do_nsize) {
2592 if(curr < target) { /* we couldn't reach our target in search due to precision */
2593 if(high >= target) { /* we could reach it at high */
2594 mindiff = high_diff;
2595 if((status = select_node(T, diff, mindiff, &clust, &curr_nc, &curr_xsize, &curr_best, errbuf)) != eslOK) return status;
2596 }
2597 else { /* we couldn't reach our threshold, this shouldn't happen */
2598 ESL_FAIL(eslEINVAL, errbuf,"Error in find_mindiff(), even with mindiff of %.5f can't produce cluster of size: %d\n", mindiff, target);
2599 }
2600 }
2601 }
2602 else { /* ! do_nsize, trying to achieve <target> clusters */
2603 /* it's possible we can't reach our target, if so, set mindiff as minimum value that gives
2604 * less than target clusters. */
2605 if(curr != target) {
2606 /*printf("targ: %d curr: %d low: %d (%f) high: %d (%f)\n", target, curr, low, low_diff, high, high_diff);*/
2607 if(high < target) {
2608 mindiff = high;
2609 if((status = select_node(T, diff, mindiff, &clust, &curr_nc, &curr_xsize, &curr_best, errbuf)) != eslOK) return status;
2610 }
2611 else
2612 while(high > target) {
2613 high += thresh;
2614 if(high > 1.0) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "find_mindiff(), mindiff has risen above 1.0");
2615 mindiff = high;
2616 if((status = select_node(T, diff, mindiff, &clust, &curr_nc, &curr_xsize, &curr_best, errbuf)) != eslOK) return status;
2617 high = curr_nc;
2618 }
2619 }
2620 }
2621 /*printf("FINAL mindiff: %f\n", mindiff); */
2622 *ret_nc = curr_nc;
2623 *ret_clust = clust;
2624 *ret_xsize = curr_xsize;
2625 *ret_best = curr_best;
2626 *ret_mindiff = mindiff;
2627
2628 return eslOK;
2629 }
2630
2631
2632 /* determine_first_last_consensus_columns
2633 *
2634 * Given an MSA, determine the first and last consensus columns
2635 * occupied by each sequence
2636 */
2637 static int determine_first_last_consensus_columns(ESL_MSA *msa, char *errbuf, int *i_am_rf, int rflen, int **ret_fA, int **ret_lA)
2638 {
2639 int status;
2640 int *fA = NULL;
2641 int *lA = NULL;
2642 int rfpos = 0;
2643 int apos = 0;
2644 int i;
2645
2646 /* contract check */
2647 if(msa->rf == NULL) { status = eslEINVAL; goto ERROR; }
2648
2649 /* determine the first and last occupied consensus position in each sequence */
2650 ESL_ALLOC(fA, sizeof(int) * msa->nseq);
2651 ESL_ALLOC(lA, sizeof(int) * msa->nseq);
2652
2653 esl_vec_ISet(lA, msa->nseq, 0);
2654 esl_vec_ISet(fA, msa->nseq, rflen);
2655 /* this could be way more efficient */
2656 for(i = 0; i < msa->nseq; i++) {
2657 rfpos = 0;
2658 for(apos = 0; apos < msa->alen; apos++) {
2659 if(i_am_rf[apos]) { /* apos is a consensus position */
2660 rfpos++;
2661 if(! esl_abc_XIsGap(msa->abc, msa->ax[i][(apos+1)])) { /* rfpos for seq i is not a gap */
2662 fA[i] = ESL_MIN(fA[i], rfpos);
2663 lA[i] = ESL_MAX(lA[i], rfpos);
2664 }
2665 }
2666 }
2667 }
2668 *ret_fA = fA;
2669 *ret_lA = lA;
2670 return eslOK;
2671
2672 ERROR: ESL_FAIL(status, errbuf, "determine_first_last_consensus_columns(): memory allocation error.");
2673 return status; /* NEVERREACHED */
2674 }
2675
2676
2677 /* Function: dst_nongap_XPairId()
2678 * Synopsis: Pairwise identity of two aligned digital seqs.
2679 * Differs from esl_dst_XPairId() in that denominator is
2680 * seq identity is number of columns that are non-gap in both
2681 * sequences (instead of length of the shorter of the two seqs).
2682 *
2683 * Incept: EPN, Fri Jun 27 15:07:44 2008
2684 *
2685 * Args: abc - digital alphabet in use
2686 * ax1 - aligned digital seq 1
2687 * ax2 - aligned digital seq 2
2688 * opt_pid - optRETURN: pairwise identity, 0<=x<=1
2689 * opt_nid - optRETURN: # of identities
2690 * opt_n - optRETURN: denominator MIN(len1,len2)
2691 *
2692 * Returns: <eslOK> on success. <opt_distance>, <opt_nid>, <opt_n>
2693 * contain the answers, for any of these that were passed
2694 * non-<NULL> pointers.
2695 *
2696 * Throws: <eslEINVAL> if the strings are different lengths (not aligned).
2697 */
2698 int
2699 dst_nongap_XPairId(const ESL_ALPHABET *abc, const ESL_DSQ *ax1, const ESL_DSQ *ax2,
2700 double *opt_distance, int *opt_nid, int *opt_n)
2701 {
2702 int status;
2703 int idents; /* total identical positions */
2704 int len; /* number of nongap colns in both seqs */
2705 int i; /* position in aligned seqs */
2706
2707 idents = len = 0;
2708 for (i = 1; ax1[i] != eslDSQ_SENTINEL && ax2[i] != eslDSQ_SENTINEL; i++)
2709 {
2710 if (esl_abc_XIsCanonical(abc, ax1[i]) && esl_abc_XIsCanonical(abc, ax2[i])) {
2711 len++;
2712 if(ax1[i] == ax2[i]) idents++;
2713 }
2714 }
2715
2716 if (ax1[i] != eslDSQ_SENTINEL || ax2[i] != eslDSQ_SENTINEL)
2717 ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
2718
2719 if (opt_distance != NULL) *opt_distance = ( len==0 ? 0. : (double) idents / (double) len );
2720 if (opt_nid != NULL) *opt_nid = idents;
2721 if (opt_n != NULL) *opt_n = len;
2722 return eslOK;
2723
2724 ERROR:
2725 if (opt_distance != NULL) *opt_distance = 0.;
2726 if (opt_nid != NULL) *opt_nid = 0;
2727 if (opt_n != NULL) *opt_n = 0;
2728 return status;
2729 }
2730
2731
2732 /* Function: dst_nongap_XDiffMx()
2733 * Synopsis: NxN difference matrix for N aligned digital seqs.
2734 * Differs from esl_dst_XDiffMx() in that denominator for
2735 * seq identity is number of columns that are non-gap in both
2736 * sequences (instead of length of the shorter of the two seqs).
2737 *
2738 * Incept: EPN, Fri Jun 27 15:10:53 2008
2739 *
2740 * Args: abc - digital alphabet in use
2741 * ax - aligned dsq's, [0..N-1][1..alen]
2742 * N - number of aligned sequences
2743 * ret_D - RETURN: NxN matrix of fractional differences
2744 *
2745 * Returns: <eslOK> on success, and <ret_D> contains the difference
2746 * matrix; caller is obligated to free <D> with
2747 * <esl_dmatrix_Destroy()>.
2748 *
2749 * Throws: <eslEINVAL> if a seq has a different
2750 * length than others. On failure, <ret_D> is returned <NULL>
2751 * and state of inputs is unchanged.
2752 */
2753 int
2754 dst_nongap_XDiffMx(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, ESL_DMATRIX **ret_D)
2755 {
2756 ESL_DMATRIX *D = NULL;
2757 int i,j;
2758 int status;
2759
2760 if (( D = esl_dmatrix_Create(N,N) ) == NULL) { status = eslEMEM; goto ERROR; }
2761
2762 for (i = 0; i < N; i++)
2763 {
2764 D->mx[i][i] = 0.;
2765 for (j = i+1; j < N; j++)
2766 {
2767 status = dst_nongap_XPairId(abc, ax[i], ax[j], &(D->mx[i][j]), NULL, NULL);
2768 if (status != eslOK) ESL_XEXCEPTION(status, "Pairwise identity calculation failed at seqs %d,%d\n", i,j);
2769 D->mx[i][j] = 1.0 - D->mx[i][j];
2770 D->mx[j][i] = D->mx[i][j];
2771 }
2772 }
2773 if (ret_D != NULL) *ret_D = D; else esl_dmatrix_Destroy(D);
2774 return eslOK;
2775
2776 ERROR:
2777 if (D != NULL) esl_dmatrix_Destroy(D);
2778 if (ret_D != NULL) *ret_D = NULL;
2779 return status;
2780 }
2781
2782 /* find_seqs_with_given_insert
2783 *
2784 * Given an MSA with RF annotation, determine which sequences have inserts after column <target>
2785 * of at least size <min> and at most size <max>. Fill an array <useme> of size msa->nseq with
2786 * TRUE seq i has the insert, FALSE if it doesn't.
2787 */
2788 static int find_seqs_with_given_insert(ESL_MSA *msa, int *i_am_rf, char *errbuf, int target, int min, int max, int **ret_useme)
2789 {
2790 int status;
2791 int apos, rfpos, clen;
2792 int **ict;
2793 int *useme;
2794 int i;
2795
2796 /* contract check */
2797 if(! (msa->flags & eslMSA_DIGITAL)) ESL_FAIL(eslEINVAL, errbuf, "in find_seqs_with_given_insert(), msa must be digitized.");
2798 if(msa->rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "No #=GC RF markup in alignment, it is needed for --seq-ins.");
2799
2800 ESL_ALLOC(useme,sizeof(int) * (msa->nseq));
2801 ESL_ALLOC(ict, sizeof(int *) * (msa->alen+2));
2802 for(i = 0; i <= msa->alen; i++)
2803 {
2804 ESL_ALLOC(ict[i], sizeof(int) * (msa->nseq));
2805 esl_vec_ISet(ict[i], (msa->nseq), 0);
2806 }
2807
2808 rfpos = 0;
2809 for(apos = 1; apos <= msa->alen; apos++)
2810 {
2811 if(i_am_rf[apos-1]) {
2812 rfpos++;
2813 }
2814 else
2815 for(i = 0; i < msa->nseq; i++)
2816 if(! esl_abc_XIsGap(msa->abc, msa->ax[i][apos])) {
2817 ict[rfpos][i]++;
2818 }
2819 }
2820 clen = rfpos;
2821 if(target > clen) ESL_FAIL(eslEINVAL, errbuf, "--seq-ins <n> enabled with <n> = %d, but non-gap RF length of alignment is only %d columns.", target, clen);
2822
2823 for(i = 0; i < msa->nseq; i++) {
2824 /* printf("ict[target:%d][i:%d]: %d, min: %d max: %d\n", target, i, ict[target][i], min, max); */
2825 useme[i] = ((ict[target][i] >= min) && (ict[target][i] <= max)) ? TRUE : FALSE;
2826 }
2827
2828 *ret_useme = useme;
2829 for(i = 0; i <= msa->alen; i++)
2830 free(ict[i]);
2831 free(ict);
2832 return eslOK;
2833
2834 ERROR:
2835 return status;
2836 }
2837
2838 /* minorize_msa()
2839 *
2840 * Given an MSA with #=GS <seq name> <<tag>> <minor set name>, make a new msa that
2841 * includes all seqs that have the same <minor set name> #=GS annotation for the
2842 * same <<tag>> (string value of <tag> is set at command line and passed into
2843 * this function)
2844 * Also set the #=GC RF markup for each minor subset as either:
2845 * (A) the #=GF <x> <y> with <x> equal to <minor set name> and <y>
2846 * as the RF line.
2847 *
2848 * or, if no such #=GF markup exists define the consensus with the
2849 * gap fraction rule, any column with <= <x> (from --gapthresh <x>)
2850 * gaps becomes an 'x' in the RF seq, all other columns are '.'.
2851 */
2852 static int
2853 minorize_msa(const ESL_GETOPTS *go, ESL_MSA *msa, char *errbuf, FILE *fp, char *tag, int outfmt)
2854 {
2855 int status;
2856 int *useme = NULL;
2857 int nalloc = 1;
2858 int nmin = 0;
2859 int *which_minor = NULL; /* [0..i..msa->nseq-1] which minor subset each sequence belongs to, -1 if none */
2860 char **minorA = NULL; /* [0..m..nmin-1] ptr to minor subset name in #=GS markup, only a ptr, don't free the char strings */
2861 int f, g, i, m, mt;
2862 int gt = -1;
2863 void *tmp;
2864 char *rf;
2865 int apos;
2866 int ip;
2867 int *order;
2868 ESL_MSA **minor_msaA;
2869
2870 /* contract check */
2871 if(msa->rf == NULL) ESL_FAIL(eslEINVAL, errbuf, "-M requires #=GC RF markup in alignment.");
2872 if(msa->gs == NULL) ESL_FAIL(eslEINVAL, errbuf, "-M requires #=GS markup in alignment denoting minor subsets.");
2873
2874 /* determine which tag matches <tag> */
2875 for(g = 0; g < msa->ngs; g++) {
2876 if(strcmp(msa->gs_tag[g], tag) == 0) {
2877 gt = g;
2878 break;
2879 }
2880 }
2881 if(gt == -1) ESL_FAIL(eslEINVAL, errbuf, "No #=GS markup has tag: %s\n", tag);
2882
2883 /* determine which minor set each seq belongs to, reallocate minorA as we go and see new minor subsets */
2884 ESL_ALLOC(which_minor, sizeof(int) * msa->nseq);
2885 ESL_ALLOC(minorA, sizeof(char *) * nalloc);
2886 esl_vec_ISet(which_minor, msa->nseq, -1);
2887
2888 for(i = 0; i < msa->nseq; i++) {
2889 if(msa->gs[gt][i] != NULL) {
2890 mt = -1;
2891 for(m = 0; m < nmin; m++) {
2892 if(strcmp(minorA[m], msa->gs[gt][i]) == 0) {
2893 mt = m;
2894 break;
2895 }
2896 }
2897 if(mt == -1) {
2898 if((nmin+1) == nalloc) {
2899 nalloc++;
2900 ESL_RALLOC(minorA, tmp, sizeof(char *) * nalloc);
2901 }
2902 minorA[nmin] = msa->gs[gt][i];
2903 mt = nmin++;
2904 }
2905 which_minor[i] = mt;
2906 }
2907 }
2908 for(i = 0; i < msa->nseq; i++) if(which_minor[i] == -1) ESL_FAIL(eslEINVAL, errbuf, "-M requires ALL sequences have #=GS markup with user supplied tag %s. Seq %d (%s) has none.\n", esl_opt_GetString(go, "-M"), i, msa->sqname[i]);
2909
2910 /* Now make the minor alignments by keeping only the relevant subset of seqs.
2911 * We do not call esl_msa_MinimGaps() b/c we want the alignment length to be
2912 * identical b/t all minor msas, and the RF also so cmalign knows how to
2913 * map the minor alignments to the major alignment */
2914 ESL_ALLOC(minor_msaA, sizeof(ESL_MSA *) * nmin);
2915 ESL_ALLOC(useme, sizeof(int) * msa->nseq);
2916 for(m = 0; m < nmin; m++) {
2917 for(i = 0; i < msa->nseq; i++) useme[i] = (which_minor[i] == m) ? TRUE : FALSE;
2918 if(esl_vec_ISum(useme, msa->nseq) == 0) esl_fatal("No sequences selected for minor MSA!\n");
2919 if((status = esl_msa_SequenceSubset(msa, useme, &(minor_msaA[m]))) != eslOK) ESL_FAIL(status, errbuf, "Error taking subset for minor subset %d with name: %s\n", m, minorA[m]);
2920
2921 /* set name */
2922 esl_msa_SetName(minor_msaA[m], minorA[m], -1);
2923
2924 /* unless --M-rf free RF annotation and set new annotation (--M-rf tells us to keep the initial RF annotation for all minor alignments */
2925 if(! esl_opt_GetBoolean(go, "--M-rf")) {
2926 if(minor_msaA[m]->rf == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "Error creating minor alignment %d, RF is NULL.", m);
2927 free(minor_msaA[m]->rf);
2928 minor_msaA[m]->rf = NULL;
2929 /* Check if we have #=GF markup denoting the RF line for each minor subset */
2930 rf = NULL;
2931 for(f = 0; f < msa->ngf; f++)
2932 if(strcmp(minorA[m], msa->gf_tag[f]) == 0) { rf = msa->gf[f]; break; }
2933 if(rf != NULL) { /* ensure the RF annotation is the length of the alignment */
2934 if(strlen(rf) != msa->alen) ESL_FAIL(eslEINCOMPAT, errbuf, "'#=GF %s <RF sequence>' markup is of length %d but it must be equal to aln length (%" PRId64 ").", msa->gf_tag[f], (int) strlen(rf), msa->alen);
2935 if((status = esl_strdup(rf, msa->alen, &(minor_msaA[m]->rf))) != eslOK) ESL_FAIL(status, errbuf, "Error duplicating RF for minor alignment %d\n", m);
2936 /* make sure minor_msaA[m]->rf does not have any non-gap columns where msa->rf has a gap (cmalign -M demands all minor consensus columns are also major consensus columns) */
2937 for (apos = 0; apos < minor_msaA[m]->alen; apos++) {
2938 if (! (esl_abc_CIsGap(minor_msaA[m]->abc, minor_msaA[m]->rf[apos]))) {
2939 if (esl_abc_CIsGap(msa->abc, msa->rf[apos])) ESL_FAIL(eslEINCOMPAT, errbuf, "'#=GF %s <RF sequence>' markup has a non-gap (%c char) at aln position %d, but the major alignment has a gap there! cmalign will choke on this.\n", msa->gf_tag[f], minor_msaA[m]->rf[(apos-1)], apos);
2940 }
2941 }
2942 }
2943 else { /* no #=GF markup denoting RF line for alignment m existed in the input file, define it based on gaps */
2944 if((status = write_rf_gapthresh(go, errbuf, minor_msaA[m], esl_opt_GetReal(go, "--M-gapt"))) != eslOK) return status;
2945 /* careful, remember with cmalign -M, the minor alignments can only have training alignment column c defined as a consensus column
2946 * if it is also consensus in the major alignment, so we have to remove any minor_msaA[m]->rf 'x' columns that are gaps in <msa>
2947 */
2948 for (apos = 0; apos < minor_msaA[m]->alen; apos++)
2949 if (esl_abc_CIsGap(msa->abc, msa->rf[apos])) minor_msaA[m]->rf[apos] = '.';
2950 }
2951 }
2952 }
2953
2954 /* Print out the alignments, first major, then minors */
2955 /* first, reorder major alignment so that it contains the minor alignment seqs in order */
2956 ip = 0;
2957 ESL_ALLOC(order, sizeof(int) * msa->nseq);
2958 for(m = 0; m < nmin; m++) {
2959 for(i = 0; i < msa->nseq; i++) {
2960 if(which_minor[i] == m) order[i] = ip++;
2961 }
2962 }
2963 if((status = reorder_msa(msa, order, errbuf)) != eslOK) return status;
2964
2965 esl_msafile_Write(fp, msa, outfmt);
2966 for(m = 0; m < nmin; m++) {
2967 esl_msafile_Write(fp, minor_msaA[m], outfmt);
2968 esl_msa_Destroy(minor_msaA[m]);
2969 }
2970 free(minor_msaA);
2971
2972 free(order);
2973 free(useme);
2974 free(which_minor);
2975 free(minorA);
2976 return eslOK;
2977
2978 ERROR:
2979 if(which_minor != NULL) free(which_minor);
2980 if(minorA != NULL) free(minorA);
2981 if(useme != NULL) free(useme);
2982 return eslEMEM;
2983 }
2984
2985
2986 /* remove_gc_markup()
2987 *
2988 * Given a GC tag <tag>, remove that markup from an MSA.
2989 * Return eslEINVAL if <tag> does not exist.
2990 */
2991 static int
2992 remove_gc_markup(ESL_MSA *msa, char *errbuf, char *tag)
2993 {
2994 int does_not_exist = FALSE;
2995
2996 /* Currently, we can only handle removal of parsed GC markup, RF, SS_cons, SA_cons, PP_cons
2997 * (the main reason is b/c I didn't know how to deal with possibility of the ESL_KEYHASH in msa->gc_idx).
2998 */
2999 if (strcmp(tag, "RF") == 0) {
3000 if (msa->rf == NULL) does_not_exist = TRUE;
3001 else { free(msa->rf); msa->rf = NULL; }
3002 }
3003 else if(strcmp(tag, "SS_cons") == 0) {
3004 if (msa->ss_cons == NULL) does_not_exist = TRUE;
3005 else { free(msa->ss_cons); msa->ss_cons = NULL; }
3006 }
3007 else if (strcmp(tag, "SA_cons") == 0) {
3008 if (msa->sa_cons == NULL) does_not_exist = TRUE;
3009 else { free(msa->sa_cons); msa->sa_cons = NULL; }
3010 }
3011 else if (strcmp(tag, "PP_cons") == 0) {
3012 if (msa->pp_cons == NULL) does_not_exist = TRUE;
3013 else { free(msa->pp_cons); msa->pp_cons = NULL; }
3014 }
3015 else {
3016 ESL_FAIL(eslEINVAL, errbuf, "--rm-gc <s> only works if <s> is \'RF\', \'SS_cons\', \'SA_cons\', or \'PP_cons\'");
3017 }
3018 if(does_not_exist) {
3019 ESL_FAIL(eslEINVAL, errbuf, "--rm-gc %s enabled but %s GC markup exists in the MSA.", tag, tag);
3020 }
3021 return eslOK;
3022 }
3023
3024
3025 /* add_gap_columns_to_msa
3026 *
3027 * Given an MSA and an array specifying a number
3028 * of all gap columns to add after each column,
3029 * add them. Reallocate all arrays as necessary.
3030 * if(do_treat_as_rf_gap) make new column a gap
3031 * in the RF line, else make it an 'x'.
3032 *
3033 * toadd is numbered 1..alen.
3034 */
3035 static int
3036 add_gap_columns_to_msa(char *errbuf, ESL_MSA *msa, int *toadd, ESL_MSA **ret_msa, int do_treat_as_rf_gap)
3037 {
3038 int status;
3039 int i,j;
3040 int apos;
3041 int nnew = 0;
3042 ESL_ALPHABET *abc;
3043 char *newstr;
3044 /* contract check */
3045 if(! (msa->flags & eslMSA_DIGITAL))
3046 ESL_FAIL(eslEINVAL, errbuf, "in add_gap_columns_to_msa(), msa must be digitized.");
3047 for(apos = 0; apos <= msa->alen; apos++)
3048 nnew += toadd[apos];
3049
3050 /* Textize the alignment */
3051 abc = msa->abc;
3052 esl_msa_Textize(msa);
3053
3054 ESL_MSA *newmsa;
3055 /*printf("msa->nseq: %d\n", msa->nseq);
3056 printf("msa->alen: %d\n", msa->alen);*/
3057 newmsa = esl_msa_Create(msa->nseq, (msa->alen+nnew));
3058
3059 /* Copy and add gaps to all valid data that is [0..(alen-1)] or [1..alen] */
3060 if(msa->ss_cons != NULL)
3061 {
3062 ESL_ALLOC(newmsa->ss_cons, sizeof(char) * (msa->alen+nnew+1));
3063 if((status = cp_and_add_gaps_to_aseq(newmsa->ss_cons, msa->ss_cons, msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3064 }
3065 if(msa->sa_cons != NULL)
3066 {
3067 ESL_ALLOC(newmsa->sa_cons, sizeof(char) * (msa->alen+nnew+1));
3068 if((status = cp_and_add_gaps_to_aseq(newmsa->sa_cons, msa->sa_cons, msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3069 }
3070 if(msa->pp_cons != NULL)
3071 {
3072 ESL_ALLOC(newmsa->pp_cons, sizeof(char) * (msa->alen+nnew+1));
3073 if((status = cp_and_add_gaps_to_aseq(newmsa->pp_cons, msa->pp_cons, msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3074 }
3075 if(msa->rf != NULL)
3076 {
3077 ESL_ALLOC(newmsa->rf, sizeof(char) * (msa->alen+nnew+1));
3078 if(do_treat_as_rf_gap)
3079 {
3080 if((status = cp_and_add_gaps_to_aseq(newmsa->rf, msa->rf, msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3081 }
3082 else if((status = cp_and_add_gaps_to_aseq(newmsa->rf, msa->rf, msa->alen, toadd, nnew, 'x') != eslOK)) goto ERROR;
3083 }
3084
3085 if(msa->ss != NULL)
3086 {
3087 ESL_ALLOC(newmsa->ss, sizeof(char *) * msa->nseq);
3088 for(i = 0; i < msa->nseq; i++)
3089 {
3090 if(msa->ss[i] != NULL)
3091 {
3092 ESL_ALLOC(newmsa->ss[i], sizeof(char) * (msa->alen+nnew+1));
3093 if((status = cp_and_add_gaps_to_aseq(newmsa->ss[i], msa->ss[i], msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3094 }
3095 }
3096 }
3097
3098 if(msa->sa != NULL)
3099 {
3100 ESL_ALLOC(newmsa->sa, sizeof(char *) * msa->nseq);
3101 for(i = 0; i < msa->nseq; i++)
3102 {
3103 if(msa->sa[i] != NULL)
3104 {
3105 ESL_ALLOC(newmsa->sa[i], sizeof(char) * (msa->alen+nnew+1));
3106 if((status = cp_and_add_gaps_to_aseq(newmsa->sa[i], msa->sa[i], msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3107 }
3108 }
3109 }
3110
3111 if(msa->pp != NULL)
3112 {
3113 ESL_ALLOC(newmsa->pp, sizeof(char *) * msa->nseq);
3114 for(i = 0; i < msa->nseq; i++)
3115 {
3116 if(msa->pp[i] != NULL)
3117 {
3118 ESL_ALLOC(newmsa->pp[i], sizeof(char) * (msa->alen+nnew+1));
3119 if((status = cp_and_add_gaps_to_aseq(newmsa->pp[i], msa->pp[i], msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3120 }
3121 }
3122 }
3123
3124 if(msa->ncomment > 0)
3125 {
3126 for(j = 0; j < msa->ncomment; j++)
3127 {
3128 if(msa->comment[j] != NULL)
3129 esl_msa_AddComment(newmsa, msa->comment[j], -1);
3130 }
3131 }
3132
3133 if(msa->ngf > 0)
3134 {
3135 for(i = 0; i < msa->ngf; i++)
3136 if(msa->gf[i] != NULL)
3137 esl_msa_AddGF(newmsa, msa->gf_tag[i], -1, msa->gf[i], -1);
3138 }
3139
3140 if(msa->ngs > 0)
3141 {
3142 for(j = 0; j < msa->ngs; j++)
3143 {
3144 for(i = 0; i < msa->nseq; i++)
3145 if(msa->gs[j][i] != NULL)
3146 esl_msa_AddGS(newmsa, msa->gs_tag[j], -1, i, msa->gs[j][i], -1);
3147 }
3148 }
3149
3150 if(msa->ngc > 0)
3151 {
3152 for(i = 0; i < msa->ngc; i++)
3153 {
3154 if(msa->gc[i] != NULL)
3155 {
3156 ESL_ALLOC(newstr, sizeof(char) * (msa->alen+nnew+1));
3157 if((status = cp_and_add_gaps_to_aseq(newstr, msa->gc[i], msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3158 esl_msa_AppendGC(newmsa, msa->gc_tag[i], newstr);
3159 free(newstr);
3160 }
3161 }
3162 }
3163
3164 if(msa->gr != NULL)
3165 {
3166 for(j = 0; j < msa->ngr; j++)
3167 {
3168 for(i = 0; i < msa->nseq; i++)
3169 {
3170 if(msa->gr[j][i] != NULL)
3171 {
3172 ESL_ALLOC(newstr, sizeof(char) * (msa->alen+nnew+1));
3173 if((status = cp_and_add_gaps_to_aseq(newstr, msa->gr[j][i], msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3174 esl_msa_AppendGR(newmsa, msa->gr_tag[j], i, newstr);
3175 free(newstr);
3176 }
3177 }
3178 }
3179 }
3180
3181 /* copy the aseqs, free as we go to save memory */
3182 for(i = 0; i < msa->nseq; i++)
3183 {
3184 esl_strdup(msa->sqname[i], -1, &(newmsa->sqname[i]));
3185 if((status = cp_and_add_gaps_to_aseq(newmsa->aseq[i], msa->aseq[i], msa->alen, toadd, nnew, '.') != eslOK)) goto ERROR;
3186 free(msa->aseq[i]);
3187 msa->aseq[i] = NULL;
3188 }
3189 newmsa->abc = abc;
3190 esl_msa_Digitize(newmsa->abc, newmsa, NULL);
3191 esl_msa_Destroy(msa);
3192 *ret_msa = newmsa;
3193
3194 return eslOK;
3195
3196 ERROR:
3197 return status;
3198 }
3199
3200
3201 /*cp_and_add_gaps_to_aseq
3202 *
3203 * Given an aligned [0..alen-1] original text string,
3204 * add toadd[apos-1] gaps after each residue.
3205 * new_aseq must be already allocated.
3206 *
3207 * toadd is numbered 1..alen.
3208 */
3209 static int cp_and_add_gaps_to_aseq(char *new_aseq, char *orig_aseq, int alen, int *toadd, int nnew, char gapchar)
3210 {
3211 int orig_apos = 0;
3212 int new_apos = 0;
3213 int i;
3214
3215 for(i = 0; i < toadd[0]; i++)
3216 new_aseq[new_apos++] = gapchar;
3217 for(orig_apos = 0; orig_apos < alen; orig_apos++)
3218 {
3219 new_aseq[new_apos++] = orig_aseq[orig_apos];
3220 for(i = 0; i < toadd[(orig_apos+1)]; i++)
3221 new_aseq[new_apos++] = gapchar;
3222 }
3223 new_aseq[new_apos] = '\0';
3224 return eslOK;
3225 }
3226
3227
3228 /* Function: convert_post_to_pp()
3229 *
3230 * Purpose: Convert 'POST' annotation in an MSA (from Infernal 0.72-1.0)
3231 * to 'PP' annotation in place. <nali> is provided only so that
3232 * we can provide it in an error message if nec.
3233 *
3234 */
3235 static int
3236 convert_post_to_pp(ESL_MSA *msa, char *errbuf, int nali)
3237 {
3238 int status;
3239 int ridx1, ridx2, ndigits;
3240 int r,i,apos;
3241 int ir2;
3242
3243 /* Find out which #=GR line is the POST, Post, or post line (if more than one exist, last one is chosen) */
3244 ridx1 = -1;
3245 ridx2 = -1;
3246 ndigits = 0;
3247 for (r = 0; r < msa->ngr; r++) {
3248 if (strcmp(msa->gr_tag[r], "POST") == 0) { ridx1 = r; ndigits = 1; }
3249 if (strcmp(msa->gr_tag[r], "Post") == 0) { ridx1 = r; ndigits = 1; }
3250 if (strcmp(msa->gr_tag[r], "post") == 0) { ridx1 = r; ndigits = 1; }
3251 if (strcmp(msa->gr_tag[r], "POSTX.") == 0) { ridx1 = r; ndigits = 1; }
3252 if (strcmp(msa->gr_tag[r], "POST.X") == 0) { ridx2 = r; ndigits = 2; }
3253 }
3254 if(ndigits == 0) {
3255 ESL_FAIL(eslEINVAL, errbuf, "--post2pp requires \"#=GR POST\", \"#=GR Post\", \"#=GR post\", \"#=GR POSTX.\", or \"#=GR POSTX.\" and \"#=GR POST.X\" annotation, it's missing from alignment %d\n", nali);
3256 }
3257 if(ndigits == 2 && ridx1 == -1) {
3258 ESL_FAIL(eslEINVAL, errbuf, "found \"#=GR POST.X\" annotation but not \"#=GR POSTX.\" in alignment %d.\n", nali);
3259 }
3260 /* make sure that the POST annotation is the only GR annotation we have,
3261 * this should be the case if alignment was created with infernal's cmalign
3262 * v0.72-v1.0.2, which is the only type of alignments that should have POST
3263 * annotation */
3264 if((ndigits == 1 && msa->ngr != 1) || (ndigits == 2 && msa->ngr != 2))
3265 ESL_FAIL(eslEINVAL, errbuf, "additional \"#=GR\" annotation exists besides posteriors, alignment wasn't created by cmalign v0.72-v1.0.2");
3266
3267 ESL_ALLOC(msa->pp, sizeof(char *) * msa->nseq);
3268 for(i = 0; i < msa->nseq; i++) {
3269 ESL_ALLOC(msa->pp[i], sizeof(char) * (msa->alen+1));
3270 }
3271 if(ndigits == 1) { /* easy case, just copy the annotation */
3272 for(i = 0; i < msa->nseq; i++) {
3273 esl_strdup(msa->gr[ridx1][i], msa->alen, &(msa->pp[i]));
3274 free(msa->gr[ridx1][i]);
3275 }
3276 free(msa->gr[ridx1]);
3277 free(msa->gr_tag[ridx1]);
3278 }
3279 else { /* ndigits == 2 */
3280 for(i = 0; i < msa->nseq; i++) {
3281 for(apos = 0; apos < msa->alen; apos++) {
3282 if(esl_abc_CIsGap(msa->abc, msa->gr[ridx1][i][apos])) {
3283 if(! esl_abc_CIsGap(msa->abc, msa->gr[ridx2][i][apos])) ESL_FAIL(eslEINVAL, errbuf, "reading post annotation for seq: %d aln column: %d, post 'tens' value gap but post 'ones' value is gap.\n", i, apos);
3284 msa->pp[i][apos] = '.';
3285 }
3286 else if(msa->gr[ridx1][i][apos] == '*') {
3287 if(msa->gr[ridx2][i][apos] != '*') ESL_FAIL(eslEINVAL, errbuf, "reading post annotation for aln %d, seq: %d aln column: %d, post 'tens' value '*' but post 'ones' value != '*'.\n", nali, i, apos);
3288 msa->pp[i][apos] = '*';
3289 }
3290 else {
3291 ir2 = (int) (msa->gr[ridx2][i][apos] - '0');
3292 if(ir2 >= 5) { /* round up, being careful to round 95 and above to '*' */
3293 msa->pp[i][apos] = (msa->gr[ridx1][i][apos] == '9') ? '*' : msa->gr[ridx1][i][apos] + 1;
3294 }
3295 else {
3296 msa->pp[i][apos] = msa->gr[ridx1][i][apos];
3297 }
3298 }
3299 }
3300 free(msa->gr[ridx1][i]);
3301 free(msa->gr[ridx2][i]);
3302 }
3303 free(msa->gr[ridx1]);
3304 free(msa->gr[ridx2]);
3305 free(msa->gr_tag[ridx1]);
3306 free(msa->gr_tag[ridx2]);
3307 }
3308 /* done filling msa->pp, now free gr annotation, we know from check above
3309 * the msa's GR annotation only consists of the posterior annotation, so
3310 * we can safely remove GR altogether (without worrying about reordering other GRs) */
3311 free(msa->gr);
3312 msa->gr = NULL;
3313 msa->ngr = 0;
3314 /* gr_idx will no longer be valid so we destroy it,
3315 * we could recreate it, but it's only used for parsing anyhow */
3316 if(msa->gr_idx != NULL) { esl_keyhash_Destroy(msa->gr_idx); msa->gr_idx = NULL; }
3317 msa->gr_idx = NULL;
3318
3319 return eslOK;
3320
3321 ERROR:
3322 esl_fatal("convert_post_to_pp(), memory allocation error.");
3323 return eslOK; /* NEVERREACHED */
3324 }
3325
3326 /* write_rf_gapthresh
3327 *
3328 * Given an MSA write/rewrite RF based on fraction
3329 * of gaps in each column. If fraction < gapthresh RF is an 'x',
3330 * otherwise it's a '.' (gap).
3331 */
3332 static int
3333 write_rf_gapthresh(const ESL_GETOPTS *go, char *errbuf, ESL_MSA *msa, float gapthresh)
3334 {
3335 int status;
3336 int64_t apos;
3337 int64_t gaps;
3338 int i;
3339
3340 if (msa->rf == NULL) ESL_ALLOC(msa->rf, sizeof(char) * (msa->alen+1));
3341
3342 for (apos = 1; apos <= msa->alen; apos++) msa->rf[(apos-1)] = '.'; // set as all gaps
3343
3344 for (apos = 1; apos <= msa->alen; apos++) {
3345 for (gaps = 0, i = 0; i < msa->nseq; i++) {
3346 if (esl_abc_XIsGap(msa->abc, msa->ax[i][apos])) gaps++;
3347 }
3348 if ((double) gaps / (double) msa->nseq < gapthresh) msa->rf[(apos-1)] = 'x'; // column passes gap threshold
3349 else msa->rf[(apos-1)] = '.'; // column fails the gap threshold
3350 }
3351 msa->rf[msa->alen] = '\0';
3352 return eslOK;
3353
3354 ERROR:
3355 return status;
3356 }
3357
3358 /* Function: compare_ints()
3359 *
3360 * Purpose: Comparison function for qsort(). Used
3361 * by msa_median_length().
3362 *
3363 * Return 1 if el1 > el2, -1 if el1 < el2 and 0 if el1 == el2.
3364 * This will result in a sorted list with smallest
3365 * element as the first element, largest as the last.
3366 */
3367 int
3368 compare_ints(const void *el1, const void *el2)
3369 {
3370 if ((* ((int *) el1)) > (* ((int *) el2))) return 1;
3371 else if ((* ((int *) el1)) < (* ((int *) el2))) return -1;
3372 return 0;
3373 }
3374