Debian Codegraph @

rmark/rmark-create.c

raw symbols SCIP
1 /* Construct a training alignment/test sequences set from an MSA.
2 * Modified from HMMER's create-profmark.c.
3 *
4 * Usage:
5 * ./rmark-create <basename> <msa Stockholm file> <FASTA db>
6 * For example:
7 * ./rmark-create rmark3 /misc/data0/databases/Rfam/Rfam.seed /misc/data0/databases/rfamseq.fasta
8 *
9 * There are three types of sequences:
10 * 1. positives:
11 * - test sequences from the input <msa Stockholm file>.
12 * 2. negatives:
13 * - long pseudo-chromosome sequences, created by shuffling
14 * randomly chosen subsequences from <FASTA db>.
15 * 3. benchmark sequences:
16 * - negative sequences with >= 0 positives embedded
17 * within them
18 *
19 * Six output files are generated:
20 * <basename>.tbl - table summarizing the benchmark
21 * <basename>.msa - MSA queries, stockholm format
22 * <basename>.fa - benchmark sequences, fasta format
23 * <basename>.pos - table summarizing positive test set;
24 * their locations in the benchmark seqs
25 * <basename>.pfa - positive sequences, fasta format
26 * <basename>.ppos - table summarizing positive test seqs;
27 * their locations in the .pfa file
28 *
29 * The .pfa and .ppos files are for running a positive-only version
30 * of the benchmark, by searching only the positive test set. This
31 * is useful for quickly determining how many positive sequences
32 * pass a filter strategy, for example.
33 *
34 * EPN, Tue Jul 6 09:48:24 2010
35 */
36
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <string.h>
40
41 #include "easel.h"
42 #include "esl_alphabet.h"
43 #include "esl_composition.h"
44 #include "esl_distance.h"
45 #include "esl_fileparser.h"
46 #include "esl_getopts.h"
47 #include "esl_hmm.h"
48 #include "esl_msa.h"
49 #include "esl_msafile.h"
50 #include "esl_msacluster.h"
51 #include "esl_msaweight.h"
52 #include "esl_random.h"
53 #include "esl_randomseq.h"
54 #include "esl_sq.h"
55 #include "esl_sqio.h"
56 #include "esl_stack.h"
57 #include "esl_vectorops.h"
58
59 static char banner[] = "construct a rmark benchmark profile training/test set";
60 static char usage1[] = "[options] <basename> <msafile> <hmmfile>";
61 static char usage2[] = "[options] -S <basename> <msafile> <seqdb>";
62 static char usage3[] = "[options] --iid <basename> <msafile>\n";
63
64 #define SHUF_OPTS "--mono,--di,--markov0,--markov1" /* toggle group, seq shuffling options */
65
66 static ESL_OPTIONS options[] = {
67 /* name type default env range togs reqs incomp help docgroup */
68 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "help; show brief info on version and usage", 1 },
69 { "-S", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "do not generate with an HMM, shuffle seqs from <seqdb>", 1 },
70 { "-1", eslARG_REAL, "0.60", NULL,"0<x<=1.0",NULL,NULL,NULL, "require all test seqs to have < x id to training", 1 },
71 { "-2", eslARG_REAL, "0.70", NULL,"0<x<=1.0",NULL,NULL,NULL, "require all test seqs to have < x id to each other", 1 },
72 { "-F", eslARG_REAL, "0.70", NULL,"0<x<=1.0",NULL,NULL,NULL, "filter out seqs <x*average length", 1 },
73 { "-N", eslARG_INT, "10", NULL, NULL, NULL,NULL,NULL, "number of benchmark seqs", 1 },
74 { "-L", eslARG_INT,"1000000",NULL,"n>0", NULL,NULL,NULL, "full length of benchmark seqs prior to test seq embedding", 1 },
75 { "-C", eslARG_INT, "1000",NULL,"n>0", NULL,NULL,"--iid", "length of of <seqdb> seqs to extract and shuffle when making test seqs", 1 },
76 { "-X", eslARG_REAL, "0.05", NULL,"0<x<=1.0",NULL,NULL,NULL, "maximum fraction of total test seq covered by positives", 1 },
77 { "-R", eslARG_INT, "5", NULL,"n>0", NULL,NULL,NULL, "minimum number of training seqs per family", 1 },
78 { "-E", eslARG_INT, "1", NULL,"n>0", NULL,NULL,NULL, "minimum number of test seqs per family", 1 },
79
80 /* Options controlling negative segment randomization method */
81 { "--iid", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-S", "generate random iid sequence for negatives", 2 },
82 { "--mono", eslARG_NONE, FALSE, NULL, NULL, NULL, "-S", SHUF_OPTS, "with -S, shuffle preserving monoresidue composition", 2 },
83 { "--di", eslARG_NONE, FALSE, NULL, NULL, NULL, "-S", SHUF_OPTS, "with -S, shuffle preserving mono- and di-residue composition", 2 },
84 { "--markov0", eslARG_NONE, FALSE, NULL, NULL, NULL, "-S", SHUF_OPTS, "with -S, generate with 0th order Markov properties per input", 2 },
85 { "--markov1", eslARG_NONE, FALSE, NULL, NULL, NULL, "-S", SHUF_OPTS, "with -S, generate with 1st order Markov properties per input", 2 },
86
87 /* Options forcing which alphabet we're working in (normally autodetected) */
88 { "--amino", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL,"--dna,--rna", "<msafile> contains protein alignments", 3 },
89 { "--dna", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL,"--amino,--rna", "<msafile> contains DNA alignments", 3 },
90 { "--rna", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL,"--amino,--dna", "<msafile> contains RNA alignments", 3 },
91
92 /* Other options */
93 { "--minDPL", eslARG_INT, "100", NULL, NULL, NULL, NULL, NULL, "minimum segment length for DP shuffling", 4 },
94 { "--seed", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "specify random number generator seed", 4 },
95 { "--sub", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--sample", "look for train/test in msa subsets via greedy algorithm", 4 },
96 { "--sample", eslARG_INT, FALSE, NULL, NULL, NULL, NULL, "-sub", "look for train/test in msa subsets via sampling, <n> samples", 4},
97 { "--skip", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "w/--sub or --sample, skip partition test", 4 },
98 { "--xtest", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "w/--sub or --sample, maximize |test|, not |train|+|test|", 4 },
99 { "--nfile", eslARG_OUTFILE,FALSE,NULL, NULL, NULL, NULL, NULL, "save benchmark database *without* positives to <f>", 4 },
100 { "--tfile", eslARG_OUTFILE,FALSE,NULL, NULL, NULL, NULL, NULL, "save orig/train/test alignments with renamed seqs to <f>", 4 },
101
102 { 0,0,0,0,0,0,0,0,0,0 },
103 };
104
105 struct cfg_s {
106 ESL_ALPHABET *abc; /* biological alphabet */
107 ESL_RANDOMNESS *r; /* random number generator */
108 ESL_HMM *hmm; /* HMM for generating background seqs */
109 double fragfrac; /* seqs less than x*avg length are removed from alignment */
110 double idthresh1; /* fractional identity threshold for train/test split */
111 double idthresh2; /* fractional identity threshold for selecting test seqs */
112 int min_ntrain; /* minimum number of sequences in the training set */
113 int min_ntest; /* minimum number of sequences in the test set */
114
115 FILE *out_msafp; /* output: training MSAs */
116 FILE *out_bmkfp; /* output: benchmark sequences */
117 FILE *out_posfp; /* output: positive sequences */
118 FILE *possummfp; /* output: summary table of the positive test set in the benchmark seqs */
119 FILE *ppossummfp; /* output: summary table of the positive-only test set */
120 FILE *negsummfp; /* output: summary table of the negative test set */
121 FILE *tblfp; /* output: summary table of the training set alignments */
122 FILE *nseqfp; /* output: (optional) negative sequences only (without embedded positives) */
123 FILE *tfp; /* output: (optional) alignments with train/test seqs renamed */
124
125 ESL_SQFILE *dbfp; /* source database for negatives */
126 int db_nseq; /* # of sequences in the db */
127 int nneg; /* number of negative long sequences we'll create */
128 int negL; /* length of long negative sequences before test seqs get embedded */
129 int negchunkL; /* length of each chunk that make up the long negative sequences */
130
131 double fq[20]; /* background frequency distribution, if we're making iid negatives */
132 };
133
134 static int process_dbfile (struct cfg_s *cfg, char *dbfile, int dbfmt);
135 static int remove_fragments (struct cfg_s *cfg, ESL_MSA *msa, ESL_MSA **ret_filteredmsa, int *ret_nfrags);
136 static int separate_sets (struct cfg_s *cfg, ESL_MSA *msa, int **ret_i_am_train, int **ret_i_am_test);
137 static int find_sets_greedily (struct cfg_s *cfg, ESL_MSA *msa, int do_maxtest, int **ret_i_am_train, int **ret_i_am_test);
138 static int find_sets_by_sampling(struct cfg_s *cfg, ESL_MSA *msa, int nsamples, int do_maxtest, int **ret_i_am_train, int **ret_i_am_test);
139 static int synthesize_negatives_and_embed_positives(ESL_GETOPTS *go, struct cfg_s *cfg, ESL_SQ **posseqs, int npos);
140 static int set_random_segment (ESL_GETOPTS *go, struct cfg_s *cfg, FILE *logfp, ESL_DSQ *dsq, int L);
141 static void read_hmmfile(char *filename, ESL_HMM **ret_hmm);
142
143 static void
144 cmdline_failure(char *argv0, char *format, ...)
145 {
146 va_list argp;
147 va_start(argp, format);
148 vfprintf(stderr, format, argp);
149 va_end(argp);
150 esl_usage(stdout, argv0, usage1);
151 esl_usage(stdout, argv0, usage2);
152 esl_usage(stdout, argv0, usage3);
153 printf("\nTo see more help on available options, do %s -h\n\n", argv0);
154 exit(1);
155 }
156
157 static void
158 cmdline_help(char *argv0, ESL_GETOPTS *go)
159 {
160 esl_banner(stdout, argv0, banner);
161 esl_usage (stdout, argv0, usage1);
162 esl_usage (stdout, argv0, usage2);
163 puts("\n where general options are:");
164 esl_opt_DisplayHelp(stdout, go, 1, 2, 80);
165 puts("\n options controlling segment randomization method:");
166 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
167 puts("\n options declaring a particular alphabet:");
168 esl_opt_DisplayHelp(stdout, go, 3, 2, 80);
169 puts("\n other options:");
170 esl_opt_DisplayHelp(stdout, go, 4, 2, 80);
171 exit(0);
172 }
173
174
175 int
176 main(int argc, char **argv)
177 {
178 ESL_GETOPTS *go = NULL; /* command line configuration */
179 struct cfg_s cfg; /* application configuration */
180 char *basename= NULL; /* base of the output file names */
181 char *alifile = NULL; /* alignment file name */
182 char *dbfile = NULL; /* name of seq db file */
183 char *hmmfile = NULL;/* name of hmm file */
184 char outfile[256]; /* name of an output file */
185 int alifmt; /* format code for alifile */
186 int dbfmt; /* format code for dbfile */
187 ESL_MSAFILE *afp = NULL; /* open alignment file */
188 ESL_MSA *origmsa = NULL; /* one multiple sequence alignment */
189 ESL_MSA *msa = NULL; /* MSA after frags are removed */
190 ESL_MSA *trainmsa= NULL; /* training set, aligned */
191 char *tmpstr = NULL; /* #=RF annotation line */
192 ESL_SQ *train_consensus = NULL;
193 ESL_MSA *tmpmsa= NULL; /* tmp aligned training/testing set, used if --tfile */
194 int *i_am_train = NULL; /* [0..msa->nseq-1]: 1 if train seq, 0 if not */
195 int *i_am_test = NULL; /* [0..msa->nseq-1]: 1 if test seq, 0 if not */
196 int nfrags; /* # of fragments removed */
197 int ntestseq; /* # of test sequences for cur fam */
198 int ntrainseq; /* # of train sequences for cur fam */
199 int nali; /* number of alignments read */
200 int npos; /* number of positive test sequences stored */
201 int npos_this_msa; /* number of positive test sequences stored for current msa */
202 ESL_SQ **posseqs=NULL; /* all the test seqs, to be embedded */
203 int64_t poslen_total; /* total length of all positive seqs */
204 double avgid;
205 double pctid;
206 void *ptr;
207 int i, traini, testi;
208 int status; /* easel return code */
209
210 /* Parse command line */
211 go = esl_getopts_Create(options);
212 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) cmdline_failure(argv[0], "Failed to parse command line: %s\n", go->errbuf);
213 if (esl_opt_VerifyConfig(go) != eslOK) cmdline_failure(argv[0], "Error in app configuration: %s\n", go->errbuf);
214 if (esl_opt_GetBoolean(go, "-h")) cmdline_help(argv[0], go);
215
216 if (( esl_opt_GetBoolean(go, "--iid") && esl_opt_ArgNumber(go) != 2) ||
217 (! esl_opt_GetBoolean(go, "--iid") && esl_opt_ArgNumber(go) != 3)) {
218 cmdline_failure(argv[0], "Incorrect number of command line arguments\n");
219 }
220 basename = esl_opt_GetArg(go, 1);
221 alifile = esl_opt_GetArg(go, 2);
222 if(! esl_opt_GetBoolean(go, "--iid")) {
223 if(esl_opt_GetBoolean(go, "-S")) dbfile = esl_opt_GetArg(go, 3);
224 else hmmfile = esl_opt_GetArg(go, 3);
225 }
226 alifmt = eslMSAFILE_STOCKHOLM;
227 dbfmt = eslSQFILE_FASTA;
228
229 /* check for incompatible option combinations */
230 if((! esl_opt_IsOn(go, "--sub")) && (! esl_opt_IsOn(go, "--sample"))) {
231 if(esl_opt_IsOn(go, "--skip")) cmdline_failure(argv[0], "--skip requires --sub or --sample");
232 if(esl_opt_IsOn(go, "--xtest")) cmdline_failure(argv[0], "--xtest requires --sub or --sample");
233 }
234
235 /* Set up the configuration structure shared amongst functions here */
236 if (esl_opt_IsDefault(go, "--seed")) cfg.r = esl_randomness_CreateTimeseeded();
237 else cfg.r = esl_randomness_Create(esl_opt_GetInteger(go, "--seed"));
238 cfg.abc = NULL; /* until we open the MSA file, below */
239 cfg.hmm = NULL;
240 cfg.fragfrac = esl_opt_GetReal(go, "-F");
241 cfg.idthresh1 = esl_opt_GetReal(go, "-1");
242 cfg.idthresh2 = esl_opt_GetReal(go, "-2");
243 cfg.min_ntrain = esl_opt_GetInteger(go, "-R");
244 cfg.min_ntest = esl_opt_GetInteger(go, "-E");
245 cfg.nneg = esl_opt_GetInteger(go, "-N");
246 cfg.negL = esl_opt_GetInteger(go, "-L");
247 cfg.negchunkL = esl_opt_GetInteger(go, "-C");
248
249 /* Open the output files */
250 if (snprintf(outfile, 256, "%s.msa", basename) >= 256) esl_fatal("Failed to construct output MSA file name");
251 if ((cfg.out_msafp = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open MSA output file %s\n", outfile);
252 if (snprintf(outfile, 256, "%s.fa", basename) >= 256) esl_fatal("Failed to construct output FASTA file name");
253 if ((cfg.out_bmkfp = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open FASTA output file %s\n", outfile);
254 if (snprintf(outfile, 256, "%s.pfa", basename) >= 256) esl_fatal("Failed to construct output positive FASTA file name");
255 if ((cfg.out_posfp = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open positive FASTA output file %s\n", outfile);
256 if (snprintf(outfile, 256, "%s.pos", basename) >= 256) esl_fatal("Failed to construct pos test set summary file name");
257 if ((cfg.possummfp = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open pos test set summary file %s\n", outfile);
258 if (snprintf(outfile, 256, "%s.ppos", basename) >= 256) esl_fatal("Failed to construct pos-only test set summary file name");
259 if ((cfg.ppossummfp = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open pos-only test set summary file %s\n", outfile);
260 if (snprintf(outfile, 256, "%s.tbl", basename) >= 256) esl_fatal("Failed to construct benchmark table file name");
261 if ((cfg.tblfp = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open benchmark table file %s\n", outfile);
262 if (esl_opt_GetBoolean(go, "-S")) {
263 if (snprintf(outfile, 256, "%s.neg", basename) >= 256) esl_fatal("Failed to construct neg test set summary file name");
264 if ((cfg.negsummfp = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open neg test set summary file %s\n", outfile);
265 }
266 else cfg.negsummfp = NULL;
267 if (esl_opt_IsOn(go, "--nfile")) {
268 if((cfg.nseqfp = fopen(esl_opt_GetString(go, "--nfile"), "w")) == NULL) esl_fatal("Failed to open negative sequence file %s\n", esl_opt_GetString(go, "--nfile"));
269 }
270 else cfg.nseqfp = NULL;
271 if (esl_opt_IsOn(go, "--tfile")) {
272 if((cfg.tfp = fopen(esl_opt_GetString(go, "--tfile"), "w")) == NULL) esl_fatal("Failed to open alignment file %s\n", esl_opt_GetString(go, "--tfile"));
273 }
274 else cfg.tfp = NULL;
275
276 /* Open the MSA file */
277 if (esl_opt_GetBoolean(go, "--amino")) cfg.abc = esl_alphabet_Create(eslAMINO);
278 else if (esl_opt_GetBoolean(go, "--dna")) cfg.abc = esl_alphabet_Create(eslDNA);
279 else if (esl_opt_GetBoolean(go, "--rna")) cfg.abc = esl_alphabet_Create(eslRNA);
280 if((status = esl_msafile_Open(&(cfg.abc), alifile, NULL, alifmt, NULL, &afp)) != eslOK) {
281 esl_msafile_OpenFailure(afp, status);
282 }
283
284 if (cfg.abc->type == eslAMINO) esl_composition_SW34(cfg.fq);
285 else esl_vec_DSet(cfg.fq, cfg.abc->K, 1.0 / (double) cfg.abc->K);
286
287 /* Open and read the HMM file of database file, depending on if -S was enabled or not */
288 if(hmmfile != NULL) read_hmmfile(hmmfile, &(cfg.hmm));
289 if(dbfile != NULL) process_dbfile(&cfg, dbfile, dbfmt);
290
291 /* Read and process MSAs one at a time */
292 nali = 0;
293 npos = 0;
294 poslen_total = 0;
295 while ((status = esl_msafile_Read(afp, &origmsa)) == eslOK)
296 {
297 npos_this_msa = 0;
298 if(origmsa->name == NULL) esl_fatal("All msa's must have a valid name (#=GC ID), alignment %d does not.", nali);
299 esl_msa_ConvertDegen2X(origmsa);
300
301 remove_fragments(&cfg, origmsa, &msa, &nfrags);
302
303 /* Test 1: can we define train/test sets such that our thresholds
304 * are satisfied (most similar train/test pair < cfg->idthresh1,
305 * and most similar test/test pair < cfg->idthresh2) and
306 * _all_ the msa's sequences are either:
307 * - in the training set OR
308 * - in the test set OR
309 * - more than cfg->idthresh2 similar to >=1 sequences in the test set
310 */
311 if(! esl_opt_GetBoolean(go, "--skip")) {
312 separate_sets (&cfg, msa, &i_am_train, &i_am_test);
313 ntrainseq = esl_vec_ISum(i_am_train, msa->nseq);
314 ntestseq = esl_vec_ISum(i_am_test, msa->nseq);
315 }
316 else { /* --skip enabled, we skipped test 1 */
317 ntestseq = ntrainseq = 0;
318 }
319
320 /* if --sub or --sample, check if we should look for subsets of
321 * the seqs in the msa that satisfy our thresholds */
322 if((esl_opt_IsOn(go, "--sub") || esl_opt_IsOn(go, "--sample")) &&
323 ((ntestseq < cfg.min_ntest) || (ntrainseq < cfg.min_ntrain)))
324 { /* Test 2: Is there a subset of the sequences in the msa
325 * that would satisfy our thresholds (most similar
326 * train/test pair < cfg->idthresh1, and most
327 * similar test/test pair < cfg->idthresh2) and that
328 * include a sufficient number of train/test seqs.
329 *
330 * We either use a greedy deterministic algorithm (by
331 * default) to look for these subsets, or we use a sampling
332 * algorithm (non-deterministic, enabled with --sample).
333 */
334 if(esl_opt_IsOn(go, "--sub")) find_sets_greedily (&cfg, msa, esl_opt_GetBoolean(go, "--xtest"), &i_am_train, &i_am_test);
335 else find_sets_by_sampling(&cfg, msa, esl_opt_GetInteger(go, "--sample"), esl_opt_GetBoolean(go, "--xtest"), &i_am_train, &i_am_test);
336 ntrainseq = esl_vec_ISum(i_am_train, msa->nseq);
337 ntestseq = esl_vec_ISum(i_am_test, msa->nseq);
338 /* we did find a satisfactory set (find_sets() checks that
339 * we have a sufficient number of test/train seqs, but
340 * check, to be sure */
341 if ((ntestseq < cfg.min_ntest) || (ntrainseq < cfg.min_ntrain))
342 esl_fatal("find_sets() returned insufficient train/test sets!");
343 }
344
345 if ((ntestseq >= cfg.min_ntest) && (ntrainseq >= cfg.min_ntrain)) {
346 /* We have a valid train/test set, that either satisfied
347 * test 1 in separate_sets() or satisfied test 2 from
348 * find_sets(). Extract and write out the training alignment. */
349 if ((status = esl_msa_SequenceSubset(msa, i_am_train, &trainmsa)) != eslOK) goto ERROR;
350 esl_msa_MinimGaps(trainmsa, NULL, NULL, FALSE);
351 esl_msafile_Write(cfg.out_msafp, trainmsa, eslMSAFILE_STOCKHOLM);
352
353 esl_dst_XAverageId(cfg.abc, trainmsa->ax, trainmsa->nseq, 10000, &avgid); /* 10000 is max_comparisons, before sampling kicks in */
354 fprintf(cfg.tblfp, "%-20s %3.0f%% %6d %6d %6d %6d %6d\n", msa->name, 100.*avgid, (int) trainmsa->alen, msa->nseq, nfrags, trainmsa->nseq, ntestseq);
355 nali++;
356
357 if(cfg.tfp != NULL) {
358 /* output 2 more alignments per family:
359 * 1. training alignment with seqs renamed as "TRAIN.<fam>.<i>"
360 * 2. test alignment with seqs renamed as "<fam>/<i>"
361 */
362 /* Rename seqs */
363 for(i = 0, traini = 0, testi = 0; i < msa->nseq; i++) {
364 if(i_am_train[i]) {
365 esl_msa_FormatSeqDescription(msa, i, msa->sqname[i]);
366 esl_msa_FormatSeqName(msa, i, "TRAIN.%s.%d", msa->name, traini+1);
367 traini++;
368 }
369 if(i_am_test[i]) {
370 esl_msa_FormatSeqDescription(msa, i, msa->sqname[i]);
371 esl_msa_FormatSeqName(msa, i, "%s/%d", msa->name, testi+1);
372 testi++;
373 }
374 }
375 /* Output train subset, note we don't use trainmsa, b/c it's has all gap columns removed */
376 if ((status = esl_msa_SequenceSubset(msa, i_am_train, &tmpmsa)) != eslOK) goto ERROR;
377 esl_msa_FormatName(tmpmsa, "TRAIN.%s", msa->name);
378 esl_msafile_Write(cfg.tfp, tmpmsa, eslMSAFILE_PFAM);
379
380
381 /* capture the consensus of the msa into train_consensus, for use in calculating pct_id later */
382 status = esl_msaweight_PB(tmpmsa);
383 ESL_REALLOC(tmpstr, msa->alen + 1 );
384 esl_msa_ReasonableRF(tmpmsa, 0.5, TRUE, tmpstr);
385 train_consensus = esl_sq_CreateFrom(msa->name, tmpstr, msa->name, msa->name, NULL);
386 esl_sq_Digitize(msa->abc, train_consensus);
387
388 /* Output test subset */
389 if ((status = esl_msa_SequenceSubset(msa, i_am_test, &tmpmsa)) != eslOK) goto ERROR;
390 esl_msa_FormatName(tmpmsa, "TEST.%s", msa->name);
391 esl_msafile_Write(cfg.tfp, tmpmsa, eslMSAFILE_PFAM);
392 esl_msa_Destroy(tmpmsa);
393 }
394
395
396 /* Save the positive test sequences, we'll embed these
397 * in the long test sequences later */
398 if(npos > 0) { ESL_RALLOC(posseqs, ptr, sizeof(ESL_SQ *) * (npos + ntestseq)); }
399 else { ESL_ALLOC (posseqs, sizeof(ESL_SQ *) * ntestseq); }
400 for(i = 0; i < msa->nseq; i++) {
401 if(i_am_test[i]) {
402 esl_sq_FetchFromMSA(msa, i, &(posseqs[npos]));
403 poslen_total += posseqs[npos]->n;
404 /* Sequence description is set as a concatenation of the
405 * family name and the sequence index in this family,
406 * separated by a '/', which never appears in an Rfam
407 * name. For example: "tRNA/3" for the third tRNA.
408 */
409 esl_sq_FormatDesc(posseqs[npos], "%s/%d", msa->name, npos_this_msa+1);
410 /* Write the sequence to the positives-only output file, and its info the positives-only table */
411 esl_sqio_Write(cfg.out_posfp, posseqs[npos], eslSQFILE_FASTA, FALSE);
412
413 if(cfg.tfp != NULL) {
414
415 esl_dst_XPairId(msa->abc, train_consensus->dsq, msa->ax[i], &pctid, NULL, NULL);
416
417 fprintf(cfg.ppossummfp, "%-35s %-35s %-35s %8d %8" PRId64 " %.0f\n",
418 posseqs[npos]->desc, /* description, this has been set earlier as the msa name plus seq idx (e.g. "tRNA/3" for 3rd tRNA in the set) */
419 posseqs[npos]->name, /* positive sequence name (from input MSA) */
420 posseqs[npos]->name, /* again, positive sequence name (from input MSA) */
421 1, posseqs[npos]->n, /* start, stop */
422 100*pctid);
423 } else {
424 fprintf(cfg.ppossummfp, "%-35s %-35s %-35s %8d %8" PRId64 "\n",
425 posseqs[npos]->desc, /* description, this has been set earlier as the msa name plus seq idx (e.g. "tRNA/3" for 3rd tRNA in the set) */
426 posseqs[npos]->name, /* positive sequence name (from input MSA) */
427 posseqs[npos]->name, /* again, positive sequence name (from input MSA) */
428 1, posseqs[npos]->n); /* start, stop */
429 }
430 npos++;
431 npos_this_msa++;
432 }
433 }
434 }
435 if(i_am_train != NULL) free(i_am_train);
436 if(i_am_test != NULL) free(i_am_test);
437 if(trainmsa != NULL) esl_msa_Destroy(trainmsa);
438 trainmsa = NULL;
439 esl_msa_Destroy(origmsa);
440 esl_msa_Destroy(msa);
441 }
442
443 if (status != eslEOF) esl_msafile_ReadFailure(afp, status);
444 else if (nali == 0) esl_fatal("No alignments found in file %s\n", alifile);
445
446 /* Make sure we summed length of the positives isn't above the max allowed */
447 if(poslen_total > (esl_opt_GetReal(go, "-X") * cfg.nneg * cfg.negL)) {
448 esl_fatal("positive seqs summed length is %.4f fraction of the test sequences, max allowed is %.4f (adjust with -X)\n",
449 ((float) poslen_total / (float) (cfg.nneg * cfg.negL)), esl_opt_GetReal(go, "-X"));
450 }
451
452 /* Generate the negative sequences and embed the positives to create the benchmark sequences */
453 if (nali > 0)
454 if((status = synthesize_negatives_and_embed_positives(go, &cfg, posseqs, npos)) != eslOK) esl_fatal("Allocation error. Out of memory.");
455
456 fclose(cfg.out_msafp);
457 fclose(cfg.out_bmkfp);
458 fclose(cfg.out_posfp);
459 fclose(cfg.possummfp);
460 fclose(cfg.ppossummfp);
461 if(cfg.negsummfp != NULL) fclose(cfg.negsummfp);
462 if(cfg.nseqfp != NULL) fclose(cfg.nseqfp);
463 if(cfg.tfp != NULL) fclose(cfg.tfp);
464 fclose(cfg.tblfp);
465 esl_randomness_Destroy(cfg.r);
466 esl_alphabet_Destroy(cfg.abc);
467 esl_msafile_Close(afp);
468 esl_getopts_Destroy(go);
469 return 0;
470
471 ERROR:
472 esl_fatal("Allocation error. Out of memory");
473 }
474
475
476 /* Open the source sequence database for negative subseqs;
477 * upon return, cfg->dbfp is open (digital, SSI indexed);
478 * and cfg->db_nseq is set.
479 */
480 static int
481 process_dbfile(struct cfg_s *cfg, char *dbfile, int dbfmt)
482 {
483 ESL_SQ *sq = esl_sq_CreateDigital(cfg->abc);
484 int status;
485 int nread; /* number of sequences of at least length cfg->negchunkL read from db */
486 int nrequired; /* number of sequences of at least length cfg->negchunkL required in db */
487
488 /* Open the sequence file in digital mode */
489 status = esl_sqfile_OpenDigital(cfg->abc, dbfile, dbfmt, NULL, &(cfg->dbfp));
490 if (status == eslENOTFOUND) esl_fatal("No such file %s", dbfile);
491 else if (status == eslEFORMAT) esl_fatal("Format of seqfile %s unrecognized.", dbfile);
492 else if (status == eslEINVAL) esl_fatal("Can't autodetect stdin or .gz.");
493 else if (status != eslOK) esl_fatal("Open failed, code %d.", status);
494
495 /* Read sequence file until we know it contains enough sequences to
496 * sample from to create the benchmark sequences if we sampled
497 * without replacement (even though we sample with replacement, so
498 * just 1 seq of length cfg->negchunkL would suffice).
499 * We don't read the whole sequence file b/c it could be very
500 * large (rfamseq is >100 Gb) and that would take a long time.
501 */
502 nread = 0;
503 nrequired = ((cfg->negL / cfg->negchunkL) + 1) * cfg->nneg;
504
505 while ((nread < nrequired) &&
506 ((status = esl_sqio_ReadInfo(cfg->dbfp, sq)) == eslOK)) {
507 if(sq->L > cfg->negchunkL) nread++;
508 esl_sq_Reuse(sq);
509 }
510 if (nread < nrequired) { /* there weren't enough seqs of sufficient length */
511 if(status == eslEOF) esl_fatal("Only read %d seqs of length %d in seq db, %d required", nread, cfg->negchunkL, nrequired);
512 else esl_fatal("Something went wrong with reading the seq db");
513 }
514 esl_sqfile_Position(cfg->dbfp, 0); /* rewind */
515
516 /* Open SSI index */
517 if (esl_sqfile_OpenSSI(cfg->dbfp, NULL) != eslOK) esl_fatal("Failed to open SSI index file");
518 /* set number of seqs in db; trust the index */
519 cfg->db_nseq = cfg->dbfp->data.ascii.ssi->nprimary;
520
521 esl_sq_Destroy(sq);
522 return eslOK;
523 }
524
525
526 /* Label all sequence fragments < fragfrac of average raw length */
527 static int
528 remove_fragments(struct cfg_s *cfg, ESL_MSA *msa, ESL_MSA **ret_filteredmsa, int *ret_nfrags)
529 {
530 int *useme = NULL;
531 double len = 0.0;
532 int i;
533 int status;
534
535 /* min length is cfg->fragfrac * average length */
536 for (i = 0; i < msa->nseq; i++)
537 len += esl_abc_dsqrlen(msa->abc, msa->ax[i]);
538 len *= cfg->fragfrac / (double) msa->nseq;
539
540 ESL_ALLOC(useme, sizeof(int) * msa->nseq);
541 for (i = 0; i < msa->nseq; i++)
542 useme[i] = (esl_abc_dsqrlen(msa->abc, msa->ax[i]) < len) ? 0 : 1;
543
544 if ((status = esl_msa_SequenceSubset(msa, useme, ret_filteredmsa)) != eslOK) goto ERROR;
545 *ret_nfrags = msa->nseq - esl_vec_ISum(useme, msa->nseq);
546
547 free(useme);
548 return eslOK;
549
550 ERROR:
551 if (useme != NULL) free(useme);
552 *ret_filteredmsa = NULL;
553 return status;
554 }
555
556 /* Test 1. Determine if valid training and test sets exist in the MSA
557 * by testing if all the following criteria are met:
558 * 1. no train/test sequence pair is > cfg->idthresh1 fractionally
559 * identical (controllable with -1).
560 * 2. no test sequence pair is > cfg->idthresh2 fractionally
561 * identical (controllable with -2).
562 * 3. all other msa sequences not in train nor test are
563 * at least cfg->idthresh2 fractionally identical
564 * with >= 1 test sequence.
565 *
566 * ret_i_am_train - [0..msa->nseq-1]: 1 if a training seq, 0 if not
567 * ret_i_am_test - [0..msa->nseq-1]: 1 if a test seq, 0 if not
568 */
569 static int
570 separate_sets(struct cfg_s *cfg, ESL_MSA *msa, int **ret_i_am_train, int **ret_i_am_test)
571 {
572 ESL_MSA *trainmsa = NULL;
573 ESL_MSA *test_msa = NULL;
574 int *assignment = NULL;
575 int *nin = NULL;
576 int *i_am_train = NULL;
577 int *i_am_test = NULL;
578 int *i_am_possibly_test = NULL;
579 int nc = 0;
580 int c;
581 int ctrain; /* index of the cluster that becomes the training alignment */
582 int nskip;
583 int i, i2;
584 int status;
585
586 ESL_ALLOC(i_am_train, sizeof(int) * msa->nseq);
587 ESL_ALLOC(i_am_possibly_test, sizeof(int) * msa->nseq);
588 ESL_ALLOC(i_am_test, sizeof(int) * msa->nseq);
589
590 if ((status = esl_msacluster_SingleLinkage(msa, cfg->idthresh1, &assignment, &nin, &nc)) != eslOK) goto ERROR;
591 ctrain = esl_vec_IArgMax(nin, nc);
592
593 for (i = 0; i < msa->nseq; i++) i_am_train[i] = (assignment[i] == ctrain) ? 1 : 0;
594 if ((status = esl_msa_SequenceSubset(msa, i_am_train, &trainmsa)) != eslOK) goto ERROR;
595
596 /* If all the seqs went into the training msa, none are left for testing; we're done here */
597 if (trainmsa->nseq == msa->nseq) {
598 esl_vec_ISet(i_am_train, msa->nseq, 0);
599 esl_vec_ISet(i_am_test, msa->nseq, 0);
600 free(assignment);
601 free(nin);
602 free(i_am_possibly_test);
603 esl_msa_Destroy(trainmsa);
604 *ret_i_am_train = i_am_train;
605 *ret_i_am_test = i_am_test;
606 return eslOK;
607 }
608
609 /* Put all the other sequences into an MSA of their own; from these, we'll
610 * choose test sequences.
611 */
612 for (i = 0; i < msa->nseq; i++) i_am_possibly_test[i] = (assignment[i] != ctrain) ? 1 : 0;
613 if ((status = esl_msa_SequenceSubset(msa, i_am_possibly_test, &test_msa)) != eslOK) goto ERROR;
614
615 /* Cluster those test sequences. */
616 free(nin); nin = NULL;
617 free(assignment); assignment = NULL;
618 esl_vec_ISet(i_am_test, msa->nseq, 0);
619 if ((status = esl_msacluster_SingleLinkage(test_msa, cfg->idthresh2, &assignment, &nin, &nc)) != eslOK) goto ERROR;
620 for (c = 0; c < nc; c++) {
621 nskip = esl_rnd_Roll(cfg->r, nin[c]); /* pick a random seq in this cluster to be the test. */
622 for (i=0, i2=0; i < msa->nseq; i++) /* i is idx in orig msa, i2 is idx in test_msa */
623 if(i_am_possibly_test[i]) { /* i is in test_msa */
624 if (assignment[i2] == c) {
625 if (nskip == 0) { /* this sequence will be a test seq, set i_am_test[i] as 1 */
626 i_am_test[i] = 1;
627 break;
628 }
629 else {
630 nskip--;
631 }
632 }
633 i2++;
634 }
635 }
636
637 esl_msa_Destroy(test_msa);
638 free(nin);
639 free(assignment);
640 free(i_am_possibly_test);
641
642 *ret_i_am_train = i_am_train;
643 *ret_i_am_test = i_am_test;
644
645 return eslOK;
646
647 ERROR:
648 if (i_am_train != NULL) free(i_am_train);
649 if (i_am_test != NULL) free(i_am_test);
650 if (i_am_possibly_test != NULL) free(i_am_possibly_test);
651 if (assignment != NULL) free(assignment);
652 if (nin != NULL) free(nin);
653 esl_msa_Destroy(trainmsa);
654 esl_msa_Destroy(test_msa);
655 *ret_i_am_train = NULL;
656 *ret_i_am_test = NULL;
657 return status;
658 }
659
660 /* Test 2. Greedy approach:
661 * Use a greedy, deterministic algorithm to see if we
662 * can define a subset of msa sequences (call it sub_msa)
663 * that comprise valid train/test sets of sufficient sizes
664 * that satisfy:
665 *
666 * 1. no train/test sequence pair is > cfg->idthresh1
667 * fractionally identical (controllable with -1).
668 * 2. no test sequence pair is > cfg->idthresh2
669 * fractionally identical (controllable with -2).
670 *
671 * The algorithm for checking is greedy and not guaranteed to find a
672 * submsa if it exists. Likewise, it is not guaranteed to find the
673 * largest such submsa.
674 *
675 * Briefly, the algorithm takes each msa sequence i, creates the
676 * training set that is compatible with i being a test sequence, and
677 * then adds all remaining (non-training) sequences j that are
678 * compatible with i (id[i][j] < cfg->idthresh2) to the test set. The
679 * set of sequences in the testing and training set define the submsa.
680 * By default, the submsa that satisfies 1 and 2 and includes the
681 * largest total number of sequences (|train| + |test|) is chosen and
682 * the corresponding training and testing sets are returned. With
683 * --xtest, the submsa with the largest number of test sequences is
684 * chosen instead.
685 */
686 static int
687 find_sets_greedily(struct cfg_s *cfg, ESL_MSA *msa, int do_xtest, int **ret_i_am_train, int **ret_i_am_test)
688 {
689 int *i_am_test = NULL;
690 int *i_am_train = NULL;
691 int *i_am_best_test = NULL;
692 int *i_am_best_train = NULL;
693 ESL_DMATRIX *S = NULL; /* pairwise identity matrix */
694 int i, j, k;
695 int ntest, ntrain;
696 int nbest_test, nbest_train;
697 int status;
698 int add_j_to_test;
699
700 ESL_ALLOC(i_am_test, sizeof(int) * msa->nseq);
701 ESL_ALLOC(i_am_train, sizeof(int) * msa->nseq);
702 ESL_ALLOC(i_am_best_test, sizeof(int) * msa->nseq);
703 ESL_ALLOC(i_am_best_train, sizeof(int) * msa->nseq);
704
705 /* initialize best_train and best_test sets */
706 esl_vec_ISet(i_am_best_train, msa->nseq, FALSE);
707 esl_vec_ISet(i_am_best_test, msa->nseq, FALSE);
708 nbest_train = 0;
709 nbest_test = 0;
710
711 /* get pairwise ID matrix */
712 if ((status = esl_dst_XPairIdMx(msa->abc, msa->ax, msa->nseq, &S)) != eslOK) goto ERROR;
713
714 for(i = 0; i < msa->nseq; i++) {
715 /* initialize train and test sets for this seq */
716 esl_vec_ISet(i_am_train, msa->nseq, FALSE);
717 esl_vec_ISet(i_am_test, msa->nseq, FALSE);
718 i_am_test[i] = TRUE; /* i is in the test set */
719 ntrain = 0;
720 ntest = 1;
721
722 /* Determine all seqs that are < cfg->idthresh1 identical to i,
723 * this will be the largest possible training set that is consistent
724 * with i being in the test set.
725 */
726 for(j = 0; j < msa->nseq; j++) {
727 if(S->mx[i][j] < cfg->idthresh1) {
728 i_am_train[j] = TRUE;
729 ntrain++;
730 }
731 }
732
733 /* If the training set is big enough, try to add all seqs not in
734 * the training set to the test set while maintaining the property
735 * that all seqs in the test set must be less than cfg->idthresh1
736 * similar to all seqs in the training set and must be at most
737 * cfg->idthresh2 similar to all seqs in the test set. */
738 if(ntrain >= cfg->min_ntrain) {
739 for(j = 0; j < msa->nseq; j++) {
740 if(i_am_train[j] == FALSE && i_am_test[j] == FALSE) {
741 add_j_to_test = TRUE;
742 for(k = 0; k < msa->nseq; k++) {
743 if(((i_am_train[k] == TRUE) && (S->mx[j][k] >= cfg->idthresh1)) || /* too similar to a training seq */
744 ((i_am_test[k] == TRUE) && (S->mx[j][k] >= cfg->idthresh2))) { /* too similar to a test seq */
745 add_j_to_test = FALSE;
746 break;
747 }
748 }
749 if(add_j_to_test == TRUE) {
750 i_am_test[j] = TRUE;
751 ntest++;
752 }
753 }
754 }
755
756 /* printf("i: %5d ntrain: %5d ntest: %5d nbest_train: %5d nbest_test: %5d\n",
757 i, ntrain, ntest, nbest_train, nbest_test); */
758
759 /* If training set is larger than test set, and we have at least
760 * the minimum allowed number of test seqs, then check if this
761 * is our best set of train and test clusters thus far found, if
762 * so, update best_test and best_train. Where the 'best' is
763 * defined as either:
764 * maximum of |train| + |test| (default)
765 * OR maximum of |test| (enabled with --xtest)
766 */
767 if((ntrain > ntest) && (ntest >= cfg->min_ntest)) { /* training and test set are sufficiently large */
768 if((( do_xtest) && (ntest > nbest_test)) ||
769 ((! do_xtest) && ((ntrain+ntest) > (nbest_train+nbest_test)))) {
770 esl_vec_ICopy(i_am_train, msa->nseq, i_am_best_train);
771 esl_vec_ICopy(i_am_test, msa->nseq, i_am_best_test);
772 nbest_train = ntrain;
773 nbest_test = ntest;
774 }
775 }
776 }
777 } /* end of for(i = 0; i < msa->nseq; i++) */
778
779 if(nbest_train == 0 || nbest_test == 0) {
780 esl_vec_ISet(i_am_best_train, msa->nseq, 0);
781 esl_vec_ISet(i_am_best_test, msa->nseq, 0);
782 }
783 else {
784 ;/* printf("Success! train: %d seqs test: %d seqs\n", nbest_train, nbest_test); */
785 }
786 *ret_i_am_train = i_am_best_train;
787 *ret_i_am_test = i_am_best_test;
788
789 free(i_am_train);
790 free(i_am_test);
791 esl_dmatrix_Destroy(S);
792 return eslOK;
793
794 ERROR:
795 if (i_am_train != NULL) free(i_am_train);
796 if (i_am_test != NULL) free(i_am_test);
797 if (i_am_best_train != NULL) free(i_am_best_train);
798 if (i_am_best_test != NULL) free(i_am_best_test);
799 esl_dmatrix_Destroy(S);
800 *ret_i_am_train = NULL;
801 *ret_i_am_test = NULL;
802 return status;
803 }
804
805
806 /* Test 2. Sampling approach:
807 * Sample sequences in a random order, adding them to growing
808 * test/train sets to see if we can define valid train/test
809 * sets of sufficient sizes that satisfy:
810 *
811 * 1. no train/test sequence pair is > cfg->idthresh1
812 * fractionally identical (controllable with -1).
813 * 2. no test sequence pair is > cfg->idthresh2
814 * fractionally identical (controllable with -2).
815 *
816 * The algorithm for is not guaranteed to find a submsa if it
817 * exists. Likewise, it is not guaranteed to find the largest such
818 * submsa.
819 *
820 * Briefly, the approach is, for each sample, to randomly select a
821 * sequence i and define it as the first test sequence. Then look at
822 * all other sequences in random order. For each, if it is less than
823 * cfg->idthresh1 fractionally identical to all existing test
824 * sequences, add it to the training set. Else if it is less than
825 * cfg->idthresh1 fractionally identical to all existing training
826 * sequences, then add it to the test set. When finished, remove
827 * redundancy from the test set such that no two test sequences
828 * are more than cfg->idthresh2 fractionally identical.
829 *
830 * By default, the train/test set resulting from any sample that
831 * satisfies 1 and 2 and includes the largest total number of
832 * sequences (|train| + |test|) is chosen and the corresponding
833 * training and testing sets are returned. With --xtest, the
834 * train/test set with the largest number of test sequences is chosen
835 * instead.
836 */
837 static int
838 find_sets_by_sampling(struct cfg_s *cfg, ESL_MSA *msa, int nsamples, int do_maxtest, int **ret_i_am_train, int **ret_i_am_test)
839 {
840 ESL_MSA *test_msa = NULL;
841 int *i_am_test = NULL;
842 int *i_am_train = NULL;
843 int *i_am_best_test = NULL;
844 int *i_am_best_train = NULL;
845 int *curlist = NULL;
846 int *test_msa2msa = NULL;
847 int *assignment = NULL;
848 int *nin = NULL;
849 int n, i, j, k;
850 int ntest, ntrain;
851 int nbest_test, nbest_train;
852 int status;
853 int tmp;
854 int ctr;
855 int nc = 0;
856 int c, p;
857 int nskip;
858 float maxid_train;
859 float maxid_test;
860
861 ESL_DMATRIX *S; /* pairwise identity matrix */
862
863 ESL_ALLOC(i_am_test, sizeof(int) * msa->nseq);
864 ESL_ALLOC(i_am_train, sizeof(int) * msa->nseq);
865 ESL_ALLOC(i_am_best_test, sizeof(int) * msa->nseq);
866 ESL_ALLOC(i_am_best_train, sizeof(int) * msa->nseq);
867 ESL_ALLOC(curlist, sizeof(int) * msa->nseq);
868
869 /* initialize best_train and best_test sets */
870 esl_vec_ISet(i_am_best_train, msa->nseq, FALSE);
871 esl_vec_ISet(i_am_best_test, msa->nseq, FALSE);
872 nbest_train = 0;
873 nbest_test = 0;
874
875 /* get pairwise ID matrix */
876 if ((status = esl_dst_XPairIdMx(msa->abc, msa->ax, msa->nseq, &S)) != eslOK) goto ERROR;
877
878 for(n = 0; n < nsamples; n++) {
879 i = esl_rnd_Roll(cfg->r, msa->nseq); /* pick a random seq to seed the test set */
880 /* initialize train and test sets for this seq */
881 esl_vec_ISet(i_am_train, msa->nseq, FALSE);
882 esl_vec_ISet(i_am_test, msa->nseq, FALSE);
883 i_am_test[i] = TRUE; /* i is in the test set */
884 ntrain = 0;
885 ntest = 1;
886 for(k = 0; k < msa->nseq; k++) curlist[k] = k;
887
888 for(ctr = 0; ctr < msa->nseq; ctr++) {
889 /* choose next seq to evaluate */
890 p = esl_rnd_Roll(cfg->r, msa->nseq - ctr);
891 j = curlist[p];
892
893 /* update curlist, this ensures we never sample the same j twice */
894 for(k = p; k < (msa->nseq-1); k++) curlist[k] = curlist[k+1];
895 curlist[msa->nseq-1] = -1;
896
897 /* find the fractional identity of j's nearest neighbors in the current
898 * test set and training set */
899 if(j != i) { /* skip when j == i, it's already in the test set */
900 if(i_am_test[j] || i_am_train[j]) esl_fatal("double picked %d on sample %d\n", j, n);
901 maxid_train = maxid_test = 0.;
902 for(k = 0; k < msa->nseq; k++) {
903 if((i_am_train[k] == TRUE) && (S->mx[j][k] > maxid_train)) { maxid_train = S->mx[j][k]; }
904 if((i_am_test[k] == TRUE) && (S->mx[j][k] > maxid_test)) { maxid_test = S->mx[j][k]; }
905 }
906 if (maxid_test < cfg->idthresh1) { i_am_train[j] = TRUE; ntrain++; } /* add j to training set */
907 else if(maxid_train < cfg->idthresh1) { i_am_test[j] = TRUE; ntest++; } /* add j to testing set */
908 }
909 }
910
911 /* if ntest > ntrain, swap the sets */
912 if(ntest > ntrain) {
913 for(j = 0; j < msa->nseq; j++) {
914 tmp = i_am_train[j];
915 i_am_train[j] = i_am_test[j];
916 i_am_test[j] = tmp;
917 }
918 tmp = ntest;
919 ntest = ntrain;
920 ntrain = tmp;
921 }
922
923 /* sanity check */
924 for(k = 0; k < msa->nseq; k++) { if(i_am_test[k] && i_am_train[k]) esl_fatal("ERROR %d is both train and test\n", k); }
925
926 /* if we have sufficient numbers of training and testing, remove
927 * redundancy from the test set, optimally (randomly select one
928 * representative from each cluster following SLC) */
929 if(ntrain >= cfg->min_ntrain && ntest >= cfg->min_ntest) {
930 if ((status = esl_msa_SequenceSubset(msa, i_am_test, &test_msa)) != eslOK) goto ERROR;
931
932 /* reset i_am_test[], we'll refill it with single seq from each cluster */
933 ESL_ALLOC(test_msa2msa, sizeof(int) * ntest);
934 esl_vec_ISet(test_msa2msa, ntest, FALSE);
935 ctr = 0;
936 for(k = 0; k < msa->nseq; k++) { if(i_am_test[k]) test_msa2msa[ctr++] = k; }
937 esl_vec_ISet(i_am_test, msa->nseq, FALSE);
938 ntest = 0;
939
940 /* Cluster the test sequences. */
941 if(nin != NULL) { free(nin); nin = NULL; }
942 if(assignment != NULL) { free(assignment); assignment = NULL; }
943 if ((status = esl_msacluster_SingleLinkage(test_msa, cfg->idthresh2, &assignment, &nin, &nc)) != eslOK) goto ERROR;
944 for (c = 0; c < nc; c++) {
945 nskip = esl_rnd_Roll(cfg->r, nin[c]); /* pick a random seq in this cluster to be the test. */
946 for (k=0; k < test_msa->nseq; k++)
947 if (assignment[k] == c) {
948 if (nskip == 0) {
949 i_am_test[test_msa2msa[k]] = TRUE;
950 ntest++;
951 break;
952 } else nskip--;
953 }
954 }
955 esl_msa_Destroy(test_msa);
956 free(test_msa2msa);
957
958 if(ntest >= cfg->min_ntest) {
959 /* printf("n: %5d ntrain: %5d ntest: %5d nbest_train: %5d nbest_test: %5d\n",
960 n, ntrain, ntest, nbest_train, nbest_test); */
961
962 /* We have sufficiently large train and test sets. Check if
963 * this i our best set of train and test clusters thus far
964 * found, if so, update best_test and best_train. Where the
965 * 'best' is defined as either:
966 * maximum of |train| + |test| (default)
967 * OR maximum of |test| (enabled with --maxtest)
968 */
969
970 if(( do_maxtest && (ntest > nbest_test)) ||
971 (! do_maxtest && ((ntrain+ntest) > (nbest_train+nbest_test)))) {
972 esl_vec_ICopy(i_am_train, msa->nseq, i_am_best_train);
973 esl_vec_ICopy(i_am_test, msa->nseq, i_am_best_test);
974 nbest_train = ntrain;
975 nbest_test = ntest;
976 }
977 }
978 }
979 } /* end of for(n = 0; n < msa->nseq; n++) */
980
981 if(nbest_train == 0 || nbest_test == 0) {
982 esl_vec_ISet(i_am_best_train, msa->nseq, 0);
983 esl_vec_ISet(i_am_best_test, msa->nseq, 0);
984 }
985 else {
986 ;/* printf("Success! train: %d seqs test: %d seqs\n", nbest_train, nbest_test); */
987 }
988 *ret_i_am_train = i_am_best_train;
989 *ret_i_am_test = i_am_best_test;
990
991 free(i_am_train);
992 free(i_am_test);
993 esl_dmatrix_Destroy(S);
994 return eslOK;
995
996 ERROR:
997 if (i_am_train != NULL) free(i_am_train);
998 if (i_am_test != NULL) free(i_am_test);
999 if (i_am_best_train != NULL) free(i_am_best_train);
1000 if (i_am_best_test != NULL) free(i_am_best_test);
1001 *ret_i_am_train = NULL;
1002 *ret_i_am_test = NULL;
1003 return status;
1004 }
1005
1006 /* sythesize_negatives_and_embed_positives()
1007 *
1008 * 1. Randomly pick which negative sequence each positive sequence will
1009 * be embedded in, and the location/orientation it will be embedded.
1010 * 2. Generate each negative sequence from the input database with the
1011 * desired shuffling procedure and use it to create a benchmark sequence.
1012 * Each benchmark sequence includes a complete negative sequence as well
1013 * as all the positives to be embedded within that negative, 'inserted'
1014 * in the appropriate positions. These benchmark sequences will be
1015 * searched during the benchmark.
1016 */
1017
1018 static int
1019 synthesize_negatives_and_embed_positives(ESL_GETOPTS *go, struct cfg_s *cfg, ESL_SQ **posseqs, int npos)
1020 {
1021 int status;
1022 ESL_SQ *negsq = NULL; /* a negative sequence */
1023 ESL_SQ *bmksq = NULL; /* an output sequence, negative sequence with embedded positive sequence(s) */
1024 int i; /* index of negative sequence */
1025 int j; /* index of positive sequence to embed in negative sequence */
1026 int64_t p; /* a position in a sequence */
1027 int64_t neg_p; /* a position in a negative sequence */
1028 int64_t bmk_p; /* a position in an output sequence */
1029 int chunkL; /* length of a sequence chunk to extract from the db while constructing negatives */
1030 int q; /* an index for one of the embedded seqs in a output sequence */
1031 void *ptr; /* for reallocating */
1032 int alloc_chunk = 2; /* number of elements to add when reallocating */
1033 int keep_rolling; /* for continuing to randomly choose numbers */
1034 ESL_DSQ *tmpdsq; /* temporary dsq, generated by the HMM */
1035
1036 /* per-positive sequence variables, all are [0..j..npos-1] */
1037 int *posseqs_i = NULL; /* negative sequence idx (i) j is embedded within */
1038 int *posseqs_p = NULL; /* sequence position idx (p) j occurs at within the negative sequence it is embedded within */
1039 int *posseqs_o = NULL; /* orientation for sequence j within the negative sequence it is embedded within (0 or 1) */
1040
1041 /* per-negative sequence variables */
1042 int *negseqs_n = NULL; /* [0..i..cfg->nneg-1] number of positive sequences to be embedded in negative sequence i */
1043 int *negseqs_poslen = NULL; /* [0..i..cfg->nneg-1] summed length of positive sequences to be embedded in negative sequence i */
1044 int **negseqs_p = NULL; /* [0..i..cfg->nneg-1][0..q..negseqs_n[i]] sequence position index (p) at which a sequence will be embedded */
1045 int *cur_alloc = NULL; /* [0..i..cfg->nneg-1] current number of elements allocated for negseqs_p[i] */
1046
1047 ESL_ALLOC(posseqs_i, sizeof(int) * npos);
1048 ESL_ALLOC(posseqs_p, sizeof(int) * npos);
1049 ESL_ALLOC(posseqs_o, sizeof(int) * npos);
1050 ESL_ALLOC(negseqs_n, sizeof(int) * cfg->nneg);
1051 ESL_ALLOC(negseqs_poslen, sizeof(int) * cfg->nneg);
1052 ESL_ALLOC(negseqs_p, sizeof(int *) * cfg->nneg);
1053 ESL_ALLOC(cur_alloc, sizeof(int) * cfg->nneg);
1054
1055 /* Initialize */
1056 esl_vec_ISet(negseqs_n, cfg->nneg, 0);
1057 esl_vec_ISet(negseqs_poslen, cfg->nneg, 0);
1058 for (i = 0; i < cfg->nneg; i++) {
1059 ESL_ALLOC(negseqs_p[i], sizeof(int *) * alloc_chunk);
1060 cur_alloc[i] = alloc_chunk;
1061 }
1062
1063 /* Randomly pick test sequence/positions/orientations in which to embed each positive */
1064 for (j = 0; j < npos; j++) {
1065 /* pick a test sequence to embed within */
1066 i = esl_rnd_Roll(cfg->r, cfg->nneg); /* i = 0..cfg->nneg-1 */
1067 if(negseqs_n[i] == cur_alloc[i]) {
1068 cur_alloc[i] += alloc_chunk;
1069 ESL_RALLOC(negseqs_p[i], ptr, sizeof(int) * (cur_alloc[i]));
1070 }
1071 posseqs_i[j] = i;
1072
1073 /* Pick a position after which to embed the sequence.
1074 * We require it to be unique: each positive test sequence must embed
1075 * at a different position
1076 */
1077 keep_rolling = TRUE;
1078 while(keep_rolling) {
1079 p = esl_rnd_Roll(cfg->r, cfg->negL) + 1; /* p = 1..cfg->negL (note the + 1) */
1080 keep_rolling = FALSE;
1081 for(q = 0; q < negseqs_n[i]; q++) {
1082 if(negseqs_p[i][q] == p) { keep_rolling = TRUE; break; }
1083 }
1084 }
1085 posseqs_p[j] = p;
1086 negseqs_p[i][negseqs_n[i]] = p; /* we store this twice, b/c we'll sort negseqs_p[i] later */
1087
1088 /* pick an orientation in which to embed */
1089 posseqs_o[j] = esl_rnd_Roll(cfg->r, 2); /* 0..1, Watson or Crick */
1090
1091 /* increment counters */
1092 negseqs_n[i]++;
1093 negseqs_poslen[i] += posseqs[j]->n;
1094 }
1095
1096 /* At this point, for each negative sequence, we now know which
1097 * positives we'll embed within it as well as where they'll be
1098 * embedded. Next, we generate the negative sequence and a benchmark
1099 * sequence for each negative. The benchmark sequence will consist of
1100 * the entire negative sequence in order, but with the positives
1101 * inserted at their corresponding positions and orientations. The
1102 * length of the benchmark sequence will be cfg->negL+negseqs_poslen[i].
1103 */
1104 bmksq = esl_sq_CreateDigital(cfg->abc);
1105 negsq = esl_sq_CreateDigital(cfg->abc);
1106 for (i = 0; i < cfg->nneg; i++) {
1107 /* Allocate and initialize the benchmark sequence */
1108 esl_sq_GrowTo(bmksq, cfg->negL+negseqs_poslen[i]);
1109 bmksq->n = cfg->negL + negseqs_poslen[i];
1110 bmksq->dsq[0] = bmksq->dsq[bmksq->n+1] = eslDSQ_SENTINEL;
1111 esl_sq_FormatName(bmksq, "rmark%d", i+1);
1112 esl_sq_FormatName(negsq, "rmark%d-nopositives", i+1);
1113
1114 /* Create the negative sequence of length cfg->negL by either
1115 * generating sequence from the HMM or by using the input database
1116 * (if -S). If using the HMM, generate and concatenate as many
1117 * seqs as necessary until the total length is cfg->negL. If -S,
1118 * select chunks of the input database of length cfg->negchunkL
1119 * (user-definable with -C) and shuffle them with the specified
1120 * method and appending. If --iid, we construct each chunk and
1121 * append them, even though it's unnecessary - we could just do
1122 * one chunk.
1123 */
1124 esl_sq_GrowTo(negsq, cfg->negL);
1125 negsq->dsq[0] = negsq->dsq[cfg->negL+1] = eslDSQ_SENTINEL;
1126 negsq->n = 0;
1127 while(negsq->n < cfg->negL) {
1128 if(esl_opt_GetBoolean(go, "-S") || esl_opt_GetBoolean(go, "--iid")) { /* shuffle part of the seqdb */
1129 chunkL = (negsq->n + cfg->negchunkL <= cfg->negL) ? cfg->negchunkL : cfg->negL - negsq->n;
1130 if(cfg->negsummfp != NULL) {
1131 /* print out sequence name, start/end posn in newly constructed negative seq, set_random_segment() will print the rest */
1132 fprintf(cfg->negsummfp, "%-10s %10" PRId64 " %10" PRId64 " ", bmksq->name, negsq->n+1, negsq->n + chunkL);
1133 }
1134 set_random_segment(go, cfg, cfg->negsummfp, negsq->dsq + negsq->n + 1, chunkL);
1135 negsq->n += chunkL;
1136 }
1137 else { /* -S not enabled, generate part of the sequence from the HMM */
1138 esl_hmm_Emit(cfg->r, cfg->hmm, &tmpdsq, NULL, &chunkL);
1139 if((negsq->n + chunkL) > cfg->negL) chunkL = cfg->negL - negsq->n;
1140 memcpy(negsq->dsq + negsq->n + 1, tmpdsq+1, sizeof(ESL_DSQ) * chunkL);
1141 free(tmpdsq);
1142 /* printf("negsq %2d %10" PRId64 "\n", i, negsq->n); */
1143 negsq->n += chunkL;
1144 }
1145 }
1146 /* no need to name negsq, we won't output it */
1147
1148 /* Construct the benchmark sequence by copying chunks of the negative
1149 * sequence and the positives to be embedded within it, in the
1150 * proper order. First, sort the list of embed positions, so we
1151 * can step through and embed easily
1152 */
1153 esl_vec_ISortIncreasing(negseqs_p[i], negseqs_n[i]);
1154
1155 neg_p = 1; /* position in negative seq, 1..negsq->n, in the for loop below we've always accounted for 1..neg_p-1 */
1156 bmk_p = 1; /* position in benchmark seq, 1..bmksq->n, in the for loop below we've always we've accounted for 1..bmk_p-1 */
1157 for(q = 0; q < negseqs_n[i]; q++) { /* foreach positive to embed within neg seq i */
1158 memcpy(bmksq->dsq+bmk_p, negsq->dsq+neg_p, sizeof(ESL_DSQ) * (negseqs_p[i][q] - neg_p + 1));
1159 bmk_p += negseqs_p[i][q] - neg_p + 1;
1160 neg_p = negseqs_p[i][q] + 1;
1161 /* Search exhaustively for the posseq idx j that embeds at neg_p (there can only be one, see above)
1162 * This is necessary b/c we sorted negseqs_p, but not posseqs_p */
1163 for(j = 0; j < npos; j++) {
1164 if((posseqs_i[j] == i) && (posseqs_p[j] == negseqs_p[i][q])) { break; }
1165 }
1166 if(j == npos) esl_fatal("Unable to find positive sequence that embeds after posn %" PRId64 " in negseq %d\n", neg_p, i);
1167 /* found it, now embed by copying, after reverse complementing if nec */
1168 if(posseqs_o[j] == 1) {
1169 if((status = esl_sq_ReverseComplement(posseqs[j])) != eslOK) esl_fatal("Failed to reverse complement");
1170 }
1171 memcpy(bmksq->dsq+bmk_p, posseqs[j]->dsq+1, sizeof(ESL_DSQ) * posseqs[j]->n);
1172 bmk_p += posseqs[j]->n;
1173
1174 /* output positive data to summary file */
1175 fprintf(cfg->possummfp, "%-35s %-10s %-35s %8" PRId64 " %8" PRId64 "\n",
1176 posseqs[j]->desc, /* description, this has been set earlier as the msa name plus seq idx (e.g. "tRNA/3" for 3rd tRNA in the set) */
1177 bmksq->name, /* output sequence name (e.g. rmark10) */
1178 posseqs[j]->name, /* positive sequence name (from input MSA) */
1179 (posseqs_o[j] == 0) ? (bmk_p - posseqs[j]->n + 1) : bmk_p, /* start point in bmksq */
1180 (posseqs_o[j] == 0) ? bmk_p : (bmk_p - posseqs[j]->n + 1)); /* end point in bmksq */
1181 }
1182
1183 /* done embedding, finish off outseq with the chunk that occurs after the final embedded seq */
1184 if(neg_p <= negsq->n) {
1185 memcpy(bmksq->dsq+bmk_p, negsq->dsq+neg_p, sizeof(ESL_DSQ) * (negsq->n - neg_p + 1));
1186 bmk_p += negsq->n - neg_p + 1;
1187 neg_p = negsq->n + 1;
1188 }
1189 /* sanity checks */
1190 if(neg_p != (negsq->n + 1)) esl_fatal("Error creating output sequence, full negative not properly included");
1191 if(bmk_p != (bmksq->n + 1)) esl_fatal("Error creating output sequence, output length incorrect");
1192
1193 /* output the sequence */
1194 esl_sqio_Write(cfg->out_bmkfp, bmksq, eslSQFILE_FASTA, FALSE);
1195 esl_sq_Reuse(bmksq);
1196 if(cfg->nseqfp != NULL) esl_sqio_Write(cfg->nseqfp, negsq, eslSQFILE_FASTA, FALSE);
1197 esl_sq_Reuse(negsq);
1198 }
1199
1200 esl_sq_Destroy(bmksq);
1201 esl_sq_Destroy(negsq);
1202 free(posseqs_i);
1203 free(posseqs_p);
1204 free(posseqs_o);
1205 for(i = 0; i < cfg->nneg; i++) {
1206 free(negseqs_p[i]);
1207 }
1208 free(negseqs_p);
1209 free(negseqs_n);
1210 free(negseqs_poslen);
1211 free(cur_alloc);
1212 return eslOK;
1213
1214 ERROR:
1215 if(bmksq != NULL) esl_sq_Destroy(bmksq);
1216 if(negsq != NULL) esl_sq_Destroy(negsq);
1217 if(posseqs_i != NULL) free(posseqs_i);
1218 if(posseqs_p != NULL) free(posseqs_p);
1219 if(posseqs_o != NULL) free(posseqs_o);
1220 if(negseqs_p != NULL) { for(i = 0; i < cfg->nneg; i++) free(negseqs_p[i]); free(negseqs_p); }
1221 if(negseqs_n != NULL) free(negseqs_n);
1222 if(negseqs_poslen != NULL) free(negseqs_poslen);
1223 if(cur_alloc != NULL) free(cur_alloc);
1224 return status;
1225 }
1226
1227 /* Fetch in a random sequence of length <L> from the the pre-digitized
1228 * concatenated sequence database, select a random subseq, shuffle it
1229 * by the chosen algorithm; set dsq[1..L] to the resulting randomized
1230 * segment.
1231 *
1232 * If <logfp> is non-NULL, append one or more "<sqname> <from> <to>"
1233 * fields to current line, to record where the random segment was
1234 * selected from. This is useful in cases where we want to track back
1235 * the origin of a high-scoring segment, in case the randomization
1236 * wasn't good enough to obscure the identity of a segment.
1237 *
1238 */
1239 static int
1240 set_random_segment(ESL_GETOPTS *go, struct cfg_s *cfg, FILE *logfp, ESL_DSQ *dsq, int L)
1241 {
1242 ESL_SQ *sq = esl_sq_CreateDigital(cfg->abc);
1243 ESL_SQ *dbsq = esl_sq_CreateDigital(cfg->abc);
1244 int minDPL = esl_opt_GetInteger(go, "--minDPL");
1245 int db_dependent = (esl_opt_GetBoolean(go, "--iid") == TRUE ? FALSE : TRUE);
1246 char *pkey = NULL;
1247 int64_t start, end;
1248 int64_t Lseq;
1249 int status;
1250
1251 if (L==0) return eslOK;
1252 if (L > cfg->negchunkL) esl_fatal("asking to fetch a segment longer than chunksize %d\n", L, cfg->negchunkL);
1253
1254 /* fetch a random subseq from the source database */
1255 esl_sq_GrowTo(sq, L);
1256 if (db_dependent)
1257 {
1258 do {
1259 if (pkey != NULL) free(pkey);
1260 esl_sq_Reuse(dbsq);
1261
1262 /* NOTE: we should be able to use esl_ssi_FindNumber() to pick
1263 * a random sequence and read it's length from the SSI
1264 * index. However, I had trouble getting that to work on the
1265 * Rfamseq database and I couldn't track down the
1266 * problem. Maybe the SSI doesn't properly store the sequence
1267 * lengths for such a large file? I resorted to positioning
1268 * the file to a random sequence, and reading that sequence to
1269 * get its length. This is much slower, but it works.
1270 *
1271 * Code block that *should* work:
1272 * if (esl_ssi_FindNumber(cfg->dbfp->data.ascii.ssi, esl_rnd_Roll(cfg->r, cfg->db_nseq), NULL, NULL, NULL, &Lseq, &pkey) != eslOK)
1273 * esl_fatal("failed to look up a random seq");
1274 */
1275 /* pick a random sequence and get its pkey */
1276 if (esl_ssi_FindNumber(cfg->dbfp->data.ascii.ssi, esl_rnd_Roll(cfg->r, cfg->db_nseq), NULL, NULL, NULL, NULL, &pkey) != eslOK)
1277 esl_fatal("failed to look up a random seq");
1278 /* position the sequence file */
1279 if(esl_sqfile_PositionByKey(cfg->dbfp, pkey) != eslOK)
1280 esl_fatal("failed to reposition to a random seq");
1281 /* read the random sequence to get its length */
1282 if(esl_sqio_Read(cfg->dbfp, dbsq) != eslOK)
1283 esl_fatal("failed to read random seq");
1284 Lseq = dbsq->L;
1285 } while (Lseq < L);
1286
1287 start = 1 + esl_rnd_Roll(cfg->r, Lseq-L);
1288 end = start + L - 1;
1289
1290 /* Another issue with SSI: the following line should suffice to
1291 * fetch the sequence, but it gave me problems, probably for the
1292 * same reasons alluded to above (which I can't figure out), so
1293 * instead of fetching it efficiently using SSI, we copy it from
1294 * <dbsq> which we only read b/c we need to be able to copy it
1295 * here. The following line *should* work (and remove the need for
1296 * reading the full sequence into memory):
1297 * if ((status = esl_sqio_FetchSubseq(cfg->dbfp, pkey, start, end, sq)) != eslOK) esl_fatal("failed to fetch subseq, status: %d", status);
1298 */
1299 sq->dsq[0] = sq->dsq[L+1] = eslDSQ_SENTINEL;
1300 memcpy(sq->dsq+1, dbsq->dsq+start, sizeof(ESL_DSQ) * L);
1301 esl_sq_ConvertDegen2X(sq);
1302 }
1303
1304 /* log sequence source info: <name> <start> <end> */
1305 if (logfp != NULL && db_dependent)
1306 fprintf(logfp, "%-35s %10" PRId64 " %10" PRId64 "\n", pkey, start, end);
1307
1308 /* Now apply the appropriate randomization algorithm, if none are turned on, use --di */
1309 if((esl_opt_GetBoolean(go, "--di")) ||
1310 ((! esl_opt_GetBoolean(go, "--mono")) &&
1311 (! esl_opt_GetBoolean(go, "--markov0")) &&
1312 (! esl_opt_GetBoolean(go, "--markov1")) &&
1313 (! esl_opt_GetBoolean(go, "--iid")))) {
1314 if (L < minDPL) status = esl_rsq_XShuffle (cfg->r, sq->dsq, L, sq->dsq);
1315 else status = esl_rsq_XShuffleDP(cfg->r, sq->dsq, L, cfg->abc->Kp, sq->dsq);
1316 }
1317 else if (esl_opt_GetBoolean(go, "--mono")) status = esl_rsq_XShuffle (cfg->r, sq->dsq, L, sq->dsq);
1318 else if (esl_opt_GetBoolean(go, "--markov0")) status = esl_rsq_XMarkov0 (cfg->r, sq->dsq, L, cfg->abc->Kp, sq->dsq);
1319 else if (esl_opt_GetBoolean(go, "--markov1")) status = esl_rsq_XMarkov1 (cfg->r, sq->dsq, L, cfg->abc->Kp, sq->dsq);
1320 else if (esl_opt_GetBoolean(go, "--iid")) status = esl_rsq_xIID (cfg->r, cfg->fq, cfg->abc->K, L, sq->dsq);
1321 else esl_fatal("no randomization option? this can't happen.");
1322 if (status != eslOK) esl_fatal("esl's shuffling failed");
1323
1324 memcpy(dsq, sq->dsq+1, sizeof(ESL_DSQ) * L);
1325 esl_sq_Destroy(sq);
1326 esl_sq_Destroy(dbsq);
1327 free(pkey);
1328 return eslOK;
1329 }
1330
1331
1332 /* read_hmmfile
1333 *
1334 * Read the input HMM file.
1335 * Lines beginning with # are comments and are ignored.
1336 * Format of file:
1337 * line 1: <alphabet-type> (1 token, must be integer between 1 and 5)
1338 * line 2: <N> (1 token, number of states)
1339 * line 3: <begin> (<N> tokens, the 'begin' probability distribution)
1340 * lines 4 to <N>+3: <transitions> (<N> tokens, transition distribution for state L-3 if line L)
1341 * lines <N>+4 to 2*<N>+3: <transitions> (<abc->K> tokens, emission distribution for state L-<N>+3 if line L,
1342 * abc->K is size of alphabet (4 for RNA))
1343 *
1344 * All tokens in each probability distribution (lines 3->2*<N>+3) should sum to 1.0.
1345 * Types of alphabet:
1346 * type alphabet abc->K
1347 * 1 RNA 4
1348 * 2 DNA 4
1349 * 3 AMINO 20
1350 * 4 COINS 2
1351 * 5 DICE 6
1352 *
1353 * We die with esl_fatal() if there's an error.
1354 * Returns: VOID
1355 */
1356 void
1357 read_hmmfile(char *filename, ESL_HMM **ret_hmm)
1358 {
1359 int status;
1360 ESL_FILEPARSER *efp;
1361 ESL_HMM *hmm = NULL;
1362 ESL_ALPHABET *abc;
1363 char *tok;
1364 int type;
1365 int i,j;
1366 int nstates;
1367
1368 if (esl_fileparser_Open(filename, NULL, &efp) != eslOK) esl_fatal("ERROR, failed to open template file %s in parse_template_file\n", filename);
1369 esl_fileparser_SetCommentChar(efp, '#');
1370
1371 status = eslOK;
1372 /* get alphabet type */
1373 if((status = esl_fileparser_GetToken(efp, &tok, NULL)) != eslOK) esl_fatal("ERROR parsing HMM file, unable to read first token");
1374 type = atoi(tok);
1375 if(type < 1 || type > 5) { esl_fatal("ERROR parsing HMM file, first token should be alphabet type, an int between 1 and 5"); }
1376 if(type != eslRNA) { esl_fatal("ERROR parsing HMM file, invalid alphabet type, it must be RNA (1)"); }
1377 abc = esl_alphabet_Create(type);
1378
1379 /* get number of states */
1380 if((status = esl_fileparser_GetToken(efp, &tok, NULL)) != eslOK) esl_fatal("ERROR parsing HMM file, unable to read first token");
1381 nstates = atoi(tok);
1382 if((status = esl_fileparser_NextLine(efp)) != eslOK) esl_fatal("ERROR parsing HMM file, ran out of lines too early.");
1383
1384 /* create HMM */
1385 hmm = esl_hmm_Create(abc, nstates);
1386
1387 /* read begin probs */
1388 j = 0;
1389 while((status = esl_fileparser_GetTokenOnLine(efp, &tok, NULL)) == eslOK) {
1390 hmm->pi[j++] = atof(tok);
1391 }
1392 if(j != hmm->M) { esl_fatal("ERROR parsing HMM file, wrong number of begin transitions, %d != %d", j, hmm->M); }
1393 if(esl_FCompare_old(esl_vec_FSum(hmm->pi, hmm->M), 1., eslSMALLX1) != eslOK) { esl_fatal("ERROR parsing HMM file, begin probs don't sum to 1."); }
1394 esl_vec_FNorm(hmm->pi, hmm->M);
1395 if((status = esl_fileparser_NextLine(efp)) != eslOK) esl_fatal("ERROR parsing HMM file, ran out of lines too early.");
1396
1397 /* read transition probs, should be hmm->M+1 of these for each state, the +1 is for the end prob */
1398 for(i = 0; i < hmm->M; i++) {
1399 j = 0;
1400 while((status = esl_fileparser_GetTokenOnLine(efp, &tok, NULL)) == eslOK) {
1401 hmm->t[i][j++] = atof(tok);
1402 }
1403 if(j != (hmm->M+1)) { esl_fatal("ERROR parsing HMM file, wrong number of transitions for state %d", i); }
1404 if(esl_FCompare_old(esl_vec_FSum(hmm->t[i], (hmm->M+1)), 1., 0.00001) != eslOK) { esl_fatal("ERROR parsing HMM file, trans probs state %d don't sum to 1.", i); }
1405 esl_vec_FNorm(hmm->t[i], (hmm->M+1));
1406
1407 if((status = esl_fileparser_NextLine(efp)) != eslOK) esl_fatal("ERROR parsing HMM file, ran out of lines too early.");
1408 }
1409
1410 /* read emission probs, should be abc->K of these per state */
1411 for(i = 0; i < hmm->M; i++) {
1412 j = 0;
1413 while((status = esl_fileparser_GetTokenOnLine(efp, &tok, NULL)) == eslOK) {
1414 hmm->e[i][j++] = atof(tok);
1415 }
1416 if(j != (hmm->K)) { esl_fatal("ERROR parsing HMM file, wrong number of emissions for state %d", i); }
1417 if(esl_FCompare_old(esl_vec_FSum(hmm->e[i], hmm->K), 1., 0.00001) != eslOK) { esl_fatal("ERROR parsing HMM file, emit probs state %d don't sum to 1.", i); }
1418 esl_vec_FNorm(hmm->e[i], hmm->K);
1419
1420 status = esl_fileparser_NextLine(efp);
1421 if((i < (hmm->M-1)) && (status != eslOK)) esl_fatal("ERROR parsing HMM file, ran out of lines too early.");
1422 }
1423 *ret_hmm = hmm;
1424
1425 esl_fileparser_Destroy(efp);
1426 return;
1427 }
1428