Debian Codegraph @

rmark/rmark-rocplot.c

raw symbols SCIP
1 /* Summarizing results of a benchmark by plotting a ROC-like plot,
2 * including confidence intervals derived by Bayesian bootstrapping.
3 *
4 * Alternatively, with the --mer or --Ethresh options, ROC-like plots
5 * are not output. With --mer, output mean MER (minimum error rate)
6 * values for all bootstrap trials. MER is the minimal sum of false
7 * negatives and false positives over all possible thresholds; a good
8 * single summary statistic for benchmark performance. With --Ethresh
9 * <x>, output mean number of true positives and false positives with
10 * E-values <= <x> for all bootstrap trials.
11 *
12 *
13 * The <.out file> from an rmark benchmark consists of lines:
14 * <E-value> <bitscore> <target_sequence> <query_model> <matching_model> <seq_idx_in_fam> <strand>
15 *
16 * The <.out> file (or stream) must be sorted by E-value, with best
17 * (lowest) E-values first.
18 *
19 * Unlike profmark, target sequence names are not informative.
20 *
21 * Positive and negative hits are determined as follows:
22 * - A hit is a positive if <matching_model> matches <query_model> and
23 * <strand> is "same", and there's no better scoring hits between
24 * <query_model> and <target_sequence>
25 * - A hit is a negative if <matching_model> is "decoy" (strand will also
26 * be "decoy").
27 * - A hit is ignored for three possible reasons:
28 * : if <matching_model> is neither "decoy" nor <query_model> OR
29 * : if <matching_model> is <query_model> and <strand> is "opposite".
30 * : <matching_model> is <query_model> and <strand> is "same" but
31 * there is a better scoring hit between <query_model> and
32 * <target_sequence>.
33 *
34 * The program also needs to find the query and positive
35 * tables for the benchmark that was run. It looks for these by
36 * appending ".tbl" and ".pos" to the <rmark> argument;
37 * that is:
38 * : <rmark>.tbl contains one line per query: 1st field is name of query
39 * : <rmark>.pos contains one line per positive: 1st field is the
40 * concatenation of the query family name a '/' and the sequence index
41 * in the family. For example: "tRNA/3" is the third tRNA in the
42 * benchmark set. (Note these are not in order in the test sequences,
43 * tRNA/3 and tRNA/1 might be in the first and second negative sequences
44 * respectively.)
45 *
46 * The program calculates a plot of fractional coverage of the positives
47 * (on the Y-axis; range 0..1) versus errors per query (on the X-axis;
48 * ranging from 1/(# of models) to 10.0 by default).
49 *
50 * The default output is an XMGRACE xydydy file, with points
51 * representing mean coverage in the bootstrap samples, and error bars
52 * representing a 95% confidence interval.
53 *
54 * A typical command line, after having run a benchmark on "rmark" under
55 * MPI with many output files:
56 *
57 * cat *.out | sort -g | ./rmark-rocplot rmark - > results.xy
58 * xmgrace -settype xydydy results.xy
59 *
60 * SRE, Wed Jun 18 13:37:31 2008 [Janelia]
61 */
62 #include <esl_config.h>
63
64 #include <stdlib.h>
65 #include <stdio.h>
66 #include <string.h>
67 #include <math.h>
68
69 #include "easel.h"
70 #include "esl_dirichlet.h"
71 #include "esl_getopts.h"
72 #include "esl_keyhash.h"
73 #include "esl_random.h"
74 #include "esl_stats.h"
75 #include "esl_vectorops.h"
76
77
78 static char banner[] = "construct a ROC plot of rmark results, using Bayesian bootstrapping";
79 static char usage[] = "[options] <rmark_basename> <.out file>\n";
80
81 static ESL_OPTIONS options[] = {
82 /* name type default env range togs reqs incomp help docgroup */
83 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "help; show brief info on version and usage", 1 },
84 { "-a", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "all: plot all bootstrap samples individually", 1 },
85 { "-n", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "plot original data, without any bootstrapping", 1 },
86 { "-s", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "plot error bars by std. dev. not confidence interval", 1 },
87 { "-N", eslARG_INT, "500", NULL, NULL, NULL,NULL, NULL, "number of bootstrap samples to take", 1 },
88 { "--min", eslARG_REAL, NULL, NULL, NULL, NULL,NULL, NULL, "set minimum x-axis value (FPs/query) to plot", 1 },
89 { "--max", eslARG_REAL, "10.", NULL, NULL, NULL,NULL, NULL, "set maximum x-axis value (FPs/query) to plot", 1 },
90 { "--steps", eslARG_INT, "10", NULL, NULL, NULL,NULL, NULL, "set number of steps to plot per 10x on x-axis", 1 },
91 { "--seed", eslARG_INT, FALSE, NULL,"n>0", NULL,NULL, NULL, "set random number generator's seed to <n>", 1 },
92 { "--nsd", eslARG_REAL, "3.", NULL,"x>0", NULL,"-s", NULL, "how many std.dev.'s big error bars should be", 1 },
93 { "--interval", eslARG_REAL,"0.95",NULL,"0<=x<=1",NULL,NULL,"-s", "confidence interval width for error bars", 1 },
94 { "--mer", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "don't construct a plot, summarize MER instead", 1 },
95 { "--Ethresh",eslARG_REAL, "1.", NULL,"x>0", NULL, NULL,"--mer", "don't construct a plot, print avg num FNs/FPs w/E < <x>", 1 },
96 { 0,0,0,0,0,0,0,0,0,0 },
97 };
98
99
100 /* The FP/query x-axis is discretized into <nxpts> points, evenly spaced on a log scale.
101 *
102 * To calculate FP/query threshold for a point i: 10^{ (base+i) / nsteps }
103 * To convert a FP/query value x to a bin i: ceil(log10(x) * nsteps)
104 */
105 struct oneplot_s {
106 double *tp; /* yaxis values, [0..nxpts-1]; # of FNs <= given FP/query on x-axis */
107 int base; /* scaled integer offset of bin #0 in tp */
108 int nsteps; /* resolution of logarithmic x-axis: # of evenly spaced points per 10x */
109 int nxpts; /* total # of points on axis */
110 double totalpos; /* total # of positives possible in this bootstrap sample */
111 double mer; /* MER: minimum error rate, sum of FP and FN over choice of all possible thresholds */
112 double mer_thr; /* MER threshold */
113 double mer_fn; /* number of false negatives at MER threshold */
114 double mer_fp; /* number of false positives at MER threshold */
115 double Ethresh; /* E-value threshold for Ethresh_fn and Ethresh_fp */
116 double Ethresh_fn; /* number of true positives with E-values <= Ethresh */
117 double Ethresh_fp; /* number of false positives with E-values <= Ethresh */
118 };
119
120 struct result_s {
121 double E; /* E-value */
122 int qidx; /* index of query */
123 int tidx; /* index of matching seq: 0..npos-1 for positives */
124 int class; /* +1 = positive; -1 = negative; 0 = ignore */
125 };
126
127
128
129 static int parse_tblfile(char *tblfile, ESL_KEYHASH *kh);
130 static int parse_results_rmark(char *resfile, int **pni, ESL_KEYHASH *modelkh, ESL_KEYHASH *poskh, struct result_s **ret_r, int *ret_nr, int *ret_nneg);
131 static int classify_pair_by_names_and_strand(const char *query, const char *target, const char *strand);
132 static double weighted_total_positives(int **pni, double *queryp, int nq, double *seqp, int npos, int nseq);
133 static struct oneplot_s *create_plot(ESL_GETOPTS *go, int nq);
134 static void destroy_plot(struct oneplot_s *plot);
135 static void make_plot(struct result_s *rp, int nr, int **pni, double *queryp, int nq, double *seqp, int nseq, int npos,
136 struct oneplot_s *plot);
137 static void write_plot (FILE *fp, struct oneplot_s *plot);
138 static void write_mer (FILE *fp, struct oneplot_s *plot);
139 static void write_Ethresh (FILE *fp, struct oneplot_s *plot);
140 static void summary_graph(ESL_GETOPTS *go, FILE *fp, struct oneplot_s *plot, double **yv);
141 static void summary_mer (ESL_GETOPTS *go, FILE *fp, struct oneplot_s *plot, double *mervec, double *merthrvec, double *merfpvec, double *merfnvec);
142 static void summary_Ethresh(ESL_GETOPTS *go, FILE *fp, struct oneplot_s *plot, double *Ethresh_fn_vec, double *Ethresh_fp_vec);
143
144 static void
145 cmdline_failure(char *argv0, char *format, ...)
146 {
147 va_list argp;
148 va_start(argp, format);
149 vfprintf(stderr, format, argp);
150 va_end(argp);
151 esl_usage(stdout, argv0, usage);
152 printf("\nTo see more help on available options, do %s -h\n\n", argv0);
153 exit(1);
154 }
155
156 static void
157 cmdline_help(char *argv0, ESL_GETOPTS *go)
158 {
159 esl_banner(stdout, argv0, banner);
160 esl_usage (stdout, argv0, usage);
161 puts("\n where options are:");
162 esl_opt_DisplayHelp(stdout, go, 1, 2, 80);
163 exit(0);
164 }
165
166 int
167 main(int argc, char **argv)
168 {
169 ESL_GETOPTS *go = NULL;
170 ESL_KEYHASH *qkh = esl_keyhash_Create();
171 ESL_KEYHASH *poskh = esl_keyhash_Create();
172 ESL_RANDOMNESS *r = NULL;
173 char *pmarkbase = NULL;
174 char *posfile = NULL;
175 char *modelfile = NULL;
176 char *resfile = NULL;
177 struct oneplot_s *plot = NULL;
178 struct result_s *rp = NULL;
179 int **pni = NULL;
180 double **yv = NULL; /* yv[0..nxpts-1][0..nboots-1]: vector of bootstrapped samples at each xaxis point */
181 double *mervec = NULL; /* [0..nboots-1]: MER of bootstrapped samples */
182 double *merthrvec = NULL; /* [0..nboots-1]: MER threshold of bootstrapped samples */
183 double *merfpvec = NULL; /* [0..nboots-1]: MER false positives of bootstrapped samples */
184 double *merfnvec = NULL; /* [0..nboots-1]: MER false negatives of bootstrapped samples */
185 double *Ethresh_fn_vec = NULL; /* [0..nboots-1]: num FNs <= Ethresh of bootstrapped samples */
186 double *Ethresh_fp_vec = NULL; /* [0..nboots-1]: num FPs <= Ethresh of bootstrapped samples */
187 int nq, npos, nneg, nseq;
188 int nresults = 0;
189 int nboots;
190 double *queryp;
191 double *seqp;
192 int i,j;
193 int xi;
194
195 /* Parse command line */
196 go = esl_getopts_Create(options);
197 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) cmdline_failure(argv[0], "Failed to parse command line: %s\n", go->errbuf);
198 if (esl_opt_VerifyConfig(go) != eslOK) cmdline_failure(argv[0], "Error in app configuration: %s\n", go->errbuf);
199 if (esl_opt_GetBoolean(go, "-h")) cmdline_help(argv[0], go);
200 if (esl_opt_ArgNumber(go) != 2) cmdline_failure(argv[0], "Incorrect number of command line arguments\n");
201 pmarkbase = esl_opt_GetArg(go, 1);
202 resfile = esl_opt_GetArg(go, 2);
203
204 nboots = esl_opt_GetInteger(go, "-N");
205
206 /* Set up the RNG */
207 if (esl_opt_IsDefault(go, "--seed")) r = esl_randomness_CreateTimeseeded();
208 else r = esl_randomness_Create(esl_opt_GetInteger(go, "--seed"));
209
210 /* Read the queries and positives into hash tables, and count them. */
211 esl_FileNewSuffix(pmarkbase, "tbl", &modelfile); parse_tblfile(modelfile, qkh); free(modelfile);
212 esl_FileNewSuffix(pmarkbase, "pos", &posfile); parse_tblfile(posfile, poskh); free(posfile);
213 nq = esl_keyhash_GetNumber(qkh);
214 npos = esl_keyhash_GetNumber(poskh);
215
216 /* Create a [0..nq-1]x[0..pos-1] matrix preclassifying each pair as +1 (positive), -1 (negative), or 0 (ignore) */
217 if ((pni = malloc(sizeof(int *) * nq)) == NULL) esl_fatal("malloc failed");
218 for (i = 0; i < nq; i++)
219 {
220 if ((pni[i] = malloc(sizeof(int) * npos)) == NULL) esl_fatal("malloc failed");
221 for (j = 0; j < npos; j++)
222 pni[i][j] = classify_pair_by_names_and_strand(esl_keyhash_Get(qkh, i), esl_keyhash_Get(poskh, j), "same");
223 }
224
225 /* Read and code the .pout file; assigning positives, negatives to the results */
226 parse_results_rmark(resfile, pni, qkh, poskh, &rp, &nresults, &nneg);
227 nseq = npos+nneg;
228
229 /* Allocate for the bootstrap weights on queries, seqs */
230 if ((queryp = malloc(sizeof(double) * nq)) == NULL) esl_fatal("malloc failed");
231 if ((seqp = malloc(sizeof(double) * nseq)) == NULL) esl_fatal("malloc failed");
232
233 /* In seqp, 0..npos-1 are the positives; npos..nseq-1 are the negatives.
234 */
235
236 /* Figure out the coordinate system for the plot's xaxis; then
237 * allocate for a single plot sample in <plot>, as well as for
238 * storing all the bootstrap results in <yv>. The <plot>
239 * holds the information about the x coordinate system.
240 */
241 plot = create_plot(go, nq);
242
243 if ((yv = malloc(sizeof(double *) * plot->nxpts)) == NULL) esl_fatal("malloc failed");
244 for (xi = 0; xi < plot->nxpts; xi++)
245 if ((yv[xi] = malloc(sizeof(double *) * nboots)) == NULL) esl_fatal("malloc failed");
246 if ((mervec = malloc(sizeof(double) * nboots)) == NULL) esl_fatal("malloc failed");
247 if ((merthrvec = malloc(sizeof(double) * nboots)) == NULL) esl_fatal("malloc failed");
248 if ((merfpvec = malloc(sizeof(double) * nboots)) == NULL) esl_fatal("malloc failed");
249 if ((merfnvec = malloc(sizeof(double) * nboots)) == NULL) esl_fatal("malloc failed");
250 if ((Ethresh_fn_vec = malloc(sizeof(double) * nboots)) == NULL) esl_fatal("malloc failed");
251 if ((Ethresh_fp_vec = malloc(sizeof(double) * nboots)) == NULL) esl_fatal("malloc failed");
252
253 /* "Bayesian" bootstraps: */
254 if (! esl_opt_GetBoolean(go, "-n"))
255 {
256 for (i = 0; i < nboots; i++)
257 {
258 esl_dirichlet_DSampleUniform(r, nq, queryp);
259 esl_dirichlet_DSampleUniform(r, nseq, seqp);
260
261 make_plot(rp, nresults, pni, queryp, nq, seqp, nseq, npos, plot);
262
263 /* Plot or store this bootstrap sample. */
264 if (esl_opt_GetBoolean(go, "-a")) {
265 if (esl_opt_GetBoolean(go, "--mer")) { write_mer (stdout, plot); }
266 else if (esl_opt_IsUsed (go, "--Ethresh")) { write_Ethresh (stdout, plot); }
267 else { write_plot (stdout, plot); }
268 }
269 else
270 {
271 for (xi = 0; xi < plot->nxpts; xi++)
272 yv[xi][i] = plot->tp[xi] / plot->totalpos;
273 mervec[i] = plot->mer;
274 merthrvec[i] = plot->mer_thr;
275 merfpvec[i] = plot->mer_fp;
276 merfnvec[i] = plot->mer_fn;
277 Ethresh_fn_vec[i] = plot->Ethresh_fn;
278 Ethresh_fp_vec[i] = plot->Ethresh_fp;
279 }
280 }
281 }
282 else /* just plot the original data with no bootstraps */
283 {
284 make_plot(rp, nresults, pni, NULL, nq, NULL, nseq, npos, plot);
285 if (esl_opt_GetBoolean (go, "--mer")){ write_mer (stdout, plot); }
286 else if (esl_opt_IsUsed(go, "--Ethresh")) { write_Ethresh (stdout, plot); }
287 else { write_plot(stdout, plot); }
288 }
289
290
291 /* Summarize the bootstraps */
292 if (! esl_opt_GetBoolean(go, "-a") && ! esl_opt_GetBoolean(go, "-n") ) {
293 if(esl_opt_GetBoolean(go, "--mer")) { summary_mer (go, stdout, plot, mervec, merthrvec, merfpvec, merfnvec); }
294 else if(esl_opt_IsUsed(go, "--Ethresh")) { summary_Ethresh(go, stdout, plot, Ethresh_fn_vec, Ethresh_fp_vec); }
295 else { summary_graph (go, stdout, plot, yv); }
296 }
297
298 for (i = 0; i < nq; i++) free(pni[i]);
299 free(pni);
300 for (xi = 0; xi < plot->nxpts; xi++) free(yv[xi]);
301 free(yv);
302 free(mervec);
303 free(merthrvec);
304 free(merfpvec);
305 free(merfnvec);
306 free(Ethresh_fn_vec);
307 free(Ethresh_fp_vec);
308 destroy_plot(plot);
309 free(queryp);
310 free(seqp);
311 free(rp);
312 esl_keyhash_Destroy(poskh);
313 esl_keyhash_Destroy(qkh);
314 esl_randomness_Destroy(r);
315 esl_getopts_Destroy(go);
316 return 0;
317 }
318
319
320
321 static int
322 parse_tblfile(char *tblfile, ESL_KEYHASH *kh)
323 {
324 ESL_FILEPARSER *efp = NULL;
325 char *tok = NULL;
326 int toklen;
327
328 if (esl_fileparser_Open(tblfile, NULL, &efp) != eslOK) esl_fatal("failed to open pmark table %s", tblfile);
329 esl_fileparser_SetCommentChar(efp, '#');
330
331 while (esl_fileparser_NextLine(efp) == eslOK)
332 {
333 if (esl_fileparser_GetTokenOnLine(efp, &tok, &toklen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, tblfile);
334 if (esl_keyhash_Store(kh, tok, toklen, NULL) != eslOK) esl_fatal("failed to add %s to seq index", tok);
335 }
336 esl_fileparser_Close(efp);
337 return eslOK;
338 }
339
340
341 static int
342 classify_pair_by_names_and_strand(const char *query, const char *target, const char *strand)
343 {
344 int qlen = strlen(query);
345 int tlen = strlen(target);
346
347 if (tlen > qlen && strncmp(query, target, qlen) == 0 && target[qlen] == '/' && strncmp(strand, "same", 4) == 0)
348 return 1; /* this tests for <model> == <query_model> */
349 else if (strncmp(target, "decoy", 5) == 0)
350 return -1; /* matches a stretch of negative sequence, doesn't overlap any positive */
351 else
352 return 0; /* ignore, could be target == query, but strand != "same", or target != "decoy" && target != query */
353 }
354
355 /* Given bootstrap sampled weights, calculate the maximum # of positives possible */
356 static double
357 weighted_total_positives(int **pni, double *queryp, int nq, double *seqp, int npos, int nseq)
358 {
359 int q, t;
360 double total_pos = 0.0;
361
362 for (q = 0; q < nq; q++)
363 for (t = 0; t < npos; t++)
364 if (pni[q][t] == 1)
365 total_pos += queryp[q] * seqp[t];
366
367 return total_pos * nq * nseq;
368 }
369
370
371 /* The output files have format:
372 * <E-value> <bitscore> <target_from> <target_to> <target_name> <query_model> <matching_model>/<pos_idx_for_query> <strand>
373 *
374 * Example of <matching_model>/<pos_idx_for_query>: "tRNA/3":
375 * "tRNA" is <matching_model>, "3" is <pos_idx_for_query>, this is the third tRNA.
376 *
377 * A hit is a positive if <query_model> equals <matching_model> and <strand> is "same"
378 *
379 * A hit is a negative if the <matching_model> is "decoy" and <pos_idx_for_query> is "0".
380 *
381 * A hit is ignored if the <query_model> != <matching_model> OR
382 * <query_model> == <matching_model> but <strand> is "opposite".
383 *
384 * This information is parsed here, such that each pairwise comparison
385 * is stored as:
386 * qidx : index of the query model
387 * tidx : index of the target sequence
388 * E : E-value of the comparison; results are already sorted on this
389 */
390 static int
391 parse_results_rmark(char *resfile, int **pni, ESL_KEYHASH *qkh, ESL_KEYHASH *poskh, struct result_s **ret_r, int *ret_nr, int *ret_nneg)
392 {
393 ESL_FILEPARSER *efp = NULL;
394 char *tok = NULL;
395 char *match = NULL;
396 char *query = NULL;
397 char *strand = NULL;
398 int toklen;
399 int qlen, mlen, slen;
400 struct result_s *rp = NULL;
401 int ralloc = 0;
402 int nr = 0;
403 int nneg = 0;
404 int nq, npos; /* number of querys, number of targets */
405 int i; /* counter */
406 int **pos_exists; /* [0..q..nq-1][0..t..npos-1], 1 if we've seen a hit from query q to target t, 0 if not */
407
408 if (esl_fileparser_Open(resfile, NULL, &efp) != eslOK) esl_fatal("failed to open pmark results file %s", resfile);
409 esl_fileparser_SetCommentChar(efp, '#');
410
411 if ((rp = malloc(sizeof(struct result_s) * 256)) == NULL) esl_fatal("malloc failed");
412 ralloc = 256;
413
414 /* set up pos_exists matrix, to keep track of whether we've seen
415 * a hit from each query to each target. This allows us to disallow
416 * multiple hits from the same query to the same target.
417 */
418 nq = esl_keyhash_GetNumber(qkh);
419 npos = esl_keyhash_GetNumber(poskh);
420 if ((pos_exists = malloc(sizeof(int *) * nq)) == NULL) esl_fatal("malloc failed");
421 for(i = 0; i < nq; i++) {
422 if ((pos_exists[i] = malloc(sizeof(int) * npos)) == NULL) esl_fatal("malloc failed");
423 esl_vec_ISet(pos_exists[i], npos, 0);
424 }
425
426 while (esl_fileparser_NextLine(efp) == eslOK)
427 {
428 if (nr == ralloc) {
429 if ((rp = realloc(rp, sizeof(struct result_s) * ralloc * 2)) == NULL) esl_fatal("realloc failed");
430 ralloc *= 2;
431 }
432
433 if (esl_fileparser_GetTokenOnLine(efp, &tok, &toklen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* E-value => rp[nr].E */
434 rp[nr].E = atof(tok);
435 if (esl_fileparser_GetTokenOnLine(efp, &tok, &toklen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* bit score ignored */
436 if (esl_fileparser_GetTokenOnLine(efp, &tok, &toklen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* target from ignored */
437 if (esl_fileparser_GetTokenOnLine(efp, &tok, &toklen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* target to ignored */
438 if (esl_fileparser_GetTokenOnLine(efp, &tok, &toklen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* target name (e.g. rmark3-2) is ignored */
439 if (esl_fileparser_GetTokenOnLine(efp, &query, &qlen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* query name; will be converted to an index */
440 if (esl_fileparser_GetTokenOnLine(efp, &match, &mlen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* match name; will be converted to an index */
441 if (esl_fileparser_GetTokenOnLine(efp, &strand, &slen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* strand; will be used to determine pos/neg */
442
443 if (esl_keyhash_Lookup(qkh, query, qlen, &(rp[nr].qidx)) != eslOK) esl_fatal("failed to find query model %s in hash", query); /* query index */
444 rp[nr].class = classify_pair_by_names_and_strand(query, match, strand);
445 if (rp[nr].class == -1) /* negatives: increment nneg and offset the index by npos */
446 {
447 rp[nr].tidx = nneg + esl_keyhash_GetNumber(poskh);
448 nneg++;
449 }
450 else /* positives/ignores: look up in poskh */
451 {
452 if (esl_keyhash_Lookup(poskh, match, mlen, &(rp[nr].tidx)) != eslOK) esl_fatal("failed to find match seq %s in hash", match); /* target index */
453 if (rp[nr].class == 1) {
454 if(pos_exists[rp[nr].qidx][rp[nr].tidx]) {
455 /* we've already seen a better scoring hit for this query/target pair,
456 * make it an ignore */
457 rp[nr].class = 0;
458 }
459 pos_exists[rp[nr].qidx][rp[nr].tidx] = 1;
460 }
461 }
462 nr++;
463 }
464
465 *ret_r = rp;
466 *ret_nr = nr;
467 *ret_nneg = nneg;
468 for(i = 0; i < nq; i++) free(pos_exists[i]);
469 free(pos_exists);
470
471 esl_fileparser_Close(efp);
472 return eslOK;
473 }
474
475
476 static struct oneplot_s *
477 create_plot(ESL_GETOPTS *go, int nq)
478 {
479 struct oneplot_s *plot;
480 double minfp, maxfp;
481 int status;
482
483 ESL_ALLOC(plot, sizeof(struct oneplot_s));
484
485 if (esl_opt_IsDefault(go, "--min")) minfp = 1.0 / (double) nq;
486 else minfp = esl_opt_GetReal(go, "--min");
487
488 maxfp = esl_opt_GetReal(go, "--max");
489 plot->nsteps = esl_opt_GetInteger(go, "--steps");
490 plot->base = (int) floor(log10(minfp) * plot->nsteps);
491 plot->nxpts = (int) ceil(log10(maxfp) * plot->nsteps) - plot->base + 1;
492
493 ESL_ALLOC(plot->tp, sizeof(double) * plot->nxpts);
494
495 /* initialize */
496 plot->Ethresh = esl_opt_GetReal(go, "--Ethresh");
497 plot->Ethresh_fn = 0;
498 plot->Ethresh_fp = 0;
499
500 return plot;
501
502 ERROR:
503 destroy_plot(plot);
504 return NULL;
505 }
506
507 static void
508 destroy_plot(struct oneplot_s *plot)
509 {
510 if (plot == NULL) return;
511 if (plot->tp != NULL) free(plot->tp);
512 free(plot);
513 }
514
515
516 /* Given the results <rp> [0..nr-1],
517 * positive/ignore classifications pni[0..nq-1][0..npos-1]
518 * and bootstrap-sampled usage probabilities <queryp>, <seqp>,
519 * and a plot axis <plot> to store results in;
520 * calculate a new ROC plot for this bootstrap sample,
521 * and store it in <plot->tp>.
522 *
523 * As a special case, if <queryp> and/or <seqp> are NULL, calculate
524 * the ROC plot for the original data without bootstrapping.
525 */
526 static void
527 make_plot(struct result_s *rp, int nresults, int **pni, double *queryp, int nq, double *seqp, int nseq, int npos,
528 struct oneplot_s *plot)
529 {
530 double weight;
531 int xi, curr_xi;
532 double true_pos, false_pos, false_neg;
533 double false_pos_per_q;
534 int j;
535
536 if (queryp != NULL && seqp != NULL)
537 plot->totalpos = weighted_total_positives(pni, queryp, nq, seqp, npos, nseq);
538 else
539 plot->totalpos = npos;
540
541 curr_xi = 0;
542 true_pos = false_pos = false_pos_per_q = 0.0;
543 false_neg = plot->totalpos;
544
545 for (j = 0; j < nresults; j++)
546 {
547 if (queryp != NULL && seqp != NULL)
548 weight = queryp[rp[j].qidx] * seqp[rp[j].tidx] * nseq * nq;
549 else
550 weight = 1.0;
551
552 if (rp[j].class == 1)
553 {
554 true_pos += weight;
555 false_neg -= weight;
556 plot->tp[curr_xi] = true_pos;
557 /*printf("pos %5d/%5d %3d %3d %g\n", (int) true_pos, j, rp[j].qidx, rp[j].tidx, rp[j].E);*/
558 }
559 else if (rp[j].class == -1)
560 {
561 false_pos += weight;
562 false_pos_per_q += weight / (double) nq; /* FP/query */
563
564 xi = (int) ceil(log10(false_pos_per_q) * plot->nsteps) - plot->base;
565
566 if (xi > curr_xi) {
567 for (curr_xi = curr_xi+1; curr_xi < xi && curr_xi < plot->nxpts; curr_xi++)
568 plot->tp[curr_xi] = true_pos;
569
570 if (curr_xi < plot->nxpts) plot->tp[curr_xi] = true_pos;
571 /*printf("neg %5d/%5d %3d %3d %g\n", (int) true_pos, j, rp[j].qidx, rp[j].tidx, rp[j].E);*/
572 }
573 }
574 else {
575 ;/*printf("ign %5s/%5d %3d %3d %g\n", "?", j, rp[j].qidx, rp[j].tidx, rp[j].E);*/
576 }
577 /* update MER (initialize it if first result) */
578 if (j == 0 || (false_pos + false_neg) < plot->mer) {
579 plot->mer = false_pos + false_neg;
580 plot->mer_fp = false_pos;
581 plot->mer_fn = false_neg;
582 plot->mer_thr = rp[j].E;
583 }
584 /* update number of FNs and FPs at or below <x> from --Ethresh <x> */
585 if (rp[j].E <= plot->Ethresh) {
586 plot->Ethresh_fn = false_neg;
587 plot->Ethresh_fp = false_pos;
588 }
589 if (curr_xi >= plot->nxpts) break;
590 }
591
592 /* Rarely, the plot won't have enough false positives to extend all the way to
593 * the left extreme of the x-axis; make sure we propagate the last true_pos */
594 for (curr_xi++; curr_xi < plot->nxpts; curr_xi++)
595 plot->tp[curr_xi] = true_pos;
596 }
597
598
599 static void
600 write_plot(FILE *fp, struct oneplot_s *plot)
601 {
602 int xi;
603 double false_pos;
604
605 for (xi = 0; xi < plot->nxpts; xi++)
606 {
607 false_pos = exp(log(10) * ((double) plot->base + (double) xi) / (double) plot->nsteps);
608 fprintf(fp, "%.5f %.5f\n", false_pos, plot->tp[xi] / plot->totalpos );
609 }
610 fprintf(fp, "&\n");
611 }
612
613
614 static void
615 write_mer(FILE *fp, struct oneplot_s *plot)
616 {
617 fprintf(fp, "MER: %5.1f ", plot->mer);
618 fprintf(fp, "FN: %5.1f ", plot->mer_fn);
619 fprintf(fp, "FP: %5.1f ", plot->mer_fp);
620 fprintf(fp, "THR: %5.3f\n", plot->mer_thr);
621 }
622
623 static void
624 write_Ethresh(FILE *fp, struct oneplot_s *plot)
625 {
626 fprintf(fp, "E-value-threshold: %g ", plot->Ethresh);
627 fprintf(fp, "FN<=E: %5.1f ", plot->Ethresh_fn);
628 fprintf(fp, "FP<=E: %5.1f\n", plot->Ethresh_fp);
629 }
630
631 static void
632 summary_graph(ESL_GETOPTS *go, FILE *fp, struct oneplot_s *plot, double **yv)
633 {
634 int nboots = esl_opt_GetInteger(go, "-N");
635 int by_stddev = esl_opt_GetBoolean(go, "-s");
636 double confidence_interval = esl_opt_GetReal (go, "--interval");
637 double nsd = esl_opt_GetReal (go, "--nsd");
638 int xi;
639 double false_pos;
640 double mean, var;
641 int ntail;
642
643 for (xi = 0; xi < plot->nxpts; xi++)
644 {
645 false_pos = exp(log(10) * ((double) plot->base + (double) xi) / (double) plot->nsteps);
646 esl_stats_DMean(yv[xi], nboots, &mean, &var);
647
648 /* the dy's in xmgrace xydydy format are dy's, and in order upper, lower */
649 if (by_stddev)
650 {
651 fprintf(fp, "%.5f %.5f %.5f %.5f\n", false_pos, mean, nsd*sqrt(var), nsd*sqrt(var));
652 }
653 else
654 {
655 esl_vec_DSortIncreasing(yv[xi], nboots);
656 ntail = (int) ((double) nboots * (1.0 - confidence_interval) / 2.0);
657
658 fprintf(fp, "%.5f %.5f %.5f %.5f\n",
659 false_pos, mean,
660 yv[xi][nboots-ntail] - mean,
661 mean - yv[xi][ntail]);
662 }
663 }
664 fprintf(fp, "&\n");
665 }
666
667
668 static void
669 summary_mer(ESL_GETOPTS *go, FILE *fp, struct oneplot_s *plot, double *mervec, double *merthrvec, double *merfpvec, double *merfnvec)
670 {
671 int nboots = esl_opt_GetInteger(go, "-N");
672 int by_stddev = esl_opt_GetBoolean(go, "-s");
673 double confidence_interval = esl_opt_GetReal (go, "--interval");
674 double nsd = esl_opt_GetReal (go, "--nsd");
675 double mermean, mervar;
676 double merthrmean, merthrvar;
677 double merfpmean, merfpvar;
678 double merfnmean, merfnvar;
679 int ntail;
680
681 esl_stats_DMean(mervec, nboots, &mermean, &mervar);
682 esl_stats_DMean(merthrvec, nboots, &merthrmean, &merthrvar);
683 esl_stats_DMean(merfpvec, nboots, &merfpmean, &merfpvar);
684 esl_stats_DMean(merfnvec, nboots, &merfnmean, &merfnvar);
685
686 esl_vec_DSortIncreasing(mervec, nboots);
687 esl_vec_DSortIncreasing(merthrvec, nboots);
688 esl_vec_DSortIncreasing(merfpvec, nboots);
689 esl_vec_DSortIncreasing(merfnvec, nboots);
690
691 ntail = (int) ((double) nboots * (1.0 - confidence_interval) / 2.0);
692
693 if (by_stddev) {
694 fprintf(fp, "[MER: %5.1f %5.1f %5.1f] ", mermean - nsd*sqrt(mervar), mermean, mermean + nsd*sqrt(mervar));
695 fprintf(fp, "[FP: %5.1f %5.1f %5.1f] ", merfpmean - nsd*sqrt(merfpvar), merfpmean, merfpmean + nsd*sqrt(merfpvar));
696 fprintf(fp, "[FN: %5.1f %5.1f %5.1f] ", merfnmean - nsd*sqrt(merfnvar), merfnmean, merfnmean + nsd*sqrt(merfnvar));
697 fprintf(fp, "[THR: %5.3f %5.3f %5.3f]\n", merthrmean - nsd*sqrt(merthrvar), merthrmean, merthrmean + nsd*sqrt(merthrvar));
698 }
699 else {
700 fprintf(fp, "[MER: %5.1f %5.1f %5.1f] ", mervec[ntail], mermean, mervec[nboots-ntail]);
701 fprintf(fp, "[FN: %5.1f %5.1f %5.1f] ", merfnvec[ntail], merfnmean, merfnvec[nboots-ntail]);
702 fprintf(fp, "[FP: %5.1f %5.1f %5.1f] ", merfpvec[ntail], merfpmean, merfpvec[nboots-ntail]);
703 fprintf(fp, "[THR: %5.3f %5.3f %5.3f]\n", merthrvec[ntail], merthrmean, merthrvec[nboots-ntail]);
704 }
705 }
706
707
708 static void
709 summary_Ethresh(ESL_GETOPTS *go, FILE *fp, struct oneplot_s *plot, double *Ethresh_fn_vec, double *Ethresh_fp_vec)
710 {
711 int nboots = esl_opt_GetInteger(go, "-N");
712 int by_stddev = esl_opt_GetBoolean(go, "-s");
713 double confidence_interval = esl_opt_GetReal (go, "--interval");
714 double nsd = esl_opt_GetReal (go, "--nsd");
715 double fnmean, fpmean, fnvar, fpvar;
716 int ntail;
717
718 esl_stats_DMean(Ethresh_fn_vec, nboots, &fnmean, &fnvar);
719 esl_stats_DMean(Ethresh_fp_vec, nboots, &fpmean, &fpvar);
720
721 esl_vec_DSortIncreasing(Ethresh_fn_vec, nboots);
722 esl_vec_DSortIncreasing(Ethresh_fp_vec, nboots);
723
724 ntail = (int) ((double) nboots * (1.0 - confidence_interval) / 2.0);
725
726 fprintf(fp, "[ETHRESH: %g] ", esl_opt_GetReal(go, "--Ethresh"));
727 if (by_stddev) {
728 fprintf(fp, "[E-TP: %5.1f %5.1f %5.1f] ", fnmean - nsd*sqrt(fnvar), fnmean, fnmean + nsd*sqrt(fnvar));
729 fprintf(fp, "[E-FP: %5.1f %5.1f %5.1f]\n", fpmean - nsd*sqrt(fpvar), fpmean, fpmean + nsd*sqrt(fpvar));
730 }
731 else {
732 fprintf(fp, "[E-TP: %5.1f %5.1f %5.1f] ", Ethresh_fn_vec[ntail], fnmean, Ethresh_fn_vec[nboots-ntail]);
733 fprintf(fp, "[E-FP: %5.1f %5.1f %5.1f]\n", Ethresh_fp_vec[ntail], fpmean, Ethresh_fp_vec[nboots-ntail]);
734 }
735 }