Debian Codegraph @

src/cmbuild.c

raw symbols SCIP
1 /* cmbuild: covariance model construction from a multiple sequence alignment.
2 *
3 * SRE, Thu Jul 27 13:19:43 2000 [StL]
4 */
5
6 #include <esl_config.h>
7 #include "config.h"
8
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <ctype.h>
13 #include <math.h>
14
15 #include "easel.h"
16 #include "esl_alphabet.h"
17 #include "esl_distance.h"
18 #include "esl_dmatrix.h"
19 #include "esl_getopts.h"
20 #include "esl_msa.h"
21 #include "esl_msafile.h"
22 #include "esl_msaweight.h"
23 #include "esl_msacluster.h"
24 #include "esl_stack.h"
25 #include "esl_stopwatch.h"
26 #include "esl_tree.h"
27 #include "esl_vectorops.h"
28
29 #include "hmmer.h"
30
31 #include "infernal.h"
32
33 #define CONOPTS "--fast,--hand,--rsearch" /* Exclusive options for model construction */
34 #define WGTOPTS "--wpb,--wgsc,--wblosum,--wnone,--wgiven" /* Exclusive options for relative weighting */
35 #define EFFOPTS "--eent,--enone,--eset" /* Exclusive options for effective sequence number calculation */
36 #define FRAGOPTS "--fragthresh,--fragnrfpos,--fraggiven" /* Exclusive options for fragment definition */
37 #define CLUSTOPTS "--ctarget,--cmaxid,--call,--corig,--cdump" /* options for clustering the input aln and building a CM from each cluster */
38
39 static ESL_OPTIONS options[] = {
40 /* name type default env range toggles reqs incomp help docgroup*/
41 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 1 },
42 { "-n", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "name the CM(s) <s>, (only if single aln in file)", 1 },
43 { "-F", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "force; allow overwriting of <cmfile_out>", 1 },
44 { "-o", eslARG_OUTFILE,FALSE, NULL, NULL, NULL, NULL, NULL, "direct summary output to file <f>, not stdout", 1 },
45 { "-O", eslARG_OUTFILE,FALSE, NULL, NULL, NULL, NULL, NULL, "resave consensus/insert column annotated MSA to file <f>", 1 },
46 { "--devhelp", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "show list of otherwise hidden developer/expert options", 1 },
47
48 /* Expert model construction options */
49 /* name type default env range toggles reqs incomp help docgroup*/
50 { "--fast", eslARG_NONE,"default", NULL, NULL, CONOPTS, NULL, NULL, "assign cols w/ >= symfrac residues as consensus", 2 },
51 { "--hand", eslARG_NONE, FALSE, NULL, NULL, CONOPTS, NULL, NULL, "use reference coordinate annotation to specify consensus", 2 },
52 { "--symfrac", eslARG_REAL, "0.5", NULL, "0<=x<=1", NULL, NULL, NULL, "fraction of non-gaps to require in a consensus column [0..1]", 2 },
53 { "--fragthresh",eslARG_REAL, "0.5", NULL, "0<=x<=1",FRAGOPTS, NULL, NULL, "if aligned seq spans <= x*alen, tag seq as a fragment", 2 },
54 { "--fragnrfpos", eslARG_INT, NULL, NULL, "n>=0", FRAGOPTS, "--hand", NULL, "w/--hand, seqs w/ > <n> 5' or 3' consensus gaps are fragments", 2 },
55 { "--fraggiven", eslARG_NONE, FALSE, NULL, NULL, FRAGOPTS, NULL, NULL, "use fragment info, if any, in input MSA, don't infer frags", 2 },
56 { "--noss", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "ignore secondary structure annotation in input alignment", 2 },
57 { "--rsearch", eslARG_INFILE, NULL, NULL, NULL, CONOPTS, NULL, "--p56", "use RSEARCH parameterization with RIBOSUM matrix file <f>", 2 },
58 { "--consrf", eslARG_NONE, FALSE, NULL, NULL, NULL, "--hand", NULL, "with --hand, rewrite RF line with consensus sequence", 2 },
59
60 /* Other model construction options */
61 /* name type default env range toggles reqs incomp help docgroup*/
62 { "--null", eslARG_INFILE, NULL, NULL, NULL, NULL, NULL, "--rsearch", "read null (random sequence) model from file <f>", 3 },
63 { "--prior", eslARG_INFILE, NULL, NULL, NULL, NULL, NULL, "--rsearch", "read priors from file <f>", 3 },
64 /* below are only shown with --devhelp */
65 { "--betaW", eslARG_REAL, "1E-7", NULL, "x>1E-18", NULL, NULL, NULL, "set tail loss prob for calc'ing W (max size of a hit) to <x>", 103 },
66 { "--beta1", eslARG_REAL, "1E-7", NULL, "x>1E-18", NULL, NULL, NULL, "set tail loss prob for calc'ing tighter set of QDBs to <x>", 103 },
67 { "--beta2", eslARG_REAL, "1E-15", NULL, "x>1E-18", NULL, NULL, NULL, "set tail loss prob for calc'ing looser set of QDBs to <x>", 103 },
68 { "--informat", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "specify input alignment is in format <s> (Stockholm or Pfam)", 103 },
69 { "--v1p0", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "parameterize CM using methods from Infernal v1.0.2", 103 },
70 { "--p56", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, "--prior", "use the default prior from Infernal v0.56 through v1.0.2", 103 },
71 { "--noh3pri", eslARG_NONE, NULL, NULL, NULL, NULL, NULL,"--v1p0,--p56","do not use the hmmer3 DNA prior for zero basepair models", 103 },
72 { "--iins", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "allow informative insert emissions, do not zero them", 103 },
73 { "--iflank", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "learn ROOT_IL/ROOT_IR transitions for 5'/3' flanking residues",103 },
74 { "--nobalance", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "don't rebalance the CM; number in strict preorder", 103 },
75 { "--nodetach", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "do not 'detach' one of two inserts that model same column", 103 },
76 { "--elself", eslARG_REAL, "0.94", NULL, "0<=x<=1", NULL, NULL, NULL, "set EL self transition prob to <x>", 103 },
77 { "--n2omega", eslARG_REAL, "0.000015258791",NULL,"x>0", NULL, NULL, NULL, "set prior probability of null2 model as <x>", 103 },
78 { "--n3omega", eslARG_REAL, "0.000015258791",NULL,"x>0", NULL, NULL, NULL, "set prior probability of null3 model as <x>", 103 },
79
80 /* Alternate relative sequence weighting strategies */
81 /* name type default env range toggles reqs incomp help docgroup*/
82 { "--wpb", eslARG_NONE,"default", NULL, NULL, WGTOPTS, NULL, NULL, "Henikoff position-based weights", 4 },
83 { "--wgsc", eslARG_NONE, NULL, NULL, NULL, WGTOPTS, NULL, NULL, "Gerstein/Sonnhammer/Chothia tree weights", 4 },
84 { "--wnone", eslARG_NONE, NULL, NULL, NULL, WGTOPTS, NULL, NULL, "don't do any relative weighting; set all to 1", 4 },
85 { "--wgiven", eslARG_NONE, NULL, NULL, NULL, WGTOPTS, NULL, NULL, "use weights as given in MSA file", 4 },
86 { "--wblosum", eslARG_NONE, NULL, NULL, NULL, WGTOPTS, NULL, NULL, "Henikoff simple filter weights", 4 },
87 { "--wid", eslARG_REAL, "0.62", NULL,"0<=x<=1", NULL, "--wblosum", NULL, "for --wblosum: set identity cutoff", 4 },
88
89 /* Alternate effective sequence weighting strategies */
90 /* name type default env range toggles reqs incomp help docgroup*/
91 { "--eent", eslARG_NONE, "default", NULL, NULL, EFFOPTS, NULL, NULL, "adjust eff seq # to achieve relative entropy target", 5 },
92 { "--enone", eslARG_NONE, FALSE, NULL, NULL, EFFOPTS, NULL, NULL, "no effective seq # weighting: just use nseq", 5 },
93 { "--ere", eslARG_REAL, NULL, NULL, "x>0", NULL, "--eent", NULL, "for --eent: set CM target relative entropy to <x>", 5 },
94 { "--eset", eslARG_REAL, NULL, NULL, "x>=0", EFFOPTS, NULL, NULL, "set eff seq # for all models to <x>", 5 },
95 { "--eminseq", eslARG_REAL, "0.1", NULL, "x>=0", NULL, "--eent", NULL, "for --eent: set minimum effective sequence number to <x>", 5 },
96 { "--emaxseq", eslARG_REAL, NULL, NULL, "x>=0", NULL, "--eent", NULL, "for --eent: set maximum effective sequence number to <x>", 5 },
97 { "--ehmmre", eslARG_REAL, NULL, NULL, "x>0", NULL, "--eent", NULL, "for --eent: set minimum HMM relative entropy to <x>", 5 },
98 { "--esigma", eslARG_REAL, "45.0", NULL, "x>0", NULL, "--eent", NULL, "for --eent: set sigma param to <x>", 5 },
99
100 /* Options controlling filter p7 HMM construction */
101 /* name type default env range toggles reqs incomp help docgroup*/
102 { "--p7ere", eslARG_REAL, NULL, NULL, NULL, NULL, NULL, "--p7ml", "for the filter p7 HMM, set minimum rel entropy/posn to <x>", 6 },
103 { "--p7ml", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "define the filter p7 HMM as the ML p7 HMM", 6 },
104 /* below are only shown with --devhelp */
105 { "--p7prior", eslARG_INFILE, NULL, NULL, NULL, NULL, NULL, "--p7ml", "read p7 prior for the filter HMM from file <f>", 106 },
106 { "--p7hprior", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, "--p7ml", "use HMMER's default p7 prior, not Infernal's p7 prior", 106 },
107 { "--p7hemit", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--p7ml", "use HMMER emission priors for filter HMM", 106 },
108
109 /* Options controlling filter p7 HMM calibration */
110 /* name type default env range toggles reqs incomp help docgroup*/
111 { "--EmN", eslARG_INT, "200", NULL, "n>0", NULL, NULL, NULL, "number of sampled seqs to use for p7 local MSV calibration", 7 },
112 { "--EvN", eslARG_INT, "200", NULL, "n>0", NULL, NULL, NULL, "number of sampled seqs to use for p7 local Vit calibration", 7 },
113 { "--ElfN", eslARG_INT, "200", NULL, "n>0", NULL, NULL, NULL, "number of sampled seqs to use for p7 local Fwd calibration", 7 },
114 { "--EgfN", eslARG_INT, "200", NULL, "n>0", NULL, NULL, NULL, "number of sampled seqs to use for p7 glocal Fwd calibration", 7 },
115 /* below are only shown with --devhelp */
116 { "--Elftp", eslARG_REAL, "0.055", NULL, "x>0.", NULL, NULL, NULL, "fit p7 local fwd exp tail to <f> fraction of scoring dist", 107 },
117 { "--Egftp", eslARG_REAL, "0.065", NULL, "x>0.", NULL, NULL, NULL, "fit p7 glocal fwd exp tail to <f> fraction of scoring dist", 107 },
118 { "--Ereal", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "sample realistic, not iid genomic seqs, for p7 calibration", 107 },
119 { "--Enull3", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use null3 correction in p7 calibrations", 107 },
120 { "--Ebias", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use bias correction in p7 calibrations", 107 },
121 { "--Efitlam", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "fit lambda, don't use a fixed one near 0.693", 107 },
122 { "--Elcmult", eslARG_REAL, "2.0", NULL, "x>0.", NULL, NULL, NULL, "length of seqs to search for local stats is <x> * cm->clen", 107 },
123 { "--Egcmult", eslARG_REAL, "2.0", NULL, "x>0.", NULL, NULL, NULL, "length of seqs to search for glocal stats is <x> * cm->clen", 107 },
124 { "--ElL", eslARG_INT, NULL, NULL, "n>0", NULL, NULL, "--Elcmult", "length of seqs to search for local stats is <n>", 107 },
125 { "--EgL", eslARG_INT, NULL, NULL, "n>0", NULL, NULL, "--Egcmult", "length of seqs to search for glocal stats is <n>", 107 },
126
127 /* Refining the input alignment */
128 /* name type default env range toggles reqs incomp help docgroup*/
129 { "--refine", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "refine input aln w/Expectation-Maximization, save to <f>", 8 },
130 { "-l", eslARG_NONE, FALSE, NULL, NULL, NULL, "--refine", NULL, "w/--refine, configure model for local alignment [default: global]", 8 },
131 { "--gibbs", eslARG_NONE, FALSE, NULL, NULL, NULL, "--refine", NULL, "w/--refine, use Gibbs sampling instead of EM", 8 },
132 { "--seed", eslARG_INT, "0", NULL, "n>=0", NULL, "--gibbs", NULL, "w/--gibbs, set RNG seed to <n> (if 0: one-time arbitrary seed)", 8 },
133 { "--cyk", eslARG_NONE, FALSE, NULL, NULL, NULL, "--refine", NULL, "w/--refine, use CYK instead of optimal accuracy", 8 },
134 { "--notrunc", eslARG_NONE, FALSE, NULL, NULL, NULL, "--refine", NULL, "w/--refine, do not use truncated alignment algorithm", 8 },
135 { "--miss", eslARG_NONE, FALSE, NULL, NULL, NULL, "--refine", NULL, "w/--refine, mark seqs w/terminal gaps as fragments", 8 },
136 /* below are only shown with --devhelp */
137 { "--sub", eslARG_NONE, FALSE, NULL, NULL, NULL, "--refine", "--notrunc,-l", "w/--refine, use sub CM for columns b/t HMM start/end points", 108 },
138 { "--nonbanded", eslARG_NONE, FALSE, NULL, NULL, NULL, "--refine", NULL, "do not use bands to accelerate alignment with --refine", 108 },
139 { "--indi", eslARG_NONE, FALSE, NULL, NULL, NULL, "--refine", NULL, "print individual sequence scores during MSA refinement", 108 },
140 { "--fins", eslARG_NONE, FALSE, NULL, NULL, NULL, "--refine", NULL, "w/--refine, flush inserts left/right in alignments", 108 },
141 { "--tau", eslARG_REAL, "1E-7", NULL, "0<x<1", NULL, "--refine", "--nonbanded", "set tail loss prob for HMM bands to <x>", 108 },
142 { "--mxsize", eslARG_REAL, "2048.0", NULL, "x>0.", NULL, "--refine", NULL, "set maximum allowable DP matrix size to <x> Mb", 108 },
143 { "--rdump", eslARG_OUTFILE , NULL, NULL, NULL, NULL, "--refine", NULL, "w/--refine, print all intermediate alignments to <f>", 108 },
144
145 /* All options below are developer options, only shown if --devhelp invoked */
146 /* Developer verbose output options */
147 /* name type default env range toggles reqs incomp help docgroup*/
148 { "--verbose", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "be verbose with output", 109 },
149 { "--cfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save count vectors to file <f>", 109 },
150 { "--efile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save emission score information to file <f>", 109 },
151 { "--tfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "dump individual sequence parsetrees to file <f>", 109 },
152 { "--cmtbl", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save tabular description of CM topology to file <f>", 109 },
153 { "--emap", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save consensus emit map to file <f>", 109 },
154 { "--gtree", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save tree description of master tree to file <f>", 109 },
155 { "--gtbl", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save tabular description of master tree to file <f>", 109 },
156 { "--occfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save expected occupancy of each CM state to <f>", 109 },
157 { "--cp9occfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save expected occupancy of each CP9 ML HMM state to <f>", 109 },
158 { "--fp7occfile", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "save expected occupancy of each filter P7 HMM state to <f>", 109 },
159
160 /* Building multiple CMs after clustering input MSA */
161 /* name type default env range toggles reqs incomp help docgroup*/
162 { "--ctarget", eslARG_INT, NULL, NULL, "n>0" , NULL, NULL, "--call", "build (at most) <n> CMs by partitioning MSA into <n> clusters", 110 },
163 { "--cmaxid", eslARG_REAL, NULL, NULL, "0.<x<1.", NULL, NULL, "--call", "max fractional id b/t 2 clusters is <x>, each cluster -> CM", 110 },
164 { "--call", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "build a separate CM from every seq in MSA", 110 },
165 { "--corig", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "build an additional CM from the original, full MSA", 110 },
166 { "--cdump", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "dump the MSA for each cluster (CM) to file <f>", 110 },
167
168 /* Developer options related to experimental local begin/end modes */
169 /* name type default env range toggles reqs incomp help docgroup*/
170 { "--pbegin", eslARG_REAL, "0.05", NULL, "0<x<1", NULL, NULL, NULL, "set aggregate local begin prob to <x>", 111 },
171 { "--pend", eslARG_REAL, "0.05", NULL, "0<x<1", NULL, NULL, NULL, "set aggregate local end prob to <x>", 111 },
172 { "--pebegin", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--pbegin", "set all local begins as equiprobable", 111 },
173 { "--pfend", eslARG_REAL, NULL, NULL, "0<x<1", NULL, NULL, "--pend", "set all local end probs to <x>", 111 },
174
175 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
176 };
177
178 /* struct cfg_s : "Global" application configuration shared by all threads/processes
179 *
180 * This structure is passed to routines within main.c, as a means of semi-encapsulation
181 * of shared data amongst different parallel processes (threads or MPI processes).
182 * This strategy is used despite the fact that a MPI version of cmbuild does not
183 * yet exist!
184 */
185 struct cfg_s {
186 FILE *ofp; /* output file (default is stdout) */
187
188 char *alifile; /* name of the alignment file we're building CMs from */
189 int fmt; /* format code for alifile */
190 ESL_MSAFILE *afp; /* open alifile */
191 ESL_ALPHABET *abc; /* digital alphabet */
192
193 char *cmfile; /* file to write CM to */
194 FILE *cmoutfp; /* CM output file handle */
195
196 char *postmsafile; /* optional file to resave annotated MSAs to */
197 FILE *postmsafp; /* open <postmsafile>, or NULL */
198
199 float *null; /* null model */
200 Prior_t *pri; /* mixture Dirichlet prior for the CM */
201 Prior_t *pri_zerobp; /* mixture Dirichlet prior for any CMs with 0 basepairs */
202
203 fullmat_t *fullmat; /* if --rsearch, the full RIBOSUM matrix */
204
205 int be_verbose; /* standard verbose output, as opposed to one-line-per-CM summary */
206 int nali; /* which # alignment this is in file */
207 int nnamed; /* number of alignments that had their own names */
208 int ncm_total; /* which # CM this is that we're constructing (we may build > 1 per file) */
209 ESL_RANDOMNESS *r; /* source of randomness, only created if --gibbs enabled */
210
211 /* optional files used for building additional filter p7 HMMs */
212 P7_BG *fp7_bg; /* background model for additional P7s */
213 P7_BUILDER *fp7_bld; /* the P7_BUILDER */
214
215 /* optional output files */
216 FILE *cfp; /* for --cfile */
217 FILE *escfp; /* for --efile */
218 FILE *tblfp; /* for --cmtbl */
219 FILE *efp; /* for --emap */
220 FILE *gfp; /* for --gtree */
221 FILE *gtblfp; /* for --gtbl */
222 FILE *tfp; /* for --tfile */
223 FILE *occfp; /* for --occfile */
224 FILE *cp9occfp; /* for --cp9occfile */
225 FILE *fp7occfp; /* for --fp7occfile */
226 FILE *cdfp; /* if --cdump, output file handle for dumping clustered MSAs */
227 FILE *refinefp; /* if --refine, output file handle for dumping refined MSAs */
228 FILE *rdfp; /* if --rfile, output file handle for dumping intermediate MSAs during iterative refinement */
229 };
230
231 static char usage[] = "[-options] <cmfile_out> <msafile>";
232 static char banner[] = "covariance model construction from multiple sequence alignments";
233
234 static void master(const ESL_GETOPTS *go, struct cfg_s *cfg);
235 static void process_commandline(int argc, char **argv, ESL_GETOPTS **ret_go, char **ret_cmfile, char **ret_alifile);
236 static void output_header(FILE *ofp, const ESL_GETOPTS *go, char *cmfile, char *alifile);
237 static int init_cfg(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf);
238 static int process_build_workunit(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa, CM_t **ret_cm, Parsetree_t **ret_mtr, Parsetree_t ***ret_msa_tr);
239 static int output_result(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, int msaidx, int cmidx, ESL_MSA *msa, CM_t *cm, Parsetree_t *mtr, Parsetree_t **tr);
240 static int check_and_clean_msa(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa);
241 static int set_relative_weights(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa);
242 static int check_fragments(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa);
243 static int mark_fragments(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa);
244 static int build_model(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, int do_print, ESL_MSA *msa, CM_t **ret_cm, Parsetree_t **ret_mtr, Parsetree_t ***ret_msa_tr);
245 static int annotate(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa, CM_t *cm);
246 static int set_model_cutoffs(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa, CM_t *cm);
247 static int set_effective_seqnumber(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa, CM_t *cm, const Prior_t *pri);
248 static int parameterize(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, int do_print, CM_t *cm, const Prior_t *prior, float msa_nseq);
249 static int configure_model(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm, int iter);
250 static int set_consensus(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm);
251 static int build_and_calibrate_p7_filter(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa, CM_t *cm, int use_mlp7_as_filter);
252 static int set_msa_name(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, ESL_MSA *msa);
253 static double set_target_relent(const ESL_GETOPTS *go, const ESL_ALPHABET *abc, int clen, int nbps);
254 static double version_1p0_default_target_relent(const ESL_ALPHABET *abc, int M, double eX);
255 static int refine_msa(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *orig_cm, ESL_MSA *input_msa, Parsetree_t **input_msa_tr, CM_t **ret_cm, ESL_MSA **ret_msa, Parsetree_t **ret_mtr, Parsetree_t ***ret_trA, int *ret_niter);
256 static int convert_parsetrees_to_unaln_coords(Parsetree_t **tr, ESL_MSA *msa);
257 /* static void model_trace_info_dump(FILE *ofp, CM_t *cm, Parsetree_t *tr, char *aseq); */
258 /* functions for dividing input MSA into clusters */
259 static int select_node(ESL_TREE *T, double *diff, double mindiff, int **ret_clust, int *ret_nc, int *ret_best, char *errbuf);
260 static float find_mindiff(ESL_TREE *T, double *diff, int target_nc, int **ret_clust, int *ret_nc, float *ret_mindiff, char *errbuf);
261 static int MSADivide(ESL_MSA *mmsa, int do_all, int do_mindiff, int do_nc, float mindiff, int target_nc, int do_orig, int *ret_num_msa, ESL_MSA ***ret_cmsa, char *errbuf);
262 static int flatten_insert_emissions(CM_t *cm);
263 static int print_column_headings(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf);
264 static void print_refine_column_headings(const ESL_GETOPTS *go, const struct cfg_s *cfg);
265 static int print_countvectors(FILE *fp, CM_t *cm);
266 static int dump_emission_info(FILE *fp, CM_t *cm, char *errbuf);
267 static P7_PRIOR * p7_prior_Read(FILE *fp);
268 static P7_PRIOR * cm_p7_prior_CreateNucleic(void);
269 static void dump_cm_occupancy_values(FILE *fp, CM_t *cm);
270 static void dump_cp9_occupancy_values(FILE *fp, char *name, CP9_t *cp9);
271 static void dump_fp7_occupancy_values(FILE *fp, char *name, P7_HMM *p7);
272 static int determine_pretend_cm_is_hmm(const ESL_GETOPTS *go, CM_t *cm);
273
274 int
275 main(int argc, char **argv)
276 {
277 ESL_GETOPTS *go = NULL; /* command line processing */
278 ESL_STOPWATCH *w = esl_stopwatch_Create();
279 if(w == NULL) cm_Fail("Memory allocation error, stopwatch could not be created.");
280 esl_stopwatch_Start(w);
281 struct cfg_s cfg;
282
283 /* setup logsum lookups (could do this only if nec based on options, but this is safer) */
284 init_ilogsum();
285 FLogsumInit();
286 process_commandline(argc, argv, &go, &(cfg.cmfile), &(cfg.alifile));
287
288 /* Initialize what we can in the config structure (without knowing the alphabet yet).
289 * We could assume RNA, but this HMMER3 based approach is more general.
290 */
291 cfg.ofp = NULL;
292 cfg.fmt = eslMSAFILE_UNKNOWN; /* possibly reset below */
293 cfg.afp = NULL; /* created in init_cfg() */
294 cfg.abc = NULL; /* created in init_cfg() */
295 cfg.cmoutfp = NULL; /* opened in init_cfg() */
296 cfg.postmsafile= esl_opt_GetString(go, "-O"); /* NULL by default */
297 cfg.postmsafp = NULL;
298 cfg.null = NULL; /* created in init_cfg() */
299 cfg.pri = NULL; /* created in init_cfg() */
300 cfg.fullmat = NULL; /* read (possibly) in init_cfg() */
301 cfg.r = NULL; /* created (possibly) in init_cfg() */
302 cfg.fp7_bg = NULL; /* created (possibly) in init_cfg() */
303 cfg.fp7_bld = NULL; /* created (possibly) in init_cfg() */
304 /* optional output files, opened in init_cfg(), if at all */
305 cfg.cfp = NULL;
306 cfg.escfp = NULL;
307 cfg.tblfp = NULL;
308 cfg.efp = NULL;
309 cfg.gfp = NULL;
310 cfg.gtblfp = NULL;
311 cfg.tfp = NULL;
312 cfg.cdfp = NULL;
313 cfg.refinefp = NULL;
314 cfg.rdfp = NULL;
315 cfg.occfp = NULL;
316 cfg.cp9occfp = NULL;
317 cfg.fp7occfp = NULL;
318
319 if (esl_opt_IsOn(go, "--informat")) {
320 cfg.fmt = esl_msafile_EncodeFormat(esl_opt_GetString(go, "--informat"));
321 if (cfg.fmt == eslMSAFILE_UNKNOWN) cm_Fail("%s is not a recognized input sequence file format\n", esl_opt_GetString(go, "--informat"));
322 if (cfg.fmt != eslMSAFILE_STOCKHOLM && cfg.fmt != eslMSAFILE_PFAM && cfg.fmt != eslMSAFILE_SELEX) {
323 cm_Fail("%s is an invalid format for cmbuild, must be Stockholm, Pfam, or Selex\n", esl_opt_GetString(go, "--informat"));
324 }
325 }
326
327 cfg.be_verbose = esl_opt_GetBoolean(go, "--verbose");
328 cfg.nali = 0; /* this counter is incremented in master */
329 cfg.nnamed = 0; /* 0 or 1 if a single MSA; == nali if multiple MSAs */
330
331 /* check if binary files from cmpress for a model with same name as cmfile already exist,
332 * if so we exit and tell user to delete them; if we went ahead and built a model (even
333 * with -F) then subsequent cmalign/cmsearch/cmscan (others) calls would use the press'd
334 * binary .i1m file instead of the new one we just built, which would be bad. We could
335 * delete the .i1* binary files with -F but that would be the only time any Infernal
336 * programs actually delete files, as opposed to overwrite them. This way is safer I
337 * think.
338 */
339 char *mfile = NULL; /* <cmfile>.i1m file: binary CMs along with their (full) filter p7 HMMs, from cmpress */
340 char *ffile = NULL; /* <cmfile>.i1f file: binary optimized filter p7 profiles, MSV filter part only, from cmpress */
341 char *pfile = NULL; /* <cmfile>.i1p file: binary optimized filter p7 profiles, remainder (excluding MSV filter), from cmpress */
342 char *ifile = NULL; /* <cmfile>.i1i file; ssi file, from cmpress */
343 char *ssifile = NULL; /* <cmfile>.ssi file; ssi file, from cmfetch --index */
344 if (esl_sprintf(&mfile, "%s.i1m", cfg.cmfile) != eslOK) cm_Fail("esl_sprintf() failed");
345 if (esl_sprintf(&ffile, "%s.i1f", cfg.cmfile) != eslOK) cm_Fail("esl_sprintf() failed");
346 if (esl_sprintf(&pfile, "%s.i1p", cfg.cmfile) != eslOK) cm_Fail("esl_sprintf() failed");
347 if (esl_sprintf(&ifile, "%s.i1i", cfg.cmfile) != eslOK) cm_Fail("esl_sprintf() failed");
348 if (esl_sprintf(&ssifile, "%s.i1ssi", cfg.cmfile) != eslOK) cm_Fail("esl_sprintf() failed");
349 if (esl_FileExists(mfile)) cm_Fail("Binary CM file %s already exists; you must delete old cmpress %s.i1* files first", mfile, cfg.cmfile);
350 if (esl_FileExists(ffile)) cm_Fail("Binary MSV filter file %s already exists; you must delete old cmpress %s.i1* files first", ffile, cfg.cmfile);
351 if (esl_FileExists(pfile)) cm_Fail("Binary optimized profile file %s already exists; you must delete old cmpress %s.i1* files first", pfile, cfg.cmfile);
352 if (esl_FileExists(ifile)) cm_Fail("Binary SSI index file %s already exists; you must delete old cmpress %s.i1* files first", ifile, cfg.cmfile);
353 if (esl_FileExists(ssifile)) cm_Fail("Binary SSI index file %s already exists; you must delete this old cmfetch index file first", ssifile, cfg.cmfile);
354 free(mfile);
355 free(ffile);
356 free(pfile);
357 free(ifile);
358 free(ssifile);
359
360 /* check if cmfile already exists, if it does and -F was not enabled then die */
361 if ((! esl_opt_GetBoolean(go, "-F")) && esl_FileExists(cfg.cmfile)) {
362 cm_Fail("CM file %s already exists. Either use -F to overwrite it, rename it, or delete it.", cfg.cmfile);
363 }
364
365 /* do work */
366 master(go, &cfg);
367
368 /* Clean up the cfg. */
369 /* close all output files */
370 if (cfg.postmsafp || cfg.cfp || cfg.escfp || cfg.tblfp || cfg.efp || cfg.gfp || cfg.gtblfp || cfg.tfp || cfg.cdfp || cfg.refinefp || cfg.rdfp || cfg.occfp || cfg.cp9occfp || cfg.fp7occfp) {
371 fprintf(cfg.ofp, "#\n");
372 }
373 if (cfg.postmsafp != NULL) {
374 fprintf(cfg.ofp, "# Processed and annotated MSAs saved to file %s.\n", esl_opt_GetString(go, "-O"));
375 fclose(cfg.postmsafp);
376 }
377 if (cfg.cfp != NULL) {
378 fprintf(cfg.ofp, "# Count vectors saved in file %s.\n", esl_opt_GetString(go, "--cfile"));
379 fclose(cfg.cfp);
380 }
381 if (cfg.escfp != NULL) {
382 fprintf(cfg.ofp, "# Emission score information saved in file %s.\n", esl_opt_GetString(go, "--efile"));
383 fclose(cfg.escfp);
384 }
385 if (cfg.tblfp != NULL) {
386 fprintf(cfg.ofp, "# CM topology description saved in file %s.\n", esl_opt_GetString(go, "--cmtbl"));
387 fclose(cfg.tblfp);
388 }
389 if (cfg.efp != NULL) {
390 fprintf(cfg.ofp, "# CM emit map saved in file %s.\n", esl_opt_GetString(go, "--emap"));
391 fclose(cfg.efp);
392 }
393 if (cfg.gfp != NULL) {
394 fprintf(cfg.ofp, "# Guide tree description saved in file %s.\n", esl_opt_GetString(go, "--gtree"));
395 fclose(cfg.gfp);
396 }
397 if (cfg.gtblfp != NULL) {
398 fprintf(cfg.ofp, "# Guide tree tabular description saved in file %s.\n", esl_opt_GetString(go, "--gtbl"));
399 fclose(cfg.gtblfp);
400 }
401 if (cfg.tfp != NULL) {
402 fprintf(cfg.ofp, "# Implicit parsetrees of seqs from input alignment saved in file %s.\n", esl_opt_GetString(go, "--tfile"));
403 fclose(cfg.tfp);
404 }
405 if (cfg.cdfp != NULL) {
406 fprintf(cfg.ofp, "# Alignments for each cluster saved in file %s.\n", esl_opt_GetString(go, "--cdump"));
407 fclose(cfg.cdfp);
408 }
409 if (cfg.refinefp != NULL) {
410 fprintf(cfg.ofp, "# Refined alignments used to build CMs saved in file %s.\n", esl_opt_GetString(go, "--refine"));
411 fclose(cfg.refinefp);
412 }
413 if (cfg.rdfp != NULL) {
414 fprintf(cfg.ofp, "# Intermediate alignments from MSA refinement saved in file %s.\n", esl_opt_GetString(go, "--rdump"));
415 fclose(cfg.rdfp);
416 }
417 if (cfg.occfp != NULL) {
418 fprintf(cfg.ofp, "# Expected occupancy values for each CM state saved in file %s.\n", esl_opt_GetString(go, "--occfile"));
419 fclose(cfg.occfp);
420 }
421 if (cfg.cp9occfp != NULL) {
422 fprintf(cfg.ofp, "# Expected occupancy values for each CM CP9 HMM state saved in file %s.\n", esl_opt_GetString(go, "--cp9occfile"));
423 fclose(cfg.cp9occfp);
424 }
425 if (cfg.fp7occfp != NULL) {
426 fprintf(cfg.ofp, "# Expected occupancy values for each filter P7 HMM state saved in file %s.\n", esl_opt_GetString(go, "--fp7occfile"));
427 fclose(cfg.fp7occfp);
428 }
429
430 if (cfg.afp != NULL) esl_msafile_Close(cfg.afp);
431 if (cfg.abc != NULL) esl_alphabet_Destroy(cfg.abc);
432 if (cfg.cmoutfp != NULL) fclose(cfg.cmoutfp);
433 if (cfg.pri != NULL) Prior_Destroy(cfg.pri);
434 if (cfg.pri_zerobp != NULL) Prior_Destroy(cfg.pri_zerobp);
435 if (cfg.null != NULL) free(cfg.null);
436 if (cfg.r != NULL) esl_randomness_Destroy(cfg.r);
437 if (cfg.fp7_bg != NULL) p7_bg_Destroy(cfg.fp7_bg);
438 if (cfg.fp7_bld != NULL) p7_builder_Destroy(cfg.fp7_bld);
439
440 esl_stopwatch_Stop(w);
441 fprintf(cfg.ofp, "#\n");
442 esl_stopwatch_Display(cfg.ofp, w, "# CPU time: ");
443 esl_stopwatch_Destroy(w);
444
445 if (esl_opt_IsOn(go, "-o")) { fclose(cfg.ofp); }
446 esl_getopts_Destroy(go);
447 return 0;
448 }
449
450 static void
451 master(const ESL_GETOPTS *go, struct cfg_s *cfg)
452 {
453 int status;
454 char errbuf[eslERRBUFSIZE];
455 ESL_MSA *msa = NULL;
456 CM_t *cm = NULL;
457 Parsetree_t *mtr;
458 Parsetree_t **tr;
459 int i = 0;
460 int niter = 0;
461 /* new_* data structures, created in refine_msa() if --refine enabled */
462 CM_t *new_cm;
463 Parsetree_t *new_mtr;
464 Parsetree_t **new_tr;
465 ESL_MSA *new_msa;
466 /* cluster option related variables */
467 int do_cluster; /* TRUE if --ctarget || --cmaxid || --call */
468 int do_ctarget; /* TRUE if --ctarget */
469 int do_cmindiff; /* TRUE if --cmaxid */
470 int do_call; /* TRUE if --call */
471 int nc; /* number of clusters, only != 0 if do_ctarget */
472 float mindiff; /* minimum fractional diff b/t clusters, only != 0. if do_cmindiff */
473 int ncm = 1; /* number of CMs to be built for current MSA */
474 int c = 0; /* counter over CMs built for a single MSA */
475 ESL_MSA **cmsa; /* pointer to cluster MSAs to build CMs from */
476
477 if ((status = init_cfg(go, cfg, errbuf)) != eslOK) cm_Fail(errbuf);
478 output_header(cfg->ofp, go, cfg->cmfile, cfg->alifile);
479
480 cfg->nali = 0;
481 cfg->ncm_total = 0;
482
483 do_ctarget = esl_opt_IsOn(go, "--ctarget");
484 do_cmindiff = esl_opt_IsOn(go, "--cmaxid");
485 do_call = esl_opt_GetBoolean(go, "--call");
486 do_cluster = (do_ctarget || do_cmindiff || do_call) ? TRUE : FALSE;
487 if((do_ctarget + do_cmindiff + do_call) > TRUE) cm_Fail("More than one of --ctarget, --cmaxid, --call were enabled, shouldn't happen.");
488
489 nc = do_ctarget ? esl_opt_GetInteger(go, "--ctarget") : 0;
490 mindiff = do_cmindiff ? (1. - esl_opt_GetReal(go, "--cmaxid")) : 0.;
491
492 while ((status = esl_msafile_Read(cfg->afp, &msa)) != eslEOF)
493 {
494 if (status != eslOK) esl_msafile_ReadFailure(cfg->afp, status);
495 cfg->nali++;
496
497 if(set_msa_name(go, cfg, errbuf, msa) != eslOK) cm_Fail(errbuf);
498 if(msa->name == NULL) cm_Fail("Error naming MSA");
499 ncm = 1; /* default: only build 1 CM for each MSA in alignment file */
500
501 if(do_cluster) /* divide input MSA into clusters, and build CM from each cluster */
502 {
503 if((status = MSADivide(msa, do_call, do_cmindiff, do_ctarget, mindiff, nc,
504 esl_opt_GetBoolean(go, "--corig"), &ncm, &cmsa, errbuf)) != eslOK) cm_Fail(errbuf);
505 esl_msa_Destroy(msa); /* we've copied the master msa into cmsa[ncm], we can delete this copy */
506 }
507 for(c = 0; c < ncm; c++)
508 {
509 cfg->ncm_total++;
510 if(do_cluster) {
511 msa = cmsa[c];
512 if(esl_opt_GetString(go, "--cdump") != NULL) {
513 if((status = esl_msafile_Write(cfg->cdfp, msa, eslMSAFILE_STOCKHOLM)) != eslOK)
514 cm_Fail("--cdump related esl_msafile_Write() call failed.");
515 }
516 }
517
518 /* if being verbose, print some stuff about what we're about to do.
519 */
520 if (cfg->be_verbose) {
521 fprintf(cfg->ofp, "Alignment: %s\n", msa->name);
522 fprintf(cfg->ofp, "Number of sequences: %d\n", msa->nseq);
523 fprintf(cfg->ofp, "Number of columns: %" PRId64 "\n", msa->alen);
524 if(esl_opt_GetString(go, "--rsearch") != NULL)
525 printf ("RIBOSUM Matrix: %s\n", cfg->fullmat->name);
526 fputs("", cfg->ofp);
527 fflush(cfg->ofp);
528 }
529
530 /* msa -> cm */
531 if ((status = process_build_workunit(go, cfg, errbuf, msa, &cm, &mtr, &tr)) != eslOK) cm_Fail(errbuf);
532 /* optionally, iterate over cm -> parsetrees -> msa -> cm ... until convergence, via EM or Gibbs */
533 if ( esl_opt_IsOn(go, "--refine")) {
534 fprintf(cfg->ofp, "#\n");
535 fprintf(cfg->ofp, "# Refining MSA for CM: %s (aln: %4d cm: %6d)\n", cm->name, cfg->nali, cfg->ncm_total);
536 if ((status = refine_msa(go, cfg, errbuf, cm, msa, tr, &new_cm, &new_msa, &new_mtr, &new_tr, &niter)) != eslOK) cm_Fail(errbuf);
537 if(cm != new_cm) FreeCM(cm);
538 cm = new_cm;
539 if (niter > 1) { /* if niter == 1, we didn't make a new mtr, or tr, so we don't free them */
540 for(i = 0; i < msa->nseq; i++) FreeParsetree(tr[i]);
541 free(tr);
542 tr = new_tr;
543 FreeParsetree(mtr);
544 mtr = new_mtr;
545 esl_msa_Destroy(msa);
546 msa = new_msa;
547 }
548 }
549 /* output cm */
550 if ((status = output_result(go, cfg, errbuf, cfg->nali, cfg->ncm_total, msa, cm, mtr, tr)) != eslOK) cm_Fail(errbuf);
551
552 if(cfg->be_verbose) {
553 fprintf(cfg->ofp, "\n");
554 SummarizeCM(cfg->ofp, cm);
555 fprintf(cfg->ofp, "//\n");
556 }
557
558 FreeCM(cm);
559 fflush(cfg->cmoutfp);
560
561 if(tr != NULL) {
562 for(i = 0; i < msa->nseq; i++) FreeParsetree(tr[i]);
563 free(tr);
564 }
565 if(mtr != NULL) FreeParsetree(mtr);
566
567 esl_msa_Destroy(msa);
568 }
569 }
570 if(do_cluster) free(cmsa);
571 if(cfg->fullmat != NULL) FreeMat(cfg->fullmat);
572 return;
573 }
574
575
576 static void
577 process_commandline(int argc, char **argv, ESL_GETOPTS **ret_go, char **ret_cmfile, char **ret_alifile)
578 {
579 ESL_GETOPTS *go = NULL;
580 char *devmsg = "*";
581 int do_dev = FALSE; /* set to TRUE if --devhelp used */
582
583 if ((go = esl_getopts_Create(options)) == NULL) cm_Fail("Internal failure creating options object");
584 if (esl_opt_ProcessEnvironment(go) != eslOK) { printf("Failed to process environment: %s\n", go->errbuf); goto ERROR; }
585 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) { printf("Failed to parse command line: %s\n", go->errbuf); goto ERROR; }
586 if (esl_opt_VerifyConfig(go) != eslOK) { printf("Failed to parse command line: %s\n", go->errbuf); goto ERROR; }
587
588 /* help format: */
589 do_dev = esl_opt_GetBoolean(go, "--devhelp") ? TRUE : FALSE;
590 if(esl_opt_GetBoolean(go, "-h") || do_dev) {
591 cm_banner(stdout, argv[0], banner);
592 esl_usage(stdout, argv[0], usage);
593
594 puts("\nBasic options:");
595 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1= group; 2 = indentation; 80=textwidth*/
596
597 puts("\nAlternative model construction strategies:");
598 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
599
600 printf("\nOther model construction options%s:\n", do_dev ? "" : devmsg);
601 esl_opt_DisplayHelp(stdout, go, 3, 2, 80);
602 if(do_dev) esl_opt_DisplayHelp(stdout, go, 103, 2, 80);
603
604 puts("\nAlternative relative sequence weighting strategies:");
605 esl_opt_DisplayHelp(stdout, go, 4, 2, 80);
606
607 puts("\nAlternative effective sequence weighting strategies:");
608 esl_opt_DisplayHelp(stdout, go, 5, 2, 80);
609
610 printf("\nOptions for HMM filter construction%s:\n", do_dev ? "" : devmsg);
611 esl_opt_DisplayHelp(stdout, go, 6, 2, 80);
612 if(do_dev) esl_opt_DisplayHelp(stdout, go, 106, 2, 80);
613
614 printf("\nOptions for HMM filter calibration%s:\n", do_dev ? "" : devmsg);
615 esl_opt_DisplayHelp(stdout, go, 7, 2, 80);
616 if(do_dev) esl_opt_DisplayHelp(stdout, go, 107, 2, 80);
617
618 printf("\nOptions for refining the input alignment%s:\n", do_dev ? "" : devmsg);
619 esl_opt_DisplayHelp(stdout, go, 8, 2, 80);
620 if(do_dev) esl_opt_DisplayHelp(stdout, go, 108, 2, 80);
621
622 if(do_dev) {
623 puts("\nDeveloper options for verbose output/debugging:");
624 esl_opt_DisplayHelp(stdout, go, 109, 2, 80);
625
626 puts("\nOptions for building multiple CMs after clustering input MSA:");
627 esl_opt_DisplayHelp(stdout, go, 110, 2, 80);
628
629 puts("\nOptions for experimental local begin/end modes:");
630 esl_opt_DisplayHelp(stdout, go, 111, 2, 80);
631 }
632 else {
633 puts("\n*Use --devhelp to show additional expert options.");
634 }
635 exit(0);
636 }
637
638 if (esl_opt_ArgNumber(go) != 2) { puts("Incorrect number of command line arguments."); goto ERROR; }
639 if ((*ret_cmfile = esl_opt_GetArg(go, 1)) == NULL) { puts("Failed to get <cmfile_out> argument on command line"); goto ERROR; }
640 if ((*ret_alifile = esl_opt_GetArg(go, 2)) == NULL) { puts("Failed to get <alifile> argument on command line"); goto ERROR; }
641
642 if (strcmp(*ret_cmfile, "-") == 0) {
643 puts("Can't write <cmfile_out> to stdout: don't use '-'"); goto ERROR;
644 }
645 if (strcmp(*ret_alifile, "-") == 0 && ! esl_opt_IsOn(go, "--informat")) {
646 puts("Must specify --informat to read <alifile> from stdin ('-')"); goto ERROR;
647 }
648
649 *ret_go = go;
650
651 return;
652
653 ERROR: /* all errors handled here are user errors, so be polite. */
654 esl_usage(stdout, argv[0], usage);
655 puts("\nwhere basic options are:");
656 esl_opt_DisplayHelp(stdout, go, 1, 2, 100); /* 1= group; 2 = indentation; 100=textwidth*/
657 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
658 exit(1);
659 }
660
661 static void
662 output_header(FILE *ofp, const ESL_GETOPTS *go, char *cmfile, char *alifile)
663 {
664 cm_banner(ofp, go->argv[0], banner);
665 fprintf(ofp, "# CM file: %s\n", cmfile);
666 fprintf(ofp, "# alignment file: %s\n", alifile);
667 if (esl_opt_IsUsed(go, "-n")) { fprintf(ofp, "# name (the single) CM: %s\n", esl_opt_GetString(go, "-n")); }
668 if (esl_opt_IsUsed(go, "-F")) { fprintf(ofp, "# overwrite CM file if necessary: yes\n"); }
669 if (esl_opt_IsUsed(go, "-o")) { fprintf(ofp, "# output directed to file: %s\n", esl_opt_GetString(go, "-o")); }
670 if (esl_opt_IsUsed(go, "-O")) { fprintf(ofp, "# processed alignment resaved to: %s\n", esl_opt_GetString(go, "-O")); }
671 if (esl_opt_IsUsed(go, "--symfrac")) { fprintf(ofp, "# minimum symbol fraction in a consensus column: %g\n", esl_opt_GetReal(go, "--symfrac")); }
672 if (esl_opt_IsUsed(go, "--fragthresh")) { fprintf(ofp, "# seq called frag if L <= x*alen: %.3f\n", esl_opt_GetReal(go, "--fragthresh")); }
673 if (esl_opt_IsUsed(go, "--hand")) { fprintf(ofp, "# use #=GC RF annotation to define consensus columns: yes\n"); }
674 if (esl_opt_IsUsed(go, "--null")) { fprintf(ofp, "# read null model from file: %s\n", esl_opt_GetString(go, "--null")); }
675 if (esl_opt_IsUsed(go, "--prior")) { fprintf(ofp, "# read prior from file: %s\n", esl_opt_GetString(go, "--prior")); }
676 if (esl_opt_IsUsed(go, "--noss")) { fprintf(ofp, "# ignore secondary structure, if any: yes\n"); }
677 if (esl_opt_IsUsed(go, "--rsearch")) { fprintf(ofp, "# RSEARCH parameterization mode w/RIBOSUM mx file: %s\n", esl_opt_GetString(go, "--rsearch")); }
678 if (esl_opt_IsUsed(go, "--consrf")) { fprintf(ofp, "# rewrite RF as consensus sequence with --hand: yes\n"); }
679 if (esl_opt_IsUsed(go, "--betaW")) { fprintf(ofp, "# tail loss probability for defining W: %g\n", esl_opt_GetReal(go, "--betaW")); }
680 if (esl_opt_IsUsed(go, "--beta1")) { fprintf(ofp, "# tail loss probability for defining tight QDBs: %g\n", esl_opt_GetReal(go, "--beta1")); }
681 if (esl_opt_IsUsed(go, "--beta2")) { fprintf(ofp, "# tail loss probability for defining loose QDBs: %g\n", esl_opt_GetReal(go, "--beta2")); }
682 if (esl_opt_IsUsed(go, "--informat")) { fprintf(ofp, "# input format specified as: %s\n", esl_opt_GetString(go, "--informat")); }
683 if (esl_opt_IsUsed(go, "--v1p0")) { fprintf(ofp, "# v1.0 parameterization mode: on\n"); }
684 if (esl_opt_IsUsed(go, "--p56")) { fprintf(ofp, "# use default priors from v0.56 through v1.0.2: yes\n"); }
685 if (esl_opt_IsUsed(go, "--iins")) { fprintf(ofp, "# allowing informative insert emission probabilities: yes\n"); }
686 if (esl_opt_IsUsed(go, "--iflank")) { fprintf(ofp, "# allowing informative ROOT_IL/IR transition probs: yes\n"); }
687 if (esl_opt_IsUsed(go, "--nobalance")) { fprintf(ofp, "# do default rebalancing of CM: no\n"); }
688 if (esl_opt_IsUsed(go, "--nodetach")) { fprintf(ofp, "# do default detachment of flawed ambiguous inserts: no\n"); }
689 if (esl_opt_IsUsed(go, "--elself")) { fprintf(ofp, "# local end (EL) self loop probability: %g\n", esl_opt_GetReal(go, "--elself")); }
690 if (esl_opt_IsUsed(go, "--n2omega")) { fprintf(ofp, "# prior probability of null2 model (if used): %g\n", esl_opt_GetReal(go, "--n2omega")); }
691 if (esl_opt_IsUsed(go, "--n3omega")) { fprintf(ofp, "# prior probability of null3 model (if used): %g\n", esl_opt_GetReal(go, "--n3omega")); }
692 if (esl_opt_IsUsed(go, "--wpb")) { fprintf(ofp, "# relative weighting scheme: Henikoff PB\n"); }
693 if (esl_opt_IsUsed(go, "--wgsc")) { fprintf(ofp, "# relative weighting scheme: G/S/C\n"); }
694 if (esl_opt_IsUsed(go, "--wnone")) { fprintf(ofp, "# relative weighting scheme: none\n"); }
695 if (esl_opt_IsUsed(go, "--wgiven")) { fprintf(ofp, "# relative weighting scheme: wts from MSA file\n"); }
696 if (esl_opt_IsUsed(go, "--wblosum")) { fprintf(ofp, "# relative weighting scheme: BLOSUM filter\n"); }
697 if (esl_opt_IsUsed(go, "--wid")) { fprintf(ofp, "# frac id cutoff for BLOSUM wgts: %f\n", esl_opt_GetReal(go, "--wid")); }
698
699 if (esl_opt_IsUsed(go, "--eent")) { fprintf(ofp, "# effective seq number scheme: entropy weighting\n"); }
700 if (esl_opt_IsUsed(go, "--enone")) { fprintf(ofp, "# effective seq number scheme: none\n"); }
701 if (esl_opt_IsUsed(go, "--ere")) { fprintf(ofp, "# minimum rel entropy target: %f bits\n", esl_opt_GetReal(go, "--ere")); }
702 if (esl_opt_IsUsed(go, "--eset")) { fprintf(ofp, "# effective seq number: set to %f\n", esl_opt_GetReal(go, "--eset")); }
703 if (esl_opt_IsUsed(go, "--eminseq")) { fprintf(ofp, "# minimum effective sequence number allowed: %g\n", esl_opt_GetReal(go, "--eminseq")); }
704 if (esl_opt_IsUsed(go, "--emaxseq")) { fprintf(ofp, "# maximum effective sequence number allowed: %g\n", esl_opt_GetReal(go, "--emaxseq")); }
705 if (esl_opt_IsUsed(go, "--ehmmre")) { fprintf(ofp, "# minimum ML CP9 HMM rel entropy target: %f bits\n", esl_opt_GetReal(go, "--ehmmre")); }
706 if (esl_opt_IsUsed(go, "--esigma")) { fprintf(ofp, "# entropy target sigma parameter: %f bits\n", esl_opt_GetReal(go, "--esigma")); }
707
708 if (esl_opt_IsUsed(go, "--refine")) { fprintf(ofp, "# input alignment refinement prior to model building: on\n"); }
709 if (esl_opt_IsUsed(go, "-l")) { fprintf(ofp, "# model configuration for aln refinement: local\n"); }
710 if (esl_opt_IsUsed(go, "--gibbs")) { fprintf(ofp, "# Gibbs sampling (instead of EM) for aln refinement: on\n"); }
711 if (esl_opt_IsUsed(go, "--seed")) {
712 if (esl_opt_GetInteger(go, "--seed") == 0) { fprintf(ofp,"# random number seed: one-time arbitrary\n"); }
713 else { fprintf(ofp,"# random number seed set to: %d\n", esl_opt_GetInteger(go, "--seed")); }
714 }
715 if (esl_opt_IsUsed(go, "--notrunc")) { fprintf(ofp, "# use truncated aln algorithms for aln refinement: no\n"); }
716 if (esl_opt_IsUsed(go, "--cyk")) { fprintf(ofp, "# use the CYK algorithm instead of optimal accuracy: yes\n"); }
717 if (esl_opt_IsUsed(go, "--sub")) { fprintf(ofp, "# alternative truncated seq alignment 'sub' mode: on\n"); }
718 if (esl_opt_IsUsed(go, "--nonbanded")) { fprintf(ofp, "# use HMM bands for accelerating aln refinement: no\n"); }
719 if (esl_opt_IsUsed(go, "--indi")) { fprintf(ofp, "# print individual seq scores during aln refinement: yes\n"); }
720 if (esl_opt_IsUsed(go, "--fins")) { fprintf(ofp, "# flush inserts left/rigth during aln refinement: yes\n"); }
721 if (esl_opt_IsUsed(go, "--tau")) { fprintf(ofp, "# tail loss probability for HMM bands set to: %g\n", esl_opt_GetReal(go, "--tau")); }
722 if (esl_opt_IsUsed(go, "--mxsize")) { fprintf(ofp, "# maximum DP matrix size set to: %.2f Mb\n", esl_opt_GetReal(go, "--mxsize")); }
723 if (esl_opt_IsUsed(go, "--rdump")) { fprintf(ofp, "# printing intermediate alns during aln refnment to: %s\n", esl_opt_GetString(go, "--rdump")); }
724
725 if (esl_opt_IsUsed(go, "--p7ml")) { fprintf(ofp, "# filter HMM is ML HMM created from CM: yes\n"); }
726 if (esl_opt_IsUsed(go, "--p7ere")) { fprintf(ofp, "# filter HMM minimum rel entropy target: %g bits\n", esl_opt_GetReal(go, "--p7ere")); }
727 if (esl_opt_IsUsed(go, "--p7prior")) { fprintf(ofp, "# read filter p7 HMM prior from: %s\n", esl_opt_GetString(go, "--p7prior")); }
728 if (esl_opt_IsUsed(go, "--p7hprior")) { fprintf(ofp, "# using HMMER3's default prior for filter p7 HMM: yes\n"); }
729 if (esl_opt_IsUsed(go, "--p7hemit")) { fprintf(ofp, "# using HMMER3's emission priors for filter p7 HMM: yes\n"); }
730
731 if (esl_opt_IsUsed(go, "--EmN")) { fprintf(ofp, "# seq number for filter HMM MSV Gumbel mu fit: %d\n", esl_opt_GetInteger(go, "--EmN")); }
732 if (esl_opt_IsUsed(go, "--EvN")) { fprintf(ofp, "# seq number for filter HMM Vit Gumbel mu fit: %d\n", esl_opt_GetInteger(go, "--EvN")); }
733 if (esl_opt_IsUsed(go, "--ElfN")) { fprintf(ofp, "# seq number for filter HMM local Fwd Gumbel mu fit: %d\n", esl_opt_GetInteger(go, "--ElfN")); }
734 if (esl_opt_IsUsed(go, "--EgfN")) { fprintf(ofp, "# seq number for filter HMM glocal Fwd Gumbel mu fit: %d\n", esl_opt_GetInteger(go, "--EgfN")); }
735 if (esl_opt_IsUsed(go, "--Elftp")) { fprintf(ofp, "# tail fit frac for filter HMM local Fwd Gumbel fit: %g\n", esl_opt_GetReal(go, "--Elftp")); }
736 if (esl_opt_IsUsed(go, "--Egftp")) { fprintf(ofp, "# tail fit frac for filter HMM glocal Fwd Gumbel fit: %g\n", esl_opt_GetReal(go, "--Egftp")); }
737 if (esl_opt_IsUsed(go, "--Ereal")) { fprintf(ofp, "# sample realistic, not iid seqs for HMM calibration: yes\n"); }
738 if (esl_opt_IsUsed(go, "--Enull3")) { fprintf(ofp, "# use null3 correction during HMM calibration: yes\n"); }
739 if (esl_opt_IsUsed(go, "--Ebias")) { fprintf(ofp, "# use bias correction during HMM calibration: yes\n"); }
740 if (esl_opt_IsUsed(go, "--Efitlam")) { fprintf(ofp, "# fit lambda for HMM calibration: yes\n"); }
741 if (esl_opt_IsUsed(go, "--Elcmult")) { fprintf(ofp, "# cm->clen multiplier for HMM local calib seq len: %f\n", esl_opt_GetReal(go, "--Elcmult")); }
742 if (esl_opt_IsUsed(go, "--Egcmult")) { fprintf(ofp, "# cm->clen multiplier for HMM glocal calib seq len: %f\n", esl_opt_GetReal(go, "--Egcmult")); }
743 if (esl_opt_IsUsed(go, "--ElL")) { fprintf(ofp, "# seq length for local filter HMM calibration: %d\n", esl_opt_GetInteger(go, "--ElL")); }
744 if (esl_opt_IsUsed(go, "--EgL")) { fprintf(ofp, "# seq length for glocal filter HMM calibration: %d\n", esl_opt_GetInteger(go, "--EgL")); }
745
746 if (esl_opt_IsUsed(go, "--verbose")) { fprintf(ofp, "# verbose mode: on\n"); }
747 if (esl_opt_IsUsed(go, "--cfile")) { fprintf(ofp, "# saving count vectors to file: %s\n", esl_opt_GetString(go, "--cfile")); }
748 if (esl_opt_IsUsed(go, "--efile")) { fprintf(ofp, "# saving emission score information to file: %s\n", esl_opt_GetString(go, "--efile")); }
749 if (esl_opt_IsUsed(go, "--tfile")) { fprintf(ofp, "# saving individual sequence parsetrees to file: %s\n", esl_opt_GetString(go, "--tfile")); }
750 if (esl_opt_IsUsed(go, "--cmtbl")) { fprintf(ofp, "# saving tabular description of CM topology to file: %s\n", esl_opt_GetString(go, "--cmtbl")); }
751 if (esl_opt_IsUsed(go, "--emap")) { fprintf(ofp, "# saving consensus emit map to file: %s\n", esl_opt_GetString(go, "--emap")); }
752 if (esl_opt_IsUsed(go, "--gtree")) { fprintf(ofp, "# saving tree description of master tree to file: %s\n", esl_opt_GetString(go, "--gtree")); }
753 if (esl_opt_IsUsed(go, "--gtbl")) { fprintf(ofp, "# saving tabular description of master tree to file: %s\n", esl_opt_GetString(go, "--gtbl")); }
754 if (esl_opt_IsUsed(go, "--occfile")) { fprintf(ofp, "# saving CM expected occupancy values to file: %s\n", esl_opt_GetString(go, "--occfile")); }
755 if (esl_opt_IsUsed(go, "--cp9occfile")) { fprintf(ofp, "# saving ML CP9 expected occupancy values to file: %s\n", esl_opt_GetString(go, "--cp9occfile")); }
756 if (esl_opt_IsUsed(go, "--fp7occfile")) { fprintf(ofp, "# saving filter P7 expected occupancy values to file: %s\n", esl_opt_GetString(go, "--fp7occfile")); }
757
758 if (esl_opt_IsUsed(go, "--ctarget")) { fprintf(ofp, "# building >1 CMs from each MSA; target num CMs: %d\n", esl_opt_GetInteger(go, "--ctarget")); }
759 if (esl_opt_IsUsed(go, "--cmaxid")) { fprintf(ofp, "# building >1 CMs from each MSA; max id b/t clusters: %g\n", esl_opt_GetReal(go, "--cmaxid")); }
760 if (esl_opt_IsUsed(go, "--call")) { fprintf(ofp, "# building a CM from each sequence in each MSA: yes\n"); }
761 if (esl_opt_IsUsed(go, "--corig")) { fprintf(ofp, "# appending original CM to cluster CMs: yes\n"); }
762 if (esl_opt_IsUsed(go, "--cdump")) { fprintf(ofp, "# writing training alns for each cluster CM to file: %s\n", esl_opt_GetString(go, "--cdump")); }
763
764 if (esl_opt_IsUsed(go, "--pbegin")) { fprintf(ofp, "# aggregate probability of local begin: %g\n", esl_opt_GetReal(go, "--pbegin")); }
765 if (esl_opt_IsUsed(go, "--pend")) { fprintf(ofp, "# aggregate probability of local end: %g\n", esl_opt_GetReal(go, "--pend")); }
766 if (esl_opt_IsUsed(go, "--pebegin")) { fprintf(ofp, "# set all local begins as equiprobable: yes\n"); }
767 if (esl_opt_IsUsed(go, "--pfend")) { fprintf(ofp, "# set all local end probs to: %g\n", esl_opt_GetReal(go, "--pfend")); }
768
769 fprintf(ofp, "# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
770
771 return;
772 }
773
774 /* init_cfg()
775 * Already set:
776 * cfg->cmfile - command line arg 1
777 * cfg->alifile - command line arg 2
778 * cfg->fmt - format of alignment file
779 * Sets:
780 * cfg->afp - open alignment file
781 * cfg->abc - digital alphabet
782 * cfg->cmoutfp - output file for CM
783 * cfg->null - NULL model, used for all models
784 * cfg->pri - prior, used for all models
785 * cfg->fullmat - RIBOSUM matrix used for all models (optional)
786 * cfg->cdfp - open file to dump MSAs to (optional)
787 */
788 static int
789 init_cfg(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf)
790 {
791 int status;
792
793 /* Set the msafile alphabet as RNA, if it's DNA we're fine.
794 * If it's not RNA nor DNA, we can't deal with it anyway,
795 * so we're hardcoded to RNA.
796 */
797 if((cfg->abc = esl_alphabet_Create(eslRNA)) == NULL) ESL_FAIL(eslEMEM, errbuf, "Failed to create alphabet for sequence file");
798
799 /* open input alignment file */
800 if((status = esl_msafile_Open(&(cfg->abc), cfg->alifile, NULL, cfg->fmt, NULL, &(cfg->afp))) != eslOK) {
801 esl_msafile_OpenFailure(cfg->afp, status);
802 }
803
804 /* open CM file for writing */
805 if ((cfg->cmoutfp = fopen(cfg->cmfile, "w")) == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to open CM file %s for writing", cfg->cmfile);
806
807 if (esl_opt_IsUsed(go, "-o")) {
808 cfg->ofp = fopen(esl_opt_GetString(go, "-o"), "w");
809 if (cfg->ofp == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to open -o output file %s\n", esl_opt_GetString(go, "-o"));
810 }
811 else cfg->ofp = stdout;
812
813 if (cfg->postmsafile) {
814 cfg->postmsafp = fopen(cfg->postmsafile, "w");
815 if (cfg->postmsafp == NULL) ESL_FAIL(eslFAIL, errbuf, "Failed to MSA resave file %s for writing", cfg->postmsafile);
816 }
817 else cfg->postmsafp = NULL;
818
819 /* Set up the priors */
820 if (esl_opt_GetString(go, "--prior") != NULL) {
821 FILE *pfp;
822 if ((pfp = fopen(esl_opt_GetString(go, "--prior"), "r")) == NULL) cm_Fail("Failed to open prior file %s\n", esl_opt_GetString(go, "--prior"));
823 if ((cfg->pri = Prior_Read(pfp)) == NULL) cm_Fail("Failed to parse prior file %s\n", esl_opt_GetString(go, "--prior"));
824 fclose(pfp);
825 cfg->pri_zerobp = NULL;
826 }
827 else if(esl_opt_GetBoolean(go, "--p56") || esl_opt_GetBoolean(go, "--v1p0")) {
828 cfg->pri = Prior_Default_v0p56_through_v1p02();
829 cfg->pri_zerobp = NULL;
830 }
831 else if(esl_opt_GetBoolean(go, "--noh3pri")) {
832 cfg->pri = Prior_Default(FALSE);
833 cfg->pri_zerobp = NULL;
834 }
835 else {
836 cfg->pri = Prior_Default(FALSE);
837 cfg->pri_zerobp = Prior_Default(TRUE);
838 }
839
840 /* Set up the null/random seq model */
841 if(esl_opt_GetString(go, "--null") != NULL) /* read freqs from a file and overwrite bg->f */
842 {
843 if((status = CMReadNullModel(cfg->abc, esl_opt_GetString(go, "--null"), &(cfg->null))) != eslOK)
844 cm_Fail("Failure reading the null model, code: %d", status);
845 }
846 else /* set up the default null model */
847 {
848 status = DefaultNullModel(cfg->abc, &(cfg->null)); /* default values, A,C,G,U = 0.25 */
849 if(status != eslOK) cm_Fail("Failure creating the null model, code: %d", status);
850 }
851
852 /* if --rsearch was enabled, set up RIBOSUM matrix */
853 if(esl_opt_GetString(go, "--rsearch") != NULL)
854 {
855 FILE *matfp;
856 if ((matfp = MatFileOpen (esl_opt_GetString(go, "--rsearch"))) == NULL)
857 cm_Fail("Failed to open matrix file %s\n", esl_opt_GetString(go, "--rsearch"));
858 if (! (cfg->fullmat = ReadMatrix(cfg->abc, matfp)))
859 cm_Fail("Failed to read matrix file %s\n", esl_opt_GetString(go, "--rsearch"));
860 ribosum_calc_targets(cfg->fullmat); /* overwrite score matrix scores w/target probs */
861 fclose(matfp);
862 }
863
864 /* if --corig enabled, make sure either --cmaxid, --ctarget, or --call also enabled */
865 if (esl_opt_GetBoolean(go, "--corig"))
866 if((! esl_opt_IsOn(go, "--ctarget")) && (! esl_opt_IsOn(go, "--cmaxid")) && (! esl_opt_IsOn(go, "--call")))
867 cm_Fail("--corig only makes sense in combination with --ctarget, --cmaxid, OR --call");
868
869 /* if --gibbs enabled, open output file for refined MSAs, and seed RNG */
870 if(esl_opt_GetBoolean(go, "--gibbs"))
871 {
872 /* create RNG */
873 cfg->r = esl_randomness_Create(esl_opt_GetInteger(go, "--seed"));
874 if (cfg->r == NULL) ESL_FAIL(eslEINVAL, errbuf, "Failed to create random number generator: probably out of memory");
875 }
876
877 /* set up objects for building additional p7 models to filter with, if nec */
878 cfg->fp7_bg = p7_bg_Create(cfg->abc);
879 /* create the P7_BUILDER, pass NULL as the <go> argument, this sets all parameters to default */
880 cfg->fp7_bld = p7_builder_Create(NULL, cfg->abc);
881 cfg->fp7_bld->w_len = -1;
882 cfg->fp7_bld->w_beta = p7_DEFAULT_WINDOW_BETA;
883 if(esl_opt_IsUsed(go, "--p7prior")) {
884 FILE *pfp;
885 if (cfg->fp7_bld->prior != NULL) p7_prior_Destroy(cfg->fp7_bld->prior);
886 if ((pfp = fopen(esl_opt_GetString(go, "--p7prior"), "r")) == NULL) cm_Fail("Failed to open p7 prior file %s\n", esl_opt_GetString(go, "--p7prior"));
887 if((cfg->fp7_bld->prior = p7_prior_Read(pfp)) == NULL) {
888 cm_Fail("Failed to parse p7 prior file %s\n", esl_opt_GetString(go, "--p7prior"));
889 }
890 fclose(pfp);
891 }
892 else if(! esl_opt_GetBoolean(go, "--p7hprior")) {
893 /* create the default Infernal p7 prior */
894 if (cfg->fp7_bld->prior != NULL) p7_prior_Destroy(cfg->fp7_bld->prior);
895 cfg->fp7_bld->prior = cm_p7_prior_CreateNucleic();
896 }
897 cfg->fp7_bld->re_target = esl_opt_IsOn(go, "--p7ere") ? esl_opt_GetReal(go, "--p7ere") : DEFAULT_ETARGET_HMMFILTER;
898
899 /* open output files */
900 /* optionally, open count vector file */
901 if (esl_opt_GetString(go, "--cfile") != NULL) {
902 if ((cfg->cfp = fopen(esl_opt_GetString(go, "--cfile"), "w")) == NULL)
903 ESL_FAIL(eslFAIL, errbuf, "Failed to open --cfile output file %s\n", esl_opt_GetString(go, "--cfile"));
904 }
905 /* optionally, open base pair info file */
906 if (esl_opt_GetString(go, "--efile") != NULL) {
907 if ((cfg->escfp = fopen(esl_opt_GetString(go, "--efile"), "w")) == NULL)
908 ESL_FAIL(eslFAIL, errbuf, "Failed to open --efile output file %s\n", esl_opt_GetString(go, "--efile"));
909 }
910 /* optionally, open CM tabular file */
911 if (esl_opt_GetString(go, "--cmtbl") != NULL) {
912 if ((cfg->tblfp = fopen(esl_opt_GetString(go, "--cmtbl"), "w")) == NULL)
913 ESL_FAIL(eslFAIL, errbuf, "Failed to open --cmtbl output file %s\n", esl_opt_GetString(go, "--cmtbl"));
914 }
915 /* optionally, open emit map file */
916 if (esl_opt_GetString(go, "--emap") != NULL) {
917 if ((cfg->efp = fopen(esl_opt_GetString(go, "--emap"), "w")) == NULL)
918 ESL_FAIL(eslFAIL, errbuf, "Failed to open --emap output file %s\n", esl_opt_GetString(go, "--emap"));
919 }
920 /* optionally, open guide tree file */
921 if (esl_opt_GetString(go, "--gtree") != NULL) {
922 if ((cfg->gfp = fopen(esl_opt_GetString(go, "--gtree"), "w")) == NULL)
923 ESL_FAIL(eslFAIL, errbuf, "Failed to open --gtree output file %s\n", esl_opt_GetString(go, "--gtree"));
924 }
925 /* optionally, open master tree file */
926 if (esl_opt_GetString(go, "--gtbl") != NULL) {
927 if ((cfg->gtblfp = fopen(esl_opt_GetString(go, "--gtbl"), "w")) == NULL)
928 ESL_FAIL(eslFAIL, errbuf, "Failed to open --gtbl output file %s\n", esl_opt_GetString(go, "--gtbl"));
929 }
930 /* optionally, open trace file */
931 if (esl_opt_GetString(go, "--tfile") != NULL) {
932 if ((cfg->tfp = fopen(esl_opt_GetString(go, "--tfile"), "w")) == NULL)
933 ESL_FAIL(eslFAIL, errbuf, "Failed to open --tfile output file %s\n", esl_opt_GetString(go, "--tfile"));
934 }
935 /* if --refine enabled, open output file for refined MSAs */
936 if (esl_opt_GetString(go, "--refine") != NULL)
937 {
938 if ((cfg->refinefp = fopen(esl_opt_GetString(go, "--refine"), "w")) == NULL)
939 ESL_FAIL(eslFAIL, errbuf, "Failed to open output file %s for writing MSAs from --refine to", esl_opt_GetString(go, "--refine"));
940 }
941 /* optionally, open --rdump output alignment file */
942 if (esl_opt_GetString(go, "--rdump") != NULL) {
943 if ((cfg->rdfp = fopen(esl_opt_GetString(go, "--rdump"), "w")) == NULL)
944 ESL_FAIL(eslFAIL, errbuf, "Failed to open --rdump output file %s\n", esl_opt_GetString(go, "--rdump"));
945 }
946 /* if --cdump enabled, open output file for cluster MSAs */
947 if (esl_opt_GetString(go, "--cdump") != NULL)
948 {
949 /* check to make sure there's a reason for this option, --cmaxid, --ctarget or --call MUST also be enabled */
950 if((! esl_opt_IsOn(go, "--ctarget")) && (!esl_opt_IsOn(go, "--cmaxid")) && (!esl_opt_IsOn(go, "--call")))
951 cm_Fail("--cdump only makes sense in combination with --ctarget, --cmaxid, OR --call");
952 if ((cfg->cdfp = fopen(esl_opt_GetString(go, "--cdump"), "w")) == NULL)
953 cm_Fail("Failed to open output file %s for writing MSAs to", esl_opt_GetString(go, "--cdump"));
954 }
955 /* optionally, open occ file */
956 if (esl_opt_GetString(go, "--occfile") != NULL) {
957 if ((cfg->occfp = fopen(esl_opt_GetString(go, "--occfile"), "w")) == NULL)
958 ESL_FAIL(eslFAIL, errbuf, "Failed to open --occfile output file %s\n", esl_opt_GetString(go, "--occfile"));
959 }
960 /* optionally, open cp9occ file */
961 if (esl_opt_GetString(go, "--cp9occfile") != NULL) {
962 if ((cfg->cp9occfp = fopen(esl_opt_GetString(go, "--cp9occfile"), "w")) == NULL)
963 ESL_FAIL(eslFAIL, errbuf, "Failed to open --cp9occfile output file %s\n", esl_opt_GetString(go, "--cp9occfile"));
964 }
965 /* optionally, open fp7occ file */
966 if (esl_opt_GetString(go, "--fp7occfile") != NULL) {
967 if ((cfg->fp7occfp = fopen(esl_opt_GetString(go, "--fp7occfile"), "w")) == NULL)
968 ESL_FAIL(eslFAIL, errbuf, "Failed to open --fp7occfile output file %s\n", esl_opt_GetString(go, "--fp7occfile"));
969 }
970
971 if (cfg->pri == NULL) ESL_FAIL(eslEINVAL, errbuf, "alphabet initialization failed");
972 if (cfg->null == NULL) ESL_FAIL(eslEINVAL, errbuf, "null model initialization failed");
973
974 cfg->nali = 0;
975 cfg->ncm_total = 0;
976 return eslOK;
977 }
978
979 /* A work unit consists of one multiple alignment, <msa>.
980 * The job is to turn it into a new CM, returned in <*ret_cm>.
981 *
982 */
983 static int
984 process_build_workunit(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa, CM_t **ret_cm, Parsetree_t **ret_mtr, Parsetree_t ***ret_msa_tr)
985 {
986 int status;
987 uint32_t checksum = 0; /* checksum calculated for the input MSA. cmalign --mapali verifies against this. */
988 CM_t *cm = NULL; /* the CM */
989 int pretend_cm_is_hmm; /* TRUE if we will use special HMM-like parameterization because this CM has 0 basepairs */
990 Prior_t *pri2use = NULL; /* cfg->pri or cfg->pri_zerobp (the latter if CM has no basepairs) */
991
992 if ((status = check_and_clean_msa (go, cfg, errbuf, msa)) != eslOK) goto ERROR;
993 if ((status = esl_msa_Checksum (msa, &checksum)) != eslOK) ESL_FAIL(status, errbuf, "Failed to calculate checksum");
994 if ((status = set_relative_weights (go, cfg, errbuf, msa)) != eslOK) goto ERROR;
995 if(esl_opt_GetBoolean(go, "--fraggiven")) {
996 if ((status = check_fragments (go, cfg, errbuf, msa)) != eslOK) goto ERROR;
997 }
998 else {
999 if ((status = mark_fragments (go, cfg, errbuf, msa)) != eslOK) goto ERROR;
1000 }
1001 if ((status = build_model (go, cfg, errbuf, TRUE, msa, &cm, ret_mtr, ret_msa_tr)) != eslOK) goto ERROR;
1002
1003 cm->checksum = checksum;
1004 cm->flags |= CMH_CHKSUM;
1005
1006 pretend_cm_is_hmm = determine_pretend_cm_is_hmm(go, cm);
1007 pri2use = (pretend_cm_is_hmm) ? cfg->pri_zerobp : cfg->pri;
1008
1009 if ((status = annotate (go, cfg, errbuf, msa, cm)) != eslOK) goto ERROR;
1010 if ((status = set_model_cutoffs (go, cfg, errbuf, msa, cm)) != eslOK) goto ERROR;
1011 if ((status = set_effective_seqnumber (go, cfg, errbuf, msa, cm, pri2use)) != eslOK) goto ERROR;
1012 if ((status = parameterize (go, cfg, errbuf, TRUE, cm, pri2use, msa->nseq)) != eslOK) goto ERROR;
1013 if ((status = configure_model (go, cfg, errbuf, cm, 1)) != eslOK) goto ERROR;
1014 if ((status = set_consensus (go, cfg, errbuf, cm)) != eslOK) goto ERROR;
1015 /* if <pretend_cm_is_hmm> OR --p7ml used, then we'll set the CM's filter p7 HMM as its maximum likelihood HMM */
1016 if ((status = build_and_calibrate_p7_filter(go, cfg, errbuf, msa, cm,
1017 (pretend_cm_is_hmm || esl_opt_GetBoolean(go, "--p7ml"))))
1018 != eslOK) goto ERROR;
1019
1020 *ret_cm = cm;
1021
1022 return eslOK;
1023
1024 ERROR:
1025 if(cm != NULL) FreeCM(cm);
1026 *ret_cm = NULL;
1027 return status;
1028 }
1029
1030 /* refine_msa()
1031 * Refine the original (input) MSA using Expectation-Maximization or Gibbs sampling
1032 * by iterating over: build MSA of optimal parses, build CM from MSA,
1033 * until the summed scores of all parses converges.
1034 *
1035 * Note: input_msa_tr is modified, it's alignment coordinates are changed
1036 * from aligned to unaligned.
1037 *
1038 */
1039 static int
1040 refine_msa(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *init_cm, ESL_MSA *input_msa,
1041 Parsetree_t **input_msa_tr, CM_t **ret_cm, ESL_MSA **ret_msa, Parsetree_t **ret_mtr, Parsetree_t ***ret_trA,
1042 int *ret_niter)
1043 {
1044 int status;
1045 float threshold = 0.01;
1046 float delta = 1.;
1047 float oldscore = IMPOSSIBLE;
1048 float totscore = 0.;
1049 int i = 0;
1050 int iter = 0;
1051 float *sc = NULL;
1052 int nseq = input_msa->nseq;
1053 char *msa_name = NULL;
1054 CM_t *cm = NULL;
1055 ESL_MSA *msa = NULL;
1056 Parsetree_t *mtr = NULL;
1057 Parsetree_t **trA = NULL;
1058 int max_niter = 200; /* maximum number of iterations */
1059 ESL_SQ_BLOCK *sq_block = NULL;
1060 ESL_SQ *tmp_sqp = NULL; /* pointer to a sequence, don't free the actual sequence */
1061 ESL_SQ **tmp_sqpA = NULL; /* array of pointers to ESL_SQ's, don't free individual sequences */
1062 Parsetree_t **tmp_trpA = NULL; /* array of pointers to parsetrees, don't free individual parsetrees */
1063 CM_ALNDATA **dataA = NULL; /* alignment data filled in AlignSequenceBlock(): parsetrees, scores, etc. */
1064 int v, nd; /* state and node counters, only used if -l */
1065 int do_trunc = (esl_opt_GetBoolean(go, "--notrunc") || esl_opt_GetBoolean(go, "--sub")) ? FALSE : TRUE;
1066
1067 /* check contract */
1068 if(input_msa == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "refine_msa(), input_msa passed in as NULL");
1069 if(input_msa->name == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "refine_msa(), input_msa must have a name");
1070 if(init_cm == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "refine_msa(), init_cm passed in as NULL");
1071 if(ret_cm == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "refine_msa(), ret_cm is NULL");
1072 if(ret_mtr == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "refine_msa(), ret_mtr is NULL");
1073 if(ret_trA == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "refine_msa(), ret_trA is NULL");
1074
1075 /* copy input MSA's name, we'll copy it to the MSA we create at each iteration */
1076 if((status = esl_strdup(input_msa->name, -1, &(msa_name))) != eslOK) ESL_FAIL(eslEINCOMPAT, errbuf, "Memory allocation error.");
1077
1078 ESL_ALLOC(sc, sizeof(float) * nseq);
1079 esl_vec_FSet(sc, nseq, 0.);
1080
1081 /* create a ESL_SQ_BLOCK of the sequences in the input MSA */
1082 sq_block = esl_sq_CreateDigitalBlock(nseq, input_msa->abc);
1083 sq_block->first_seqidx = 0;
1084 for(i = 0; i < nseq; i++) {
1085 tmp_sqp = sq_block->list + i;
1086 if(input_msa->ss && input_msa->ss[i]) ESL_ALLOC(tmp_sqp->ss, sizeof(char) * tmp_sqp->salloc);
1087 esl_sq_GetFromMSA(input_msa, i, tmp_sqp);
1088 sq_block->count++;
1089 }
1090
1091 /* allocate lists of pointers to sequences and parsetrees */
1092 ESL_ALLOC(tmp_sqpA, sizeof(ESL_SQ *) * nseq);
1093 ESL_ALLOC(tmp_trpA, sizeof(Parsetree_t *) * nseq);
1094
1095 /* determine scores of implicit parsetrees of input MSA seqs to initial CM */
1096 convert_parsetrees_to_unaln_coords(input_msa_tr, input_msa);
1097 for(i = 0; i < nseq; i++) {
1098 tmp_sqp = sq_block->list + i;
1099 if((status = ParsetreeScore(init_cm, NULL, errbuf, input_msa_tr[i], tmp_sqp->dsq, FALSE, &(sc[i]), NULL, NULL, NULL, NULL)) != eslOK) return status;
1100 }
1101 oldscore = esl_vec_FSum(sc, nseq);
1102
1103 /* print header for tabular output */
1104 print_refine_column_headings(go, cfg);
1105 /* Only print initial score (parsetree scores) if we're not doing
1106 * truncated alignment (--notrunc or --sub enabled). If we are doing
1107 * truncated alignment the parsetree scores will be far higher than
1108 * the scores after the first iteration of truncated realignment
1109 * since we'll use truncation penalties for those. This is a sloppy
1110 * fix. What we should do is determine the most likely *truncated*
1111 * parsetree when we convert the alignment to parsetrees, but we
1112 * don't do that yet.
1113 */
1114 if(! do_trunc) {
1115 fprintf(cfg->ofp, " %5d %13.2f %10s\n", iter, oldscore, "-");
1116 }
1117 /* print initial alignment to --rdump file, if --rdump was enabled */
1118 if(cfg->rdfp != NULL) {
1119 if((status = esl_msafile_Write(cfg->rdfp, input_msa, eslMSAFILE_STOCKHOLM)) != eslOK) {
1120 ESL_FAIL(status, errbuf, "refine_msa(), esl_msafile_Write() call failed.");
1121 }
1122 }
1123
1124 while(iter <= max_niter)
1125 {
1126 iter++;
1127 if(iter == 1) {
1128 cm = init_cm;
1129 msa = input_msa;
1130 }
1131
1132 /* 1. cm -> parsetrees */
1133 if((status = DispatchSqBlockAlignment(cm, errbuf, sq_block, esl_opt_GetReal(go, "--mxsize"), NULL, NULL, cfg->r, &dataA)) != eslOK) return status;
1134
1135 /* sum parse scores and check for convergence */
1136 totscore = 0.;
1137 for(i = 0; i < nseq; i++) totscore += dataA[i]->sc;
1138 delta = (totscore - oldscore) / fabs(totscore);
1139 if(esl_opt_GetBoolean(go, "--indi")) print_refine_column_headings(go, cfg);
1140 if(iter > 1 || (! do_trunc)) { fprintf(cfg->ofp, " %5d %13.2f %10.3f\n", iter, totscore, delta); }
1141 else { fprintf(cfg->ofp, " %5d %13.2f %10s\n", iter, totscore, "-"); }
1142 if(delta <= threshold && delta > (-1. * eslSMALLX1)) {
1143 for(i = 0; i < nseq; i++) cm_alndata_Destroy(dataA[i], FALSE); /* FALSE: don't free sequences, ESL_SQ_BLOCK still points at them */
1144 free(dataA);
1145 break; /* break out of loop before max number of iterations are reached */
1146 }
1147 oldscore = totscore;
1148
1149 /* 2. parsetrees -> msa */
1150 if( iter > 1) esl_msa_Destroy(msa);
1151 msa = NULL; /* even if iter == 1; we set msa to NULL, so we don't klobber input_msa */
1152 /* get list of pointers to sq's, parsetrees in dataA, to pass to Parsetrees2Alignment() */
1153 for(i = 0; i < nseq; i++) { tmp_sqpA[i] = dataA[i]->sq; tmp_trpA[i] = dataA[i]->tr; }
1154 if((status = Parsetrees2Alignment(cm, errbuf, cm->abc, tmp_sqpA, NULL, tmp_trpA, NULL, nseq, NULL, NULL,
1155 /*do_full=*/ TRUE, /* we want all match columns */
1156 /*do_matchonly=*/FALSE, /* we don't want ONLY match columns */
1157 /*allow_trunc=*/ esl_opt_GetBoolean(go, "--miss"), /* if --miss, mark fragments with ~ */
1158 &msa)) != eslOK)
1159 ESL_FAIL(status, errbuf, "refine_msa(), Parsetrees2Alignment() call failed.");
1160 if((status = esl_strdup(msa_name, -1, &(msa->name))) != eslOK) ESL_FAIL(status, errbuf, "refine_msa(), esl_strdup() call failed.");
1161 esl_msa_Digitize(cm->abc, msa, NULL);
1162
1163 /* print intermediate alignment to --rdump file, if --rdump was enabled */
1164 if(cfg->rdfp != NULL) {
1165 if((status = esl_msafile_Write(cfg->rdfp, msa, eslMSAFILE_STOCKHOLM)) != eslOK)
1166 ESL_FAIL(status, errbuf, "refine_msa(), esl_msafile_Write() call failed.");
1167 }
1168 /* 3. msa -> cm */
1169 if(iter > 1) { /* free previous iterations cm, mtr and tr */
1170 FreeCM(cm);
1171 FreeParsetree(mtr);
1172 for(i = 0; i < nseq; i++) FreeParsetree(trA[i]);
1173 free(trA);
1174 }
1175 cm = NULL; /* even if iter == 1; we set cm to NULL, so we don't klobber init_cm */
1176 mtr = NULL;
1177 trA = NULL;
1178 for(i = 0; i < nseq; i++) cm_alndata_Destroy(dataA[i], FALSE); /* FALSE: don't free sequences, ESL_SQ_BLOCK still points at them */
1179 free(dataA);
1180 if ((status = process_build_workunit(go, cfg, errbuf, msa, &cm, &mtr, &trA)) != eslOK) cm_Fail(errbuf);
1181 }
1182
1183 /* write out final alignment to --refine output file */
1184 if((status = esl_msafile_Write(cfg->refinefp, msa, eslMSAFILE_STOCKHOLM)) != eslOK)
1185 ESL_FAIL(status, errbuf, "refine_msa(), esl_msafile_Write() call failed.");
1186
1187 /* If the model is local (-l was used), then we need to convert it
1188 * to global before we return, because we can only output CMs in
1189 * global mode. This is the one and only place in Infernal where we
1190 * go from local back to global. This is purposefully not done
1191 * elsewhere for safety, as part of the rule that a model can only
1192 * be 'configured' a single time. (If we converted back to global
1193 * this would be in a sense reconfiguring). But here we allow it
1194 * since otherwise we couldn't allow -l with the --refine
1195 * option. It's purposefully hard-coded here, and not a function,
1196 * because we don't want to encourage this sort of thing.
1197 */
1198 if(cm->flags & CMH_LOCAL_BEGIN) { /* local begins on */
1199 if(cm->root_trans == NULL) ESL_FAIL(eslFAIL, errbuf, "trying to globalize model but cm->root_trans is NULL...");
1200 for (v = 0; v < cm->M; v++) cm->begin[v] = 0.;
1201 for (v = 0; v < cm->cnum[0]; v++) cm->t[0][v] = cm->root_trans[v];
1202 cm->flags &= ~CMH_LOCAL_BEGIN; /* drop the local begin flag */
1203 }
1204 if(cm->flags & CMH_LOCAL_END) { /* local ends on */
1205 for (v = 0; v < cm->M; v++) cm->end[v] = 0.;
1206 /* now, renormalize transitions */
1207 for (nd = 1; nd < cm->nodes; nd++) {
1208 if ((cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd ||
1209 cm->ndtype[nd] == MATR_nd || cm->ndtype[nd] == BEGL_nd ||
1210 cm->ndtype[nd] == BEGR_nd) &&
1211 cm->ndtype[nd+1] != END_nd)
1212 {
1213 v = cm->nodemap[nd];
1214 esl_vec_FNorm(cm->t[v], cm->cnum[v]);
1215 }
1216 }
1217 /* note: we don't have to worry about globalizing the CP9, it won't be output to the CM file*/
1218 cm->flags &= ~CMH_LOCAL_END; /* turn off local ends flag */
1219 cm->flags &= ~CMH_BITS; /* local end changes invalidate log odds scores */
1220 CMLogoddsify(cm); /* recalculates log odds scores */
1221 }
1222 /* end of globalization of model */
1223
1224 *ret_cm = cm;
1225 *ret_msa = msa;
1226 *ret_trA = trA;
1227 *ret_mtr = mtr;
1228 *ret_niter = iter;
1229
1230 /* clean up */
1231 if(sq_block != NULL) esl_sq_DestroyBlock(sq_block);
1232 free(sc);
1233 free(msa_name);
1234 free(tmp_trpA);
1235 free(tmp_sqpA);
1236
1237 return eslOK;
1238
1239 ERROR:
1240 /* no cleanup, we die */
1241 cm_Fail("in refine_msa(), error, status: %d\n", status);
1242 return status; /* NEVERREACHED */
1243 }
1244
1245
1246 /* Function: print_column_headings()
1247 * Date: EPN, Fri Feb 29 10:08:25 2008
1248 *
1249 * Purpose: Print column headings for tabular output to output file (stdout unless -o).
1250 *
1251 * Returns: eslOK on success
1252 */
1253 static int
1254 print_column_headings(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf)
1255 {
1256 fprintf(cfg->ofp, "# %-6s %-20s %8s %8s %6s %5s %4s %4s %11s\n", "", "", "", "", "", "", "", "", "rel entropy");
1257 fprintf(cfg->ofp, "# %-6s %-20s %8s %8s %6s %5s %4s %4s %11s\n", "", "", "", "", "", "", "", "", "-----------");
1258 fprintf(cfg->ofp, "# %-6s %-20s %8s %8s %6s %5s %4s %4s %5s %5s %s\n", "idx", "name", "nseq", "eff_nseq", "alen", "clen", "bps", "bifs", "CM", "HMM", "description");
1259 fprintf(cfg->ofp, "# %-6s %-20s %8s %8s %6s %5s %4s %4s %5s %5s %s\n", "------", "--------------------", "--------", "--------", "------", "-----", "----", "----", "-----", "-----", "-----------");
1260
1261 return eslOK;
1262 }
1263
1264 static int
1265 output_result(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, int msaidx, int cmidx, ESL_MSA *msa, CM_t *cm, Parsetree_t *mtr, Parsetree_t **tr)
1266 {
1267 int status;
1268 int i;
1269 float sc, struct_sc;
1270
1271 if(msaidx == 1 && cmidx == 1) {
1272 if((status = print_column_headings(go, cfg, errbuf)) != eslOK) return status;
1273 }
1274
1275 if ((status = cm_Validate(cm, 0.0001, errbuf)) != eslOK) return status;
1276
1277 if ((status = cm_file_WriteASCII(cfg->cmoutfp, -1, cm)) != eslOK) ESL_FAIL(status, errbuf, "CM save failed");
1278
1279 fprintf(cfg->ofp, "%8d %-20s %8d %8.2f %6" PRId64 " %5d %4d %4d %5.3f %5.3f %s\n",
1280 cmidx,
1281 cm->name,
1282 msa->nseq,
1283 cm->eff_nseq,
1284 msa->alen,
1285 cm->clen,
1286 CMCountStatetype(cm, MP_st),
1287 CMCountStatetype(cm, B_st),
1288 cm_MeanMatchRelativeEntropy(cm),
1289 cp9_MeanMatchRelativeEntropy(cm->cp9),
1290 (msa->desc) ? msa->desc : "");
1291
1292
1293 /* dump optional info to files: */
1294 if(cfg->tblfp != NULL) PrintCM(cfg->tblfp, cm); /* tabular description of CM topology */
1295 /* emit map */
1296 if(cfg->efp != NULL) {
1297 CMEmitMap_t *emap;
1298 emap = CreateEmitMap(cm);
1299 DumpEmitMap(cfg->efp, emap, cm);
1300 FreeEmitMap(emap);
1301 }
1302 /* save tabular description of guide tree topology, if nec */
1303 if(cfg->gtblfp != NULL) PrintParsetree(cfg->gtblfp, mtr);
1304 /* save tree description of guide tree topology, if nec */
1305 if(cfg->gfp != NULL) MasterTraceDisplay(cfg->gfp, mtr, cm);
1306 /* save base pair info, if nec */
1307 if(cfg->escfp != NULL) if((status = dump_emission_info(cfg->escfp, cm, errbuf)) != eslOK) return status;
1308 /* save CM occ values, if nec */
1309 if(cfg->occfp != NULL) dump_cm_occupancy_values(cfg->occfp, cm);
1310 /* save cp9 occ values, if nec */
1311 if(cfg->cp9occfp != NULL) dump_cp9_occupancy_values(cfg->cp9occfp, cm->name, cm->cp9);
1312 /* save fp7 occ values, if nec */
1313 if(cfg->fp7occfp != NULL) dump_fp7_occupancy_values(cfg->fp7occfp, cm->name, cm->fp7);
1314
1315 /* save parsetrees if nec */
1316 if(cfg->tfp != NULL) {
1317 for (i = 0; i < msa->nseq; i++) {
1318 fprintf(cfg->tfp, ">%s\n", msa->sqname[i]);
1319
1320 if((status = ParsetreeScore(cm, NULL, errbuf, tr[i], msa->ax[i], FALSE, &sc, &struct_sc, NULL, NULL, NULL)) != eslOK) return status;
1321 fprintf(cfg->tfp, " %16s %.2f bits\n", "SCORE:", sc);
1322 fprintf(cfg->tfp, " %16s %.2f bits\n", "STRUCTURE SCORE:", struct_sc);
1323 ParsetreeDump(cfg->tfp, tr[i], cm, msa->ax[i]);
1324 fprintf(cfg->tfp, "//\n");
1325 }
1326 }
1327
1328 /* Finally, output processed MSA, if nec (-O used). This will have
1329 * WT and RF annotation. Additionally, if model has 0 basepairs,
1330 * the MSA may have been modified with cm_parsetree_Doctor() by
1331 * removing D->I and I->D transitions.
1332 */
1333 if (cfg->postmsafp != NULL && msa != NULL) {
1334 ESL_SQ **sq = NULL;
1335 ESL_MSA *omsa = NULL;
1336 int *a2ua_map = NULL;
1337 int apos, uapos, x;
1338
1339 ESL_ALLOC(sq, sizeof(ESL_SQ *) * msa->nseq);
1340 ESL_ALLOC(a2ua_map, sizeof(int) * (msa->alen+1));
1341 for(i = 0; i < msa->nseq; i++) {
1342 if((status = esl_sq_FetchFromMSA(msa, i, &(sq[i]))) != eslOK) ESL_FAIL(status, errbuf, "problem creating -O output alignment, probably out of memory");
1343 }
1344
1345 /* for each sequence, convert aligned coordinates in each parsetree to unaligned coordinates */
1346 for(i = 0; i < msa->nseq; i++) {
1347 /* create a2ua_map: map of aligned positions to unaligned positions,
1348 * 1..alen; a2ua_map[x] = 0, if alignment position x is a gap in sequence i
1349 */
1350 esl_vec_ISet(a2ua_map, msa->alen+1, 0);
1351 uapos = 1;
1352 for(apos = 1; apos <= msa->alen; apos++) {
1353 if(esl_abc_XIsResidue(msa->abc, msa->ax[i][apos])) a2ua_map[apos] = uapos++;
1354 }
1355 /* use a2ua_map to update parsetree coordinates, so Parsetrees2Alignment() will work properly */
1356 for(x = 0; x < tr[i]->n; x++) {
1357 if(tr[i]->emitl[x] != -1) tr[i]->emitl[x] = a2ua_map[tr[i]->emitl[x]];
1358 if(tr[i]->emitr[x] != -1) tr[i]->emitr[x] = a2ua_map[tr[i]->emitr[x]];
1359 }
1360 }
1361 if((status = Parsetrees2Alignment(cm, errbuf, cm->abc, sq, msa->wgt, tr, NULL, msa->nseq, NULL, NULL,
1362 /*do_full=*/TRUE,
1363 /*do_matchonly=*/FALSE,
1364 /*allow_trunc=*/TRUE,
1365 &omsa)) != eslOK) return status;
1366 /* Transfer information from old MSA to new */
1367 esl_msa_SetName (omsa, msa->name, -1);
1368 esl_msa_SetDesc (omsa, msa->desc, -1);
1369 esl_msa_SetAccession(omsa, msa->acc, -1);
1370 esl_msafile_Write(cfg->postmsafp, omsa, eslMSAFILE_STOCKHOLM);
1371
1372 esl_msa_Destroy(omsa);
1373 for(i = 0; i < msa->nseq; i++) esl_sq_Destroy(sq[i]);
1374 free(sq);
1375 free(a2ua_map);
1376 }
1377
1378 return eslOK;
1379
1380 ERROR:
1381 cm_Fail("in output_result(), out of memory");
1382 return status; /* NEVERREACHED */
1383 }
1384
1385 /* check_and_clean_msa
1386 * Ensure we can build a CM from the MSA.
1387 * This requires it has a name.
1388 */
1389 static int
1390 check_and_clean_msa(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa)
1391 {
1392 int status;
1393 ESL_STOPWATCH *w = NULL;
1394
1395 if (cfg->be_verbose) {
1396 w = esl_stopwatch_Create();
1397 esl_stopwatch_Start(w);
1398 fprintf(cfg->ofp, "%-40s ... ", "Checking MSA");
1399 fflush(cfg->ofp);
1400 }
1401
1402 if (esl_opt_GetBoolean(go, "--hand") && msa->rf == NULL) ESL_FAIL(eslFAIL, errbuf, "--hand used, but alignment #%d has no reference coord annotation", cfg->nali);
1403 if (esl_opt_GetBoolean(go, "--noss")) { /* --noss: if SS_cons exists, strip all BPs from it; if it doesn't create it with zero bps */
1404 if(msa->ss_cons == NULL) { ESL_ALLOC(msa->ss_cons, sizeof(char) * (msa->alen+1)); msa->ss_cons[msa->alen] = '\0'; }
1405 memset(msa->ss_cons, '.', msa->alen);
1406 }
1407 if (msa->ss_cons == NULL) ESL_FAIL(eslFAIL, errbuf, "Alignment #%d has no consensus structure annotation, and --noss not used.", cfg->nali);
1408 if (! clean_cs(msa->ss_cons, msa->alen, (! cfg->be_verbose))) ESL_FAIL(eslFAIL, errbuf, "Failed to parse consensus structure annotation in alignment #%d", cfg->nali);
1409
1410 if ( esl_opt_IsOn(go, "--rsearch")) {
1411 if(msa->nseq != 1) ESL_FAIL(eslEINCOMPAT, errbuf,"with --rsearch option, all of the input alignments must have exactly 1 sequence");
1412 /* We can't have ambiguous bases in the MSA, only A,C,G,U will do. The reason is that rsearch_CMProbifyEmissions() expects each
1413 * cm->e prob vector to have exactly 1.0 count for exactly 1 singlet or base pair. If we have ambiguous residues we'll have a
1414 * fraction of a count for more than one residue/base pair for some v.
1415 * ribosum_MSA_resolve_degeneracies() replaces ambiguous bases with most likely compatible base */
1416 ribosum_MSA_resolve_degeneracies(cfg->fullmat, msa); /* cm_Fails() if some error is encountered */
1417 }
1418
1419 /* MSA better have a name, we named it before */
1420 if(msa->name == NULL) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "MSA is nameless, (we thought we named it...) shouldn't happen");
1421
1422 if (cfg->be_verbose) {
1423 fprintf(cfg->ofp, "done. ");
1424 esl_stopwatch_Stop(w);
1425 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
1426 }
1427 if(w != NULL) esl_stopwatch_Destroy(w);
1428 return eslOK;
1429
1430 ERROR:
1431 ESL_FAIL(status, errbuf, "out of memory");
1432 return status; /* NOT REACHED */
1433 }
1434
1435 /* set_relative_weights():
1436 * Set msa->wgt vector, using user's choice of relative weighting algorithm.
1437 */
1438 static int
1439 set_relative_weights(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa)
1440 {
1441 ESL_STOPWATCH *w = NULL;
1442
1443 if (cfg->be_verbose) {
1444 w = esl_stopwatch_Create();
1445 esl_stopwatch_Start(w);
1446 fprintf(cfg->ofp, "%-40s ... ", "Relative sequence weighting");
1447 fflush(cfg->ofp);
1448 }
1449
1450 // set up the msaweight configuration, only relevant for --wpb (default)
1451 ESL_MSAWEIGHT_CFG *mw_cfg = esl_msaweight_cfg_Create();
1452 mw_cfg->ignore_rf = esl_opt_GetBoolean(go, "--hand") ? 0 : 1; // if --hand is used, do not ignore RF, else do
1453
1454 if (esl_opt_GetBoolean(go, "--wnone")) esl_vec_DSet(msa->wgt, msa->nseq, 1.);
1455
1456 if (esl_opt_GetBoolean(go, "--wnone")) esl_vec_DSet(msa->wgt, msa->nseq, 1.);
1457 else if (esl_opt_GetBoolean(go, "--wgiven")) ;
1458 else if (esl_opt_GetBoolean(go, "--wpb")) esl_msaweight_PB_adv(mw_cfg, msa, NULL);
1459 else if (esl_opt_GetBoolean(go, "--wgsc")) esl_msaweight_GSC(msa);
1460 else if (esl_opt_GetBoolean(go, "--wblosum")) esl_msaweight_BLOSUM(msa, esl_opt_GetReal(go, "--wid"));
1461
1462 if (cfg->be_verbose) {
1463 fprintf(cfg->ofp, "done. ");
1464 esl_stopwatch_Stop(w);
1465 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
1466 }
1467
1468 if(w != NULL) esl_stopwatch_Destroy(w);
1469 if(mw_cfg != NULL) esl_msaweight_cfg_Destroy(mw_cfg);
1470 return eslOK;
1471 }
1472
1473 /* check_fragments()
1474 * With --fraggiven, we use fragment info in the input msa instead of
1475 * defining fragments based on sequence length. This function is called
1476 * only when --fraggiven is used, and checks that for each aligned
1477 * seq:
1478 * - either all or no characters before the first residue are ~
1479 * - either all or no characters after the final residue are ~
1480 * - there are no internal ~ values (after first residue but before final one)
1481 *
1482 * Dies: if any of the 3 checks above fails
1483 */
1484 static int
1485 check_fragments(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa)
1486 {
1487 ESL_STOPWATCH *w = NULL;
1488
1489 int idx; /* counter over sequences */
1490 int lpos, rpos; /* counter over alignment positions */
1491 int spos, epos; /* first/final residue for sequence */
1492 int lmiss, rmiss; /* number of consecutive missing data symbols at 5' and 3' ends */
1493
1494 if (cfg->be_verbose) {
1495 w = esl_stopwatch_Create();
1496 esl_stopwatch_Start(w);
1497 fprintf(cfg->ofp, "%-40s ... ", "Checking fragments");
1498 fflush(cfg->ofp);
1499 }
1500
1501 if (! (msa->flags & eslMSA_DIGITAL)) {
1502 cm_Fail("ERROR in check_fragments, msa is not digitized");
1503 }
1504
1505 /* sequence should either have 0 missing (~) or
1506 * all ~ before first residue *and/or* all ~ after final residue
1507 */
1508 for (idx = 0; idx < msa->nseq; idx++) {
1509 spos = lmiss = 0;
1510 if (msa->flags & eslMSA_DIGITAL) {
1511 for (lpos = 1; lpos <= msa->alen; lpos++) {
1512 if(esl_abc_XIsResidue(msa->abc, msa->ax[idx][lpos])) {
1513 spos = lpos;
1514 lpos = msa->alen+1; // breaks loop
1515 }
1516 else if(esl_abc_XIsMissing(msa->abc, msa->ax[idx][lpos])) {
1517 lmiss++;
1518 }
1519 }
1520 }
1521 if(spos == 0) cm_Fail("Sequence %d has 0 residues", idx+1);
1522
1523 epos = msa->alen+1;
1524 rmiss = 0;
1525 if (msa->flags & eslMSA_DIGITAL) {
1526 for (rpos = msa->alen; rpos >= 1; rpos--) {
1527 if(esl_abc_XIsResidue(msa->abc, msa->ax[idx][rpos])) {
1528 epos = rpos;
1529 rpos = 0; // breaks loop
1530 }
1531 else if(esl_abc_XIsMissing(msa->abc, msa->ax[idx][rpos])) {
1532 rmiss++;
1533 }
1534 }
1535 }
1536 if(epos == (msa->alen+1)) cm_Fail("Sequence %d has 0 residues", idx+1);
1537
1538 /* check if sequence is a fragment or not */
1539 if((lmiss > 0) && (lmiss != (spos-1))) {
1540 cm_Fail("Sequence %d seems to be a fragment but first residue is position %d and it only has %d ~ at 5' end (should be %d)", idx+1, spos, lmiss, spos-1);
1541 }
1542 if((rmiss > 0) && (rmiss != (msa->alen - epos))) {
1543 cm_Fail("Sequence %d seems to be a fragment but final residue is position %d and it only has %d ~ at 3' end (should be %d)", idx+1, epos, rmiss, msa->alen-epos);
1544 }
1545 /* finally make sure there's no internal ~ */
1546 for (lpos = spos; lpos <= epos; lpos++) {
1547 if(esl_abc_XIsMissing(msa->abc, msa->ax[idx][lpos])) {
1548 cm_Fail("Sequence %d has ~ at position %d, but these should only occur before first residue or after final residue", lpos);
1549 }
1550 }
1551 }
1552
1553 if (cfg->be_verbose) {
1554 fprintf(cfg->ofp, "done. ");
1555 esl_stopwatch_Stop(w);
1556 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
1557 }
1558
1559 if(w != NULL) esl_stopwatch_Destroy(w);
1560 w = NULL;
1561 return eslOK;
1562 }
1563
1564 /* mark_fragments()
1565 * Define fragment sequences in the MSA and replace
1566 * terminal gaps with missing data symbols.
1567 *
1568 */
1569 static int
1570 mark_fragments(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa)
1571 {
1572 int status;
1573 ESL_STOPWATCH *w = NULL;
1574 ESL_BITFIELD *fragassign = NULL; /* [0..i..msa->nseq-1] 1 if seq i is a fragment else 0 */
1575 int i; /* counter over sequences */
1576 int pos; /* counter over alignment positions */
1577
1578 /* variables only used if --fragnrfpos is used */
1579 int *matassign = NULL; /* [1..alen] array; 0=insert col, 1=match col */
1580 int lpos, rpos; /* counter over alignment positions */
1581 int lrfpos_gap; /* number of 5'-terminal consensus gaps in current sequence */
1582 int rrfpos_gap; /* number of 3'-terminal consensus gaps in current sequence */
1583
1584 if (cfg->be_verbose) {
1585 w = esl_stopwatch_Create();
1586 esl_stopwatch_Start(w);
1587 fprintf(cfg->ofp, "%-40s ... ", "Marking fragments");
1588 fflush(cfg->ofp);
1589 }
1590
1591 if (! (msa->flags & eslMSA_DIGITAL)) cm_Fail("ERROR in mark_fragments() msa is not digitized");
1592
1593 if(esl_opt_IsUsed(go, "--fragnrfpos") && esl_opt_IsUsed(go, "--hand")) { /* --fragnrfpos requires --hand (also enforced by getopts above) */
1594 if(msa->rf == NULL) cm_Fail("--hand used but MSA does not have RF annotation");
1595 if ((fragassign = esl_bitfield_Create(msa->nseq)) == NULL) { status = eslEMEM; goto ERROR; }
1596 AssignMatchColumnsForMsa(msa, errbuf, /*use_rf=*/TRUE, /*use_wts=*/FALSE, esl_opt_GetReal(go, "--symfrac"), &matassign);
1597 for (i = 0; i < msa->nseq; i++) {
1598 lrfpos_gap = 0;
1599 rrfpos_gap = 0;
1600 for (lpos = 1; lpos <= msa->alen; lpos++) {
1601 if (matassign[lpos]) {
1602 if(esl_abc_XIsResidue(msa->abc, msa->ax[i][lpos])) {
1603 lpos = msa->alen + 1; /* breaks loop */
1604 }
1605 else {
1606 lrfpos_gap++;
1607 }
1608 }
1609 }
1610 for (rpos = msa->alen; rpos >= 1; rpos--) {
1611 if (matassign[rpos]) {
1612 if(esl_abc_XIsResidue(msa->abc, msa->ax[i][rpos])) {
1613 rpos = 0; /* breaks loop */
1614 }
1615 else {
1616 rrfpos_gap++;
1617 }
1618 }
1619 }
1620 if((lrfpos_gap > esl_opt_GetInteger(go, "--fragnrfpos")) ||
1621 (rrfpos_gap > esl_opt_GetInteger(go, "--fragnrfpos"))) {
1622 esl_bitfield_Set(fragassign, i);
1623 }
1624 }
1625 } /* end of if(--fragnrfpos && --hand) */
1626 else {
1627 /* determine fragments based on fragthresh */
1628 if ((status = esl_msa_MarkFragments(msa, esl_opt_GetReal(go, "--fragthresh"), &fragassign)) != eslOK) ESL_XFAIL(status, errbuf, "Unable to mark fragments");
1629 }
1630
1631 /* regardless of how we defined fragments, update MSA so fragments have missing data at ends */
1632 for (i = 0; i < msa->nseq; i++) {
1633 if (esl_bitfield_IsSet(fragassign, i)) {
1634 for (pos = 1; pos <= msa->alen; pos++) {
1635 if (esl_abc_XIsResidue(msa->abc, msa->ax[i][pos])) break;
1636 msa->ax[i][pos] = esl_abc_XGetMissing(msa->abc);
1637 }
1638 for (pos = msa->alen; pos >= 1; pos--) {
1639 if (esl_abc_XIsResidue(msa->abc, msa->ax[i][pos])) break;
1640 msa->ax[i][pos] = esl_abc_XGetMissing(msa->abc);
1641 }
1642 }
1643 }
1644
1645 if (cfg->be_verbose) {
1646 fprintf(cfg->ofp, "done. ");
1647 esl_stopwatch_Stop(w);
1648 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
1649 }
1650
1651 if(w != NULL) esl_stopwatch_Destroy(w);
1652 if(fragassign != NULL) esl_bitfield_Destroy(fragassign);
1653 if(matassign != NULL) free(matassign);
1654 w = NULL;
1655 fragassign = NULL;
1656 matassign = NULL;
1657
1658 return eslOK;
1659
1660 ERROR:
1661 if (cfg->be_verbose) {
1662 fprintf(cfg->ofp, "FAILED. ");
1663 esl_stopwatch_Stop(w);
1664 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
1665 }
1666 if(matassign != NULL) free(matassign);
1667 if(w != NULL) esl_stopwatch_Destroy(w);
1668 if(fragassign != NULL) esl_bitfield_Destroy(fragassign);
1669 return status;
1670 }
1671
1672 /* build_model():
1673 * Given <msa>, collect counts;
1674 * upon return, <*ret_cm> is newly allocated and contains
1675 * relative-weighted observed counts.
1676 * Optionally, caller can request an array of inferred parsetrees for
1677 * the <msa> too.
1678 */
1679 static int
1680 build_model(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, int do_print, ESL_MSA *msa, CM_t **ret_cm, Parsetree_t **ret_mtr, Parsetree_t ***ret_msa_tr)
1681 {
1682 int status;
1683 Parsetree_t **tr = NULL;
1684 Parsetree_t *mtr = NULL;
1685 int idx;
1686 CM_t *cm;
1687 ESL_STOPWATCH *w = NULL;
1688 int use_rf;
1689 int use_wts;
1690 int* used_el = NULL;
1691 int pretend_cm_is_hmm; /* TRUE if we will use special HMM-like parameterization because this CM has 0 basepairs */
1692 double **dbl_e = NULL; /* copy of cm->e in doubles */
1693 Prior_t *pri2use = NULL; /* cfg->pri or cfg->pri_zerobp (the latter if CM has no basepairs) */
1694 int v; /* counter over states */
1695 int a; /* counter over symbols */
1696
1697 if (cfg->be_verbose && do_print) {
1698 w = esl_stopwatch_Create();
1699 esl_stopwatch_Start(w);
1700 fprintf(cfg->ofp, "%-40s ... ", "Constructing model ");
1701 fflush(cfg->ofp);
1702 }
1703
1704 use_rf = (esl_opt_GetBoolean(go, "--hand")) ? TRUE : FALSE;
1705 use_wts = (use_rf || esl_opt_GetBoolean(go, "--v1p0")) ? FALSE : TRUE;
1706 if((status = HandModelmaker(msa, errbuf, use_rf,
1707 FALSE, /* use_el: never when building a model */
1708 use_wts, esl_opt_GetReal(go, "--symfrac"), &cm, &mtr)) != eslOK) return status;
1709
1710 /* set the CM's null model, if rsearch mode, use the bg probs used to calc RIBOSUM */
1711 if( esl_opt_IsOn(go, "--rsearch")) CMSetNullModel(cm, cfg->fullmat->g);
1712 else CMSetNullModel(cm, cfg->null);
1713
1714 /* if we're using RSEARCH emissions (--rsearch) set the flag */
1715 if(esl_opt_GetString(go, "--rsearch") != NULL) cm->flags |= CM_RSEARCHEMIT;
1716
1717 /* rebalance CM */
1718 if(! esl_opt_GetBoolean(go, "--nobalance"))
1719 {
1720 CM_t *new = NULL;
1721 if((status = CMRebalance(cm, errbuf, &new)) != eslOK) return status;
1722 FreeCM(cm);
1723 cm = new;
1724 }
1725
1726 /* get counts */
1727 ESL_ALLOC(tr, sizeof(Parsetree_t *) * (msa->nseq));
1728 /* define the used_el array as all FALSE values, this means
1729 * Transmogrify will never create a parsetree with an EL, even if
1730 * the alignment seems to imply it. This is not ideal, but
1731 * currently necessary. If we wanted to allow ELs that existed in
1732 * the MSA (e.g. if the alignment were generated by cmalign) we'd
1733 * probably want to ensure that no EL columns in msa->rf get
1734 * defined as match columns, but that requires a significant change
1735 * to how match/insert columns are defined that I'm not ready to
1736 * make right now (very close to 1.1 release). We'll be forced to
1737 * revisit this when/if a jackhmmer analog in infernal is
1738 * ever implemented - in that case we will want to handle EL
1739 * emissions (more) correctly.
1740 */
1741 ESL_ALLOC(used_el, sizeof(int) * (msa->alen+1));
1742 esl_vec_ISet(used_el, msa->alen+1, FALSE);
1743
1744 pretend_cm_is_hmm = determine_pretend_cm_is_hmm(go, cm);
1745 pri2use = (pretend_cm_is_hmm) ? cfg->pri_zerobp : cfg->pri;
1746
1747 for (idx = 0; idx < msa->nseq; idx++) {
1748 if((status = Transmogrify(cm, errbuf, mtr, msa->ax[idx], used_el, msa->alen, &(tr[idx]))) != eslOK) return status;
1749 if(pretend_cm_is_hmm) {
1750 if((status = cm_parsetree_Doctor(cm, errbuf, tr[idx], NULL, NULL)) != eslOK) return status;
1751 }
1752 ParsetreeCountExceptTruncatedMPs(cm, tr[idx], msa->ax[idx], msa->wgt[idx]);
1753 /*ParsetreeDump(cfg->ofp, tr[idx], cm, msa->ax[idx]);*/
1754 }
1755
1756 /* make a copy of the emission count vectors, but in double format,
1757 * we want a stable copy of these counts to use to determine mean
1758 * posterior estimates using a dirichlet prior, and we don't want
1759 * those counts to change as we add counts from truncated MP
1760 * emissions in each parsetree, which would make CM
1761 * parameterization dependent on the order of sequences in the
1762 * input alignment and would make mean posterior estimates based on
1763 * partial MP emissions, which seems dubious. (We need it to be
1764 * doubles because doubles are required by
1765 * esl_mixdchlet_MPParamaters().)
1766 */
1767 ESL_ALLOC(dbl_e, cm->M * sizeof(double *));
1768 for(v = 0; v < cm->M; v++) {
1769 dbl_e[v] = NULL;
1770 if(cm->sttype[v] == MP_st) {
1771 ESL_ALLOC(dbl_e[v], cm->abc->K * cm->abc->K * sizeof(double));
1772 for(a = 0; a < (cm->abc->K * cm->abc->K); a++) {
1773 dbl_e[v][a] = (double) cm->e[v][a];
1774 }
1775 }
1776 }
1777 for (idx = 0; idx < msa->nseq; idx++) {
1778 ParsetreeCountOnlyTruncatedMPs(cm, tr[idx], msa->ax[idx], msa->wgt[idx], dbl_e, pri2use);
1779 }
1780
1781 free(used_el);
1782 cm->nseq = msa->nseq;
1783 cm->eff_nseq = msa->nseq;
1784
1785 if(cfg->be_verbose && do_print) {
1786 fprintf(cfg->ofp, "done. ");
1787 esl_stopwatch_Stop(w);
1788 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
1789 }
1790
1791 /* Set transition counts into ROOT_IL and ROOT_IR to 0, we don't
1792 * learn those counts from the alignment, unless --v1p0 (b/c we used
1793 * to in versions up to v1.0.2) or --iflank (which turns this
1794 * specific behavior off). The emission scores for these states will
1795 * be zeroed later so we don't touch them.
1796 */
1797 if((! esl_opt_GetBoolean(go, "--v1p0")) && (! esl_opt_GetBoolean(go, "--iflank"))) {
1798 if((status = cm_zero_flanking_insert_counts(cm, errbuf)) != eslOK) return status;
1799 }
1800
1801 /* ensure the dual insert states we will detach were populated with 0 counts */
1802 if(!(esl_opt_GetBoolean(go, "--nodetach")))
1803 {
1804 if(cfg->be_verbose && do_print) {
1805 esl_stopwatch_Start(w);
1806 fprintf(cfg->ofp, "%-40s ... ", "Finding and checking dual inserts");
1807 }
1808 cm_find_and_detach_dual_inserts(cm,
1809 TRUE, /* Do check (END_E-1) insert states have 0 counts */
1810 FALSE); /* Don't detach the states yet, wait til CM is priorified */
1811 if (cfg->be_verbose && do_print) {
1812 fprintf(cfg->ofp, "done. ");
1813 esl_stopwatch_Stop(w);
1814 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
1815 }
1816 }
1817
1818 /* create the emitmap */
1819 if(cm->emap == NULL) cm->emap = CreateEmitMap(cm);
1820
1821 /* set the EL self transition probability */
1822 cm->el_selfsc = sreLOG2(esl_opt_GetReal(go, "--elself"));
1823
1824 /* set the beta parameters, these will be used to calculate W and QDBs that get stored in the CM file */
1825 cm->beta_W = esl_opt_GetReal(go, "--betaW");
1826 cm->qdbinfo->beta1 = esl_opt_GetReal(go, "--beta1");
1827 cm->qdbinfo->beta2 = esl_opt_GetReal(go, "--beta2");
1828
1829 /* set the cm->null2_omega and cm->null3_omega parameters */
1830 if(esl_opt_IsUsed(go, "--n2omega")) { /* user set --n2omega, use that */
1831 cm->null2_omega = esl_opt_GetReal(go, "--n2omega");
1832 }
1833 else { /* user didn't set --n2omega, definition of cm->null2_omega depends on whether --p56 was set or not */
1834 cm->null2_omega = ((esl_opt_GetBoolean(go, "--p56") == TRUE) ? V1P0_NULL2_OMEGA : esl_opt_GetReal(go, "--n2omega"));
1835 }
1836 if(esl_opt_IsUsed(go, "--n3omega")) { /* user set --n3omega, use that */
1837 cm->null3_omega = esl_opt_GetReal(go, "--n3omega");
1838 }
1839 else { /* user didn't set --n3omega, definition of cm->null3_omega depends on whether --p56 was set or not */
1840 cm->null3_omega = ((esl_opt_GetBoolean(go, "--p56") == TRUE) ? V1P0_NULL3_OMEGA : esl_opt_GetReal(go, "--n3omega"));
1841 }
1842
1843 /* Before converting to probabilities, save a count vector file, if asked.
1844 * Used primarily for making data files for training priors.
1845 */
1846 if (cfg->cfp != NULL) {
1847 if ((status = print_countvectors(cfg->cfp, cm)) != eslOK) goto ERROR;
1848 }
1849
1850 *ret_cm = cm;
1851 if(ret_mtr == NULL) FreeParsetree(mtr);
1852 else *ret_mtr = mtr;
1853 if(ret_msa_tr == NULL) {
1854 for(idx = 0; idx < msa->nseq; idx++)
1855 FreeParsetree(tr[idx]);
1856 free(tr);
1857 tr = NULL;
1858 }
1859 else *ret_msa_tr = tr;
1860
1861 if(w != NULL) esl_stopwatch_Destroy(w);
1862 if(dbl_e != NULL) {
1863 for(v = 0; v < cm->M; v++) {
1864 if(dbl_e[v] != NULL) {
1865 free(dbl_e[v]);
1866 }
1867 }
1868 free(dbl_e);
1869 dbl_e = NULL;
1870 }
1871 return eslOK;
1872
1873 ERROR:
1874 if(mtr != NULL) FreeParsetree(mtr);
1875 if(tr != NULL) {
1876 for(idx = 0; idx < msa->nseq; idx++)
1877 FreeParsetree(tr[idx]);
1878 free(tr);
1879 tr = NULL;
1880 }
1881 if(w != NULL) esl_stopwatch_Destroy(w);
1882 if(dbl_e != NULL) {
1883 for(v = 0; v < cm->M; v++) {
1884 if(dbl_e[v] != NULL) {
1885 free(dbl_e[v]);
1886 }
1887 }
1888 free(dbl_e);
1889 dbl_e = NULL;
1890 }
1891 return status;
1892 }
1893
1894 /* annotate()
1895 * Transfer annotation information from MSA to new CM.
1896 *
1897 * We've ensured the msa has a name in set_msa_name() so if
1898 * for some inconceivable reason it doesn't
1899 * we die.
1900 *
1901 */
1902 static int
1903 annotate(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa, CM_t *cm)
1904 {
1905 int status = eslOK;
1906 ESL_STOPWATCH *w = NULL;
1907
1908 if (cfg->be_verbose) {
1909 w = esl_stopwatch_Create();
1910 esl_stopwatch_Start(w);
1911 fprintf(cfg->ofp, "%-40s ... ", "Transferring MSA annotation");
1912 fflush(cfg->ofp);
1913 }
1914
1915 if ((status = cm_SetName (cm, msa->name)) != eslOK) ESL_XFAIL(status, errbuf, "Unable to set name for CM");
1916 if ((status = cm_SetAccession (cm, msa->acc)) != eslOK) ESL_XFAIL(status, errbuf, "Failed to record MSA accession");
1917 if ((status = cm_SetDescription (cm, msa->desc)) != eslOK) ESL_XFAIL(status, errbuf, "Failed to record MSA description");
1918 if ((status = cm_AppendComlog (cm, go->argc, go->argv, FALSE, 0)) != eslOK) ESL_XFAIL(status, errbuf, "Failed to record command log");
1919 if ((status = cm_SetCtime (cm)) != eslOK) ESL_XFAIL(status, errbuf, "Failed to record timestamp");
1920
1921 if (cfg->be_verbose) {
1922 fprintf(cfg->ofp, "done. ");
1923 esl_stopwatch_Stop(w);
1924 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
1925 }
1926
1927 if(w != NULL) esl_stopwatch_Destroy(w);
1928 return eslOK;
1929
1930 ERROR:
1931 if (cfg->be_verbose) {
1932 fprintf(cfg->ofp, "FAILED. ");
1933 esl_stopwatch_Stop(w);
1934 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
1935 }
1936 if(w != NULL) esl_stopwatch_Destroy(w);
1937 return status;
1938 }
1939
1940 /* set_model_cutoffs()
1941 * If the msa had them available, set the Rfam
1942 * cutoffs in the model.
1943 *
1944 * Always returns eslOK;
1945 *
1946 */
1947 static int
1948 set_model_cutoffs(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa, CM_t *cm)
1949 {
1950 if(msa->cutset[eslMSA_TC1]) {
1951 cm->tc = msa->cutoff[eslMSA_TC1];
1952 cm->flags |= CMH_TC;
1953 }
1954 if(msa->cutset[eslMSA_GA1]) {
1955 cm->ga = msa->cutoff[eslMSA_GA1];
1956 cm->flags |= CMH_GA;
1957 }
1958 if(msa->cutset[eslMSA_NC1]) {
1959 cm->nc = msa->cutoff[eslMSA_NC1];
1960 cm->flags |= CMH_NC;
1961 }
1962 return eslOK;
1963 }
1964
1965 /* set_effective_seqnumber()
1966 * Incept: EPN, Fri Jul 27 10:38:11 2007
1967 * <cm> comes in with weighted observed counts. It goes out with
1968 * those observed counts rescaled to sum to the "effective sequence
1969 * number".
1970 *
1971 * <prior> is needed because we may need to parameterize test models
1972 * looking for the right relative entropy. (for --eent, the default)
1973 *
1974 * Based on HMMER3's hmmbuild func of same name, we don't allow
1975 * --eclust here though.
1976 */
1977 static int
1978 set_effective_seqnumber(const ESL_GETOPTS *go, const struct cfg_s *cfg,
1979 char *errbuf, ESL_MSA *msa, CM_t *cm, const Prior_t *pri)
1980 {
1981 int status;
1982 double neff;
1983 int used_hmm_etarget = FALSE;
1984 ESL_STOPWATCH *w = NULL;
1985
1986 if(cfg->be_verbose) {
1987 w = esl_stopwatch_Create();
1988 esl_stopwatch_Start(w);
1989 fprintf(cfg->ofp, "%-40s ... ", "Set effective sequence number");
1990 fflush(cfg->ofp);
1991 }
1992
1993 if((esl_opt_GetBoolean(go, "--enone")) || ( esl_opt_IsOn(go, "--rsearch")))
1994 {
1995 neff = msa->nseq;
1996 if(cfg->be_verbose) fprintf(cfg->ofp, "done. ");
1997 }
1998 else if(esl_opt_IsOn(go, "--eset"))
1999 {
2000 neff = esl_opt_GetReal(go, "--eset");
2001 if(cfg->be_verbose) fprintf(cfg->ofp, "done. ");
2002 cm->eff_nseq = neff;
2003 cm_Rescale(cm, neff / (float) msa->nseq);
2004 }
2005 else if (esl_opt_GetBoolean(go, "--eent") == TRUE)
2006 {
2007 double etarget;
2008 double hmm_etarget;
2009 double hmm_re;
2010 int clen = 0;
2011 int nd;
2012 for(nd = 0; nd < cm->nodes; nd++) {
2013 if(cm->ndtype[nd] == MATP_nd) clen += 2;
2014 else if(cm->ndtype[nd] == MATL_nd) clen += 1;
2015 else if(cm->ndtype[nd] == MATR_nd) clen += 1;
2016 }
2017 if(esl_opt_GetBoolean(go, "--v1p0")) {
2018 /* determine etarget with default method used by Infernal version 1.0-->1.0.2 */
2019 etarget = version_1p0_default_target_relent(cm->abc, clen, 6.0);
2020 }
2021 else {
2022 etarget = set_target_relent(go, cm->abc, clen, CMCountNodetype(cm, MATP_nd));
2023 }
2024
2025 status = cm_EntropyWeight(cm, pri, etarget,
2026 esl_opt_GetReal(go, "--eminseq"),
2027 (esl_opt_IsUsed(go, "--emaxseq") ? esl_opt_GetReal(go, "--emaxseq") : (double) cm->nseq),
2028 FALSE, &hmm_re, &neff);
2029 /* if --ehmmre <x> enabled, ensure HMM relative entropy per match column is at least <x>, if not,
2030 * recalculate neff so HMM relative entropy of <x> is achieved.
2031 */
2032 if( esl_opt_IsOn(go, "--ehmmre")) {
2033 hmm_etarget = esl_opt_GetReal(go, "--ehmmre");
2034 printf("hmm_etarget: %f\n", hmm_etarget);
2035 if(hmm_re < hmm_etarget) {
2036 status = cm_EntropyWeight(cm, pri, hmm_etarget,
2037 esl_opt_GetReal(go, "--eminseq"),
2038 (esl_opt_IsUsed(go, "--emaxseq") ? esl_opt_GetReal(go, "--emaxseq") : (double) cm->nseq),
2039 TRUE, &hmm_re, &neff); /* TRUE says: pretend model is an HMM for entropy weighting */
2040 if (status == eslEMEM) ESL_FAIL(status, errbuf, "memory allocation failed");
2041 else if (status != eslOK) ESL_FAIL(status, errbuf, "internal failure in entropy weighting algorithm");
2042 used_hmm_etarget = TRUE;
2043 }
2044 }
2045 if (status == eslEMEM) ESL_FAIL(status, errbuf, "memory allocation failed");
2046 else if (status != eslOK) ESL_FAIL(status, errbuf, "internal failure in entropy weighting algorithm");
2047 cm->eff_nseq = neff;
2048 cm_Rescale(cm, neff / (float) msa->nseq);
2049
2050 if(cfg->be_verbose) {
2051 if(used_hmm_etarget) fprintf(cfg->ofp, "done. ");
2052 else fprintf(cfg->ofp, "done. ");
2053 esl_stopwatch_Stop(w);
2054 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
2055 }
2056 }
2057 if(w != NULL) esl_stopwatch_Destroy(w);
2058
2059 return eslOK;
2060 }
2061
2062 /* parameterize()
2063 * Converts counts to probability parameters.
2064 */
2065 static int
2066 parameterize(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, int do_print, CM_t *cm, const Prior_t *prior, float msa_nseq)
2067 {
2068 int status;
2069 ESL_STOPWATCH *w = NULL;
2070
2071 if (cfg->be_verbose && do_print){
2072 w = esl_stopwatch_Create();
2073 esl_stopwatch_Start(w);
2074 fprintf(cfg->ofp, "%-40s ... ", "Converting counts to probabilities");
2075 fflush(cfg->ofp);
2076 }
2077 PriorifyCM(cm, prior);
2078
2079 if( esl_opt_IsOn(go, "--rsearch")) {
2080 rsearch_CMProbifyEmissions(cm, cfg->fullmat); /* use those probs to set CM probs from cts */
2081 /*debug_print_cm_params(cm);*/
2082 }
2083
2084 if(! esl_opt_GetBoolean(go, "--nodetach")) /* Detach dual inserts where appropriate, if
2085 * we get here we've already checked these states */
2086 {
2087 cm_find_and_detach_dual_inserts(cm,
2088 FALSE, /* Don't check states have 0 counts (they won't due to priors) */
2089 TRUE); /* Detach the states by setting trans probs into them as 0.0 */
2090 }
2091
2092 if(! esl_opt_GetBoolean(go, "--iins")) {
2093 /* set all insert emission probabilities equal to the cm->null probabilities */
2094 if((status = flatten_insert_emissions(cm)) != eslOK) ESL_FAIL(status, errbuf, "flatten_insert_emissions() failed");
2095 /* Note: flatten_insert_emissions() is purposefully a static
2096 * function local to cmbuild.c b/c once CM files are calibrated no
2097 * other executable (i.e. cmsearch) should be able to modify the
2098 * scores of the CM, as that would invalidate the E-value stats */
2099 }
2100
2101 CMRenormalize(cm);
2102 /* don't CMLogoddsify() here, that will come when we configure with cm_Configure() */
2103
2104 if (cfg->be_verbose && do_print) {
2105 fprintf(cfg->ofp, "done. ");
2106 esl_stopwatch_Stop(w);
2107 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
2108 }
2109 if(w != NULL) esl_stopwatch_Destroy(w);
2110
2111 return eslOK;
2112 }
2113
2114 /* configure_model()
2115 * Configure the model. This determines QDBs and W.
2116 * If niter is 1, we possibly output in verbose mode,
2117 * else we don't.
2118 */
2119 static int
2120 configure_model(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm, int iter)
2121 {
2122 int status;
2123 ESL_STOPWATCH *w = NULL;
2124 int nstarts, nexits, nd;
2125
2126 if (iter == 1 && cfg->be_verbose){
2127 w = esl_stopwatch_Create();
2128 esl_stopwatch_Start(w);
2129 fprintf(cfg->ofp, "%-40s ... ", "Configuring model");
2130 fflush(cfg->ofp);
2131 }
2132
2133 /* potentially redefine pbegin, pend based on command line options */
2134 /* (defaults are DEFAULT_PBEGIN, DEFAULT_PEND (set in CreateCMShell()) */
2135 if(esl_opt_IsUsed(go, "--pbegin")) cm->pbegin = esl_opt_GetReal(go, "--pbegin");
2136 if(esl_opt_IsUsed(go, "--pend")) cm->pend = esl_opt_GetReal(go, "--pend");
2137
2138 /* possibly overwrite local begin probs such that all begin points are equiprobable (--pebegin) */
2139 if(esl_opt_GetBoolean(go, "--pebegin")) {
2140 nstarts = 0;
2141 for (nd = 2; nd < cm->nodes; nd++)
2142 if (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd || cm->ndtype[nd] == MATR_nd || cm->ndtype[nd] == BIF_nd)
2143 nstarts++;
2144 cm->pbegin = 1.- (1./(1+nstarts));
2145 }
2146 /* possibly overwrite cm->pend so that local end prob from all legal states is fixed,
2147 * this is strange in that cm->pend may be placed as a number greater than 1., this number
2148 * is then divided by nexits in ConfigLocalEnds() to get the prob for each v --> EL transition,
2149 * this is guaranteed by the way we calculate it to be < 1., it's the argument from --pfend */
2150 if(esl_opt_IsOn(go, "--pfend")) {
2151 nexits = 0;
2152 for (nd = 1; nd < cm->nodes; nd++) {
2153 if ((cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd ||
2154 cm->ndtype[nd] == MATR_nd || cm->ndtype[nd] == BEGL_nd ||
2155 cm->ndtype[nd] == BEGR_nd) &&
2156 cm->ndtype[nd+1] != END_nd)
2157 nexits++;
2158 }
2159 cm->pend = nexits * esl_opt_GetReal(go, "--pfend");
2160 }
2161
2162 /* we must calculate QDBs so we can write them to the CM file */
2163 cm->config_opts |= CM_CONFIG_QDB;
2164
2165 /* if --refine, we have to set additional flags and configuration options
2166 * before calling cm_Configure().
2167 */
2168 if(esl_opt_IsUsed(go, "--refine")) {
2169 cm->tau = esl_opt_GetReal(go, "--tau"); /* this will be DEFAULT_TAU unless changed at command line */
2170
2171 /* update cm->align->opts */
2172 if (esl_opt_GetBoolean(go, "--gibbs")) { cm->align_opts |= CM_ALIGN_SAMPLE; }
2173 else if(esl_opt_GetBoolean(go, "--cyk")) { cm->align_opts |= CM_ALIGN_CYK; }
2174 else { cm->align_opts |= CM_ALIGN_OPTACC; }
2175 if ( esl_opt_GetBoolean(go, "--sub")) { cm->align_opts |= CM_ALIGN_SUB; }
2176 else if(! esl_opt_GetBoolean(go, "--notrunc")) { cm->align_opts |= CM_ALIGN_TRUNC; }
2177
2178 if(esl_opt_GetBoolean(go, "--nonbanded")) {
2179 cm->align_opts |= CM_ALIGN_SMALL;
2180 cm->align_opts |= CM_ALIGN_NONBANDED;
2181 cm->align_opts |= CM_ALIGN_CYK;
2182 cm->align_opts &= ~CM_ALIGN_OPTACC; /* turn optimal accuracy OFF */
2183 }
2184 else cm->align_opts |= CM_ALIGN_HBANDED;
2185
2186 if(esl_opt_GetBoolean(go, "--fins")) cm->align_opts |= CM_ALIGN_FLUSHINSERTS;
2187
2188 /* update cm->config_opts */
2189 if ( esl_opt_GetBoolean(go, "--sub")) { cm->config_opts |= CM_CONFIG_SUB; }
2190 else if(! esl_opt_GetBoolean(go, "--notrunc")) { cm->config_opts |= CM_CONFIG_TRUNC; }
2191 if(esl_opt_GetBoolean(go, "--nonbanded")) cm->config_opts |= CM_CONFIG_NONBANDEDMX;
2192
2193 if(esl_opt_GetBoolean(go, "-l")) {
2194 cm->config_opts |= CM_CONFIG_LOCAL;
2195 cm->config_opts |= CM_CONFIG_HMMLOCAL;
2196 cm->config_opts |= CM_CONFIG_HMMEL;
2197 }
2198 }
2199
2200 /* finally, configure the model */
2201 if((status = cm_Configure(cm, errbuf, -1)) != eslOK) return status;
2202
2203 if (iter == 1 && cfg->be_verbose) {
2204 fprintf(cfg->ofp, "done. ");
2205 esl_stopwatch_Stop(w);
2206 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
2207 }
2208
2209 if(w != NULL) esl_stopwatch_Destroy(w);
2210
2211 return eslOK;
2212 }
2213
2214
2215 /* set_consensus()
2216 * Set CM consensus using cm->cmcons. We have to do this
2217 * after configuring the model because bit scores must
2218 * be valid.
2219 */
2220 static int
2221 set_consensus(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, CM_t *cm)
2222 {
2223 int status = eslOK;
2224 ESL_STOPWATCH *w = NULL;
2225
2226 if (cfg->be_verbose) {
2227 w = esl_stopwatch_Create();
2228 esl_stopwatch_Start(w);
2229 fprintf(cfg->ofp, "%-40s ... ", "Setting CM consensus");
2230 fflush(cfg->ofp);
2231 }
2232
2233 if(! (cm->flags & CMH_BITS)) ESL_XFAIL(eslEINVAL, errbuf, "Trying to set cm->consensus before bit scores are valid");
2234
2235 if ((status = cm_SetConsensus (cm, cm->cmcons, NULL)) != eslOK) ESL_XFAIL(status, errbuf, "Failed to calculate consensus sequence");
2236
2237 if(esl_opt_IsUsed(go, "--consrf")) {
2238 /* overwrite cm->rf with cm->cmcons->cseq */
2239 if(cm->rf == NULL || (! (cm->flags & CMH_RF))) ESL_XFAIL(status, errbuf, "Failed to overwrite RF with consensus (--consrf)");
2240 strcpy(cm->rf, cm->consensus);
2241 }
2242
2243 if (cfg->be_verbose) {
2244 fprintf(cfg->ofp, "done. ");
2245 esl_stopwatch_Stop(w);
2246 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
2247 }
2248
2249 if(w != NULL) esl_stopwatch_Destroy(w);
2250 return eslOK;
2251
2252 ERROR:
2253 if (cfg->be_verbose) {
2254 fprintf(cfg->ofp, "FAILED. ");
2255 esl_stopwatch_Stop(w);
2256 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
2257 }
2258 if(w != NULL) esl_stopwatch_Destroy(w);
2259 return status;
2260 }
2261
2262 /* build_and_calibrate_p7_filter()
2263 * Build and calibrate the additional p7 HMM filter (differs from the
2264 * ML p7 HMM filter which was built in configure_model()).
2265 * If <use_mlp7_as_filter>, do just that. This will be true
2266 * if --p7ml was used OR if model has zero basepairs and
2267 * --noh3pri was NOT used.
2268 */
2269 static int
2270 build_and_calibrate_p7_filter(const ESL_GETOPTS *go, const struct cfg_s *cfg, char *errbuf, ESL_MSA *msa, CM_t *cm, int use_mlp7_as_filter)
2271 {
2272 int status;
2273 CM_t *acm = NULL;
2274 P7_HMM *fhmm = NULL;
2275 int lmsvL, lvitL, lfwdL, gfwdL;
2276 int lmsvN, lvitN, lfwdN, gfwdN;
2277 double agfmu, agflambda;
2278 float lftailp, gftailp;
2279 int k, apos, cpos;
2280 ESL_MSA *amsa = NULL;
2281 double mlp7_re, fhmm_re;
2282 double neff;
2283 ESL_STOPWATCH *w = NULL;
2284
2285 if (cfg->be_verbose){
2286 w = esl_stopwatch_Create();
2287 esl_stopwatch_Start(w);
2288 fprintf(cfg->ofp, "%-40s ... ", "Calibrating p7 HMM filter");
2289 fflush(cfg->ofp);
2290 }
2291
2292 /* calibrate p7 HMM */
2293
2294 /* Define relevant parameters: */
2295 /* first, set all to default */
2296 lmsvL = lvitL = 200;
2297 lfwdL = 100;
2298 gfwdL = ESL_MAX(100, 2.*cm->clen);
2299 lmsvN = esl_opt_GetInteger(go, "--EmN");
2300 lvitN = esl_opt_GetInteger(go, "--EvN");
2301 lfwdN = esl_opt_GetInteger(go, "--ElfN");
2302 gfwdN = esl_opt_GetInteger(go, "--EgfN");
2303 lftailp = esl_opt_GetReal(go, "--Elftp");
2304 gftailp = esl_opt_GetReal(go, "--Egftp");
2305
2306 /* now, modify if nec based on command-line options */
2307 if(esl_opt_IsUsed(go, "--ElL")) {
2308 lmsvL = lvitL = lfwdL = esl_opt_GetInteger(go, "--ElL");
2309 }
2310 else if(esl_opt_IsUsed(go, "--Elcmult")) {
2311 lmsvL = lvitL = lfwdL = esl_opt_GetReal(go, "--Elcmult") * cm->clen;
2312 }
2313
2314 if(esl_opt_IsUsed(go, "--EgL")) {
2315 gfwdL = esl_opt_GetInteger(go, "--EgL");
2316 }
2317 else if(esl_opt_IsUsed(go, "--Egcmult")) {
2318 gfwdL = esl_opt_GetReal(go, "--Egcmult") * cm->clen;
2319 }
2320
2321 if(esl_opt_GetBoolean(go, "--Efitlam")) {
2322 lmsvN = esl_opt_IsUsed(go, "--EmN") ? esl_opt_GetInteger(go, "--EmN") : 10000;
2323 lvitN = esl_opt_IsUsed(go, "--EvN") ? esl_opt_GetInteger(go, "--EvN") : 10000;
2324 lfwdN = esl_opt_IsUsed(go, "--ElfN") ? esl_opt_GetInteger(go, "--ElfN") : 10000;
2325 gfwdN = esl_opt_IsUsed(go, "--EgfN") ? esl_opt_GetInteger(go, "--EgfN") : 10000;
2326 lftailp = esl_opt_IsUsed(go, "--Elftp") ? esl_opt_GetReal(go, "--Elftp") : 0.01;
2327 gftailp = esl_opt_IsUsed(go, "--Egftp") ? esl_opt_GetReal(go, "--Egftp") : 0.01;
2328 }
2329
2330 /* Build the HMM filter (cm->fp7) */
2331 if(use_mlp7_as_filter) {
2332 /* use the ML p7 HMM as the HMM filter */
2333 fhmm = cm->mlp7;
2334 }
2335 else {
2336 /* Default strategy:
2337 *
2338 * Build a p7 HMM <fhmm> with p7_builder with entropy weighting
2339 * and rel ent target of <x> from (--p7ere <x>). Then _overwrite_
2340 * it's emission probabilities with marginalized emission
2341 * probabilities from a temporary CM built such that it's ML p7
2342 * HMM has mean match state entropy the same as <fhmm>.
2343 *
2344 * The motivation for this is that rmark3 benchmarking (xref:
2345 * ~nawrockie/notebook/11_0226_inf_p7s_with_cp9_transitions/00LOG)
2346 * revealed that HMMs built with H3 transitions and emissions from
2347 * a marginalized CM are the best for filtering.
2348 *
2349 * The --p7hemit option makes it so HMMER emissions are used instead
2350 * of the marginalized CM emissions.
2351 *
2352 * NOTE: We could avoid this if we had a way of using Infernal's
2353 * emission priors (there are different prior for base pairs and
2354 * singlets) in p7_Builder(), but that would require parsing the
2355 * secondary structure and getting an Infernal function into
2356 * hmmer). For now, we build a temporary CM and copy it's
2357 * emissions.
2358 *
2359 * First, annotate the msa with RF annotation corresponding to the
2360 * definition of match columns used by the CM using the cm->map.
2361 * This will guarantree that the HMM has the same number of match
2362 * columns as the CM, which is important because we copy
2363 * marginalized ml emissions from a CM onto the HMM. Note that we
2364 * also set cfg->fp7_bld->arch_strategy as p7_ARCH_HAND.
2365 */
2366 amsa = esl_msa_Clone(msa);
2367 /* if msa had bit score cutoffs, get rid of those, they pertain to the CM, not to the HMM */
2368 amsa->cutset[eslMSA_GA1] = amsa->cutset[eslMSA_GA2] = FALSE;
2369 amsa->cutset[eslMSA_TC1] = amsa->cutset[eslMSA_TC2] = FALSE;
2370 amsa->cutset[eslMSA_NC1] = amsa->cutset[eslMSA_NC2] = FALSE;
2371 if(amsa->rf != NULL) free(amsa->rf);
2372 ESL_ALLOC(amsa->rf, sizeof(char) * (amsa->alen+1));
2373 if(! (cm->flags & CMH_MAP)) { cm_Fail("Unable to create additional p7 HMM, CM has no map, this shouldn't happen"); }
2374 /* init to all inserts, then set match states based on cm->map */
2375 for (apos = 0; apos < amsa->alen; apos++) amsa->rf[apos] = '.';
2376 for (cpos = 1; cpos <= cm->clen; cpos++) amsa->rf[cm->map[cpos]-1] = 'x'; /* note off by one */
2377 cfg->fp7_bld->arch_strategy = p7_ARCH_HAND;
2378
2379 if ((status = p7_Builder(cfg->fp7_bld, amsa, cfg->fp7_bg, &fhmm,
2380 /*opt_trarr=*/NULL, /*opt_gm=*/NULL, /*opt_om=*/NULL, /*opt_postmsa=*/NULL)) != eslOK)
2381 { strcpy(errbuf, cfg->fp7_bld->errbuf); return status; }
2382
2383 /* remove the RF annotation, it only exists because we created amsa->rf above */
2384 if(fhmm->rf != NULL) {
2385 free(fhmm->rf);
2386 fhmm->rf = NULL;
2387 fhmm->flags &= ~p7H_RF;
2388 }
2389 if(cm->flags & CMH_RF && cm->rf != NULL) { /* copy CM's rf annotation to fhmm, remember they have same # consensus columns */
2390 ESL_ALLOC(fhmm->rf, sizeof(char) * (cm->clen+2));
2391 strcpy(fhmm->rf, cm->rf);
2392 fhmm->flags |= p7H_RF;
2393 }
2394 /* overwrite the HMM consensus structure annotation with the CM's it'll be in full WUSS format */
2395 if(! (fhmm->flags & p7H_CS)) { cm_Fail("additional p7 HMM unexpectedly does not have consensus structure annotation"); }
2396 fhmm->cs[0] = ' ';
2397 strcpy(fhmm->cs+1, cm->cmcons->cstr); /* careful: off-by-one */
2398 fhmm->cs[cm->clen+1] = '\0';
2399
2400 esl_msa_Destroy(amsa);
2401
2402 if(! esl_opt_GetBoolean(go, "--p7hemit")) {
2403 /* Overwrite the emission probabilities of the HMM with
2404 * emissions from a ML HMM built from a CM. First, build the
2405 * CM, it will have the same HMM mean match state entropy as the
2406 * fhmm we just built.
2407 */
2408 if ((status = build_model(go, cfg, errbuf, FALSE, msa, &acm, NULL, NULL)) != eslOK) return status;
2409 fhmm_re = p7_MeanMatchRelativeEntropy(fhmm, cfg->fp7_bg);
2410
2411 status = cm_EntropyWeight(acm, cfg->pri, fhmm_re, esl_opt_GetReal(go, "--eminseq"),
2412 (esl_opt_IsUsed(go, "--emaxseq") ? esl_opt_GetReal(go, "--emaxseq") : (double) cm->nseq),
2413 TRUE, &mlp7_re, &neff); /* TRUE says: pretend model is an HMM for entropy weighting */
2414 if (status == eslEMEM) ESL_FAIL(status, errbuf, "memory allocation failed");
2415 else if (status != eslOK) ESL_FAIL(status, errbuf, "internal failure in entropy weighting algorithm");
2416 acm->eff_nseq = neff;
2417 cm_Rescale(acm, acm->eff_nseq / (float) msa->nseq);
2418 if((status = parameterize (go, cfg, errbuf, FALSE, acm, cfg->pri, msa->nseq)) != eslOK) return status;
2419 /* We have to configure the model to get cm->W, which gets
2420 * copied to cm->mlp7->max_length. Alternatively we could
2421 * use p7_Builder_MaxLength() but anecdotally that gives
2422 * lengths >> W (more than 2*W commonly).
2423 * configure_model() will build the mlp7 HMM.
2424 */
2425 if((status = configure_model(go, cfg, errbuf, acm, 2)) != eslOK) return status;
2426
2427 /* copy the ML p7 emission probs from the CM we just built */
2428 /* match emissions: copy, then normalize (norm should be unnec actually) */
2429 for (k = 1; k <= fhmm->M; k++) esl_vec_FCopy(acm->mlp7->mat[k], fhmm->abc->K, fhmm->mat[k]);
2430 for (k = 1; k <= fhmm->M; k++) esl_vec_FNorm(fhmm->mat[k], fhmm->abc->K);
2431 /* special case */
2432 esl_vec_FSet(fhmm->mat[0], fhmm->abc->K, 0.);
2433 fhmm->mat[0][0] = 1.0;
2434
2435 /* insert emissions: copy, then normalize (norm should be unnec actually) */
2436 for (k = 0; k <= fhmm->M; k++) esl_vec_FCopy(acm->mlp7->ins[k], fhmm->abc->K, fhmm->ins[k]);
2437 for (k = 0; k <= fhmm->M; k++) esl_vec_FNorm(fhmm->ins[k], fhmm->abc->K);
2438 /* reset HMM composition */
2439 if ((status = p7_hmm_SetComposition(fhmm)) != eslOK) goto ERROR;
2440 fhmm->eff_nseq = acm->eff_nseq;
2441
2442 FreeCM(acm);
2443 }
2444 }
2445
2446 /* calibrate the HMM filter */
2447 if((status = cm_p7_Calibrate(fhmm, errbuf,
2448 lmsvL, lvitL, lfwdL, gfwdL, /* length of sequences to search for local (lL) and glocal (gL) modes */
2449 lmsvN, lvitN, lfwdN, gfwdN, /* number of seqs to search for each alg */
2450 lftailp, /* fraction of tail mass to fit for local Fwd */
2451 gftailp, /* fraction of tail mass to fit for glocal Fwd */
2452 &agfmu, &agflambda))
2453 != eslOK) ESL_FAIL(status, errbuf, "Error calibrating additional p7 HMM");
2454
2455 if((status = cm_p7_hmm_SetConsensus(fhmm)) != eslOK) ESL_FAIL(status, errbuf, "Unable to set the HMM filter consensus annotation");
2456 if((status = cm_SetFilterHMM(cm, fhmm, agfmu, agflambda)) != eslOK) ESL_FAIL(status, errbuf, "Unable to set the HMM filter for the CM");
2457 if((status = p7_hmm_AppendComlog (cm->fp7, go->argc, go->argv)) != eslOK) ESL_FAIL(status, errbuf, "Failed to record command log for filter HMM");
2458
2459 if (cfg->be_verbose) {
2460 fprintf(cfg->ofp, "done. ");
2461 esl_stopwatch_Stop(w);
2462 esl_stopwatch_Display(cfg->ofp, w, "CPU time: ");
2463 }
2464 if(w != NULL) esl_stopwatch_Destroy(w);
2465
2466 return eslOK;
2467
2468 ERROR:
2469 ESL_FAIL(status, errbuf, "out of memory");
2470 return status; /* never reached */
2471 }
2472
2473
2474 /* set_target_relent()
2475 * Incept: EPN, Tue Aug 17 09:14:15 2010
2476 *
2477 * Purpose: Implements a length-dependent calculation of the target relative entropy
2478 * per position, attempting to ensure that the information content of
2479 * the model is high enough to find local alignments; but don't set it
2480 * below a hard limit for RNA (DEFAULT_ETARGET).
2481 *
2482 * Args: clen - consensus length (2*MATP + MATL + MATR)
2483 *
2484 */
2485 static double
2486 set_target_relent(const ESL_GETOPTS *go, const ESL_ALPHABET *abc, int clen, int nbps)
2487 {
2488 double etarget;
2489 double re_target;
2490 double esigma = esl_opt_GetReal(go, "--esigma"); /* default Infernal/HMMER3 sigma is 45.0 */
2491
2492 if(esl_opt_IsOn(go, "--ere")) {
2493 re_target = esl_opt_GetReal(go, "--ere");
2494 }
2495 else {
2496 if(abc->type != eslRNA) cm_Fail("ERROR, alphabet not RNA, user needs to specify target entropy with --ere");
2497 /* set target differently if we have 0 basepairs or not */
2498 re_target = (nbps > 0) ? DEFAULT_ETARGET : DEFAULT_ETARGET_HMMFILTER;
2499 }
2500 /* the defn of etarget below is identical to how hmmer3 does it in hmmer/src/p7_builder.c as of svn rev 3986 (04.16.12) */
2501 etarget = (esigma - eslCONST_LOG2R * log( 2.0 / ((double) clen * (double) (clen+1)))) / (double) clen; /* HMMER3.0 default, xref J5/36. */
2502 etarget = ESL_MAX(etarget, re_target);
2503
2504 return etarget;
2505 }
2506
2507 /* version_1p0_default_target_relent()
2508 * Incept: EPN, Tue Jul 10 10:13:43 2007
2509 * based on HMMER3's hmmbuild.c:default_target_relent()
2510 * SRE, Fri May 25 15:14:16 2007 [Janelia]
2511 *
2512 * Purpose: Calculate default target relative entropy using the
2513 * method in Infernal version 1.0 --> 1.0.2.
2514 *
2515 * Implements a length-dependent calculation of the target relative entropy
2516 * per position, attempting to ensure that the information content of
2517 * the model is high enough to find local alignments; but don't set it
2518 * below a hard alphabet-dependent limit (CM_ETARGET).
2519 * notes.
2520 *
2521 * Args: clen - consensus length (2*MATP + MATL + MATR)
2522 * eX - X parameter: minimum total rel entropy target
2523 *
2524 */
2525 static double
2526 version_1p0_default_target_relent(const ESL_ALPHABET *abc, int clen, double eX)
2527 {
2528 double etarget;
2529
2530 /* HMMER3 default eX = 6.0 as of Tue Jul 10 2007
2531 */
2532 etarget = 6.* (eX + log((double) ((clen * (clen+1)) / 2)) / log(2.)) / (double)(2*clen + 4);
2533
2534 switch (abc->type) {
2535 case eslRNA: if (etarget < DEFAULT_ETARGET) etarget = DEFAULT_ETARGET; break;
2536 default: cm_Fail("ERROR in default_target_relent(), alphabet not RNA!\n");
2537 }
2538 return etarget;
2539 }
2540
2541 /* set_msa_name()
2542 * Make sure the alignment has a name; this name will
2543 * then be transferred to the model.
2544 *
2545 * We can only do this for a single alignment in a file. For multi-MSA
2546 * files, each MSA is required to have a name already.
2547 *
2548 * Priority is:
2549 * 1. Use -n <name> if set, overriding any name the alignment might already have.
2550 * 2. Use alignment's existing name, if non-NULL.
2551 * 3. Make a name, from alignment file name without path and without filename extension
2552 * (e.g. "/usr/foo/globins.slx" gets named "globins")
2553 * If none of these succeeds, return <eslEINVAL>.
2554 *
2555 * If a multiple MSA database (e.g. Stockholm/Pfam), and we encounter
2556 * an MSA that doesn't already have a name, return <eslEINVAL> if nali > 1.
2557 * (We don't know we're in a multiple MSA database until we're on the second
2558 * alignment.)
2559 *
2560 * If we're in MPI mode, we assume we're in a multiple MSA database,
2561 * even on the first alignment.
2562 *
2563 * Because we can't tell whether we've got more than one
2564 * alignment 'til we're on the second one, these fatal errors
2565 * only happen after the first HMM has already been built.
2566 * Oh well.
2567 */
2568 static int
2569 set_msa_name(const ESL_GETOPTS *go, struct cfg_s *cfg, char *errbuf, ESL_MSA *msa)
2570 {
2571 char *name = NULL;
2572 int status;
2573
2574 if (cfg->nali == 1) /* first (only?) MSA in file: */
2575 {
2576 if(esl_opt_IsUsed(go, "-n"))
2577 {
2578 if((status = esl_msa_SetName(msa, esl_opt_GetString(go, "-n"), -1)) != eslOK) return status;
2579 }
2580 else if (msa->name != NULL)
2581 {
2582 cfg->nnamed++;
2583 }
2584 else if (cfg->afp->bf->filename)
2585 {
2586 if ((status = esl_FileTail(cfg->afp->bf->filename, TRUE, &name)) != eslOK) return status; /* TRUE=nosuffix */
2587 if ((status = esl_msa_SetName(msa, name, -1)) != eslOK) return status;
2588 free(name);
2589 }
2590 else ESL_FAIL(eslEINVAL, errbuf, "Failed to set model name: msa has no name, no msa filename, and no -n");
2591 }
2592 else
2593 {
2594 if (esl_opt_IsUsed(go, "-n")) ESL_FAIL(eslEINVAL, errbuf, "Oops. Wait. You can't use -n with an alignment database.");
2595 else if (msa->name != NULL) cfg->nnamed++;
2596 else ESL_FAIL(eslEINVAL, errbuf, "Oops. Wait. I need name annotation on each alignment in a multi MSA file; failed on #%d", cfg->nali);
2597
2598 /* special kind of failure: the *first* alignment didn't have a name, and we used the filename to
2599 * construct one; now that we see a second alignment, we realize this was a boo-boo*/
2600 if (cfg->nnamed != cfg->nali) ESL_FAIL(eslEINVAL, errbuf, "Oops. Wait. I need name annotation on each alignment in a multi MSA file; first MSA didn't have one");
2601 }
2602 return eslOK;
2603 }
2604
2605 /* Function: print_countvectors()
2606 * Date: SRE, Tue May 7 16:21:10 2002 [St. Louis]
2607 *
2608 * Purpose: Save emission count vectors to a file.
2609 * Used to gather data for training Dirichlet priors.
2610 *
2611 * Args: ofp - open file to output count vectors to.
2612 * cm - a model containing counts (before probify'ing)
2613 *
2614 */
2615 static int
2616 print_countvectors(FILE *ofp, CM_t *cm)
2617 {
2618 int v,x;
2619
2620 /* Print emission counts */
2621 for (v = 0; v < cm->M; v++) {
2622 if (cm->sttype[v] == MP_st || cm->sttype[v] == ML_st || cm->sttype[v] == MR_st) {
2623 fprintf(ofp, "E\t%-7s ", UniqueStatetype(cm->stid[v]));
2624 if (cm->sttype[v] == MP_st) {
2625 for (x = 0; x < cm->abc->K*cm->abc->K; x++)
2626 fprintf(ofp, "%8.3f ", cm->e[v][x]);
2627 } else {
2628 for (x = 0; x < cm->abc->K; x++)
2629 fprintf(ofp, "%8.3f ", cm->e[v][x]);
2630 }
2631 fprintf(ofp, "\n");
2632 }
2633 }
2634
2635 /* Print transition counts */
2636 for (v = 0; v < cm->M; v++) {
2637 if(cm->sttype[v] != B_st && cm->sttype[v] != E_st) {
2638 fprintf(ofp, "T\t%-7s : %-2d", UniqueStatetype(cm->stid[v]), cm->ndtype[(cm->ndidx[v] + 1)]);
2639 for (x = 0; x < cm->cnum[v]; x++) {
2640 fprintf(ofp, "%8.3f ", cm->t[v][x]);
2641 }
2642 fprintf(ofp, "\n");
2643 }
2644 }
2645 fprintf(ofp, "//\n");
2646 return eslOK;
2647 }
2648
2649 /* EPN 08.18.05
2650 * model_trace_info_dump()
2651 * Function: model_trace_info_dump
2652 *
2653 * Purpose: Given a trace from a sequence used to create the model,
2654 * print the subsequence length rooted at each start state.
2655 * The sequence positions in a Parsetree_t tr
2656 * returned from Transmogrify refer to aligned positions.
2657 * We want subsequence lengths that refer to unaligned lengths.
2658 *
2659 * Args: ofp - filehandle to print to
2660 * cm - the CM
2661 * tr - the parsetree (trace)
2662 * aseq - the aligned sequence the trace corresponds to
2663 * Returns: (void)
2664 */
2665
2666 void
2667 model_trace_info_dump(FILE *ofp, CM_t *cm, Parsetree_t *tr, char *aseq)
2668 {
2669 int status;
2670 int a, i, j, tpos, d, l, r;
2671 int *map;
2672
2673 ESL_ALLOC(map, sizeof(int) * strlen(aseq));
2674
2675 a=0;
2676 for (i = 0; i < strlen(aseq); i++)
2677 if (! esl_abc_CIsGap(cm->abc, aseq[i])) map[i] = a++;
2678 else map[i] = -1;
2679
2680 for (tpos = 0; tpos < tr->n; tpos++)
2681 if(cm->sttype[tr->state[tpos]] == S_st)
2682 {
2683 l = tr->emitl[tpos]-1;
2684 r = tr->emitr[tpos]-1;
2685 i = map[l];
2686 j = map[r];
2687 /* tr->emitl[tpos]-1 might map to a gap (root node emits the gaps
2688 * also). So we look for first residue that exists in the unaligned
2689 * seq. Then we do the same for j, looking backwards.
2690 */
2691 while (i == -1)
2692 i = map[++l];
2693 while (j == -1)
2694 j = map[--r];
2695
2696 d = j-i+1;
2697 /* assume ofp is open (probably not good) */
2698 fprintf(ofp, "state:%d d:%d\n", tr->state[tpos], d);
2699 /*fprintf(ofp, "state:%d d:%d i:%d j:%d emitl:%d emitr:%d\n", tr->state[tpos], d, i, j, tr->emitl[tpos], tr->emitr[tpos]);*/
2700 }
2701 free(map);
2702
2703 ERROR:
2704 cm_Fail("Memory allocation error.");
2705 }
2706
2707 /* convert_parsetrees_to_unaln_coords()
2708 *
2709 * Given a digitized MSA <msa> and parsetrees <tr> that correspond to
2710 * the ALIGNED coordinates in <msa>, modify tr[i]->emitl and tr[i]->emitr
2711 * so they correspond with UNALIGNED coordinates. Written so we can call
2712 * Parsetrees2Alignment() to make a new msa, that will replace <msa> for
2713 * training a CM.
2714 */
2715 static int
2716 convert_parsetrees_to_unaln_coords(Parsetree_t **tr, ESL_MSA *msa)
2717 {
2718 int status;
2719 int **map = NULL;
2720 int i = 0;
2721 int x = 0;
2722 int apos = 1;
2723 int uapos = 1;
2724 /* contract check */
2725 if(! (msa->flags & eslMSA_DIGITAL)) cm_Fail("get_unaln_seqs_from_msa() msa is not digitized.\n");
2726
2727 /* For each seq in the MSA, map the aligned sequences coords to
2728 * the unaligned coords, we stay in digitized seq coords (1..alen)
2729 */
2730 ESL_ALLOC(map, sizeof(int *) * msa->nseq);
2731 for (i = 0; i < msa->nseq; i++) {
2732 ESL_ALLOC(map[i], sizeof(int) * (msa->alen+1));
2733 map[i][0] = -1; /* invalid */
2734 uapos = 1;
2735 for(apos = 1; apos <= msa->alen; apos++)
2736 if (!esl_abc_XIsGap(msa->abc, msa->ax[i][apos])) map[i][apos] = uapos++;
2737 else map[i][apos] = -1;
2738 }
2739 for (i = 0; i < msa->nseq; i++) {
2740 /* tr[i] is in alignment coords, convert it to unaligned coords, */
2741 for(x = 0; x < tr[i]->n; x++) {
2742 if(tr[i]->emitl[x] != -1) tr[i]->emitl[x] = map[i][tr[i]->emitl[x]];
2743 if(tr[i]->emitr[x] != -1) tr[i]->emitr[x] = map[i][tr[i]->emitr[x]];
2744 }
2745 }
2746 for (i = 0; i < msa->nseq; i++) free(map[i]);
2747 free(map);
2748
2749 return eslOK;
2750
2751 ERROR:
2752 cm_Fail("memory allocation error.");
2753 return status; /* NEVERREACHED */
2754 }
2755
2756 /* Function: MSADivide()
2757 * EPN, Wed Mar 21 17:26:39 2007
2758 *
2759 * Purpose: Given an MSA, divide it into multiple MSAs, each with
2760 * a different cluster of the original sequences. Each
2761 * MSA will be used to construct a separate CM.
2762 *
2763 * Different modes:
2764 *
2765 * 1. if(do_all): each seq is its own cluster, so
2766 * the number of new MSAs is number of seqs in input
2767 * master MSA.
2768 *
2769 * 2. if(do_mindiff): define clusters
2770 * such that we maximize the number of clusters while
2771 * satisfying: minimum fractional difference b/t any
2772 * 2 seqs in different clusters >= 'mindiff'.
2773 * The contract states that mindiff > 0. in this case.
2774 *
2775 * 3. if(do_nc).: define clusters
2776 * such that we have exactly 'target_nc' clusters by
2777 * searching for the 'mindiff' that gives exactly
2778 * 'target_nc' clusters. (We guarantee we can do this
2779 * by rounding 'diff' fractional difference values b/t
2780 * seqs to nearest 0.001).
2781 *
2782 * *. (NOT YET IMPLEMENTED)
2783 * if(do_pickone): in mode 2 or 3, we select a single
2784 * sequence from each cluster to represent that cluster.
2785 * The sequence is chosen that has the minimum average
2786 * fractional difference with all other seqs in the cluster.
2787 * (NOT YET IMPLEMENTED)
2788 *
2789 * Args:
2790 * ESL_MSA *mmsa - the master MSA, we cluster the seqs in this guy
2791 * and build a new MSA from each cluster
2792 * int do_all - TRUE (mode 1): each seq is its own cluster
2793 * int do_mindiff - TRUE (mode 2): satisfy clusters are at least mindiff different
2794 * int do_nc - TRUE (mode 3): set mindiff such that we get excatly target_nc clusters
2795 * float mindiff - the minimum fractional difference allowed
2796 * between 2 seqs of different clusters
2797 * (0. indicates mode 3)
2798 * int target_nc - number of clusters to define (0 indicates mode 2)
2799 * int do_orig - TRUE to include the master MSA as one of the new MSAs
2800 * int *ret_num_msa - number of MSAs in ret_MSA
2801 * ESL_MSA ***ret_cmsa - new MSAs, one for each cluster
2802 * char *errbuf - buffer for error messages
2803 *
2804 * Return: ret_cmsa (alloc'ed here) and ret_num_msa
2805 */
2806 int
2807 MSADivide(ESL_MSA *mmsa, int do_all, int do_mindiff, int do_nc, float mindiff, int target_nc,
2808 int do_orig, int *ret_num_msa, ESL_MSA ***ret_cmsa, char *errbuf)
2809 {
2810 int status; /* Easel status code */
2811 ESL_MSA **cmsa = NULL;/* the new MSAs we're creating from clusters of seqs in mmsa */
2812 int i; /* counter over sequences */
2813 int m; /* counter over new MSAs */
2814 int n; /* counter over tree nodes */
2815 ESL_TREE *T = NULL;/* the tree, created by Single-Linkage Clustering */
2816 ESL_DMATRIX *D = NULL;/* the distance matrix */
2817 double *diff = NULL; /* [0..T->N-2], diff[n]= min distance between any leaf in right and
2818 * left subtree of node n of tree T */
2819 int nc; /* number of clusters/MSAs */
2820 int *clust = NULL;/* [0..T->N-1], cluster number (0..nc-1) this seq is in */
2821 int *csize = NULL;/* [0..nc-1], size of each cluster */
2822 int **useme = NULL;/* [0.m.nc-1][0.i.N] TRUE to use seq i in new MSA m, FALSE not to */
2823 int best; /* 'best' node, returned by select_node() */
2824 void *tmp;
2825 char *buffer = NULL;
2826 int ndigits;
2827
2828 /* Contract check */
2829 if((do_all + do_nc + do_mindiff) != 1) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() exactly 1 of do_all, do_nc, do_mindiff must be TRUE.");
2830 if( do_nc && target_nc == 0) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() target_nc is 0 but do_nc is TRUE!");
2831 if( do_mindiff && mindiff <= 0.) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() mindiff is <= 0. but do_mindiff is TRUE!");
2832 if( do_mindiff && target_nc != 0) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() do_mindiff is TRUE, but target_nc != 0");
2833 /* mmsa must be digital */
2834 if(!(mmsa->flags & eslMSA_DIGITAL)) ESL_FAIL(eslEINCOMPAT, errbuf, "MSADivide() MSA is not digital.");
2835
2836 if(do_nc) mindiff = 0.;
2837
2838 /* Mode 1: Each seq becomes own MSA. Easy. */
2839 if(do_all) {
2840 ESL_ALLOC(clust, sizeof(int) * (mmsa->nseq));
2841 ESL_ALLOC(csize, sizeof(int) * (mmsa->nseq));
2842 nc = 0;
2843 /* each seq is its own cluster */
2844 for(i = 0; i < mmsa->nseq; i++) {
2845 clust[i] = nc++;
2846 csize[i] = 1;
2847 }
2848 printf("# Alignment split into %d clusters; each comprised of exactly 1 sequence\n", nc);
2849 printf("#\n");
2850 }
2851 else { /* Mode 2 or Mode 3 */
2852 /* Create distance matrix and infer tree by single linkage clustering */
2853 if((status = esl_dst_XDiffMx(mmsa->abc, mmsa->ax, mmsa->nseq, &D)) != eslOK) ESL_FAIL(status, errbuf, "esl_dst_XDiffMx() error, status: %d", status);
2854 if((status = esl_tree_SingleLinkage(D, &T)) != eslOK) ESL_FAIL(status, errbuf, "esl_tree_SingleLinkage() error, status: %d", status);
2855 if((status = esl_tree_SetTaxaParents(T)) != eslOK) ESL_FAIL(status, errbuf, "esl_tree_SetTaxaParentse() error, status: %d", status);
2856 /*esl_tree_WriteNewick(cfg->ofp, T);*/
2857 if((status = esl_tree_Validate(T, errbuf) != eslOK)) return status;
2858
2859 /* determine the diff values:
2860 * (use: n_child > n, unless n's children are taxa)
2861 * diff[n] is minimum distance between any taxa (leaf) in left subtree of
2862 * n to any taxa in right subtree of n.
2863 *
2864 * EPN, Thu Jan 13 13:27:07 2011:
2865 * Technically, we don't have to do this, diff values are already
2866 * stored in T->ld and T->rd using the current esl_tree.c code,
2867 * but previously (versions ->1.0.2) we had to calculate diff[] here.
2868 * I'm leaving it in the code because later code relies on it
2869 * (see note on rounding of diff values in "Mode 3" comment block below)
2870 */
2871 ESL_ALLOC(diff, (sizeof(double) * ESL_MAX(1, T->N - 1))); /* one for each node, avoid 0 malloc */
2872 for (n = (T->N-2); n >= 0; n--) {
2873 diff[n] = T->ld[n]; /* or we could set it to T->rd[n], they're identical */
2874 diff[n] *= 1000.;
2875 diff[n] = (float) ((int) diff[n]);
2876 diff[n] /= 1000.;
2877 /*printf("diff[n:%d]: %f\n", n, diff[n]);*/
2878 }
2879 /*for (n = 0; n < (T->N-1); n++)
2880 printf("diff[n:%d]: %f\n", n, diff[n]);
2881 for (n = 0; n < (T->N-1); n++)
2882 printf("left[n:%d]: %d right[n:%d]: %d\n", n, T->left[n], n, T->right[n]);*/
2883
2884 if(do_mindiff) { /* Mode 2 */
2885 /* Define clusters that are at least mindiff different
2886 * from each other. */
2887 if((status = select_node(T, diff, mindiff, &clust, &nc, &best, errbuf)) != eslOK) return status;
2888 printf("# Alignment split into %d clusters; each will be used to train a CM.\n", nc);
2889 printf("# Maximum identity b/t any 2 seqs in different clusters: %.2f\n", (1.-mindiff));
2890 printf("#\n");
2891 }
2892 else { /* Mode 3, do_nc == TRUE, mindiff was set to 0.0 above */
2893 /* Find the minimum fractional difference (mindiff) that
2894 * gives exactly target_nc clusters, also define clusters
2895 * based on that mindiff, this is all done with find_mindiff(),
2896 * which does a binary search for mindiff, we're guaranteed to
2897 * find exactly target_nc clusters b/c diff values are rounded
2898 * to nearest 0.001. */
2899 if(target_nc > (T->N)) target_nc = T->N; /* max num clusters is num seqs */
2900 if((status = find_mindiff(T, diff, target_nc, &clust, &nc, &mindiff, errbuf)) != eslOK) return status;
2901 printf("# Alignment split into %d clusters; each will be used to train a CM.\n", nc);
2902 printf("# Maximum identity b/t any 2 seqs in different clusters: %.2f\n", (1.-mindiff));
2903 printf("#\n");
2904 }
2905 /* Determine the size of each cluster */
2906 ESL_ALLOC(csize, (sizeof(int) * (nc)));
2907 esl_vec_ISet(csize, nc, 0);
2908 for(i = 0; i < mmsa->nseq; i++)
2909 csize[clust[i]]++;
2910
2911 /*printf("Distance matrix:\n");
2912 esl_dmatrix_Dump(cfg->ofp, D, NULL, NULL);*/
2913 }
2914
2915 /* Create one new MSA for each cluster,
2916 * if(do_orig): keep the original MSA as cmsa[nc] */
2917 if(do_orig) {
2918 ESL_ALLOC(cmsa, (sizeof(ESL_MSA *) * (nc+1)));
2919 for(m = 0; m < nc; m++) cmsa[m] = NULL;
2920 }
2921 else {
2922 ESL_ALLOC(cmsa, (sizeof(ESL_MSA *) * (nc)));
2923 for(m = 0; m < nc; m++) cmsa[m] = NULL;
2924 }
2925 ESL_ALLOC(useme, (sizeof(int *) * (nc+1)));
2926 for(m = 0; m <= nc; m++) {
2927 ESL_ALLOC(useme[m], (sizeof(int)) * mmsa->nseq);
2928 if(m < nc) esl_vec_ISet(useme[m], mmsa->nseq, FALSE);
2929 else esl_vec_ISet(useme[m], mmsa->nseq, TRUE); /* keep all seqs in cmsa[nc]*/
2930 }
2931
2932 for(i = 0; i < mmsa->nseq; i++)
2933 if(clust[i] != -1)
2934 useme[clust[i]][i] = TRUE;
2935 ESL_ALLOC(buffer, sizeof(char) * (IntMaxDigits() + 2)); /* IntMaxDigits() returns number of digits in INT_MAX */
2936 for(m = 0; m < nc; m++) {
2937 if((status = esl_msa_SequenceSubset(mmsa, useme[m], &(cmsa[m]))) != eslOK) ESL_FAIL(status, errbuf, "MSADivide(), esl_msa_SequenceSubset error, status: %d.", status);
2938 /* rename the MSA it by adding ".<m+1>" */
2939 if(cmsa[m]->name == NULL) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "MSADivide(), an msa's name is NULL, shouldn't happen.");
2940 ndigits = strlen(cmsa[m]->name);
2941 ndigits += snprintf(buffer, (IntMaxDigits() + 2), ".%d", (m+1));
2942 ESL_RALLOC(cmsa[m]->name, tmp, sizeof(char)*(ndigits+1));
2943 if ((status = esl_strcat(&cmsa[m]->name, -1, buffer, (ndigits+1))) != eslOK) goto ERROR;
2944 if ((status = esl_strchop(cmsa[m]->name, ndigits)) != eslOK) goto ERROR;
2945 free(useme[m]);
2946 }
2947 if(do_orig) {
2948 if((status = esl_msa_SequenceSubset(mmsa, useme[nc], &(cmsa[nc]))) != eslOK) ESL_FAIL(status, errbuf, "MSADivide(), esl_msa_SequenceSubset error, status: %d.", status);
2949 }
2950 free(useme[nc]);
2951 free(useme);
2952
2953 if(do_orig) *ret_num_msa = nc+1;
2954 else *ret_num_msa = nc;
2955 *ret_cmsa = cmsa;
2956
2957 if(!do_all) { /* else we didn't allocate these structures */
2958 esl_tree_Destroy(T);
2959 esl_dmatrix_Destroy(D);
2960 free(diff);
2961 diff = NULL;
2962 }
2963 if(clust != NULL) free(clust);
2964 if(csize != NULL) free(csize);
2965 if(buffer!= NULL) free(buffer);
2966
2967 return eslOK;
2968
2969 ERROR:
2970 if(diff != NULL) free(diff);
2971 if(clust != NULL) free(clust);
2972 if(csize != NULL) free(csize);
2973 if(buffer!= NULL) free(buffer);
2974 if(cmsa != NULL) {
2975 for(m = 0; m < nc; m++)
2976 if(cmsa[m] != NULL) esl_msa_Destroy(cmsa[m]);
2977 free(cmsa);
2978 }
2979 return status;
2980 }
2981
2982 /* Function: select_node()
2983 * EPN, Fri Mar 23 08:48:37 2007
2984 * Adapted from SRE's select_node() in maketestset.c originally written
2985 * for the PROFMARK HMMER benchmark.
2986 *
2987 *
2988 * Purpose: Define clusters of the taxa (seqs) in the tree such
2989 * that minimum disparity b/t any 2 seqs in different
2990 * clusters is greater than <mindiff> and the number of
2991 * clusters is maximized. <ret_best> is the index of the node
2992 * of the tree under which the largest cluster belongs.
2993 * <ret_nc> is the number of clusters after clustering,
2994 * <ret_clust> is an array [0..T->N-1] specifying which
2995 * cluster each taxa belongs to.
2996 *
2997 * For high disparities, this cluster may contain all
2998 * the sequences, and we'll return the root node (0).
2999 *
3000 * Args:
3001 * ESL_TREE *T - the tree
3002 * double *diff - [0..T->N-2]: for each node of the tree, the minimum
3003 * distance (sum of branch lengths) from any taxa (leaf)
3004 * in left subtree to any taxa in right subtree.
3005 * double mindiff - (see description above)
3006 * int **ret_clust- [0..T->N-1] cluster number this seq is in, alloc'ed, filled here
3007 * int *ret_nc - number of clusters
3008 * int *ret_best - RETURN: index of node of tree under which largest cluster belongs (see Purpose).
3009 * char *errbuf - buffer for error messages
3010 *
3011 * Returns: node index (as explained in Purpose)
3012 */
3013 static int
3014 select_node(ESL_TREE *T, double *diff, double mindiff, int **ret_clust, int *ret_nc, int *ret_best, char *errbuf)
3015 {
3016 int status; /* Easel status code */
3017 ESL_STACK *ns1; /* stack for traversing tree */
3018 ESL_STACK *ns2; /* another stack for traversing tree */
3019 int c; /* counter for clusters */
3020 int best; /* index of current best node */
3021 int maxsize; /* size of cluster for best node */
3022 int n, np; /* counters over tree nodes */
3023 int *clust; /* [1..T->N-1] cluster number this seq is in */
3024
3025 /*printf("in selec_node mindiff: %f T->N: %d\n", mindiff, T->N);*/
3026 /* set tree cladesizes if not already set */
3027 if(T->cladesize == NULL)
3028 if((status = esl_tree_SetCladesizes(T)) != eslOK) ESL_FAIL(status, errbuf, "select_node(), esl_tree_SetCladeSizes error, status: %d.", status);
3029
3030 ESL_ALLOC(clust, (sizeof(int) * T->N));
3031 esl_vec_ISet(clust, T->N, 0);
3032
3033 if((ns1 = esl_stack_ICreate()) == NULL) ESL_FAIL(status, errbuf, "select_node(), failed to create a stack, probably out of memory, status: %d.", status);
3034 if((ns2 = esl_stack_ICreate()) == NULL) ESL_FAIL(status, errbuf, "select_node(), failed to create a stack, probably out of memory, status: %d.", status);
3035
3036 /* push root on stack to start */
3037 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);
3038 maxsize = 0;
3039 best = 0;
3040 c = 0;
3041 while (esl_stack_IPop(ns1, &n) != eslEOD) {
3042 if ((n == 0 || diff[T->parent[n]] > mindiff) &&
3043 diff[n] <= mindiff) { /* we're at a cluster */
3044 if (T->cladesize[n] > maxsize) {
3045 maxsize = T->cladesize[n];
3046 best = n;
3047 }
3048 /* determine all taxa in the clade rooted at n*/
3049 esl_stack_IPush(ns2, n);
3050 while (esl_stack_IPop(ns2, &np) != eslEOD) {
3051 /*printf("np: %d T->left[np]: %d\n", np, T->left[np]);*/
3052 if(T->left[np] <= 0) clust[(-1*T->left[np])] = c;
3053 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); }
3054 if(T->right[np] <= 0) clust[(-1*T->right[np])] = c;
3055 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); }
3056 }
3057 c++;
3058 }
3059 else { /* we're not a cluster, keep traversing */
3060 /*printf("n: %d T->left[n]: %d\n", n, T->left[n]);*/
3061 if(T->left[n] <= 0) clust[(-1*T->left[n])] = c++; /* single seq with its own cluster */
3062 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); }
3063 if(T->right[n] <= 0) clust[(-1*T->right[n])] = c++; /* single seq with its own cluster */
3064 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); }
3065 }
3066 }
3067 esl_stack_Destroy(ns1);
3068 esl_stack_Destroy(ns2);
3069 *ret_nc = c;
3070 *ret_clust = clust;
3071 *ret_best = best;
3072 /*printf("nc: %d(%d) best: %d maxsize: %d nc: %d\n\n", *ret_nc, c, best, maxsize, c);
3073 for(n = 0; n < T->N; n++)
3074 printf("clust[%d]: %d\n", n, clust[n]);*/
3075 return eslOK;
3076
3077 ERROR:
3078 if(clust != NULL) free(clust);
3079 ESL_FAIL(status, errbuf, "select_node(), memory allocation error, status: %d.", status);
3080 }
3081
3082
3083 /* Function: find_mindiff()
3084 * EPN, Fri Mar 23 18:59:42 2007
3085 *
3086 * Purpose: Given a tree resulting from single linkage clustering,
3087 * find the min fractional difference (mindiff) that when used to
3088 * define clusters (such that no seq in cluster A is less
3089 * than mindiff different than any seq in cluster B),
3090 * gives >= target_nc.
3091 *
3092 * Args:
3093 * ESL_TREE *T - the tree
3094 * double *diff - [0..T->N-2]: for each node of the tree, the minimum
3095 * distance (sum of branch lengths) from any taxa (leaf)
3096 * in left subtree to any taxa in right subtree.
3097 * int target_nc - number of clusters we want
3098 * int **ret_clust- [0..T->N-1] cluster number this seq is in, alloc'ed, filled here
3099 * int *ret_nc - number of clusters
3100 * char *errbuf - buffer for error messages
3101 *
3102 * Returns: fractional difference (as explained in Purpose)
3103 */
3104 static float
3105 find_mindiff(ESL_TREE *T, double *diff, int target_nc, int **ret_clust, int *ret_nc, float *ret_mindiff, char *errbuf)
3106 {
3107 int status;
3108 float high = 1.0;
3109 float low = 0.0;
3110 int high_nc = 0;
3111 /*int low_nc = 0;*/
3112 float mindiff = 0.5;
3113 int curr_nc = -1;
3114 int curr_best = -1;
3115 int keep_going = TRUE;
3116 float thresh = 0.001;
3117 int *clust = NULL;
3118
3119 /* Contract check */
3120 if(target_nc > T->N) ESL_FAIL(eslEINCOMPAT, errbuf, "find_mindiff(), desired number of clusters is greater than number of seqs in the tree");
3121
3122 while(keep_going) {
3123 if(clust != NULL) free(clust);
3124 if((status = select_node(T, diff, mindiff, &clust, &curr_nc, &curr_best, errbuf)) != eslOK) return status;
3125 if(curr_nc < target_nc) {
3126 high = mindiff;
3127 high_nc = curr_nc;
3128 mindiff -= (mindiff - low) / 2.;
3129 if((fabs(high-0.) < thresh) && (fabs(low-0.) < thresh)) keep_going = FALSE;
3130 /* stop, high and low have converged at 0. */
3131 /*printf("LOWER nc: %d mindiff: %f low: %f high: %f\n", curr_nc, mindiff, low, high);*/
3132 }
3133 else {/* curr_nc >= target_nc */
3134 low = mindiff;
3135 /*low_nc = curr_nc;*/
3136 mindiff += (high - mindiff) / 2.;
3137 if(fabs(high-low) < thresh) keep_going = FALSE; /* stop, high and low have converged */
3138 /*printf("GREATER nc: %d mindiff: %f low: %f high: %f\n", curr_nc, mindiff, low, high);*/
3139 }
3140 }
3141 /* it's possible we can't reach our target, if so, set mindiff as minimum value that gives
3142 * less than target_nc clusters. */
3143 if(curr_nc != target_nc) {
3144 /*printf("targ: %d curr: %d low: %d (%f) high: %d (%f)\n", target_nc, curr_nc, low_nc, low, high_nc, high);*/
3145 if(high_nc < target_nc) {
3146 mindiff = high;
3147 if((status = select_node(T, diff, mindiff, &clust, &curr_nc, &curr_best, errbuf)) != eslOK) return status;
3148 }
3149 else
3150 while(high_nc > target_nc) {
3151 high += thresh;
3152 if(high > 1.0) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "find_mindiff(), mindiff has risen above 1.0");
3153 mindiff = high;
3154 if((status = select_node(T, diff, mindiff, &clust, &curr_nc, &curr_best, errbuf)) != eslOK) return status;
3155 high_nc = curr_nc;
3156 }
3157 }
3158 /*printf("FINAL mindiff: %f\n", mindiff); */
3159 *ret_nc = curr_nc;
3160 *ret_clust = clust;
3161 *ret_mindiff = mindiff;
3162
3163 return eslOK;
3164 }
3165
3166 /* Function: flatten_insert_emissions()
3167 *
3168 * Purpose: Set the insert emission *probabilities* of a CM to it's
3169 * null model probabilities. Subsequently in CMLogoddsify(),
3170 * all insert emissions scores will become 0.0 bits.
3171 * This option is called by default for all CMs unless --iins
3172 * was enabled on the command line. It is impt that if we're
3173 * going to zero insert scores, we do it within the CM file
3174 * (as opposed to previous versions of infernal which allowed us
3175 * to zero inserts with cmsearch, for example), because now we
3176 * have E-values and if a Gumbel is fit to a CM with zeroed
3177 * inserts or with informative inserts, those insert scores should
3178 * never change as long as that Gumbel is used.
3179 *
3180 * Returns: eslOK on success.
3181 */
3182 int
3183 flatten_insert_emissions(CM_t *cm)
3184 {
3185 int v;
3186
3187 /* Contract check */
3188 if(cm->abc == NULL) cm_Fail("flatten_insert_emissions(), cm->abc is NULL.\n");
3189 if(cm->null == NULL) cm_Fail("flatten_insert_emissions(), cm->null is NULL.\n");
3190
3191 esl_vec_FNorm(cm->null, cm->abc->K);
3192 for (v = 0; v < cm->M; v++) {
3193 if(cm->sttype[v] == IL_st || cm->sttype[v] == IR_st) {
3194 esl_vec_FSet(cm->e[v], (cm->abc->K * cm->abc->K), 0.); /* zero them out */
3195 esl_vec_FCopy(cm->null, cm->abc->K, cm->e[v]); /* overwrite first cm->abc->K values (rest are irrelevant for non-MP states) with cm->null */
3196 }
3197 }
3198 return eslOK;
3199 }
3200
3201 /* Function: print_refine_column_headings()
3202 * Date: EPN, Fri Feb 29 10:36:03 2008
3203 *
3204 * Purpose: Print column headings for tabular output of refine_msa() to
3205 * output file (stdout unless -o).
3206 *
3207 * Returns: eslOK on success
3208 */
3209 static void
3210 print_refine_column_headings(const ESL_GETOPTS *go, const struct cfg_s *cfg)
3211 {
3212 fprintf(cfg->ofp, "#\n");
3213 fprintf(cfg->ofp, "# %-5s %-13s %10s\n", "iter", "bit score sum", "fract diff");
3214 fprintf(cfg->ofp, "# %-5s %-13s %10s\n", "-----", "-------------", "----------");
3215 return;
3216 }
3217
3218 /* Function: dump_emission_info()
3219 * Date: EPN, Wed Jul 9 14:47:51 2008
3220 *
3221 * Purpose: Dump information on the emissions (singlets and base pairs) in the model.
3222 *
3223 * Returns: eslOK on success, eslEMEM and fills errbuf on memory allocation error
3224 */
3225 static int
3226 dump_emission_info(FILE *fp, CM_t *cm, char *errbuf)
3227 {
3228 int status;
3229 int nd, v;
3230 int i = 0;
3231 int ab, a, b;
3232 float tsc, esc;
3233 float bpsc, lsc, rsc;
3234 float tlsc, trsc, tbpsc, tdiffsc;
3235 CMEmitMap_t *emap;
3236 float *lme = NULL;
3237 float *rme = NULL;
3238
3239 ESL_ALLOC(lme, sizeof(float) * cm->abc->K);
3240 ESL_ALLOC(rme, sizeof(float) * cm->abc->K);
3241
3242 emap = CreateEmitMap(cm);
3243 esc = tsc = 0.;
3244 tlsc = trsc = tbpsc = tdiffsc = 0.;
3245
3246 fprintf(fp, "# %5s %3s %5s %5s %5s %1s %7s\n", "idx", "L/R", "v", "nd", "pos", "a", "sc");
3247 fprintf(fp, "# %5s %3s %5s %5s %5s %1s %7s\n", "-----", "---", "-----", "-----", "-----", "-", "-------");
3248
3249 /* singlet section */
3250 for (v = 0; v < cm->M; v++) {
3251 if(cm->stid[v] == MATL_ML) {
3252 i++;
3253 nd = cm->ndidx[v];
3254 esc = 0.;
3255 for(a = 0; a < cm->abc->K; a++) {
3256 esc += cm->e[v][a] * cm->esc[v][a];
3257 }
3258 a = esl_vec_FArgMax(cm->esc[v], cm->abc->K);
3259 fprintf(fp, " %5d %3s %5d %5d %5d %c %7.3f\n", i, "L", v, nd, emap->lpos[nd], cm->abc->sym[a], esc);
3260 tsc += esc;
3261 }
3262 if(cm->stid[v] == MATR_MR) {
3263 i++;
3264 nd = cm->ndidx[v];
3265 esc = 0.;
3266 for(a = 0; a < cm->abc->K; a++) {
3267 esc += cm->e[v][a] * cm->esc[v][a];
3268 }
3269 a = esl_vec_FArgMax(cm->esc[v], cm->abc->K);
3270 fprintf(fp, " %5d %3s %5d %5d %5d %c %7.3f\n", i, "R", v, nd, emap->rpos[nd], cm->abc->sym[a], esc);
3271 tsc += esc;
3272 }
3273 }
3274 fprintf(fp, "# %5s %3s %5s %5s %5s %1s %7s\n", "-----", "---", "-----", "-----", "-----", "-", "-------");
3275 fprintf(fp, "# total %3s %5s %5s %5s %1s %7.3f\n", "-", "-", "-", "-", "-", tsc);
3276 fprintf(fp, "#\n");
3277 fprintf(fp, "//\n");
3278 fprintf(fp, "#\n");
3279
3280 /* base pair section */
3281 fprintf(fp, "# %5s %5s %5s %5s %5s %2s %7s %7s %7s %7s\n", "idx", "v", "nd", "lpos", "rpos", "ab", "bpsc", "marglsc", "margrsc", "bpdiff");
3282 fprintf(fp, "# %5s %5s %5s %5s %5s %2s %7s %7s %7s %7s\n", "-----", "-----", "-----", "-----", "-----", "--", "-------", "-------", "-------", "-------");
3283
3284 i = 0;
3285 for (v = 0; v < cm->M; v++) {
3286 if(cm->sttype[v] == MP_st) {
3287 i++;
3288 nd = cm->ndidx[v];
3289 bpsc = lsc = rsc = 0.;
3290 esl_vec_FSet(lme, cm->abc->K, 0.);
3291 esl_vec_FSet(rme, cm->abc->K, 0.);
3292 for(a = 0; a < cm->abc->K; a++) {
3293 for(b = 0; b < cm->abc->K; b++) {
3294 ab = (a * cm->abc->K) + b;
3295 bpsc += cm->e[v][ab] * cm->esc[v][ab];
3296 lme[a] += cm->e[v][ab];
3297 rme[b] += cm->e[v][ab];
3298 }
3299 }
3300 lsc = 0.;
3301 rsc = 0.;
3302 for(a = 0; a < cm->abc->K; a++) {
3303 lsc += lme[a] * cm->lmesc[v][a];
3304 rsc += rme[a] * cm->rmesc[v][a];
3305 }
3306
3307 ab = esl_vec_FArgMax(cm->esc[v], (cm->abc->K * cm->abc->K));
3308 a = ab / cm->abc->K;
3309 b = ab % cm->abc->K;
3310 fprintf(fp, " %5d %5d %5d %5d %5d %c%c %7.3f %7.3f %7.3f %7.3f\n", i, v, nd, emap->lpos[nd], emap->rpos[nd], cm->abc->sym[a], cm->abc->sym[b],
3311 bpsc, lsc, rsc, (bpsc - (lsc+rsc)));
3312 tlsc += lsc;
3313 trsc += rsc;
3314 tbpsc += bpsc;
3315 tdiffsc += bpsc - (lsc + rsc);
3316 }
3317 }
3318 fprintf(fp, "# %5s %5s %5s %5s %5s %2s %7s %7s %7s %7s\n", "-----", "-----", "-----", "-----", "-----", "--", "-------", "-------", "-------", "-------");
3319 fprintf(fp, "# total %5s %5s %5s %5s %2s %7.3f %7.3f %7.3f %7.3f\n", "-", "-", "-", "-", "-", tbpsc, tlsc, trsc, tdiffsc);
3320
3321 FreeEmitMap(emap);
3322 if(lme != NULL) free(lme);
3323 if(rme != NULL) free(rme);
3324 return eslOK;
3325
3326 ERROR:
3327 ESL_FAIL(status, errbuf, "out of memory when trying to output emission information");
3328 return status; /* NEVER REACHED */
3329 }
3330
3331
3332 /* Function: p7_prior_Read()
3333 * Incept: EPN, Tue Nov 16 13:44:35 2010
3334 *
3335 * Purpose: Input a p7 prior from an open stream
3336 * (probably an open file).
3337 *
3338 * Returns: A prior <pri>. NULL if an error occurs.
3339 */
3340 P7_PRIOR *
3341 p7_prior_Read(FILE *fp)
3342 {
3343 P7_PRIOR *pri = NULL;
3344 int status;
3345 ESL_FILEPARSER *efp = NULL;
3346
3347 ESL_ALLOC(pri, sizeof(P7_PRIOR));
3348 pri->tm = pri->ti = pri->td = pri->em = pri->ei = NULL;
3349
3350 if ((efp = esl_fileparser_Create(fp)) == NULL) goto ERROR;
3351 esl_fileparser_SetCommentChar(efp, '#');
3352
3353 /* Transition section: 3 sets of transitions out of match, out of insert, and out of delete */
3354 if (esl_mixdchlet_Read(efp, &(pri->tm)) != eslOK) goto ERROR;
3355 if (esl_mixdchlet_Read(efp, &(pri->ti)) != eslOK) goto ERROR;
3356 if (esl_mixdchlet_Read(efp, &(pri->td)) != eslOK) goto ERROR;
3357
3358 /* Emission section: match emissions, then insert emissions */
3359 if (esl_mixdchlet_Read(efp, &(pri->em)) != eslOK) goto ERROR;
3360 if (esl_mixdchlet_Read(efp, &(pri->ei)) != eslOK) goto ERROR;
3361
3362 esl_fileparser_Destroy(efp);
3363
3364 return pri;
3365
3366 ERROR:
3367 if(efp != NULL) esl_fileparser_Destroy(efp);
3368 if(pri != NULL) p7_prior_Destroy(pri);
3369 return NULL;
3370 }
3371
3372
3373 /* Function: cm_p7_prior_CreateNucleic()
3374 * Incept: EPN, Thu Mar 10 14:08:25 2011
3375 *
3376 * Purpose: Creates the default Infernal mixture Dirichlet prior
3377 * for p7 HMMs for RNA.
3378 *
3379 * The transition priors (match, insert, delete) are all
3380 * single Dirichlets, originally trained by Travis
3381 * Wheeler. And, at the time of writing, are the same
3382 * default transitions used by HMMER for DNA/RNA HMMs.
3383 *
3384 * The match emission priors were trained on Rfam.
3385 * This is the 'ss1' prior described in
3386 * ~nawrockie/notebook/10_1116_hmmer_dinuc_priors/00LOG.
3387 * These are very nearly identical to the defaults used
3388 * by HMMER, but in HMMER they've been rounded.
3389 *
3390 * The insert emission prior is flat, plus-1.
3391 *
3392 * Returns: a pointer to the new <P7_PRIOR> structure.
3393 */
3394 P7_PRIOR *cm_p7_prior_CreateNucleic(void)
3395 {
3396 int status;
3397 P7_PRIOR *pri = NULL;
3398 int q;
3399
3400 int num_comp = 4;
3401
3402 static double defmq[5] = { 0.079226, 0.259549, 0.241578, 0.419647 };
3403 static double defm[4][4] = {
3404 { 1.294511, 0.400028, 6.579555, 0.509916},
3405 { 0.090031, 0.028634, 0.086396, 0.041186},
3406 { 0.158085, 0.448297, 0.114815, 0.394151},
3407 { 1.740028, 1.487773, 1.565443, 1.947555}
3408 };
3409
3410 ESL_ALLOC(pri, sizeof(P7_PRIOR));
3411 pri->tm = pri->ti = pri->td = pri->em = pri->ei = NULL;
3412
3413 pri->tm = esl_mixdchlet_Create(1, 3); // match transitions; single component; 3 params
3414 pri->ti = esl_mixdchlet_Create(1, 2); // insert transitions; single component; 2 params
3415 pri->td = esl_mixdchlet_Create(1, 2); // delete transitions; single component; 2 params
3416 pri->em = esl_mixdchlet_Create(num_comp, 4); // match emissions; X component; 4 params
3417 pri->ei = esl_mixdchlet_Create(1, 4); // insert emissions; single component; 4 params
3418
3419 if (pri->tm == NULL || pri->ti == NULL || pri->td == NULL || pri->em == NULL || pri->ei == NULL) goto ERROR;
3420
3421 /* Transition priors: taken from hmmer's p7_prior.c::p7_prior_CreateNucleic() */
3422 /* Roughly, learned from rmark benchmark - hand-beautified (trimming overspecified significant digits)
3423 */
3424 pri->tm->q[0] = 1.0;
3425 pri->tm->alpha[0][0] = 2.0; // TMM
3426 pri->tm->alpha[0][1] = 0.1; // TMI
3427 pri->tm->alpha[0][2] = 0.1; // TMD
3428
3429 pri->ti->q[0] = 1.0;
3430 pri->ti->alpha[0][0] = 0.06; // TIM
3431 pri->ti->alpha[0][1] = 0.2; // TII
3432
3433 pri->td->q[0] = 1.0;
3434 pri->td->alpha[0][0] = 0.1; // TDM
3435 pri->td->alpha[0][1] = 0.2; // TDD
3436
3437 /* Match emission priors */
3438 for (q = 0; q < num_comp; q++)
3439 {
3440 pri->em->q[q] = defmq[q];
3441 esl_vec_DCopy(defm[q], 4, pri->em->alpha[q]);
3442 }
3443
3444 /* Insert emission priors. */
3445 pri->ei->q[0] = 1.0;
3446 esl_vec_DSet(pri->ei->alpha[0], 4, 1.0);
3447
3448 return pri;
3449
3450 ERROR:
3451 if (pri != NULL) p7_prior_Destroy(pri);
3452 return NULL;
3453 }
3454
3455 /* Function: dump_cm_occupancy_values()
3456 * Date: EPN, Tue Jul 17 19:53:06 2018 [Benasque]
3457 *
3458 * Purpose: Calculate and dump CM occupancy values, the expected
3459 * number of times each CM state is entered.
3460 *
3461 * Returns: void
3462 */
3463 static void
3464 dump_cm_occupancy_values(FILE *fp, CM_t *cm)
3465 {
3466 double *psi; /* expected num times each state visited in HMM*/
3467 int v;
3468
3469 psi = cm_ExpectedStateOccupancy(cm);
3470
3471 fprintf(fp, "# model_name: %s\n", cm->name);
3472 fprintf(fp, "# number_of_states: %d\n", cm->M);
3473 fprintf(fp, "# columns: <state_idx> <state_expected_occupancy>\n");
3474 for(v = 0; v < cm->M; v++) {
3475 fprintf(fp, "%d %.5f\n", v, psi[v]);
3476 }
3477 fprintf(fp, "//\n");
3478
3479 free(psi);
3480
3481 return;
3482 }
3483
3484 /* Function: dump_cp9_occupancy_values()
3485 * Date: EPN, Tue Jul 17 19:22:57 2018 [Benasque]
3486 *
3487 * Purpose: Calculate and dump ML CP9 HMM occupancy values, the
3488 * expected number of times each state is entered.
3489 *
3490 * Returns: void
3491 */
3492 static void
3493 dump_cp9_occupancy_values(FILE *fp, char *name, CP9_t *cp9)
3494 {
3495 int k;
3496 double **phi; /* expected num times each state visited in HMM*/
3497
3498 fill_phi_cp9(cp9, &phi, 1, FALSE);
3499
3500 fprintf(fp, "# model_name: %s\n", name);
3501 fprintf(fp, "# number_of_nodes: %d\n", cp9->M);
3502 fprintf(fp, "# columns: <node_idx> <expected_occupancy_match> <expected_occupancy_insert> <expected_occupancy_delete>\n");
3503 for(k = 0; k <= cp9->M; k++) {
3504 fprintf(fp, "%d %.5f %.5f %.5f\n", k, phi[k][HMMMATCH], phi[k][HMMINSERT], phi[k][HMMDELETE]);
3505 }
3506 fprintf(fp, "//\n");
3507
3508 for(k = 0; k <= cp9->M; k++) free(phi[k]);
3509 free(phi);
3510
3511 return;
3512 }
3513
3514 /* Function: dump_fp7_occupancy_values()
3515 * Date: EPN, Tue Jul 17 19:22:57 2018 [Benasque]
3516 *
3517 * Purpose: Calculate and dump filter P7 HMM occupancy values, the
3518 * expected number of times each CM state is entered.
3519 *
3520 * Returns: void
3521 */
3522 static void
3523 dump_fp7_occupancy_values(FILE *fp, char *name, P7_HMM *p7)
3524 {
3525 int status;
3526 int k;
3527 float *mocc = NULL;
3528 float *iocc = NULL;
3529
3530 ESL_ALLOC(mocc, sizeof(float) * (p7->M+1));
3531 ESL_ALLOC(iocc, sizeof(float) * (p7->M+1));
3532
3533 if (p7_hmm_CalculateOccupancy(p7, mocc, iocc) != eslOK) cm_Fail("Error in p7_hmm_CalculateOccupancy()");
3534
3535 fprintf(fp, "# model_name: %s\n", name);
3536 fprintf(fp, "# number_of_nodes: %d\n", p7->M);
3537 fprintf(fp, "# columns: <node_idx> <expected_occupancy_match> <expected_occupancy_insert> <expected_occupancy_delete>\n");
3538 for(k = 0; k <= p7->M; k++) {
3539 fprintf(fp, "%d %.5f %.5f %.5f\n", k, mocc[k], iocc[k], 1. - mocc[k]);
3540 }
3541 fprintf(fp, "//\n");
3542
3543 free(mocc);
3544 free(iocc);
3545
3546 return;
3547
3548 ERROR:
3549 cm_Fail("memory allocation error.");
3550 return; /* NEVERREACHED */
3551 }
3552
3553 /* Function: determine_pretend_cm_is_hmm()
3554 * Date: EPN, Thu Nov 3 15:23:27 2022
3555 *
3556 * Purpose: Determine if we are going to pretend the CM
3557 * is an HMM for parameterization purposes.
3558 *
3559 * Returns: TRUE or FALSE
3560 */
3561 static int
3562 determine_pretend_cm_is_hmm(const ESL_GETOPTS *go, CM_t *cm)
3563 {
3564 int pretend_cm_is_hmm;
3565
3566 if((CMCountNodetype(cm, MATP_nd) == 0) &&
3567 (! esl_opt_GetBoolean(go, "--v1p0")) &&
3568 (! esl_opt_GetBoolean(go, "--p56")) &&
3569 (! esl_opt_GetBoolean(go, "--noh3pri")) &&
3570 (! esl_opt_IsUsed (go, "--prior"))) {
3571 pretend_cm_is_hmm = TRUE;
3572 }
3573 else {
3574 pretend_cm_is_hmm = FALSE;
3575 }
3576
3577 return pretend_cm_is_hmm;
3578 }