Debian Codegraph @

easel/miniapps/cmd_downsample.c

raw symbols SCIP
1 #include <esl_config.h>
2
3 #include <string.h>
4
5 #include "easel.h"
6 #include "esl_buffer.h"
7 #include "esl_getopts.h"
8 #include "esl_sq.h"
9 #include "esl_sqio.h"
10 #include "esl_subcmd.h"
11 #include "esl_mem.h"
12 #include "esl_rand64.h"
13
14
15 static ESL_OPTIONS cmd_options[] = {
16 /* name type default env range toggles reqs incomp help docgroup*/
17 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
18 { "-s", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "sequence sampling: <infile> is file or stream of seqs", 0 },
19 { "-S", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "big sequence sample: <infile> is (seekable) seq file", 0 },
20 { "--seed", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number generator seed", 0 },
21 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
22 };
23
24 static void downsample_lines (ESL_RAND64 *rng, int64_t M, char *infile);
25 static void downsample_seqs (ESL_RAND64 *rng, int64_t M, char *infile);
26 static void downsample_seqs_big(ESL_RAND64 *rng, int64_t M, char *infile);
27
28 int
29 esl_cmd_downsample(const char *topcmd, const ESL_SUBCMD *sub, int argc, char **argv)
30 {
31 ESL_GETOPTS *go = esl_subcmd_CreateDefaultApp(topcmd, sub, cmd_options, argc, argv);
32 ESL_RAND64 *rng = esl_rand64_Create(esl_opt_GetInteger(go, "--seed")); // 64-bit RNG, so we can sample from very large data
33 char *Marg = esl_opt_GetArg(go, 1); // ptr to the string rep of M
34 char *infile = esl_opt_GetArg(go, 2); // the original set of N records
35 int64_t M; // size of the smaller result sample of M records
36 int nc;
37 int status;
38
39 status = esl_mem_strtoi64(Marg, strlen(Marg), 10, &nc, &M);
40 if (status != eslOK || nc != strlen(Marg)) esl_fatal("First argument is an integer: number of data elements to take from <infile>");
41
42 if (esl_opt_GetBoolean(go, "-s")) downsample_seqs (rng, M, infile);
43 else if (esl_opt_GetBoolean(go, "-S")) downsample_seqs_big(rng, M, infile);
44 else downsample_lines (rng, M, infile);
45
46 esl_rand64_Destroy(rng);
47 esl_getopts_Destroy(go);
48 return 0;
49 }
50
51
52 /* downsample_lines()
53 * SRE, Tue 21 Aug 2018 [Gleypa okkur, Olafur Arnalds]
54 *
55 * Sample <M> lines from <infile> randomly, and outputs them to
56 * <stdout>. Uses a reservoir sampling algorithm that requires $O(ML)$
57 * memory, for line length $L$. It holds the selected sample
58 * of lines in memory, before writing it out.
59 *
60 * Adapted from `esl_selectn` miniapp.
61 */
62 static void
63 downsample_lines(ESL_RAND64 *rng, int64_t M, char *infile)
64 {
65 ESL_BUFFER *bf = NULL;
66 char **larr = NULL; // sampled line ptr array, [0..M-1]
67 int64_t N = 0; // number of lines read so far
68 char *p; // ptr to an input line in <bf>
69 esl_pos_t plen; // length of line <p>
70 int64_t r; // random #, 0..n-1
71 int64_t i;
72 int status;
73
74 status = esl_buffer_Open(infile, NULL, &bf);
75 if (status == eslENOTFOUND) esl_fatal("open failed: %s", bf->errmsg);
76 else if (status == eslFAIL) esl_fatal("gzip -dc failed: %s", bf->errmsg);
77 else if (status != eslOK) esl_fatal("open failed with error code %d", status);
78
79 if (( larr = malloc(sizeof(char *) * M)) == NULL) esl_fatal("allocation failed");
80 for (i = 0; i < M; i++) larr[i] = NULL;
81
82 while ( (status = esl_buffer_GetLine(bf, &p, &plen)) == eslOK)
83 {
84 N++;
85 if (N > M)
86 {
87 if ( (r = esl_rand64_Roll(rng, N)) < M) {
88 free(larr[r]);
89 esl_memstrdup(p, plen, &(larr[r]));
90 }
91 }
92 else esl_memstrdup(p, plen, &(larr[N-1]));
93 }
94 if (status != eslEOF) esl_fatal("unexpected error in reading line from %s", infile);
95 if (N < M) esl_fatal("input only has %" PRId64 " lines; not enough to select %" PRId64 " from them", N, M);
96
97 for (i = 0; i < M; i++) printf("%s\n", larr[i]);
98
99 esl_buffer_Close(bf);
100 for (i = 0; i < M; i++) free(larr[i]);
101 free(larr);
102 }
103
104
105 /* downsample_seqs()
106 * SRE, Tue 21 Aug 2018 [Ramin Djawadi, Game of Thrones]
107 *
108 * Sample <M> sequences from <infile> randomly, and output them to
109 * <stdout>. Uses a reservoir sampling algorithm that gathers all <M>
110 * sequence in memory until writing them, requiring $O(MS)$ memory for
111 * sequence objects of size $S$ (including their sequence and their
112 * metadata). Because the sequences are parsed into text-mode <ESL_SQ>
113 * objects, unparsed sequence record metadata are lost. The order of
114 * the sequences in <infile> is not preserved in the sample.
115 *
116 * If <M> is large and $O(MS)$ memory is of concern, or to preserve
117 * metadata or sequence order, see <sample_seqs_big()>.
118 */
119 static void
120 downsample_seqs(ESL_RAND64 *rng, int64_t M, char *infile)
121 {
122 ESL_SQFILE *sqfp = NULL;
123 int infmt = eslSQFILE_UNKNOWN;
124 ESL_SQ *sq = esl_sq_Create();
125 ESL_SQ **sqarr = NULL; // the sample: ptrs to <M> sequences
126 ESL_SQ *tmpsq; // for swapping a new sequence into the sample
127 int64_t N = 0;
128 int64_t i, r;
129 int status;
130
131 /* Text-mode open, so that if file happens to have special characters/capitalization conventions, we try to keep them. */
132 status = esl_sqfile_Open(infile, infmt, NULL, &sqfp);
133 if (status == eslENOTFOUND) esl_fatal("Couldn't open seq file %s for reading.", infile);
134 else if (status == eslEFORMAT) esl_fatal("Couldn't determine format of input sequence data.");
135 else if (status != eslOK) esl_fatal("Sequence file open failed, unexpected code %d.", status);
136
137 if (( sqarr = malloc(sizeof(ESL_SQ *) * M)) == NULL) esl_fatal("allocation failed");
138 for (i = 0; i < M; i++) sqarr[i] = NULL;
139
140 while ( (status = esl_sqio_Read(sqfp, sq)) == eslOK)
141 {
142 N++;
143 if (N > M)
144 {
145 if ( (r = esl_rand64_Roll(rng, N)) < M) {
146 tmpsq = sqarr[r];
147 sqarr[r] = sq;
148 sq = tmpsq;
149 }
150 }
151 else
152 {
153 sqarr[N-1] = sq;
154 sq = esl_sq_Create();
155 }
156
157 esl_sq_Reuse(sq);
158 }
159 if (status == eslEFORMAT) esl_fatal("Sequence input parse failed:\n %s", esl_sqfile_GetErrorBuf(sqfp));
160 else if (status != eslEOF) esl_fatal("Unexpected sequence input read error %d", status);
161
162 if (N < M) esl_fatal("input only has %" PRId64 " sequences; not enough to select %" PRId64 " from them", N, M);
163
164 for (i = 0; i < M; i++)
165 esl_sqio_Write(stdout, sqarr[i], eslSQFILE_FASTA, /*update=*/FALSE); // FASTA because infile could be MSA(s)
166
167 esl_sqfile_Close(sqfp);
168 for (i = 0; i < M; i++) esl_sq_Destroy(sqarr[i]);
169 esl_sq_Destroy(sq);
170 free(sqarr);
171 }
172
173 /* qsort_increasing_offsets()
174 * qsort()'s pawn, for sorting offsets in downsample_seqs_big() below.
175 */
176 static int
177 qsort_increasing_offsets(const void *xp1, const void *xp2)
178 {
179 off_t x1 = * (off_t *) xp1;
180 off_t x2 = * (off_t *) xp2;
181 if (x1 < x2) return -1;
182 if (x1 > x2) return 1;
183 return 0;
184 }
185
186
187 /* downsample_seqs_big()
188 * Alternative sequence sampling strategy that scales to larger samples.
189 * SRE, Fri 24 Aug 2018 [Bombay Bicycle Club, Shuffle]
190 *
191 * Instead of holding the entire sequence sample in memory, only hold
192 * disk record offsets; then make a second pass through the file to
193 * retrieve and output the sampled records. Requires 8M bytes of
194 * memory (assuming sizeof(off_t) = 8), but requires that <infile> is
195 * rewindable: a file, not a stdin pipe or a gunzip stream. Also
196 * assumes that the sequence is a contiguous chunk of bytes in <infile>,
197 * so <infile> has to be an unaligned sequence file, not an alignment.
198 *
199 * Other advantages: it exactly regurgitates the sequence record, with
200 * all its metadata intact; and it preserves the order of the
201 * sequences in <infile>.
202 */
203 static void
204 downsample_seqs_big(ESL_RAND64 *rng, int64_t M, char *infile)
205 {
206 ESL_SQFILE *sqfp = NULL;
207 int infmt = eslSQFILE_UNKNOWN;
208 ESL_SQ *sq = esl_sq_Create();
209 off_t *offlist = malloc(sizeof(off_t) * M); // sample of sequence record offsets
210 int64_t N = 0;
211 int64_t i, r;
212 int status;
213
214 if ( ! offlist) esl_fatal("allocation failed");
215
216 /* Open <infile> and make sure we're going to be able to rewind it
217 */
218 status = esl_sqfile_Open(infile, infmt, NULL, &sqfp);
219 if (status == eslENOTFOUND) esl_fatal("Couldn't open seq file %s for reading.", infile);
220 else if (status == eslEFORMAT) esl_fatal("Couldn't determine format of input sequence data.");
221 else if (status != eslOK) esl_fatal("Sequence file open failed, unexpected code %d.", status);
222
223 if (! esl_sqfile_IsRewindable(sqfp)) esl_fatal("To use -S, <infile> must be a sequence file, not a (nonrewindable) stream");
224 if ( esl_sqio_IsAlignment(sqfp->format) ) esl_fatal("To use -S, <infile> must be an unaligned sequence file, not an alignment");
225
226 /* First pass: sample <infile>, holding sequence record offsets for the sample
227 */
228 while ((status = esl_sqio_ReadInfo(sqfp, sq)) == eslOK)
229 {
230 N++;
231 if (N > M) {
232 if (( r = esl_rand64_Roll(rng, N) ) < M) offlist[r] = sq->roff;
233 } else offlist[N-1] = sq->roff;
234
235 esl_sq_Reuse(sq);
236 }
237 if (status == eslEFORMAT) esl_fatal("Sequence input parse failed:\n %s", esl_sqfile_GetErrorBuf(sqfp));
238 else if (status != eslEOF) esl_fatal("Unexpected sequence input read error %d", status);
239 if (N < M) esl_fatal("input only has %" PRId64 " sequences; not enough to select %" PRId64 " from them", N, M);
240
241 /* Sort offsets, so we preserve order of the original <infile>
242 */
243 qsort((void *) offlist, M, sizeof(off_t), qsort_increasing_offsets);
244
245 /* Retrieve and echo the sample
246 */
247 for (i = 0; i < M; i++)
248 {
249 if (( status = esl_sqfile_Position(sqfp, offlist[i])) != eslOK) esl_fatal("failed to reposition to where sample %" PRId64 " was supposed to be", i);
250 if (( status = esl_sqio_ReadInfo(sqfp, sq)) != eslOK) esl_fatal("failed to read seq info where sample %" PRId64 " was supposed to be", i);
251 if (( status = esl_sqio_Echo(sqfp, sq, stdout)) != eslOK) esl_fatal("failed to echo seq from where sample %" PRId64 " was supposed to be", i);
252 esl_sq_Reuse(sq);
253 }
254
255 esl_sqfile_Close(sqfp);
256 esl_sq_Destroy(sq);
257 free(offlist);
258 }