Debian Codegraph @

hmmer/profmark/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 * The <.out file> from a profmark benchmark consists of lines:
5 * <E-value> <bitscore> <target_sequence> <query_model>
6 * Target sequence names are either
7 * decoy\d+ for negatives (decoys); example: decoy75382
8 * <model>/<#>[/<to>-<from>]+ for positives; example: CHP02677/42/297-773/781-1257
9 *
10 * The <.out> file (or stream) must be sorted by E-value, with best
11 * (lowest) E-values first.
12 *
13 * The format of these names is important - true/false
14 * positive/negatives are classified by matching query model name to
15 * the format of the target sequence name. A hit is a positive if
16 * <query_model> matches the <model> component of the target name -
17 * i.e. the embedded domains in the target are homologous to this
18 * query. A hit is a negative if the target name matches /decoy\d+/.
19 * A hit is ignored if the target contains domains (isn't a decoy) but
20 * <query_model> doesn't match <model>.
21 *
22 * The program also needs to find the query, positive, and negative
23 * tables for the benchmark that was run. It looks for these by
24 * appending ".tbl", ".neg", and ".pos" to the <pmark> argument;
25 * that is:
26 * <pmark>.tbl contains one line per query: 1st field is name of query
27 * <pmark>.pos contains one line per positive: 1st field is name of sequence
28 * <pmark>.neg contains one line per decoy: 1st field is name of decoy
29 *
30 * The program calculates a plot of fractional coverage of the positives
31 * (on the Y-axis; range 0..1) versus errors per query (on the X-axis;
32 * ranging from 1/(# of models) to 10.0 by default).
33 *
34 * The default output is an XMGRACE xydydy file, with points
35 * representing mean coverage in the bootstrap samples, and error bars
36 * representing a 95% confidence interval.
37 *
38 * A typical command line, after having run a benchmark on "pmark" under
39 * MPI with many output files:
40 *
41 * cat *.out | sort -g | ./rocplot pmark - > results.xy
42 * xmgrace -settype xydydy results.xy
43 *
44 * SRE, Wed Jun 18 13:37:31 2008 [Janelia]
45 */
46 #include <esl_config.h>
47
48 #include <stdlib.h>
49 #include <stdio.h>
50 #include <string.h>
51 #include <math.h>
52
53 #include "easel.h"
54 #include "esl_dirichlet.h"
55 #include "esl_getopts.h"
56 #include "esl_keyhash.h"
57 #include "esl_random.h"
58 #include "esl_stats.h"
59 #include "esl_vectorops.h"
60
61
62 static char banner[] = "construct a ROC plot of profmark results, using Bayesian bootstrapping";
63 static char usage[] = "[options] <profmark_basename> <.out file>\n";
64
65 static ESL_OPTIONS options[] = {
66 /* name type default env range togs reqs incomp help docgroup */
67 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "help; show brief info on version and usage", 1 },
68 { "-a", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "all: plot all bootstrap samples individually", 1 },
69 { "-n", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "plot original data, without any bootstrapping", 1 },
70 { "-s", eslARG_NONE, FALSE, NULL, NULL, NULL,NULL, NULL, "plot error bars by std. dev. not confidence interval", 1 },
71 { "-N", eslARG_INT, "500", NULL, NULL, NULL,NULL, NULL, "number of bootstrap samples to take", 1 },
72 { "--min", eslARG_REAL, NULL, NULL, NULL, NULL,NULL, NULL, "set minimum x-axis value (FPs/query) to plot", 1 },
73 { "--max", eslARG_REAL, "10.", NULL, NULL, NULL,NULL, NULL, "set maximum x-axis value (FPs/query) to plot", 1 },
74 { "--steps", eslARG_INT, "10", NULL, NULL, NULL,NULL, NULL, "set number of steps to plot per 10x on x-axis", 1 },
75 { "--seed", eslARG_INT, FALSE, NULL,"n>0", NULL,NULL, NULL, "set random number generator's seed to <n>", 1 },
76 { "--nsd", eslARG_REAL, "3.", NULL,"x>0", NULL,"-s", NULL, "how many std.dev.'s big error bars should be", 1 },
77 { "--interval", eslARG_REAL,"0.95",NULL,"0<=x<=1",NULL,NULL,"-s", "confidence interval width for error bars", 1 },
78 { 0,0,0,0,0,0,0,0,0,0 },
79 };
80
81
82 /* The FP/query x-axis is discretized into <nxpts> points, evenly spaced on a log scale.
83 *
84 * To calculate FP/query threshold for a point i: 10^{ (base+i) / nsteps }
85 * To convert a FP/query value x to a bin i: ceil(log10(x) * nsteps)
86 */
87 struct oneplot_s {
88 double *tp; /* yaxis values, [0..nxpts-1]; # of TPs <= given FP/query on x-axis */
89 int base; /* scaled integer offset of bin #0 in tp */
90 int nsteps; /* resolution of logarithmic x-axis: # of evenly spaced points per 10x */
91 int nxpts; /* total # of points on axis */
92 double totalpos; /* total # of positives possible in this bootstrap sample */
93 };
94
95 struct result_s {
96 double E; /* E-value */
97 int qidx; /* index of query */
98 int tidx; /* index of target seq: 0..npos-1 for positives; npos..npos+nneg-1 for negatives */
99 int class; /* +1 = positive; -1 = negative; 0 = ignore */
100 };
101
102
103
104 static int parse_tblfile(char *tblfile, ESL_KEYHASH *kh);
105 static int parse_results(char *resfile, int **pni, ESL_KEYHASH *modelkh, ESL_KEYHASH *poskh, ESL_KEYHASH *negkh, struct result_s **ret_r, int *ret_nr);
106 static int classify_pair_by_names(const char *query, const char *target);
107 static double weighted_total_positives(int **pni, double *queryp, int nq, double *seqp, int npos, int nseq);
108 static struct oneplot_s *create_plot(ESL_GETOPTS *go, int nq);
109 static void destroy_plot(struct oneplot_s *plot);
110 static void make_plot(struct result_s *rp, int nr, int **pni, double *queryp, int nq, double *seqp, int nseq, int npos,
111 struct oneplot_s *plot);
112 static void write_plot(FILE *fp, struct oneplot_s *plot);
113 static void summary_graph(ESL_GETOPTS *go, FILE *fp, struct oneplot_s *plot, double **yv);
114
115
116 static void
117 cmdline_failure(char *argv0, char *format, ...)
118 {
119 va_list argp;
120 va_start(argp, format);
121 vfprintf(stderr, format, argp);
122 va_end(argp);
123 esl_usage(stdout, argv0, usage);
124 printf("\nTo see more help on available options, do %s -h\n\n", argv0);
125 exit(1);
126 }
127
128 static void
129 cmdline_help(char *argv0, ESL_GETOPTS *go)
130 {
131 esl_banner(stdout, argv0, banner);
132 esl_usage (stdout, argv0, usage);
133 puts("\n where options are:");
134 esl_opt_DisplayHelp(stdout, go, 1, 2, 80);
135 exit(0);
136 }
137
138 int
139 main(int argc, char **argv)
140 {
141 ESL_GETOPTS *go = NULL;
142 ESL_KEYHASH *qkh = esl_keyhash_Create();
143 ESL_KEYHASH *poskh = esl_keyhash_Create();
144 ESL_KEYHASH *negkh = esl_keyhash_Create();
145 ESL_RANDOMNESS *r = NULL;
146 char *pmarkbase = NULL;
147 char *negfile = NULL;
148 char *posfile = NULL;
149 char *modelfile = NULL;
150 char *resfile = NULL;
151 struct oneplot_s *plot = NULL;
152 struct result_s *rp = NULL;
153 int **pni = NULL;
154 double **yv = NULL; /* yv[0..nxpts-1][0..nboots-1]: vector of bootstrapped samples at each xaxis point */
155 int nq, npos, nneg, nseq;
156 int nresults = 0;
157 int nboots;
158 double *queryp;
159 double *seqp;
160 int i,j;
161 int xi;
162
163 /* Parse command line */
164 go = esl_getopts_Create(options);
165 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) cmdline_failure(argv[0], "Failed to parse command line: %s\n", go->errbuf);
166 if (esl_opt_VerifyConfig(go) != eslOK) cmdline_failure(argv[0], "Error in app configuration: %s\n", go->errbuf);
167 if (esl_opt_GetBoolean(go, "-h")) cmdline_help(argv[0], go);
168 if (esl_opt_ArgNumber(go) != 2) cmdline_failure(argv[0], "Incorrect number of command line arguments\n");
169 pmarkbase = esl_opt_GetArg(go, 1);
170 resfile = esl_opt_GetArg(go, 2);
171
172 nboots = esl_opt_GetInteger(go, "-N");
173
174 /* Set up the RNG */
175 if (esl_opt_IsDefault(go, "--seed")) r = esl_randomness_CreateTimeseeded();
176 else r = esl_randomness_Create(esl_opt_GetInteger(go, "--seed"));
177
178 /* Read the queries, positives, and decoys into hash tables, and count them. */
179 esl_FileNewSuffix(pmarkbase, "tbl", &modelfile); parse_tblfile(modelfile, qkh); free(modelfile);
180 esl_FileNewSuffix(pmarkbase, "pos", &posfile); parse_tblfile(posfile, poskh); free(posfile);
181 esl_FileNewSuffix(pmarkbase, "neg", &negfile); parse_tblfile(negfile, negkh); free(negfile);
182 nq = esl_keyhash_GetNumber(qkh);
183 npos = esl_keyhash_GetNumber(poskh);
184 nneg = esl_keyhash_GetNumber(negkh);
185 nseq = npos+nneg;
186
187 /* Create a [0..nq-1]x[0..pos-1] matrix preclassifying each pair as +1 (positive), -1 (negative), or 0 (ignore) */
188 if ((pni = malloc(sizeof(int *) * nq)) == NULL) esl_fatal("malloc failed");
189 for (i = 0; i < nq; i++)
190 {
191 if ((pni[i] = malloc(sizeof(int) * npos)) == NULL) esl_fatal("malloc failed");
192 for (j = 0; j < npos; j++)
193 pni[i][j] = classify_pair_by_names(esl_keyhash_Get(qkh, i), esl_keyhash_Get(poskh, j));
194 }
195
196 /* Read and code the .out file; assigning positives, negatives to the results */
197 parse_results(resfile, pni, qkh, poskh, negkh, &rp, &nresults);
198
199 /* Allocate for the bootstrap weights on queries, seqs */
200 if ((queryp = malloc(sizeof(double) * nq)) == NULL) esl_fatal("malloc failed");
201 if ((seqp = malloc(sizeof(double) * nseq)) == NULL) esl_fatal("malloc failed");
202
203 /* In seqp, 0..npos-1 are the positives; npos..nseq-1 are the negatives.
204 * To convert a negative's key index to the nseq index, add npos to it.
205 */
206
207 /* Figure out the coordinate system for the plot's xaxis; then
208 * allocate for a single plot sample in <plot>, as well as for
209 * storing all the bootstrap results in <yv>. The <plot>
210 * holds the information about the x coordinate system.
211 */
212 plot = create_plot(go, nq);
213
214 if ((yv = malloc(sizeof(double *) * plot->nxpts)) == NULL) esl_fatal("malloc failed");
215 for (xi = 0; xi < plot->nxpts; xi++)
216 if ((yv[xi] = malloc(sizeof(double *) * nboots)) == NULL) esl_fatal("malloc failed");
217
218
219 /* "Bayesian" bootstraps: */
220 if (! esl_opt_GetBoolean(go, "-n"))
221 {
222 for (i = 0; i < nboots; i++)
223 {
224 esl_dirichlet_DSampleUniform(r, nq, queryp);
225 esl_dirichlet_DSampleUniform(r, nseq, seqp);
226
227 make_plot(rp, nresults, pni, queryp, nq, seqp, nseq, npos, plot);
228
229 /* Plot or store this bootstrap sample. */
230 if (esl_opt_GetBoolean(go, "-a"))
231 write_plot(stdout, plot);
232 else
233 {
234 for (xi = 0; xi < plot->nxpts; xi++)
235 yv[xi][i] = plot->tp[xi] / plot->totalpos;
236 }
237 }
238 }
239 else /* just plot the original data with no bootstraps */
240 {
241 make_plot(rp, nresults, pni, NULL, nq, NULL, nseq, npos, plot);
242 write_plot(stdout, plot);
243 }
244
245 /* Summarize the bootstraps */
246 if (! esl_opt_GetBoolean(go, "-a") && ! esl_opt_GetBoolean(go, "-n") )
247 summary_graph(go, stdout, plot, yv);
248
249 for (i = 0; i < nq; i++) free(pni[i]);
250 free(pni);
251 for (xi = 0; xi < plot->nxpts; xi++) free(yv[xi]);
252 free(yv);
253 destroy_plot(plot);
254 free(queryp);
255 free(seqp);
256 free(rp);
257 esl_keyhash_Destroy(negkh);
258 esl_keyhash_Destroy(poskh);
259 esl_keyhash_Destroy(qkh);
260 esl_randomness_Destroy(r);
261 esl_getopts_Destroy(go);
262 return 0;
263 }
264
265
266
267 static int
268 parse_tblfile(char *tblfile, ESL_KEYHASH *kh)
269 {
270 ESL_FILEPARSER *efp = NULL;
271 char *tok = NULL;
272 int toklen;
273
274 if (esl_fileparser_Open(tblfile, NULL, &efp) != eslOK) esl_fatal("failed to open pmark table %s", tblfile);
275 esl_fileparser_SetCommentChar(efp, '#');
276
277 while (esl_fileparser_NextLine(efp) == eslOK)
278 {
279 if (esl_fileparser_GetTokenOnLine(efp, &tok, &toklen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, tblfile);
280 if (esl_keyhash_Store(kh, tok, toklen, NULL) != eslOK) esl_fatal("failed to add %s to seq index", tok);
281 }
282 esl_fileparser_Close(efp);
283 return eslOK;
284 }
285
286
287 static int
288 classify_pair_by_names(const char *query, const char *target)
289 {
290 int qlen = strlen(query);
291 int tlen = strlen(target);
292
293 if (tlen > qlen && strncmp(query, target, qlen) == 0 && target[qlen] == '/')
294 return 1; /* this tests for <model> == <query_model> */
295 else if (strncmp(target, "decoy", 5) == 0)
296 return -1; /* or a decoy */
297 else
298 return 0; /* ignore */
299 }
300
301 /* Given bootstrap sampled weights, calculate the maximum # of positives possible */
302 static double
303 weighted_total_positives(int **pni, double *queryp, int nq, double *seqp, int npos, int nseq)
304 {
305 int q, t;
306 double total_pos = 0.0;
307
308 for (q = 0; q < nq; q++)
309 for (t = 0; t < npos; t++)
310 if (pni[q][t] == 1)
311 total_pos += queryp[q] * seqp[t];
312
313 return total_pos * nq * nseq;
314 }
315
316
317 /* The output files have format:
318 * <E-value> <bitscore> <target_sequence> <query_model>
319 *
320 * Target sequence names are either
321 * decoy\d+ for negatives (decoys); example: decoy75382
322 * <model>/<#>[/<to>-<from>]+ for positives; example: CHP02677/42/297-773/781-1257
323 *
324 * A hit is a positive if <query_model> matches the <model> component of the
325 * target name - i.e. the embedded domains in the target are homologous to this
326 * query.
327 *
328 * A hit is a negative if the target name matches /decoy\d+/.
329 *
330 * A hit is ignored if the target contains domains (isn't a decoy) but <query_model>
331 * doesn't match <model>.
332 *
333 * This information is parsed digested here, such that each pairwise comparison
334 * is stored as:
335 * qidx : index of the query model
336 * tidx : index of the target sequence
337 * E : E-value of the comparison; results are already sorted on this
338 */
339 static int
340 parse_results(char *resfile, int **pni, ESL_KEYHASH *qkh, ESL_KEYHASH *poskh, ESL_KEYHASH *negkh, struct result_s **ret_r, int *ret_nr)
341 {
342 ESL_FILEPARSER *efp = NULL;
343 char *tok = NULL;
344 char *target = NULL;
345 char *query = NULL;
346 int toklen;
347 int qlen, tlen;
348 struct result_s *rp = NULL;
349 int ralloc = 0;
350 int nr = 0;
351
352 if (esl_fileparser_Open(resfile, NULL, &efp) != eslOK) esl_fatal("failed to open pmark results file %s", resfile);
353 esl_fileparser_SetCommentChar(efp, '#');
354
355 if ((rp = malloc(sizeof(struct result_s) * 256)) == NULL) esl_fatal("malloc failed");
356 ralloc = 256;
357
358 while (esl_fileparser_NextLine(efp) == eslOK)
359 {
360 if (nr == ralloc) {
361 if ((rp = realloc(rp, sizeof(struct result_s) * ralloc * 2)) == NULL) esl_fatal("realloc failed");
362 ralloc *= 2;
363 }
364
365 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 */
366 rp[nr].E = atof(tok);
367 if (esl_fileparser_GetTokenOnLine(efp, &tok, &toklen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* bit score ignored */
368 if (esl_fileparser_GetTokenOnLine(efp, &target, &tlen) != eslOK) esl_fatal("failed to parse line %d of %s", efp->linenumber, resfile); /* target name; will be converted to an index */
369 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 */
370 if (esl_keyhash_Lookup(qkh, query, qlen, &(rp[nr].qidx)) != eslOK) esl_fatal("failed to find query model %s in hash", query); /* query index */
371 rp[nr].class = classify_pair_by_names(query, target);
372
373 if (rp[nr].class == -1) /* negatives: look up in negkh, and offset the index by npos */
374 {
375 if (esl_keyhash_Lookup(negkh, target, tlen, &(rp[nr].tidx)) != eslOK) esl_fatal("failed to find target seq %s in hash", target); /* target index */
376 rp[nr].tidx += esl_keyhash_GetNumber(poskh);
377 }
378 else /* positives/ignores: look up in poskh */
379 {
380 if (esl_keyhash_Lookup(poskh, target, tlen, &(rp[nr].tidx)) != eslOK) esl_fatal("failed to find target seq %s in hash", target); /* target index */
381 }
382 nr++;
383 }
384
385 *ret_r = rp;
386 *ret_nr = nr;
387 esl_fileparser_Close(efp);
388 return eslOK;
389 }
390
391
392 static struct oneplot_s *
393 create_plot(ESL_GETOPTS *go, int nq)
394 {
395 struct oneplot_s *plot;
396 double minfp, maxfp;
397 int status;
398
399 ESL_ALLOC(plot, sizeof(struct oneplot_s));
400
401 if (esl_opt_IsDefault(go, "--min")) minfp = 1.0 / (double) nq;
402 else minfp = esl_opt_GetReal(go, "--min");
403
404 maxfp = esl_opt_GetReal(go, "--max");
405 plot->nsteps = esl_opt_GetInteger(go, "--steps");
406 plot->base = (int) floor(log10(minfp) * plot->nsteps);
407 plot->nxpts = (int) ceil(log10(maxfp) * plot->nsteps) - plot->base + 1;
408
409 ESL_ALLOC(plot->tp, sizeof(double) * plot->nxpts);
410
411 return plot;
412
413 ERROR:
414 destroy_plot(plot);
415 return NULL;
416 }
417
418 static void
419 destroy_plot(struct oneplot_s *plot)
420 {
421 if (plot == NULL) return;
422 if (plot->tp != NULL) free(plot->tp);
423 free(plot);
424 }
425
426
427 /* Given the results <rp> [0..nr-1],
428 * positive/ignore classifications pni[0..nq-1][0..npos-1]
429 * and bootstrap-sampled usage probabilities <queryp>, <seqp>,
430 * and a plot axis <plot> to store results in;
431 * calculate a new ROC plot for this bootstrap sample,
432 * and store it in <plot->tp>.
433 *
434 * As a special case, if <queryp> and/or <seqp> are NULL, calculate
435 * the ROC plot for the original data without bootstrapping.
436 */
437 static void
438 make_plot(struct result_s *rp, int nresults, int **pni, double *queryp, int nq, double *seqp, int nseq, int npos,
439 struct oneplot_s *plot)
440 {
441 double weight;
442 int xi, curr_xi;
443 double true_pos, false_pos;
444 int j;
445
446 if (queryp != NULL && seqp != NULL)
447 plot->totalpos = weighted_total_positives(pni, queryp, nq, seqp, npos, nseq);
448 else
449 plot->totalpos = npos;
450
451 curr_xi = 0;
452 true_pos = false_pos = 0.0;
453
454 for (j = 0; j < nresults; j++)
455 {
456 if (queryp != NULL && seqp != NULL)
457 weight = queryp[rp[j].qidx] * seqp[rp[j].tidx] * nseq * nq;
458 else
459 weight = 1.0;
460
461 if (rp[j].class == 1)
462 {
463 true_pos += weight;
464 plot->tp[curr_xi] = true_pos;
465 }
466 else if (rp[j].class == -1)
467 {
468 false_pos += weight / (double) nq; /* FP/query */
469
470 xi = (int) ceil(log10(false_pos) * plot->nsteps) - plot->base;
471
472 if (xi > curr_xi) {
473 for (curr_xi = curr_xi+1; curr_xi < xi && curr_xi < plot->nxpts; curr_xi++)
474 plot->tp[curr_xi] = true_pos;
475
476 if (curr_xi < plot->nxpts) plot->tp[curr_xi] = true_pos;
477 }
478 }
479 if (curr_xi >= plot->nxpts) break;
480 }
481
482 /* Rarely, the plot won't have enough false positives to extend all the way to
483 * the left extreme of the x-axis; make sure we propagate the last true_pos */
484 for (curr_xi++; curr_xi < plot->nxpts; curr_xi++)
485 plot->tp[curr_xi] = true_pos;
486 }
487
488
489 static void
490 write_plot(FILE *fp, struct oneplot_s *plot)
491 {
492 int xi;
493 double false_pos;
494
495 for (xi = 0; xi < plot->nxpts; xi++)
496 {
497 false_pos = exp(log(10) * ((double) plot->base + (double) xi) / (double) plot->nsteps);
498 fprintf(fp, "%.5f %.5f\n", false_pos, plot->tp[xi] / plot->totalpos );
499 }
500 fprintf(fp, "&\n");
501 }
502
503
504
505 static void
506 summary_graph(ESL_GETOPTS *go, FILE *fp, struct oneplot_s *plot, double **yv)
507 {
508 int nboots = esl_opt_GetInteger(go, "-N");
509 int by_stddev = esl_opt_GetBoolean(go, "-s");
510 double confidence_interval = esl_opt_GetReal (go, "--interval");
511 double nsd = esl_opt_GetReal (go, "--nsd");
512 int xi;
513 double false_pos;
514 double mean, var;
515 int ntail;
516
517 for (xi = 0; xi < plot->nxpts; xi++)
518 {
519 false_pos = exp(log(10) * ((double) plot->base + (double) xi) / (double) plot->nsteps);
520 esl_stats_DMean(yv[xi], nboots, &mean, &var);
521
522 /* the dy's in xmgrace xydydy format are dy's, and in order upper, lower */
523 if (by_stddev)
524 {
525 fprintf(fp, "%.5f %.5f %.5f %.5f\n", false_pos, mean, nsd*sqrt(var), nsd*sqrt(var));
526 }
527 else
528 {
529 esl_vec_DSortIncreasing(yv[xi], nboots);
530 ntail = (int) ((double) nboots * (1.0 - confidence_interval) / 2.0);
531
532 fprintf(fp, "%.5f %.5f %.5f %.5f\n",
533 false_pos, mean,
534 yv[xi][nboots-ntail] - mean,
535 mean - yv[xi][ntail]);
536 }
537 }
538 fprintf(fp, "&\n");
539 }