Debian Codegraph @

hmmer/profmark/create-profmark.c

raw symbols SCIP
1 /* Construct a training alignment/test sequences benchmark from an MSA dataset.
2 *
3 * Usage:
4 * create-profmark <basename> <msafile> <seqdb>
5 * or:
6 * create-profmark --onlysplit <basename> <msafile>
7 *
8 * Contents:
9 * 1. Command line processing and configuration options
10 * 2. Splitting MSAs to create train/test sets (of domains)
11 * 3. Synthesizing positive and negative test sets (of sequences)
12 * 4. Top-level main()
13 *
14 * Outline:
15 * main
16 * create_config
17 * open_iofiles
18 * [for each MSA:]
19 * process_msa
20 * remove_fragments
21 * train_test_by_iset | train_test_by_cluster
22 * split_msa_by_iset | split_msa_by_cluster
23 * filter_msa_by_iset x2 | filter_msa_by_cluster x2
24 * validate_split
25 * synthesize_onedom_negatives | synthesize_twodom_negatives
26 * embed_one | embed_two
27 * set_random_segment x3 | set_random_segment x5
28 */
29 #include <stdio.h>
30 #include <string.h>
31
32 #include "easel.h"
33 #include "esl_alphabet.h"
34 #include "esl_cluster.h"
35 #include "esl_composition.h"
36 #include "esl_distance.h"
37 #include "esl_getopts.h"
38 #include "esl_iset.h"
39 #include "esl_lognormal.h"
40 #include "esl_random.h"
41 #include "esl_msa.h"
42 #include "esl_msafile.h"
43 #include "esl_sq.h"
44 #include "esl_sqio.h"
45 #include "esl_vectorops.h"
46
47
48 /*****************************************************************
49 * 1. Command line processing and configuration options
50 *****************************************************************/
51
52 static char banner[] = "construct a benchmark profile training/test set";
53 static char usage[] = "[options] <basename> <msafile> <seqdb>\n (with --onlysplit, omit <seqdb>)";
54
55 #define pmSPLIT_OPTS "--cobalt,--blue,--cluster,--random" // toggle group of training/testset-separating options
56 #define pmSHUFFLE_OPTS "--mono,--di,--markov0,--markov1,--reverse" // toggle group of nonhomolog seq shuffling/generating options
57
58 typedef enum { pmCLUSTER = 0,
59 pmCOBALT = 1,
60 pmBLUE = 2,
61 pmRANDOM = 3 } PM_SPLIT;
62
63 typedef enum { pmMONOSHUFFLE = 0,
64 pmDISHUFFLE = 1,
65 pmMARKOV0 = 2,
66 pmMARKOV1 = 3,
67 pmREVERSE = 4,
68 pmIID = 5 } PM_SHUFFLE;
69
70 static ESL_OPTIONS options[] = {
71 /* name type default env range togs reqs incomp help docgroup */
72 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "help; show brief info on version and usage", 1 },
73 { "-1", eslARG_REAL, "0.25", NULL, "0<x<=1.0", NULL, NULL, NULL, "split so no train/test seq pair has > x identity", 1 },
74 { "-2", eslARG_REAL, "0.50", NULL, "0<x<=1.0", NULL, NULL, NULL, "filter test seqs so no pair has > x identity", 1 },
75 { "-3", eslARG_REAL, "1.0", NULL, "0<x<=1.0", NULL, NULL, NULL, "filter training seqs so no pair has > x identity", 1 },
76 { "-N", eslARG_INT, "200000", NULL, "n>=0", NULL, NULL, NULL, "number of negative test seqs", 1 },
77 { "-S", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "specify RNG seed (0: use a random seed)", 1 },
78
79 /* Options defining other characteristics of the benchmark */
80 { "--fragthresh", eslARG_REAL, "0.5", NULL, "0<=x<=1", NULL, NULL, NULL, "exclude sequence fragments with aspan/alen < x", 2 },
81 { "--mintrain", eslARG_INT, "10", NULL, "n>0", NULL, NULL, NULL, "minimum number of training domains required per input MSA", 2 },
82 { "--mintest", eslARG_INT, "2", NULL, "n>0", NULL, NULL, NULL, "minimum number of test domains required per input MSA", 2 },
83 { "--maxtrain", eslARG_INT, FALSE, NULL, "n>=0", NULL, NULL, NULL, "maximum number of training domains taken per input MSA", 2 },
84 { "--maxtest", eslARG_INT, "10", NULL, "n>=0", NULL, NULL, NULL, "maximum number of test domains taken per input MSA", 2 },
85 { "--double", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "embed two, not one domain in each positive", 2 },
86
87 /* Options controlling choice of method for splitting into testing and training sets */
88 { "--cobalt", eslARG_NONE,"default", NULL, NULL, pmSPLIT_OPTS, NULL, NULL, "greedy algorithm with random order", 3 },
89 { "--blue", eslARG_NONE, FALSE, NULL, NULL, pmSPLIT_OPTS, NULL, NULL, "multi-round random election process", 3 },
90 { "--cluster", eslARG_NONE, FALSE, NULL, NULL, pmSPLIT_OPTS, NULL, NULL, "single linkage clustering", 3 },
91 { "--random", eslARG_NONE, FALSE, NULL, NULL, pmSPLIT_OPTS, NULL, NULL, "random selection of training set", 3 },
92
93 /* Other options controlling splitting/filtering method */
94 { "--bestof", eslARG_INT, NULL, NULL, "n>0", NULL, NULL, "--cluster,--firstof", "output best of n runs of an iset splitting algorithm", 4 },
95 { "--firstof", eslARG_INT, NULL, NULL, "n>0", NULL, NULL, "--cluster,--bestof", "output first passing split, try at most n times", 4 },
96 { "--rp", eslARG_REAL, "0.75", NULL,"0<x<=1.0", NULL, "--random", NULL, "set prob to put seq in training set with --random split", 4 },
97
98 /* Options controlling choice of method for nonhomologous segment randomization */
99 { "--mono", eslARG_NONE,"default", NULL, NULL, pmSHUFFLE_OPTS, NULL, NULL, "shuffle preserving monoresidue composition", 5 },
100 { "--di", eslARG_NONE, FALSE, NULL, NULL, pmSHUFFLE_OPTS, NULL, NULL, "shuffle preserving mono- and di-residue composition", 5 },
101 { "--markov0", eslARG_NONE, FALSE, NULL, NULL, pmSHUFFLE_OPTS, NULL, NULL, "generate with 0th order Markov properties per input", 5 },
102 { "--markov1", eslARG_NONE, FALSE, NULL, NULL, pmSHUFFLE_OPTS, NULL, NULL, "generate with 1st order Markov properties per input", 5 },
103 { "--reverse", eslARG_NONE, FALSE, NULL, NULL, pmSHUFFLE_OPTS, NULL, NULL, "reverse each input", 5 },
104 { "--iid", eslARG_NONE, FALSE, NULL, NULL, pmSHUFFLE_OPTS, NULL, NULL, "generate random iid sequence for negatives", 5 },
105
106 /* Options defining other characteristics of nonhomologous segments */
107 { "--dmu", eslARG_REAL, "4.8", NULL, NULL, NULL, NULL, NULL, "set mu param, domain length lognormal distribution", 6 }, // [xref H12/147 for these fits]
108 { "--dsigma", eslARG_REAL, "0.69", NULL, NULL, NULL, NULL, NULL, "set sigma param, domain length lognormal distribution", 6 },
109 { "--smu", eslARG_REAL, "5.6", NULL, NULL, NULL, NULL, NULL, "set mu param, sequence length lognormal distribution", 6 },
110 { "--ssigma", eslARG_REAL, "0.75", NULL, NULL, NULL, NULL, NULL, "set sigma param, sequence length lognormal distribution", 6 },
111 { "--minDPL", eslARG_INT, "100", NULL, NULL, NULL, NULL, NULL, "minimum segment length for DP shuffling", 6 },
112
113 /* Options forcing which alphabet we're working in (normally autodetected) */
114 { "--amino", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--dna,--rna", "<msafile> contains protein alignments", 7 },
115 { "--dna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--amino,--rna", "<msafile> contains DNA alignments", 7 },
116 { "--rna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "--amino,--dna", "<msafile> contains RNA alignments", 7 },
117
118 /* Other options I will probably organize better someday */
119 { "--onlysplit", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "split to .{train/test}.msa, no +/- seqs, no <seqfile> arg", 8 },
120 { "--speedtest", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "don't compute expensive avgid/avgconn statistics for .tbl file", 8 },
121 { 0,0,0,0,0,0,0,0,0,0 },
122 };
123
124 /* PM_CONFIG
125 *
126 * Don't make this const. It contains things that have dynamic state:
127 * RNG, open i/o files.
128 */
129 typedef struct {
130 ESL_MSAFILE *afp; // open MSA database for training/test splits
131 ESL_SQFILE *dbfp; // open seq database for shuffled negative segments
132 ESL_SSI *dbssi; // open SSI index; a less buried copy of dbfp->data.ascii.ssi. closing <dbfp> closes it.
133 int64_t db_nseq; // # of sequences in db; same as dbssi->nprimary
134
135 FILE *out_tbl; // summary table, columnar and whitespace-delim
136 FILE *out_train; // query MSAs (training sets) are written here, Stockholm format
137 FILE *out_test; // Usually .test.fa (FASTA) with pos/neg seqs; with --onlysplit, .test.msa.
138 FILE *out_postbl; // summary table for positive synthetic seqs (NULL if --onlysplit)
139 FILE *out_negtbl; // summary table for negative synthetic seqs (NULL if --onlysplit)
140
141 float idthresh1; // fractional id threshold for train/test split (no train/test pair > this id) (1.0 = iid random split, typical in machine learning)
142 float idthresh2; // ... for filtering test seqs (no test pair have > this id) (1.0 = no filtering)
143 float idthresh3; // ... for filtering training seqs (no train pair have > this fid) (1.0 = no filtering)
144 int tot_negatives; // number of synthetic negative test seqs to make
145 ESL_RANDOMNESS *rng; // random number generator
146
147 float fragthresh; // exclude sequences in original alignment with aspan/alen < fragthresh (default 0.5)
148 int min_ntrain; // minimum number of training domains per input alignment
149 int min_ntest; // ... of test
150 int max_ntrain; // maximum number of training domains per input alignment; 0=unlimited/option not turned on
151 int max_ntest; // ... of test
152 int do_double; // embed two instead of one domain in each positive
153
154 PM_SPLIT which_algo; // default: pmCOBALT; or pmBLUE | pmCLUSTER | pmRANDOM
155 PM_SHUFFLE which_shuf; // default: pmMONOSHUFFLE; or pmDISHUFFLE | pmMARKOV0 | pmMARKOV1 | pmREVERSE | pmIID
156
157 int do_bestof; // TRUE to take best splitting result of <ntries> runs
158 int do_firstof; // TRUE to take first successful split of <ntries> runs
159 int ntries; // (max) number of times to try to split with Cobalt, Blue, or Random, with do_bestof | do_firstof
160 double S_randp; // for pmRANDOM: probability of putting seq in set S
161
162 double dom_mu; // mu parameter for nonhomologous segment lognormal length distribution
163 double dom_sigma; // ... ditto for segment/domain sigma param
164 double seq_mu; // ... mu for whole nonhomologous sequence length
165 double seq_sigma; // ... sigma for seq length
166 int minDPL; // when using dishuffling option, for any shuffled segment < this length, use monoshuffling instead
167
168 int do_onlysplit; // if TRUE, only split to MSA outputs .{train/test}.msa. Don't generate pos/neg seqs.
169 int do_speedtest; // if TRUE, skip expensive avgid/avgconn statistics for the .tbl file, just write 0
170
171 int max_comparisons; // max # of pairwise comparisons to allow in XAvgSubsetConnectivity() before switching to sampling
172
173 ESL_ALPHABET *abc; // digital sequence alphabet
174 double *fq; // background residue frequencies, for iid random generation
175 } PM_CONFIG;
176
177
178 static void
179 cmdline_help(char *argv0, ESL_GETOPTS *go)
180 {
181 esl_banner(stdout, argv0, banner);
182 esl_usage (stdout, argv0, usage);
183 puts("\n where general options are:");
184 esl_opt_DisplayHelp(stdout, go, 1, 2, 80);
185 puts("\n options defining other characteristics of the benchmark:");
186 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
187 puts("\n options controlling choice of method for splitting:");
188 esl_opt_DisplayHelp(stdout, go, 3, 2, 80);
189 puts("\n other options controlling splitting/filtering methods:");
190 esl_opt_DisplayHelp(stdout, go, 4, 2, 80);
191 puts("\n options controlling choice of method for nonhomologous segment randomization:");
192 esl_opt_DisplayHelp(stdout, go, 5, 2, 80);
193 puts("\n other options controlling nonhomologous segments/sequences:");
194 esl_opt_DisplayHelp(stdout, go, 6, 2, 80);
195 puts("\n options to assert what alphabet we're working in (normally autodetected):");
196 esl_opt_DisplayHelp(stdout, go, 7, 2, 80);
197 puts("\n other options:");
198 esl_opt_DisplayHelp(stdout, go, 8, 2, 80);
199 exit(0);
200 }
201
202 static void
203 cmdline_failure(char *argv0, char *format, ...)
204 {
205 va_list argp;
206 printf("There's a problem with your command line:\n");
207 va_start(argp, format);
208 vfprintf(stderr, format, argp);
209 va_end(argp);
210 printf("\n");
211 esl_usage(stdout, argv0, usage);
212 printf("To see more help on available options, do %s -h\n\n", argv0);
213 exit(1);
214 }
215
216 static void
217 destroy_config(PM_CONFIG *cfg)
218 {
219 if (cfg) {
220 if (cfg->afp) esl_msafile_Close(cfg->afp);
221 if (cfg->dbfp) esl_sqfile_Close (cfg->dbfp); // this closes cfg->dbssi too
222
223 if (cfg->out_tbl) fclose(cfg->out_tbl);
224 if (cfg->out_train) fclose(cfg->out_train);
225 if (cfg->out_test) fclose(cfg->out_test);
226 if (cfg->out_postbl) fclose(cfg->out_postbl);
227 if (cfg->out_negtbl) fclose(cfg->out_negtbl);
228
229 esl_randomness_Destroy(cfg->rng);
230 esl_alphabet_Destroy(cfg->abc);
231 free(cfg->fq);
232 free(cfg);
233 }
234 }
235
236 static PM_CONFIG *
237 create_config(char *argv0, ESL_GETOPTS *go)
238 {
239 PM_CONFIG *cfg = NULL;
240 int status;
241
242 ESL_ALLOC(cfg, sizeof(PM_CONFIG));
243
244 cfg->afp = NULL; // input files are opened later by open_iofiles()
245 cfg->dbfp = NULL;
246 cfg->dbssi = NULL;
247 cfg->db_nseq = 0;
248
249 cfg->out_tbl = NULL; // output files, ditto.
250 cfg->out_train = NULL;
251 cfg->out_test = NULL;
252 cfg->out_postbl = NULL;
253 cfg->out_negtbl = NULL;
254
255 cfg->idthresh1 = esl_opt_GetReal(go, "-1");
256 cfg->idthresh2 = esl_opt_GetReal(go, "-2");
257 cfg->idthresh3 = esl_opt_GetReal(go, "-3");
258 cfg->tot_negatives = esl_opt_GetInteger(go, "-N");
259
260 if ((cfg->rng = esl_randomness_Create(esl_opt_GetInteger(go, "-S"))) == NULL) goto ERROR;
261
262 cfg->fragthresh = esl_opt_GetReal (go, "--fragthresh");
263 cfg->min_ntrain = esl_opt_GetInteger(go, "--mintrain");
264 cfg->min_ntest = esl_opt_GetInteger(go, "--mintest");
265 cfg->max_ntrain = (esl_opt_IsOn(go, "--maxtrain") ? esl_opt_GetInteger(go, "--maxtrain") : 0);
266 cfg->max_ntest = (esl_opt_IsOn(go, "--maxtest") ? esl_opt_GetInteger(go, "--maxtest") : 0);
267 cfg->do_double = esl_opt_GetBoolean(go, "--double");
268
269 if (esl_opt_GetBoolean(go, "--cobalt")) cfg->which_algo = pmCOBALT;
270 else if (esl_opt_GetBoolean(go, "--blue")) cfg->which_algo = pmBLUE;
271 else if (esl_opt_GetBoolean(go, "--cluster")) cfg->which_algo = pmCLUSTER;
272 else if (esl_opt_GetBoolean(go, "--random")) cfg->which_algo = pmRANDOM;
273 else esl_fatal("no split algorithm selected (this can't happen)");
274
275 if (esl_opt_GetBoolean(go, "--mono")) cfg->which_shuf = pmMONOSHUFFLE;
276 else if (esl_opt_GetBoolean(go, "--di")) cfg->which_shuf = pmDISHUFFLE;
277 else if (esl_opt_GetBoolean(go, "--markov0")) cfg->which_shuf = pmMARKOV0;
278 else if (esl_opt_GetBoolean(go, "--markov1")) cfg->which_shuf = pmMARKOV1;
279 else if (esl_opt_GetBoolean(go, "--reverse")) cfg->which_shuf = pmREVERSE;
280 else if (esl_opt_GetBoolean(go, "--iid")) cfg->which_shuf = pmIID;
281 else esl_fatal("no shuffle selected (this can't happen)");
282
283 if (esl_opt_IsOn(go, "--bestof")) { cfg->ntries = esl_opt_GetInteger(go, "--bestof"); cfg->do_bestof = TRUE; cfg->do_firstof = FALSE; }
284 else if (esl_opt_IsOn(go, "--firstof")) { cfg->ntries = esl_opt_GetInteger(go, "--firstof"); cfg->do_bestof = FALSE; cfg->do_firstof = TRUE; }
285 else { cfg->ntries = 1; cfg->do_bestof = FALSE; cfg->do_firstof = FALSE; }
286 cfg->S_randp = esl_opt_GetReal(go, "--rp");
287
288 cfg->seq_mu = esl_opt_GetReal (go, "--smu");
289 cfg->seq_sigma = esl_opt_GetReal (go, "--ssigma");
290 cfg->dom_mu = esl_opt_GetReal (go, "--dmu");
291 cfg->dom_sigma = esl_opt_GetReal (go, "--dsigma");
292 cfg->minDPL = esl_opt_GetInteger(go, "--minDPL");
293
294 if (esl_opt_GetBoolean(go, "--amino")) cfg->abc = esl_alphabet_Create(eslAMINO);
295 else if (esl_opt_GetBoolean(go, "--dna")) cfg->abc = esl_alphabet_Create(eslDNA);
296 else if (esl_opt_GetBoolean(go, "--rna")) cfg->abc = esl_alphabet_Create(eslRNA);
297 else cfg->abc = NULL; // by default, we don't know alphabet until we see the open msafile
298 cfg->fq = NULL; // ... and therefore we won't allocate or set iid bg fq's until we're in open_iofiles
299
300 cfg->do_onlysplit = esl_opt_GetBoolean(go, "--onlysplit");
301 cfg->do_speedtest = esl_opt_GetBoolean(go, "--speedtest");
302
303 /* Configuration that is currently not runtime-configurable */
304 cfg->max_comparisons = 10000; // [xref 2022/0725-avgpid-by-sampling]
305
306 /* Configuration problems too complex to be detected by ESL_GETOPTS */
307 if (cfg->seq_mu < cfg->dom_mu)
308 cmdline_failure(argv0, "You want to set the mu for seq length larger than for domain length,\nwhen you use the --smu or --dmu options.\n");
309 if (cfg->do_double && cfg->min_ntest < 2)
310 cmdline_failure(argv0, "--double embeds two domains per synthetic positive seq; --mintest must be >= 2.\n");
311 return cfg;
312
313 ERROR:
314 destroy_config(cfg);
315 return NULL;
316 }
317
318 static void
319 open_iofiles(PM_CONFIG *cfg, const char *basename, const char *msafile, const char *dbfile)
320 {
321 int alifmt = eslMSAFILE_STOCKHOLM; // currently require msafile to be in Stockholm (it's a multi-MSA file)
322 int dbfmt = eslSQFILE_FASTA; // we currently require db to be in FASTA format, and with an SSI index
323 char outfile[256]; // constructed name of an output file, <basename>.suffix
324 int status;
325
326 /* default config has cfg->abc = NULL and we get the alphabet from the msafile;
327 * but alphabet may have been asserted, in which case cfg->abc is already the alphabet
328 */
329 status = esl_msafile_Open(&(cfg->abc), msafile, /*env:*/NULL, alifmt, /*fmtdata:*/NULL, &(cfg->afp));
330 if (status != eslOK) esl_msafile_OpenFailure(cfg->afp, status);
331
332 /* only now are we sure that we have the alphabet set; now we can initialize cfg->fq background frequencies */
333 ESL_ALLOC(cfg->fq, sizeof(double) * cfg->abc->K);
334 if (cfg->abc->type == eslAMINO) esl_composition_SW34(cfg->fq);
335 else esl_vec_DSet(cfg->fq, cfg->abc->K, 1.0 / (double) cfg->abc->K);
336
337 if (! cfg->do_onlysplit)
338 {
339 /* Open the sequence file in digital mode */
340 status = esl_sqfile_OpenDigital(cfg->abc, dbfile, dbfmt, NULL, &(cfg->dbfp));
341 if (status == eslENOTFOUND) esl_fatal("No such file %s", dbfile);
342 else if (status == eslEFORMAT) esl_fatal("Format of seqfile %s unrecognized.", dbfile);
343 else if (status == eslEINVAL) esl_fatal("Can't autodetect stdin or .gz.");
344 else if (status != eslOK) esl_fatal("Open failed, code %d.", status);
345
346 /* Open its SSI index */
347 if (esl_sqfile_OpenSSI(cfg->dbfp, NULL) != eslOK) // <NULL> means no optional ssi filename; use the default <dbfile>.ssi
348 esl_fatal("Failed to find an SSI index %s.ssi for <seqdb>\nUse `esl-sfetch --index %s` to create the SSI index file", dbfile, dbfile);
349 cfg->dbssi = cfg->dbfp->data.ascii.ssi;
350 cfg->db_nseq = cfg->dbssi->nprimary;
351 }
352
353 /* Output files depend on --onlysplit
354 * default: .tbl .train.msa .test.fa .pos .neg
355 * --onlysplit: .tbl .train.msa .test.msa - -
356 */
357 if (snprintf(outfile, 256, "%s.tbl", basename) >= 256) esl_fatal("Failed to construct output summary table file name");
358 if ((cfg->out_tbl = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open output summary table file %s", outfile);
359
360 if (snprintf(outfile, 256, "%s.train.msa", basename) >= 256) esl_fatal("Failed to construct output training MSA file name");
361 if ((cfg->out_train = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open output training MSA file %s", outfile);
362
363 if (cfg->do_onlysplit)
364 {
365 if (snprintf(outfile, 256, "%s.test.msa", basename) >= 256) esl_fatal("Failed to construct output test MSA file name");
366 if ((cfg->out_test = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open output test MSA file %s", outfile);
367 }
368 else
369 {
370 if (snprintf(outfile, 256, "%s.test.fa", basename) >= 256) esl_fatal("Failed to construct output test sequences file name");
371 if ((cfg->out_test = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open output test sequences file %s", outfile);
372
373 if (snprintf(outfile, 256, "%s.pos", basename) >= 256) esl_fatal("Failed to construct output positives table file name");
374 if ((cfg->out_postbl = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open output positives table file %s", outfile);
375
376 if (snprintf(outfile, 256, "%s.neg", basename) >= 256) esl_fatal("Failed to construct output negatives table file name");
377 if ((cfg->out_negtbl = fopen(outfile, "w")) == NULL) esl_fatal("Failed to open output negatives table file %s", outfile);
378 }
379 return;
380
381 ERROR:
382 esl_fatal("allocation failed");
383 }
384 /*********** end, command line processing ***********************/
385
386
387
388 /*****************************************************************
389 * 2. Splitting MSAs to create train/test sets (of domains)
390 *****************************************************************/
391
392 /* Need to pass the clustering routine two parameters -
393 * %id threshold and alphabet ptr - so make a structure that bundles them.
394 */
395 typedef struct {
396 double t; // two seqs are linked if they have >t pairwise identity, as defined by esl_dst_XPairId(): smaller rlen as denominator
397 const ESL_MSA *msa;
398 } PM_LINK_PARAMS;
399
400
401 /* is_linked()
402 *
403 * This helper function gets passed to the clustering/linking routines, along
404 * with the <struct islinked_param_s> packet. Seq pairs with > maxid
405 * are defined as "linked".
406 */
407 static int
408 is_linked(const void *v1, const void *v2, const void *p, int *ret_link)
409 {
410 PM_LINK_PARAMS *prm = (PM_LINK_PARAMS *) p;
411 int idx1 = *(int *) v1;
412 int idx2 = *(int *) v2;
413 double pid;
414 int status;
415
416 if ( (status = esl_dst_XPairId(prm->msa->abc, prm->msa->ax[idx1], prm->msa->ax[idx2], &pid, NULL, NULL)) != eslOK) goto ERROR;
417 *ret_link = (pid > prm->t ? TRUE : FALSE);
418 return eslOK;
419
420 ERROR:
421 *ret_link = FALSE;
422 return status;
423 }
424
425 /* split_msa_by_cluster()
426 *
427 * Use the cluster algorithm to split into a training/test set such
428 * that no train/test pair have >t pairwise identity.
429 *
430 * Input is a list of <nV> sequence indices in <V>;
431 * these are indices of sequences in the original <msa>.
432 * V[0..nV-1] = aseq indices 0..nseq-1
433 *
434 * Output is a training set <S> of <*ret_nS> sequences and a test set
435 * <T> of <*ret_nT> sequences. Caller provides space for <S> and <T>,
436 * each allocated for at least <nV> integer indices.
437 *
438 * Briefly: do single linkage clustering, using the is_linked()
439 * function at >t identity; assign largest cluster as training
440 * set S; assign all other clusters as test set T.
441 *
442 * The cluster algorithm must put all <nV> sequences into either
443 * the train or test sets; nS + nT = nV. Though the training
444 * set is the largest single cluster, the aggregated test set
445 * might still come out larger (nT can be >nS).
446 */
447 static int
448 split_msa_by_cluster(const ESL_MSA *msa, const int *V, int nV, double t, int *S, int *ret_nS, int *T, int *ret_nT)
449 {
450 PM_LINK_PARAMS prm;
451 int *wrk = NULL; // esl_cluster_SingleLinkage() requires an allocated tmp workspace of at least 2*nV ints
452 int *assignment = NULL; // .. and it returns cluster assignment[0..nV-1] = 0..nc-1
453 int *nin = NULL; // # of seqs in each cluster; nin[0..nc-1]
454 int nS = 0; // size of training set
455 int nT = 0; // size of test set
456 int nc; // number of single-linkage clusters
457 int ctrain; // which cluster we assign as the training set, [0..nc-1]
458 int i;
459 int status;
460
461 ESL_ALLOC(wrk, 2 * nV * sizeof(int));
462 ESL_ALLOC(assignment, nV * sizeof(int));
463
464 prm.t = t;
465 prm.msa = msa;
466
467 /* esl_cluster_SingleLinkage() is written generally enough that we
468 * can use V itself, the list of vertex indices, as the objects to
469 * be clustered. We just need to keep straight that the output is
470 * assignment[0..nV-1].
471 */
472 if (( status = esl_cluster_SingleLinkage(V, nV, sizeof(int), is_linked, &prm, wrk, assignment, &nc)) != eslOK) goto ERROR;
473
474 ESL_ALLOC(nin, sizeof(int) * nc);
475 esl_vec_ISet(nin, nc, 0);
476 for (i = 0; i < nV; i++) nin[assignment[i]]++; // nin[0..nc-1] is the size of each single linkage cluster
477
478 ctrain = esl_vec_IArgMax(nin, nc); // make the biggest cluster the training set
479 for (i = 0; i < nV; i++)
480 if (assignment[i] == ctrain) S[nS++] = V[i]; else T[nT++] = V[i];
481
482 free(nin); free(assignment); free(wrk);
483 *ret_nS = nS;
484 *ret_nT = nT;
485 return eslOK;
486
487 ERROR:
488 free(nin); free(assignment); free(wrk);
489 *ret_nS = 0;
490 *ret_nT = 0;
491 return status;
492 }
493
494 /* filter_msa_by_cluster()
495 * As above, but here we filter instead of split: remove seqs from <V> to get a
496 * subset <S> such that no pair has >t identity. For each single linkage cluster,
497 * choose one random sequence.
498 */
499 static int
500 filter_msa_by_cluster(ESL_RANDOMNESS *rng, const ESL_MSA *msa, const int *V, int nV, double t, int *S, int *ret_nS)
501 {
502 PM_LINK_PARAMS prm;
503 int *wrk = NULL;
504 int *assignment = NULL;
505 int *nin = NULL;
506 int nc;
507 int i,c,which;
508 int nS = 0;
509 int status;
510
511 ESL_ALLOC(wrk, 2 * nV * sizeof(int));
512 ESL_ALLOC(assignment, nV * sizeof(int));
513 prm.t = t;
514 prm.msa = msa;
515
516 if (( status = esl_cluster_SingleLinkage(V, nV, sizeof(int), is_linked, &prm, wrk, assignment, &nc)) != eslOK) goto ERROR;
517
518 ESL_ALLOC(nin, sizeof(int) * nc);
519 esl_vec_ISet(nin, nc, 0);
520 for (i = 0; i < nV; i++) nin[assignment[i]]++;
521
522 for (c = 0; c < nc; c++)
523 {
524 which = esl_rnd_Roll(rng, nin[c]); // pick one random representative per cluster.
525 for (i = 0; i < nV; i++)
526 if (assignment[i] == c) { if (which > 0) which--; else { S[nS++] = V[i]; break; } }
527 }
528
529 free(nin); free(assignment); free(wrk);
530 *ret_nS = nS;
531 return eslOK;
532
533 ERROR:
534 free(nin); free(assignment); free(wrk);
535 *ret_nS = 0;
536 return status;
537 }
538
539 /* split_msa_by_iset()
540 * As above, but now using one of the other splitting algorithms from Sam's iset paper.
541 */
542 static int
543 split_msa_by_iset(ESL_RANDOMNESS *rng, const ESL_MSA *msa, const int *V, int nV,
544 int which_algo, double t, double S_randp,
545 int *S, int *ret_nS, int *T, int *ret_nT)
546 {
547 PM_LINK_PARAMS prm;
548 int *wrk = NULL;
549 int *assignment = NULL;
550 int nS = 0;
551 int nT = 0;
552 int i;
553 int status;
554
555 ESL_ALLOC(wrk, 4 * nV * sizeof(int));
556 ESL_ALLOC(assignment, nV * sizeof(int));
557 prm.t = t;
558 prm.msa = msa;
559
560 switch (which_algo) {
561 case pmBLUE: status = esl_iset_biBlue (rng, V, nV, sizeof(int), is_linked, &prm, wrk, assignment); break;
562 case pmCOBALT: status = esl_iset_biCobalt(rng, V, nV, sizeof(int), is_linked, &prm, wrk, assignment); break;
563 case pmRANDOM: status = esl_iset_biRandom(rng, S_randp, V, nV, sizeof(int), is_linked, &prm, assignment); break;
564 default: ESL_XEXCEPTION(eslEINVAL, "no such iset algorithm");
565 }
566
567 for (i = 0; i < nV; i++)
568 if (assignment[i] == 1) S[nS++] = V[i];
569 else if (assignment[i] == 2) T[nT++] = V[i];
570
571 free(assignment); free(wrk);
572 *ret_nS = nS;
573 *ret_nT = nT;
574 return eslOK;
575
576 ERROR:
577 free(assignment); free(wrk);
578 *ret_nS = *ret_nT = 0;
579 return status;
580 }
581
582
583 /* filter_msa_by_iset()
584 * As above, but using one of the iset algorithms to filter a set.
585 */
586 static int
587 filter_msa_by_iset(ESL_RANDOMNESS *rng, const ESL_MSA *msa, const int *V, int nV,
588 int which_algo, double t,
589 int *S, int *ret_nS)
590 {
591 PM_LINK_PARAMS prm;
592 int *wrk = NULL;
593 int *assignment = NULL;
594 int nS = 0;
595 int i;
596 int status;
597
598 ESL_ALLOC(wrk, 4 * nV * sizeof(int));
599 ESL_ALLOC(assignment, nV * sizeof(int));
600 prm.t = t;
601 prm.msa = msa;
602
603 switch (which_algo) {
604 case pmCOBALT: esl_iset_monoCobalt(rng, V, nV, sizeof(int), is_linked, &prm, wrk, assignment); break;
605 case pmBLUE: esl_iset_monoBlue (rng, V, nV, sizeof(int), is_linked, &prm, wrk, assignment); break;
606 case pmRANDOM: esl_iset_monoCobalt(rng, V, nV, sizeof(int), is_linked, &prm, wrk, assignment); break; // yes, Cobalt. We have no monoRandom() filter; Cobalt essentially is one.
607 default: ESL_XEXCEPTION(eslEINVAL, "no such iset algorithm");
608 }
609
610 for (i = 0; i < nV; i++)
611 if (assignment[i] == 1) S[nS++] = V[i];
612
613 *ret_nS = nS;
614 free(wrk); free(assignment);
615 return eslOK;
616
617 ERROR:
618 *ret_nS = 0;
619 free(wrk); free(assignment);
620 return status;
621 }
622
623
624 /* train_test_by_cluster()
625 *
626 * Main routine for using our older algorithm (called Cluster in
627 * [Petti22]) to split an input sequence alignment into a training and
628 * test set.
629 *
630 * We may have already removed some seqs from the input MSA <msa>,
631 * so the input is defined as a subset <V> relative to <msa>, a list
632 * of sequence indices: V[i=0..nV-1] = 0..nseq-1.
633 *
634 * First we construct a split of V to sets S and T such that no
635 * sequence in S has >= idthresh1 fractional pairwise identity to any
636 * sequence in T. We do a single linkage clustering at >= idthresh1
637 * and define the largest cluster as S, and the rest as T.
638 *
639 * Then we filter T to remove closely related test sequences, such that no
640 * pair of test sequences has >= idthresh2. We do a single linkage clustering
641 * at idthresh2 and randomly choose one representative of each cluster.
642 *
643 * Optionally, we also filter S, at idthresh3.
644 *
645 * The result is the two sets S and T, defined as subset lists as in V, of
646 * size nS and nT. Caller provides allocated space for S and T sufficient
647 * to hold up to <nseq> indices.
648 *
649 * <cfg> bundles configuration options:
650 * rng : random number generator
651 * idthresh1 : defines the training/test set split of V into S,T
652 * idthresh2 : defines filtering of test set T to remove similar seqs; no pair > idthresh2 (1.0 = no filtering)
653 * idthresh3 : ditto for training set S
654 *
655 * Returns:
656 * <eslOK> on success and <S> contains a list of <nS> indices in
657 * the training set; ditto <T>, <nT> for test set.
658 *
659 * <eslFAIL> if we fail to identify a successful split that
660 * satisfies the minimum training and test set sizes (default 1, but
661 * may be optionally configured higher). Now <nS> and <nT> are
662 * both set to 0.
663 *
664 * Throws:
665 * <eslEMEM> on allocation failure
666 */
667 static int
668 train_test_by_cluster(const PM_CONFIG *cfg, const ESL_MSA *msa, const int *V, int nV,
669 int *S, int *ret_nS, int *T, int *ret_nT)
670 {
671 int *pre_S = NULL;
672 int *pre_T = NULL;
673 int pre_nS, pre_nT;
674 int nS, nT;
675 int status;
676
677 if (nV < cfg->min_ntrain + cfg->min_ntest) { status = eslFAIL; goto ERROR; }
678
679 ESL_ALLOC(pre_S, sizeof(int) * nV);
680 ESL_ALLOC(pre_T, sizeof(int) * nV);
681
682 if (( status = split_msa_by_cluster (msa, V, nV, cfg->idthresh1, pre_S, &pre_nS, pre_T, &pre_nT)) != eslOK) goto ERROR;
683 if (pre_nS < cfg->min_ntrain || pre_nT < cfg->min_ntest) { status = eslFAIL; goto ERROR; }
684
685 if (cfg->idthresh2 < 1.0) {
686 if (( status = filter_msa_by_cluster(cfg->rng, msa, pre_T, pre_nT, cfg->idthresh2, T, &nT)) != eslOK) goto ERROR;
687 if (nT < cfg->min_ntest) { status = eslFAIL; goto ERROR; }
688 } else {
689 esl_vec_ICopy(pre_T, pre_nT, T);
690 nT = pre_nT;
691 }
692
693 if (cfg->idthresh3 < 1.0) {
694 if (( status = filter_msa_by_cluster(cfg->rng, msa, pre_S, pre_nS, cfg->idthresh3, S, &nS)) != eslOK) goto ERROR;
695 if (nS < cfg->min_ntrain) { status = eslFAIL; goto ERROR; }
696 } else {
697 esl_vec_ICopy(pre_S, pre_nS, S);
698 nS = pre_nS;
699 }
700
701 free(pre_S); free(pre_T);
702 *ret_nS = nS;
703 *ret_nT = nT;
704 return eslOK;
705
706 ERROR:
707 free(pre_S); free(pre_T);
708 *ret_nS = 0;
709 *ret_nT = 0;
710 return status;
711 }
712
713
714 static int
715 train_test_by_iset(PM_CONFIG *cfg, const ESL_MSA *msa, const int *V, int nV,
716 int *S, int *ret_nS, int *T, int *ret_nT, int *ret_ntries)
717 {
718 double best_score = -eslINFINITY;
719 double score;
720 int *pre_S = NULL;
721 int *pre_T = NULL;
722 int *try_S = NULL;
723 int *try_T = NULL;
724 int pre_nS, pre_nT;
725 int try_nS, try_nT;
726 int nS, nT;
727 int trial = 0;
728 int status;
729
730 if (nV < cfg->min_ntrain + cfg->min_ntest) { status = eslFAIL; goto ERROR; } // doomed from the start; this MSA too small
731
732 ESL_ALLOC(pre_S, sizeof(int) * nV);
733 ESL_ALLOC(pre_T, sizeof(int) * nV);
734 ESL_ALLOC(try_S, sizeof(int) * nV);
735 ESL_ALLOC(try_T, sizeof(int) * nV);
736
737 while (trial < cfg->ntries)
738 {
739 trial++;
740 if (( status = split_msa_by_iset (cfg->rng, msa, V, nV, cfg->which_algo, cfg->idthresh1, cfg->S_randp, pre_S, &pre_nS, pre_T, &pre_nT)) != eslOK) goto ERROR;
741 if (pre_nS < cfg->min_ntrain || pre_nT < cfg->min_ntest) continue;
742
743 if (cfg->idthresh2 < 1.0) {
744 if (( status = filter_msa_by_iset(cfg->rng, msa, pre_T, pre_nT, cfg->which_algo, cfg->idthresh2, try_T, &try_nT)) != eslOK) goto ERROR;
745 if (try_nT < cfg->min_ntest) continue;
746 } else {
747 esl_vec_ICopy(pre_T, pre_nT, try_T);
748 try_nT = pre_nT;
749 }
750
751 if (cfg->idthresh3 < 1.0) {
752 if (( status = filter_msa_by_iset(cfg->rng, msa, pre_S, pre_nS, cfg->which_algo, cfg->idthresh3, try_S, &try_nS)) != eslOK) goto ERROR;
753 if (try_nS < cfg->min_ntrain) continue;
754 } else {
755 esl_vec_ICopy(pre_S, pre_nS, try_S);
756 try_nS = pre_nS;
757 }
758
759 if ( ( score = log((double) try_nS) + log((double) try_nT)) > best_score) // 2 log(geometric mean); robust to overflow of ntrain*ntest
760 {
761 best_score = score; // best_score is >= 0 because ntrain,ntest >= 0 (because min_n{train,test} >= 1)
762 nS = try_nS; esl_vec_ICopy(try_S, try_nS, S);
763 nT = try_nT; esl_vec_ICopy(try_T, try_nT, T);
764 if (cfg->do_firstof) break;
765 }
766 }
767 if (best_score == -eslINFINITY) { status = eslFAIL; goto ERROR; }
768
769 free(pre_S); free(pre_T); free(try_S); free(try_T);
770 *ret_nS = nS;
771 *ret_nT = nT;
772 *ret_ntries = trial;
773 return eslOK;
774
775 ERROR:
776 free(pre_S); free(pre_T); free(try_S); free(try_T);
777 *ret_nS = 0;
778 *ret_nT = 0;
779 *ret_ntries = trial;
780 return status;
781 }
782 /****************** end, splitting MSAs **************************/
783
784
785
786 /*****************************************************************
787 * 3. Synthesizing positive and negative test sets (of sequences)
788 *****************************************************************/
789
790 static void
791 embed_two(ESL_RANDOMNESS *rng, int L, int d1n, int d2n, int *ret_L1, int *ret_L2, int *ret_L3)
792 {
793 int i,j;
794
795 /* L' = L - d1n - d2n; the total length of nonhomologous sequence.
796 * Choose i,j points in that sequence to insert our two domains after.
797 */
798 i = esl_rnd_Roll(rng, L - d1n - d2n + 1 ); // i = 0..L'
799 j = esl_rnd_Roll(rng, L - d1n - d2n + 1 ); // j = 0..L'
800 if (i > j) ESL_SWAP(i, j, int);
801
802 /* now 1 .. i = random region 1 (if i==0, there's none);
803 * i+1 .. i+d1n = domain 1
804 * i+d1n+1 .. j+d1n = random region 2 (if i==j, there's none);
805 * j+d1n+1 .. j+d1n+d2n = domain 2
806 * j+d1n+d2n+1 .. L = random region 3 (if j == L' (L-d1n-d2n), there's none);
807 */
808 *ret_L1 = i;
809 *ret_L2 = j-i;
810 *ret_L3 = L - d1n - d2n - j;
811 }
812
813 static void
814 embed_one(ESL_RANDOMNESS *rng, int L, int d1n, int *ret_L1, int *ret_L2)
815 {
816 int i;
817
818 i = esl_rnd_Roll(rng, L - d1n + 1 ); // i = 0..L'
819 /* now 1 .. i = random region 1 (if i==0, there's none);
820 * i+1 .. i+d1n = domain 1
821 * i+d1n+1 .. L = random region 2 (if i==L', there's none)
822 */
823 *ret_L1 = i;
824 *ret_L2 = L - d1n - i;
825 }
826
827
828 static void
829 set_random_segment(const PM_CONFIG *cfg, FILE *logfp, int W, ESL_DSQ *dsqp)
830 {
831 ESL_SQ *sq = esl_sq_CreateDigital(cfg->abc);
832 int db_dependent = TRUE; // some choices for randomization don't need a source db seq, such as i.i.d. generation
833 char *pkey = NULL; // name of db seq we'll grab segment from
834 int64_t which; // index of db seq we'll grab a segment from; 0..db_nseq-1
835 off_t rec_offset; // byte offset of that db seq in dbfile
836 int64_t L; // db seq length. int64_t because be prepared for full chromosomes, for a DNA-based benchmark.
837 int64_t i,j,ip; // ... likewise for subseq coords in it
838 ESL_DSQ x; // shuffling routines expect complete dsq with sentinels; we have to hack sentinels in, then replace them
839 int n; // when we're having to concat the source: length of one copied chunk
840 int pos; // ... position to copy next chunk to
841
842 if (db_dependent)
843 {
844 /* Select by random <which> index number, and look up length
845 * before we fetch any sequence
846 */
847 which = esl_rnd_Roll(cfg->rng, cfg->db_nseq);
848 esl_ssi_FindNumber(cfg->dbssi, which, NULL /*opt_fh*/, &rec_offset, NULL /*opt_doff*/, &L, &pkey);
849
850 /* Possible future optimization: we have the record and data
851 * offsets; we could go ahead and position the disk, we don't
852 * need to look up offsets again with
853 * esl_sqio_Fetch{Subseq}(). But we don't currently have a
854 * ReadSubseq() to use with pre-positioning.
855 */
856
857 if (L >= W) // our source db sequence is long enough to take a subseq of length W from it
858 {
859 i = 1 + esl_rnd_Roll(cfg->rng, L-W+1); // i is 1..L-W+1
860 j = i + W - 1; // j is W..L
861 esl_sqio_FetchSubseq(cfg->dbfp, pkey, i,j, sq);
862 esl_sq_ConvertDegen2X(sq);
863 memcpy(dsqp, sq->dsq+1, sizeof(ESL_DSQ) * W);
864 }
865 else // our source db sequence is too short; concatenate it before taking subseq of length W
866 {
867 esl_sqio_Fetch(cfg->dbfp, pkey, sq);
868 esl_sq_ConvertDegen2X(sq);
869 ESL_DASSERT1(( sq->n == L ));
870 i = ip = 1 + esl_rnd_Roll(cfg->rng, L); // i is 1..L; first window is L-i+1 long. ip is our tmp stepping var; i is for the logfile.
871 pos = 0;
872 while (pos < W)
873 {
874 n = ESL_MIN(L-ip+1, W-pos); // L-i+1 is the max len we can copy from sq; W-pos+1 is how much we still need
875 memcpy(dsqp+pos, sq->dsq+ip, sizeof(ESL_DSQ) * n);
876 pos += n;
877 j = ip + n - 1;
878 ip = 1;
879 }
880 }
881 } // now dsqp points (directly) to W residues sampled from the seq db; they're not shuffled yet
882
883 if (logfp)
884 fprintf(logfp, " %-32s %6" PRId64 " %6" PRId64 " %6" PRId64 " %c", pkey, L, i, j, (L >= W ? '.' : 'c'));
885
886
887 /* esl_randomseq routines expect complete dsq's with sentinels, but
888 * here <dsqp> is usually pointing into the middle of a longer
889 * dsq. Hack sentinels on its edges at -1 and W+1, remembering
890 * whatever's there; put original positions back when we're done.
891 * Since we're making the seq left to right, we only need to replace at -1.
892 */
893 x = dsqp[-1]; dsqp[-1] = dsqp[W] = eslDSQ_SENTINEL;
894
895 if (cfg->which_shuf == pmMONOSHUFFLE) esl_rsq_XShuffle (cfg->rng, dsqp-1, W, dsqp-1);
896 else if (cfg->which_shuf == pmDISHUFFLE) {
897 if (W < cfg->minDPL) esl_rsq_XShuffle (cfg->rng, dsqp-1, W, dsqp-1);
898 else esl_rsq_XShuffleDP(cfg->rng, dsqp-1, W, cfg->abc->Kp, dsqp-1);
899 }
900 else if (cfg->which_shuf == pmMARKOV0) esl_rsq_XMarkov0 (cfg->rng, dsqp-1, W, cfg->abc->Kp, dsqp-1);
901 else if (cfg->which_shuf == pmMARKOV1) esl_rsq_XMarkov1 (cfg->rng, dsqp-1, W, cfg->abc->Kp, dsqp-1);
902 else if (cfg->which_shuf == pmREVERSE) esl_rsq_XReverse ( dsqp-1, W, dsqp-1);
903 else if (cfg->which_shuf == pmIID) esl_rsq_xIID (cfg->rng, cfg->fq, cfg->abc->K, W, dsqp-1);
904 dsqp[-1] = x;
905
906 esl_sq_Destroy(sq);
907 if (pkey) free(pkey);
908 }
909
910
911 static void
912 set_homologous_segment(FILE *logfp, const ESL_MSA *msa, int idx, ESL_DSQ *dsqp)
913 {
914 int apos;
915 int rlen = 0;
916
917 for (apos = 1; msa->ax[idx][apos] != eslDSQ_SENTINEL; apos++)
918 if (! esl_abc_XIsGap(msa->abc, msa->ax[idx][apos]))
919 {
920 *dsqp++ = msa->ax[idx][apos];
921 rlen++;
922 }
923
924 if (logfp)
925 fprintf(logfp, " %-32s %6d %6d %6d .", msa->sqname[idx], rlen, 1, rlen);
926
927 // all embedded segments are full length, so "<rlen> 1 <rlen>" output is redundant
928 // but in future, we might embed partial length homologous segments,
929 // to test local alignment
930 }
931
932
933 static void
934 synthesize_twodom_positives(const PM_CONFIG *cfg, const ESL_MSA *msa, const int *T, int nT, int *tot_npos)
935 {
936 ESL_SQ *sq = esl_sq_CreateDigital(cfg->abc);
937 int i = 0; // counter over positive test seqs we create
938 int L; // total sequence length
939 int d1n, d2n; // lengths of embedded homologous test domains
940 int L1,L2,L3; // lengths of nonhomologous segments
941 #if eslDEBUGLEVEL >= 1
942 char errbuf[eslERRBUFSIZE];
943 #endif
944
945 while (i < nT-1) // while we have at least two domains in the test set to embed...
946 {
947 d1n = esl_abc_dsqrlen(msa->abc, msa->ax[T[i]]);
948 d2n = esl_abc_dsqrlen(msa->abc, msa->ax[T[i+1]]);
949 do {
950 L = (int) ceil(esl_lognormal_Sample(cfg->rng, cfg->seq_mu, cfg->seq_sigma));
951 } while (d1n+d2n > L);
952
953 embed_two(cfg->rng, L, d1n, d2n, &L1, &L2, &L3);
954 esl_sq_GrowTo(sq, L);
955
956 (*tot_npos)++;
957 esl_sq_FormatName(sq, "%s/%d/%d-%d/%d-%d", msa->name, *tot_npos, L1+1, L1+d1n, L1+d1n+L2+1, L1+d1n+L2+d2n);
958 esl_sq_FormatDesc(sq, "domains: %s %s", msa->sqname[T[i]], msa->sqname[T[i+1]]);
959 sq->n = L;
960 sq->dsq[0] = sq->dsq[L+1] = eslDSQ_SENTINEL;
961
962 fprintf(cfg->out_postbl, "%-40s %5d %5d %5d %5d %5d %5d", sq->name, (int) sq->n, L1, d1n, L2, d2n, L3);
963 set_random_segment (cfg, cfg->out_postbl, L1, sq->dsq+1);
964 set_homologous_segment( cfg->out_postbl, msa, T[i], sq->dsq+1+L1);
965 set_random_segment (cfg, cfg->out_postbl, L2, sq->dsq+1+L1+d1n);
966 set_homologous_segment( cfg->out_postbl, msa, T[i+1], sq->dsq+1+L1+d1n+L2);
967 set_random_segment (cfg, cfg->out_postbl, L3, sq->dsq+1+L1+d1n+L2+d2n);
968 fprintf(cfg->out_postbl, "\n");
969
970 esl_sqio_Write(cfg->out_test, sq, eslSQFILE_FASTA, FALSE);
971 #if eslDEBUGLEVEL >= 1
972 if ( esl_sq_Validate(sq, errbuf) != eslOK) esl_fatal(errbuf);
973 #endif
974 esl_sq_Reuse(sq);
975 i += 2;
976 }
977 esl_sq_Destroy(sq);
978 }
979
980
981 static void
982 synthesize_twodom_negatives(const PM_CONFIG *cfg)
983 {
984 ESL_SQ *sq = esl_sq_CreateDigital(cfg->abc);
985 int L;
986 int L1,L2,L3,d1n,d2n;
987 int nneg;
988 #if eslDEBUGLEVEL >= 1
989 char errbuf[eslERRBUFSIZE];
990 #endif
991
992 for (nneg = 1; nneg <= cfg->tot_negatives; nneg++)
993 {
994 do {
995 L = (int) ceil( esl_lognormal_Sample(cfg->rng, cfg->seq_mu, cfg->seq_sigma) ); // ceil() to make it an integer >= 1
996 d1n = (int) ceil( esl_lognormal_Sample(cfg->rng, cfg->dom_mu, cfg->dom_sigma) );
997 d2n = (int) ceil( esl_lognormal_Sample(cfg->rng, cfg->dom_mu, cfg->dom_sigma) );
998 } while (d1n+d2n > L);
999
1000 embed_two(cfg->rng, L, d1n, d2n, &L1, &L2, &L3);
1001 esl_sq_GrowTo(sq, L);
1002
1003 esl_sq_FormatName(sq, "decoy%d", nneg);
1004 esl_sq_FormatDesc(sq, "L=%d in segments %d/%d/%d/%d/%d", L, L1, d1n, L2, d2n, L3);
1005 sq->n = L;
1006 sq->dsq[0] = sq->dsq[L+1] = eslDSQ_SENTINEL;
1007
1008 fprintf(cfg->out_negtbl, "%-15s %5d %5d %5d %5d %5d %5d", sq->name, (int) sq->n, L1, d1n, L2, d2n, L3);
1009 set_random_segment(cfg, cfg->out_negtbl, L1, sq->dsq+1);
1010 set_random_segment(cfg, cfg->out_negtbl, d1n, sq->dsq+1+L1);
1011 set_random_segment(cfg, cfg->out_negtbl, L2, sq->dsq+1+L1+d1n);
1012 set_random_segment(cfg, cfg->out_negtbl, d2n, sq->dsq+1+L1+d1n+L2);
1013 set_random_segment(cfg, cfg->out_negtbl, L3, sq->dsq+1+L1+d1n+L2+d2n);
1014 fprintf(cfg->out_negtbl, "\n");
1015
1016 esl_sqio_Write(cfg->out_test, sq, eslSQFILE_FASTA, FALSE);
1017 #if eslDEBUGLEVEL >= 1
1018 if ( esl_sq_Validate(sq, errbuf) != eslOK) esl_fatal(errbuf);
1019 #endif
1020 esl_sq_Reuse(sq);
1021 }
1022
1023 esl_sq_Destroy(sq);
1024 }
1025
1026 /* synthesize_onedom_positives()
1027 * Embed one test domain per test sequence, and write them to the .fa file.
1028 *
1029 * In:
1030 * cfg - command line configuration options
1031 * msa - original MSA from input file
1032 * T - array of indices of test subset of domains in <msa>
1033 * nT - number of test domains in <T>
1034 *
1035 * Out:
1036 * Synthetic positive test seqs written to cfg->out_test file
1037 * Tabular info about them written to cfg->out_postbl file
1038 *
1039 * <*totpos> is a running total of the # of positive test seqs we've
1040 * made so far, over all MSAs. This is used as part of the construction
1041 * of the name of a positive test seq.
1042 */
1043 static void
1044 synthesize_onedom_positives(const PM_CONFIG *cfg, const ESL_MSA *msa, const int *T, int nT, int *tot_npos)
1045 {
1046 ESL_SQ *sq = esl_sq_CreateDigital(cfg->abc);
1047 int i = 0; // counter over positive test seqs we create
1048 int L; // total sequence length
1049 int d1n; // length of embedded homologous test domain
1050 int L1,L2; // lengths of nonhomologous segments
1051 #if eslDEBUGLEVEL >= 1
1052 char errbuf[eslERRBUFSIZE];
1053 #endif
1054
1055 for (i = 0; i < nT; i++)
1056 {
1057 d1n = esl_abc_dsqrlen(msa->abc, msa->ax[T[i]]);
1058 do {
1059 L = (int) ceil(esl_lognormal_Sample(cfg->rng, cfg->seq_mu, cfg->seq_sigma));
1060 } while (d1n > L);
1061
1062 embed_one(cfg->rng, L, d1n, &L1, &L2);
1063 esl_sq_GrowTo(sq, L);
1064
1065 (*tot_npos)++;
1066 esl_sq_FormatName(sq, "%s/%d/%d-%d", msa->name, *tot_npos, L1+1, L1+d1n);
1067 esl_sq_FormatDesc(sq, "domain: %s", msa->sqname[T[i]]);
1068 sq->n = L;
1069 sq->dsq[0] = sq->dsq[L+1] = eslDSQ_SENTINEL;
1070
1071 fprintf(cfg->out_postbl, "%-40s %5d %5d %5d %5d", sq->name, (int) sq->n, L1, d1n, L2);
1072 set_random_segment (cfg, cfg->out_postbl, L1, sq->dsq+1);
1073 set_homologous_segment( cfg->out_postbl, msa, T[i], sq->dsq+1+L1);
1074 set_random_segment (cfg, cfg->out_postbl, L2, sq->dsq+1+L1+d1n);
1075 fprintf(cfg->out_postbl, "\n");
1076
1077 esl_sqio_Write(cfg->out_test, sq, eslSQFILE_FASTA, FALSE);
1078 #if eslDEBUGLEVEL >= 1
1079 if ( esl_sq_Validate(sq, errbuf) != eslOK) esl_fatal(errbuf);
1080 #endif
1081 esl_sq_Reuse(sq);
1082 }
1083 esl_sq_Destroy(sq);
1084 }
1085
1086
1087 static void
1088 synthesize_onedom_negatives(const PM_CONFIG *cfg)
1089 {
1090 ESL_SQ *sq = esl_sq_CreateDigital(cfg->abc);
1091 int L,L1,L2,d1n;
1092 int nneg;
1093 #if eslDEBUGLEVEL >= 1
1094 char errbuf[eslERRBUFSIZE];
1095 #endif
1096
1097 for (nneg = 1; nneg <= cfg->tot_negatives; nneg++)
1098 {
1099 do {
1100 L = (int) ceil( esl_lognormal_Sample(cfg->rng, cfg->seq_mu, cfg->seq_sigma) ); // ceil() to make it an integer >= 1
1101 d1n = (int) ceil( esl_lognormal_Sample(cfg->rng, cfg->dom_mu, cfg->dom_sigma) );
1102 } while (d1n > L);
1103
1104 embed_one(cfg->rng, L, d1n, &L1, &L2);
1105 esl_sq_GrowTo(sq, L);
1106
1107 esl_sq_FormatName(sq, "decoy%d", nneg);
1108 esl_sq_FormatDesc(sq, "L=%d in segments %d/%d/%d", L, L1, d1n, L2);
1109 sq->n = L;
1110 sq->dsq[0] = sq->dsq[L+1] = eslDSQ_SENTINEL;
1111
1112 fprintf(cfg->out_negtbl, "%-15s %5d %5d %5d %5d", sq->name, (int) sq->n, L1, d1n, L2);
1113 set_random_segment(cfg, cfg->out_negtbl, L1, sq->dsq+1);
1114 set_random_segment(cfg, cfg->out_negtbl, d1n, sq->dsq+1+L1);
1115 set_random_segment(cfg, cfg->out_negtbl, L2, sq->dsq+1+L1+d1n);
1116 fprintf(cfg->out_negtbl, "\n");
1117
1118 esl_sqio_Write(cfg->out_test, sq, eslSQFILE_FASTA, FALSE);
1119 #if eslDEBUGLEVEL >= 1
1120 if ( esl_sq_Validate(sq, errbuf) != eslOK) esl_fatal(errbuf);
1121 #endif
1122 esl_sq_Reuse(sq);
1123 }
1124
1125 esl_sq_Destroy(sq);
1126 }
1127 /************** end, synthesizing pos/neg seqs ******************/
1128
1129
1130
1131 /*****************************************************************
1132 * 4. Top-level main()
1133 *****************************************************************/
1134
1135 /* remove_fragments()
1136 *
1137 * Fragments are defined as those with aspan/alen < fragthresh, where aspan
1138 * is # of alignment columns from leftmost to rightmost residue.
1139 *
1140 * Caller provides an array <V> allocated for up to <msa->nseq>
1141 * sequences; upon return, this is a sorted list of the indices
1142 * <0..nseq-1> for <nV> sequences that aren't fragments.
1143 *
1144 * (It's more efficient to do alignment membership using sparse sets
1145 * such as <V> relative to the original MSA, as opposed to extracting
1146 * new alignments of subsets.)
1147 *
1148 * <fragthresh> = 0 : no fragments removed; all seqs defined as "full length"
1149 * <fragthresh> = 1 : all except fully spanning seqs are fragments
1150 * There's no way to set <fragthresh> such that all seqs are fragments.
1151 *
1152 * This function essentially just translates the ESL_BITFIELD output
1153 * of esl_msa_MarkFragments() (which defines the fragment rule) to
1154 * our sparse set in <V>.
1155 */
1156 static void
1157 remove_fragments(const ESL_MSA *msa, float fragthresh, int *V, int *ret_nV)
1158 {
1159 ESL_BITFIELD *fragassign = NULL;
1160 int i, nV;
1161 int status;
1162
1163 if (( status = esl_msa_MarkFragments(msa, fragthresh, &fragassign)) != eslOK) esl_fatal("esl_msa_MarkFragments() failed unexpectedly");
1164
1165 for (i = 0, nV = 0; i < msa->nseq; i++)
1166 if (! esl_bitfield_IsSet(fragassign, i)) V[nV++] = i;
1167
1168 esl_bitfield_Destroy(fragassign);
1169 *ret_nV = nV;
1170 }
1171
1172 #if eslDEBUGLEVEL >= 1 // validate_split is expensive, and only compiled & used when debugging code
1173 /* validate_split()
1174 *
1175 * Check the result of splitting <msa> into training and test sets <S>
1176 * and <T>, of size <nS> and <nT>. If something's wrong with them, exit
1177 * with an informative esl_fatal() error message.
1178 */
1179 static void
1180 validate_split(PM_CONFIG *cfg, const ESL_MSA *msa, const int *S, int nS, const int *T, int nT)
1181 {
1182 int i,j;
1183 double pid;
1184
1185 /* Training and test set are disjoint, and no sequence in training
1186 * set has > idthresh1 identity to any test sequence.
1187 */
1188 for (i = 0; i < nS; i++)
1189 for (j = 0; j < nT; j++)
1190 {
1191 if (S[i] == T[j]) // self comparison would have given 100% identity anyway, but may as well check
1192 esl_fatal("training/test sets for %s not disjoint: %d in both (%s)", msa->name, S[i], msa->sqname[S[i]]);
1193
1194 esl_dst_XPairId(cfg->abc, msa->ax[S[i]], msa->ax[T[j]], &pid, /*opt_nid=*/NULL, /*opt_n=*/NULL); // deliberately not using is_linked(), to doublecheck
1195 if (pid > cfg->idthresh1)
1196 esl_fatal("training/test set for %s have a pair at %.3f identity: %d and %d (%s and %s)",
1197 msa->name, pid, S[i], T[j], msa->sqname[S[i]], msa->sqname[T[j]]);
1198 }
1199
1200 /* Test set obeys size thresholds, has no duplicates, and if idthresh2 is set, no pair > idthresh2 */
1201 if (cfg->min_ntest > 0 && nT < cfg->min_ntest) esl_fatal("test set for %s too small (%d < %d)", msa->name, nT, cfg->min_ntest);
1202 if (cfg->max_ntest > 0 && nT > cfg->max_ntest) esl_fatal("test set for %s too large (%d > %d)", msa->name, nT, cfg->max_ntest);
1203 for (i = 0; i < nT; i++)
1204 for (j = i+1; j < nT; j++)
1205 {
1206 if (T[i] == T[j])
1207 esl_fatal("test set for %s has a duplicate: %d appears twice (%s)", msa->name, T[i], msa->sqname[T[i]]);
1208
1209 esl_dst_XPairId(cfg->abc, msa->ax[T[i]], msa->ax[T[j]], &pid, /*opt_nid=*/NULL, /*opt_n=*/NULL);
1210 if (cfg->idthresh2 < 1.0 && pid > cfg->idthresh2)
1211 esl_fatal("test set for %s contains a pair at %.3f identity: %d and %d (%s and %s)",
1212 msa->name, pid, T[i], T[j], msa->sqname[T[i]], msa->sqname[T[j]]);
1213 }
1214
1215 /* Same, for training set and idthresh3 */
1216 if (cfg->min_ntrain > 0 && nS < cfg->min_ntrain) esl_fatal("training set for %s too small (%d < %d)", msa->name, nS, cfg->min_ntrain);
1217 if (cfg->max_ntrain > 0 && nS > cfg->max_ntrain) esl_fatal("training set for %s too large (%d > %d)", msa->name, nS, cfg->max_ntrain);
1218 for (i = 0; i < nS; i++)
1219 for (j = i+1; j < nS; j++)
1220 {
1221 if (S[i] == S[j])
1222 esl_fatal("training set for %s has a duplicate: %d appears twice (%s)", msa->name, S[i], msa->sqname[S[i]]);
1223
1224 esl_dst_XPairId(cfg->abc, msa->ax[S[i]], msa->ax[S[j]], &pid, /*opt_nid=*/NULL, /*opt_n=*/NULL);
1225 if (cfg->idthresh3 < 1.0 && pid > cfg->idthresh3)
1226 esl_fatal("training set for %s contains a pair at %.3f identity: %d and %d (%s and %s)",
1227 msa->name, pid, S[i], S[j], msa->sqname[S[i]], msa->sqname[S[j]]);
1228 }
1229 }
1230 #endif //eslDEBUGLEVEL >= 1
1231
1232
1233 /* write_msa_subset()
1234 * Extract a smaller MSA from <msa>, containing the sequences identified
1235 * by a list <S> of <nS> indices; write it in Stockholm format to <ofp>.
1236 *
1237 * This is essentially a translation layer to existing esl_msa functions.
1238 * If we need to, we could extract and write more efficiently, without
1239 * the indirections.
1240 */
1241 static void
1242 write_msa_subset(FILE *ofp, const ESL_MSA *msa, const int *S, int nS)
1243 {
1244 ESL_MSA *submsa = NULL;
1245 int *useme = malloc(sizeof(int) * msa->nseq);
1246 int i;
1247 int status;
1248
1249 if (useme == NULL) esl_fatal("allocation failed");
1250 esl_vec_ISet(useme, msa->nseq, FALSE);
1251 for (i = 0; i < nS; i++) useme[S[i]] = TRUE;
1252
1253 if ((status = esl_msa_SequenceSubset(msa, useme, &submsa)) != eslOK) esl_fatal("esl_msa_SequenceSubset() failed unexpectedly");
1254 if ((status = esl_msa_MinimGaps(submsa, /*errbuf=*/NULL, /*textgaps=*/NULL, /*consider_rf=*/FALSE)) != eslOK) esl_fatal("esl_msa_MinimGaps() failed unexpectedly");
1255 if ((status = esl_msafile_Write(ofp, submsa, eslMSAFILE_STOCKHOLM)) != eslOK) esl_fatal("failed to write MSA to its output file");
1256
1257 free(useme);
1258 esl_msa_Destroy(submsa);
1259 }
1260
1261 /* process_msa()
1262 *
1263 * <msa> may be modified here: non-IUPAC residue symbols are converted in-place to X.
1264 */
1265 static void
1266 process_msa(PM_CONFIG *cfg, ESL_MSA *msa, int *tot_npos)
1267 {
1268 int *V = NULL; // set of non-fragment seqs in input MSA; as an ordered list of nV indices 0..nseq-1
1269 int *S = NULL; // ... training set
1270 int *T = NULL; // ... test set
1271 int nV, nS, nT;
1272 double avgid = 0.0; // average pairwise identity in MSA (after fragment removal)
1273 double avgconn = 0.0; // average pairwise connectivity at idthresh1
1274 int ntries = 1; // with randomized iset algorithms and --bestof or (especially) --firstof, how many tries we made at splitting
1275 int prv_npos = *tot_npos; // remember previous total number of synthetic positive seqs created
1276 int split_success;
1277 int status;
1278
1279 ESL_ALLOC(V, sizeof(int) * msa->nseq);
1280 nV = 0;
1281
1282 esl_msa_ConvertDegen2X(msa); // some programs we'd want to benchmark can't handle IUPAC degeneracy coding
1283 remove_fragments(msa, cfg->fragthresh, V, &nV);
1284 ESL_ALLOC(S, sizeof(int) * nV);
1285 ESL_ALLOC(T, sizeof(int) * nV);
1286 nS = nT = 0;
1287
1288 /* Calculate avg pid and avg connectivity for summary stats output in .tbl file.
1289 * Generally useful, but expensive. With the --speedtest speed benchmarking option,
1290 * skip it and leave avgid/avgconn as 0.0 in the .tbl file.
1291 */
1292 if (!cfg->do_speedtest && nV > 1)
1293 esl_dst_XAvgSubsetConnectivity(msa->abc, msa->ax, msa->nseq, V, nV,
1294 cfg->max_comparisons, cfg->idthresh1, &avgid, &avgconn);
1295
1296 if (cfg->which_algo == pmCLUSTER) status = train_test_by_cluster(cfg, msa, V, nV, S, &nS, T, &nT);
1297 else status = train_test_by_iset (cfg, msa, V, nV, S, &nS, T, &nT, &ntries);
1298
1299 if (status == eslOK) split_success = TRUE;
1300 else if (status == eslFAIL) split_success = FALSE;
1301 else esl_fatal("unexpected error in train/test splitting");
1302
1303 esl_vec_IShuffle(cfg->rng, S, nS); if (cfg->max_ntrain) nS = ESL_MIN(nS, cfg->max_ntrain); // because we just shuffled, downsampling is simple
1304 esl_vec_IShuffle(cfg->rng, T, nT); if (cfg->max_ntest) nT = ESL_MIN(nT, cfg->max_ntest);
1305
1306 #if eslDEBUGLEVEL >= 1 // validation is expensive too; only do it in debugging code, not production
1307 if (split_success) validate_split(cfg, msa, S, nS, T, nT);
1308 #endif
1309
1310 if (cfg->do_onlysplit)
1311 {
1312 if (split_success && ! cfg->do_speedtest) {
1313 write_msa_subset(cfg->out_train, msa, S, nS);
1314 write_msa_subset(cfg->out_test, msa, T, nT);
1315 }
1316 }
1317 else if (split_success)
1318 {
1319 write_msa_subset(cfg->out_train, msa, S, nS);
1320
1321 if (cfg->do_double) synthesize_twodom_positives(cfg, msa, T, nT, tot_npos);
1322 else synthesize_onedom_positives(cfg, msa, T, nT, tot_npos);
1323 }
1324
1325 fprintf(cfg->out_tbl, "%-20s %6d %6" PRId64 " %6d %3.0f%% %3.0f%% %3d %4s %6d %6d %6d\n",
1326 msa->name, msa->nseq, msa->alen, msa->nseq-nV, 100.*avgid, 100.*avgconn, ntries,
1327 (split_success ? "ok" : "FAIL"), nS, nT, *tot_npos - prv_npos);
1328
1329 free(V); free(S); free(T);
1330 return;
1331
1332 ERROR:
1333 esl_fatal("allocation failed");
1334 }
1335
1336
1337
1338
1339 int
1340 main(int argc, char **argv)
1341 {
1342 ESL_GETOPTS *go = NULL; // command line configuration
1343 PM_CONFIG *cfg = NULL; // program configuration, all bundled up
1344 char *basename = NULL;
1345 char *msafile = NULL;
1346 char *dbfile = NULL;
1347 ESL_MSA *msa = NULL;
1348 int tot_npos = 0; // running count of total # of true positives synthesized, over all MSAs
1349 int status;
1350
1351 go = esl_getopts_Create(options);
1352 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) cmdline_failure(argv[0], "Failed to parse command line: %s\n", go->errbuf);
1353 if (esl_opt_VerifyConfig(go) != eslOK) cmdline_failure(argv[0], "Error in command line configuration: %s\n", go->errbuf);
1354 if (esl_opt_GetBoolean(go, "-h")) cmdline_help (argv[0], go);
1355
1356 if (( esl_opt_GetBoolean(go, "--onlysplit") && esl_opt_ArgNumber(go) != 2) ||
1357 (! esl_opt_GetBoolean(go, "--onlysplit") && esl_opt_ArgNumber(go) != 3))
1358 cmdline_failure(argv[0], "Incorrect number of command line arguments.\n");
1359
1360 cfg = create_config(argv[0], go);
1361 basename = esl_opt_GetArg(go, 1);
1362 msafile = esl_opt_GetArg(go, 2);
1363 if (! cfg->do_onlysplit) dbfile = esl_opt_GetArg(go, 3);
1364 open_iofiles(cfg, basename, msafile, dbfile);
1365 esl_getopts_Destroy(go);
1366
1367 while (( status = esl_msafile_Read(cfg->afp, &msa)) == eslOK)
1368 {
1369 process_msa(cfg, msa, &tot_npos); // table output is from process_msa().
1370 esl_msa_Destroy(msa);
1371 }
1372 if (status != eslEOF) esl_msafile_ReadFailure(cfg->afp, status);
1373
1374 if (! cfg->do_onlysplit) {
1375 if (cfg->do_double) synthesize_twodom_negatives(cfg);
1376 else synthesize_onedom_negatives(cfg);
1377 }
1378
1379 destroy_config(cfg); // includes closing io files
1380 return eslOK;
1381 }
1382