Debian Codegraph @

meryl/build.C

raw symbols SCIP
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <strings.h>
5 #include <math.h>
6
7 #include "bio++.H"
8 #include "meryl.H"
9 #include "libmeryl.H"
10 #include "seqStream.H"
11 #include "merStream.H"
12
13 void runThreaded(merylArgs *args);
14
15 // You probably want this to be the same as KMER_WORDS, but in rare
16 // cases, it can be less.
17 //
18 #define SORTED_LIST_WIDTH KMER_WORDS
19
20 // to make the sorted list be wider, we also need to store wide
21 // things in the bitpackedarray buckets. probably easy (do multiple
22 // adds of data, each at most 64 bits) but not braindead.
23
24 #if SORTED_LIST_WIDTH == 1
25
26 class sortedList_t {
27 public:
28 uint64 _w;
29 uint32 _p;
30
31 bool operator<(sortedList_t &that) {
32 return(_w < that._w);
33 };
34
35 bool operator>=(sortedList_t &that) {
36 return(_w >= that._w);
37 };
38
39 sortedList_t &operator=(sortedList_t &that) {
40 _w = that._w;
41 _p = that._p;
42 return(*this);
43 };
44 };
45
46 #else
47
48 class sortedList_t {
49 public:
50 uint64 _w[SORTED_LIST_WIDTH];
51 uint32 _p;
52
53 bool operator<(sortedList_t &that) {
54 for (uint32 i=SORTED_LIST_WIDTH; i--; ) {
55 if (_w[i] < that._w[i]) return(true);
56 if (_w[i] > that._w[i]) return(false);
57 }
58 return(false);
59 };
60
61 bool operator>=(sortedList_t &that) {
62 for (uint32 i=SORTED_LIST_WIDTH; i--; ) {
63 if (_w[i] > that._w[i]) return(true);
64 if (_w[i] < that._w[i]) return(false);
65 }
66 return(true);
67 };
68
69 sortedList_t &operator=(sortedList_t &that) {
70 for (uint32 i=SORTED_LIST_WIDTH; i--; )
71 _w[i] = that._w[i];
72 _p = that._p;
73 return(*this);
74 };
75 };
76
77 #endif
78
79
80
81
82 void
83 adjustHeap(sortedList_t *M, int64 i, int64 n) {
84 sortedList_t m = M[i];
85 int64 j = (i << 1) + 1; // let j be the left child
86
87 while (j < n) {
88 if (j<n-1 && M[j] < M[j+1])
89 j++; // j is the larger child
90
91 if (m >= M[j]) // a position for M[i] has been found
92 break;
93
94 M[(j-1)/2] = M[j]; // Move larger child up a level
95
96 j = (j << 1) + 1;
97 }
98
99 M[(j-1)/2] = m;
100 }
101
102
103 void
104 submitPrepareBatch(merylArgs *args) {
105 FILE *F;
106 char nam[1024];
107 char cmd[1024];
108
109 sprintf(nam, "%s-prepare.sh", args->outputFile);
110
111 errno = 0;
112 F = fopen(nam, "w");
113 if (errno)
114 fprintf(stderr, "Failed to open '%s': %s\n", nam, strerror(errno)), exit(1);
115
116 fprintf(F, "#!/bin/sh\n\n");
117 fprintf(F, ". $SGE_ROOT/$SGE_CELL/common/settings.sh\n");
118 fprintf(F, "%s -forcebuild %s\n", args->execName, args->options);
119 fclose(F);
120
121 if (args->sgeMergeOpt)
122 sprintf(cmd, "qsub -cwd -b n -j y -o %s-prepare.err %s -N mp%s %s-prepare.sh",
123 args->outputFile, args->sgeMergeOpt, args->sgeJobName, args->outputFile);
124 else
125 sprintf(cmd, "qsub -cwd -b n -j y -o %s-prepare.err -N mp%s %s-prepare.sh",
126 args->outputFile, args->sgeJobName, args->outputFile);
127 fprintf(stderr, "%s\n", cmd);
128 if (system(cmd))
129 fprintf(stderr, "%s\nFailed to execute qsub command: %s\n", cmd, strerror(errno)), exit(1);
130 }
131
132
133 void
134 submitCountBatches(merylArgs *args) {
135 FILE *F;
136 char nam[1024];
137 char cmd[1024];
138
139 sprintf(nam, "%s-count.sh", args->outputFile);
140
141 errno = 0;
142 F = fopen(nam, "w");
143 if (errno)
144 fprintf(stderr, "Failed to open '%s': %s\n", nam, strerror(errno)), exit(1);
145
146 fprintf(F, "#!/bin/sh\n\n");
147 fprintf(F, ". $SGE_ROOT/$SGE_CELL/common/settings.sh\n");
148 fprintf(F, "batchnum=`expr $SGE_TASK_ID - 1`\n");
149 fprintf(F, "%s -v -countbatch $batchnum -o %s\n", args->execName, args->outputFile);
150 fclose(F);
151
152 if (args->sgeBuildOpt)
153 sprintf(cmd, "qsub -t 1-"uint64FMT" -cwd -b n -j y -o %s-count-\\$TASK_ID.err %s -N mc%s %s-count.sh",
154 args->segmentLimit, args->outputFile, args->sgeBuildOpt, args->sgeJobName, args->outputFile);
155 else
156 sprintf(cmd, "qsub -t 1-"uint64FMT" -cwd -b n -j y -o %s-count-\\$TASK_ID.err -N mc%s %s-count.sh",
157 args->segmentLimit, args->outputFile, args->sgeJobName, args->outputFile);
158 fprintf(stderr, "%s\n", cmd);
159 if (system(cmd))
160 fprintf(stderr, "%s\nFailed to execute qsub command: %s\n", cmd, strerror(errno)), exit(1);
161
162 // submit the merge
163
164 sprintf(nam, "%s-merge.sh", args->outputFile);
165
166 errno = 0;
167 F = fopen(nam, "w");
168 if (errno)
169 fprintf(stderr, "Failed to open '%s': %s\n", nam, strerror(errno)), exit(1);
170
171 fprintf(F, "#!/bin/sh\n\n");
172 fprintf(F, ". $SGE_ROOT/$SGE_CELL/common/settings.sh\n");
173 fprintf(F, "%s -mergebatch -o %s\n", args->execName, args->outputFile);
174 fclose(F);
175
176 if (args->sgeMergeOpt)
177 sprintf(cmd, "qsub -hold_jid mc%s -cwd -b n -j y -o %s-merge.err %s -N mm%s %s-merge.sh",
178 args->sgeJobName, args->outputFile, args->sgeMergeOpt, args->sgeJobName, args->outputFile);
179 else
180 sprintf(cmd, "qsub -hold_jid mc%s -cwd -b n -j y -o %s-merge.err -N mm%s %s-merge.sh",
181 args->sgeJobName, args->outputFile, args->sgeJobName, args->outputFile);
182 fprintf(stderr, "%s\n", cmd);
183 if (system(cmd))
184 fprintf(stderr, "%s\nFailed to execute qsub command: %s\n", cmd, strerror(errno)), exit(1);
185 }
186
187
188 void
189 prepareBatch(merylArgs *args) {
190 bool fatalError = false;
191
192 if (args->inputFile == 0L)
193 fprintf(stderr, "ERROR - no input file specified.\n"), fatalError = true;
194
195 if (args->outputFile == 0L)
196 fprintf(stderr, "ERROR - no output file specified.\n"), fatalError = true;
197
198 if ((args->doForward == false) &&
199 (args->doReverse == false) &&
200 (args->doCanonical == false))
201 fprintf(stderr, "ERROR - need to specify at least one of -f, -r, -C\n"), fatalError = true;
202
203 if ((args->doForward && args->doReverse) ||
204 (args->doForward && args->doCanonical) ||
205 (args->doReverse && args->doCanonical))
206 fprintf(stderr, "ERROR - only one of -f, -r and -C may be specified!\n"), fatalError = true;
207
208 if (args->lowCount > args->highCount)
209 fprintf(stderr, "ERROR - lowCount > highCount??\n"), fatalError = true;
210
211 if (args->segmentLimit && args->memoryLimit)
212 fprintf(stderr, "ERROR: Only one of -memory and -segments can be specified.\n"), fatalError=true;
213
214 if (fatalError)
215 exit(1);
216
217 // If we were given no segment or memory limit, but threads, we
218 // really want to create n segments.
219 //
220 if ((args->numThreads > 0) && (args->segmentLimit == 0) && (args->memoryLimit == 0))
221 args->segmentLimit = args->numThreads;
222
223
224 {
225 seqStream *seqstr = new seqStream(args->inputFile);
226
227 args->numBasesActual = 0;
228 for (uint32 i=0; i<seqstr->numberOfSequences(); i++)
229 args->numBasesActual += seqstr->lengthOf(i);
230
231 merStream *merstr = new merStream(new kMerBuilder(args->merSize), seqstr, true, true);
232
233 args->numMersActual = merstr->approximateNumberOfMers() + 1;
234
235 delete merstr;
236 }
237
238 #warning not submitting prepareBatch to grid
239 #if 0
240 if ((args->isOnGrid) || (args->sgeJobName == 0L)) {
241 } else {
242
243 // Shucks, we need to build the merstream file. Lets do it
244 // on the grid!
245 //
246 submitPrepareBatch(args);
247 exit(0);
248 }
249 #endif
250
251
252 // If there is a memory limit, figure out how to divide the work into an integer multiple of
253 // numThreads segments.
254 //
255 // Otherwise, if there is a segment limit, split the total number of mers into n pieces.
256 //
257 // Otherwise, we must be doing it all in one fell swoop.
258 //
259 if (args->memoryLimit) {
260 args->mersPerBatch = estimateNumMersInMemorySize(args->merSize, args->memoryLimit, args->positionsEnabled, args->beVerbose);
261
262 if (args->mersPerBatch > args->numMersActual)
263 args->mersPerBatch = args->numMersActual;
264
265 args->mersPerBatch = (uint64)ceil((double)args->mersPerBatch / (double)args->numThreads);
266 args->segmentLimit = (uint64)ceil((double)args->numMersActual / (double)args->mersPerBatch);
267
268 args->segmentLimit = args->numThreads * (uint32)ceil((double)args->segmentLimit / (double)args->numThreads);
269
270 } else if (args->segmentLimit) {
271 args->mersPerBatch = (uint64)ceil((double)args->numMersActual / (double)args->segmentLimit);
272
273 } else {
274 args->mersPerBatch = args->numMersActual;
275 args->segmentLimit = 1;
276 }
277
278 args->basesPerBatch = (uint64)ceil((double)args->numBasesActual / (double)args->segmentLimit);
279
280 // Choose the optimal number of buckets to reduce memory usage. Yes, this is already done in
281 // estimateNumMersInMemorySize() (but not saved) and we need to do it for the other cases anyway.
282 //
283 // We use the number of mers per batch + 1 because we need to store the first position after the
284 // last mer. That is, if there are two mers, we will store that the first mer is at position 0,
285 // the second mer is at position 1, and the end of the second mer is at position 2.
286 //
287 args->bucketPointerWidth = logBaseTwo64(args->basesPerBatch + 1);
288 args->numBuckets_log2 = optimalNumberOfBuckets(args->merSize, args->basesPerBatch, args->positionsEnabled);
289 args->numBuckets = (uint64ONE << args->numBuckets_log2);
290 args->merDataWidth = args->merSize * 2 - args->numBuckets_log2;
291
292 if (args->merDataWidth > SORTED_LIST_WIDTH * 64) {
293 fprintf(stderr, " numMersActual = "uint64FMT"\n", args->numMersActual);
294 fprintf(stderr, " mersPerBatch = "uint64FMT"\n", args->mersPerBatch);
295 fprintf(stderr, " basesPerBatch = "uint64FMT"\n", args->basesPerBatch);
296 fprintf(stderr, " numBuckets = "uint64FMT" ("uint32FMT" bits)\n", args->numBuckets, args->numBuckets_log2);
297 fprintf(stderr, " bucketPointerWidth = "uint32FMT"\n", args->bucketPointerWidth);
298 fprintf(stderr, " merDataWidth = "uint32FMT"\n", args->merDataWidth);
299 fprintf(stderr, "Sorry! merSize too big! Increase KMER_WORDS in libbio.kmer.H\n");
300 exit(1);
301 }
302
303 if (args->beVerbose) {
304 if (args->memoryLimit)
305 fprintf(stderr, "Computing "uint64FMT" segments using "uint32FMT" threads and "uint64FMT"MB memory ("uint64FMT"MB if in one batch).\n",
306 args->segmentLimit, args->numThreads,
307 estimateMemory(args->merSize, args->mersPerBatch, args->positionsEnabled) * args->numThreads,
308 estimateMemory(args->merSize, args->numMersActual, args->positionsEnabled));
309 else
310 fprintf(stderr, "Computing "uint64FMT" segments using "uint32FMT" threads and "uint64FMT"MB memory ("uint64FMT"MB if in one batch).\n",
311 estimateMemory(args->merSize, args->mersPerBatch, args->positionsEnabled) * args->numThreads,
312 estimateMemory(args->merSize, args->numMersActual, args->positionsEnabled));
313
314 fprintf(stderr, " numMersActual = "uint64FMT"\n", args->numMersActual);
315 fprintf(stderr, " mersPerBatch = "uint64FMT"\n", args->mersPerBatch);
316 fprintf(stderr, " basesPerBatch = "uint64FMT"\n", args->basesPerBatch);
317 fprintf(stderr, " numBuckets = "uint64FMT" ("uint32FMT" bits)\n", args->numBuckets, args->numBuckets_log2);
318 fprintf(stderr, " bucketPointerWidth = "uint32FMT"\n", args->bucketPointerWidth);
319 fprintf(stderr, " merDataWidth = "uint32FMT"\n", args->merDataWidth);
320 }
321 }
322
323
324
325
326 void
327 runSegment(merylArgs *args, uint64 segment) {
328 merStream *M = 0L;
329 merylStreamWriter *W = 0L;
330 speedCounter *C = 0L;
331 uint32 *bucketSizes = 0L;
332 uint64 *bucketPointers = 0L;
333 uint64 *merDataArray[SORTED_LIST_WIDTH] = { 0L };
334 uint32 *merPosnArray = 0L;
335
336 // If this segment exists already, skip it.
337 //
338 // XXX: This should be a command line option.
339 // XXX: This should check that the files are complete meryl files.
340 //
341 char *filename = new char [strlen(args->outputFile) + 17];
342 sprintf(filename, "%s.batch"uint64FMT".mcdat", args->outputFile, segment);
343
344 if (fileExists(filename)) {
345 if (args->beVerbose)
346 fprintf(stderr, "Found result for batch "uint64FMT" in %s.\n", segment, filename);
347 delete [] filename;
348 return;
349 }
350
351 if ((args->beVerbose) && (args->segmentLimit > 1))
352 fprintf(stderr, "Computing segment "uint64FMT" of "uint64FMT".\n", segment+1, args->segmentLimit);
353
354 delete [] filename;
355
356
357
358 //
359 // We can do all allocations up front:
360 // mer data storage (the buckets themselves, plus 64 for slop)
361 // bucket pointers (plus an extra bucket at the end and a little for slop)
362 // bucket size counting space, last because we toss it out quickly
363 //
364 if (args->beVerbose)
365 fprintf(stderr, " Allocating "uint64FMT"MB for mer storage ("uint32FMT" bits wide).\n",
366 (args->basesPerBatch * args->merDataWidth + 64) >> 23, args->merDataWidth);
367
368 // Mer storage - if mers are bigger than 32, we allocate full
369 // words. The last allocation is always a bitPacked array.
370
371 for (uint64 mword=0, width=args->merDataWidth; width > 0; ) {
372 if (width >= 64) {
373 merDataArray[mword] = new uint64 [ args->basesPerBatch + 1 ];
374 width -= 64;
375 mword++;
376 } else {
377 merDataArray[mword] = new uint64 [ (args->basesPerBatch * width + 64) >> 6 ];
378 width = 0;
379 }
380 }
381
382 if (args->positionsEnabled) {
383 if (args->beVerbose)
384 fprintf(stderr, " Allocating "uint64FMT"MB for mer position storage.\n",
385 (args->basesPerBatch * 32 + 32) >> 23);
386 merPosnArray = new uint32 [ args->basesPerBatch + 1 ];
387 }
388
389 if (args->beVerbose)
390 fprintf(stderr, " Allocating "uint64FMT"MB for bucket pointer table ("uint32FMT" bits wide).\n",
391 (args->numBuckets * args->bucketPointerWidth + 128) >> 23, args->bucketPointerWidth);
392 bucketPointers = new uint64 [(args->numBuckets * args->bucketPointerWidth + 128) >> 6];
393
394
395 if (args->beVerbose)
396 fprintf(stderr, " Allocating "uint64FMT"MB for counting the size of each bucket.\n", args->numBuckets >> 18);
397 bucketSizes = new uint32 [ args->numBuckets ];
398 for (uint64 i=args->numBuckets; i--; )
399 bucketSizes[i] = uint32ZERO;
400
401
402 // Position the mer stream at the start of this segments' mers.
403 // The last segment goes until the stream runs out of mers,
404 // everybody else does args->basesPerBatch mers.
405
406 C = new speedCounter(" Counting mers in buckets: %7.2f Mmers -- %5.2f Mmers/second\r", 1000000.0, 0x1fffff, args->beVerbose);
407 M = new merStream(new kMerBuilder(args->merSize, args->merComp),
408 new seqStream(args->inputFile),
409 true, true);
410 M->setBaseRange(args->basesPerBatch * segment, args->basesPerBatch * segment + args->basesPerBatch);
411
412 char mstring[256];
413
414 if (args->doForward) {
415 while (M->nextMer()) {
416 //fprintf(stderr, "FMER %s\n", M->theFMer().merToString(mstring));
417 bucketSizes[ args->hash(M->theFMer()) ]++;
418 C->tick();
419 }
420 }
421
422 if (args->doReverse) {
423 while (M->nextMer()) {
424 //fprintf(stderr, "RMER %s\n", M->theRMer().merToString(mstring));
425 bucketSizes[ args->hash(M->theRMer()) ]++;
426 C->tick();
427 }
428 }
429
430 if (args->doCanonical) {
431 while (M->nextMer()) {
432 if (M->theFMer() <= M->theRMer()) {
433 //fprintf(stderr, "FMER %s\n", M->theFMer().merToString(mstring));
434 bucketSizes[ args->hash(M->theFMer()) ]++;
435 } else {
436 //fprintf(stderr, "RMER %s\n", M->theRMer().merToString(mstring));
437 bucketSizes[ args->hash(M->theRMer()) ]++;
438 }
439 C->tick();
440 }
441 }
442
443 delete C;
444 delete M;
445
446 // Create the hash index using the counts. The hash points
447 // to the end of the bucket; when we add a word, we move the
448 // hash bucket pointer down one.
449 //
450 // When done, we can deallocate the counting table.
451 //
452 if (args->beVerbose)
453 fprintf(stderr, " Creating bucket pointers.\n");
454
455 {
456 uint64 mi=0;
457 uint64 mj=0;
458 uint64 mc=0;
459
460 while (mi < args->numBuckets) {
461 mc += bucketSizes[mi++];
462 setDecodedValue(bucketPointers, mj, args->bucketPointerWidth, mc);
463 mj += args->bucketPointerWidth;
464 }
465
466 // Add the location of the end of the table. This is not
467 // modified when adding words, but is used to determine
468 // the size of the last bucket.
469 //
470 setDecodedValue(bucketPointers, mj, args->bucketPointerWidth, mc);
471 }
472
473
474 // All done with the counting table, get rid of it.
475 //
476 if (args->beVerbose)
477 fprintf(stderr, " Releasing "uint64FMT"MB from counting the size of each bucket.\n", args->numBuckets >> 18);
478 delete [] bucketSizes;
479
480
481 C = new speedCounter(" Filling mers into list: %7.2f Mmers -- %5.2f Mmers/second\r", 1000000.0, 0x1fffff, args->beVerbose);
482 M = new merStream(new kMerBuilder(args->merSize, args->merComp),
483 new seqStream(args->inputFile),
484 true, true);
485 M->setBaseRange(args->basesPerBatch * segment, args->basesPerBatch * segment + args->basesPerBatch);
486
487 while (M->nextMer()) {
488
489 kMer const &m = ((args->doReverse) || (args->doCanonical && (M->theFMer() > M->theRMer()))) ?
490 M->theRMer()
491 :
492 M->theFMer();
493
494 uint64 element = preDecrementDecodedValue(bucketPointers,
495 args->hash(m) * args->bucketPointerWidth,
496 args->bucketPointerWidth);
497
498 #if SORTED_LIST_WIDTH == 1
499 // Even though this would work in the general loop below, we
500 // special case one word mers to avoid the loop overhead.
501 //
502 setDecodedValue(merDataArray[0],
503 element * args->merDataWidth,
504 args->merDataWidth,
505 m.endOfMer(args->merDataWidth));
506 #else
507 for (uint64 mword=0, width=args->merDataWidth; width>0; ) {
508 if (width >= 64) {
509 merDataArray[mword][element] = m.getWord(mword);
510 width -= 64;
511 mword++;
512 } else {
513 setDecodedValue(merDataArray[mword],
514 element * width,
515 width,
516 m.getWord(mword) & uint64MASK(width));
517 width = 0;
518 }
519 }
520 #endif
521
522 if (args->positionsEnabled)
523 merPosnArray[element] = M->thePositionInStream();
524
525 C->tick();
526 }
527
528 delete C;
529 delete M;
530
531 char *batchOutputFile = new char [strlen(args->outputFile) + 33];
532 sprintf(batchOutputFile, "%s.batch"uint64FMT, args->outputFile, segment);
533
534 C = new speedCounter(" Writing output: %7.2f Mmers -- %5.2f Mmers/second\r", 1000000.0, 0x1fffff, args->beVerbose);
535 W = new merylStreamWriter((args->segmentLimit == 1) ? args->outputFile : batchOutputFile,
536 args->merSize, args->merComp,
537 args->numBuckets_log2,
538 args->positionsEnabled);
539
540 // Sort each bucket into sortedList, then output the mers
541 //
542 sortedList_t *sortedList = 0L;
543 uint32 sortedListMax = 0;
544 uint32 sortedListLen = 0;
545
546 for (uint64 bucket=0, bucketPos=0; bucket < args->numBuckets; bucket++) {
547 uint64 st = getDecodedValue(bucketPointers, bucketPos, args->bucketPointerWidth);
548 bucketPos += args->bucketPointerWidth;
549 uint64 ed = getDecodedValue(bucketPointers, bucketPos, args->bucketPointerWidth);
550
551 if (ed < st) {
552 fprintf(stderr, "ERROR: In segment "uint64FMT"\n", segment);
553 fprintf(stderr, "ERROR: Bucket "uint64FMT" (out of "uint64FMT") ends before it starts!\n",
554 bucket, args->numBuckets);
555 fprintf(stderr, "ERROR: start="uint64FMT"\n", st);
556 fprintf(stderr, "ERROR: end ="uint64FMT"\n", ed);
557 }
558 assert(ed >= st);
559
560 if ((ed - st) > (uint64ONE << 30)) {
561 fprintf(stderr, "ERROR: In segment "uint64FMT"\n", segment);
562 fprintf(stderr, "ERROR: Bucket "uint64FMT" (out of "uint64FMT") is HUGE!\n",
563 bucket, args->numBuckets);
564 fprintf(stderr, "ERROR: start="uint64FMT"\n", st);
565 fprintf(stderr, "ERROR: end ="uint64FMT"\n", ed);
566 }
567
568 // Nothing here? Keep going.
569 if (ed == st)
570 continue;
571
572 sortedListLen = (uint32)(ed - st);
573
574 // Allocate more space, if we need to.
575 //
576 if (sortedListLen > sortedListMax) {
577 delete [] sortedList;
578 sortedList = new sortedList_t [2 * sortedListLen + 1];
579 sortedListMax = 2 * sortedListLen;
580 }
581
582 // Clear out the sortedList -- if we don't, we leave the high
583 // bits unset which will probably make the sort random.
584 //
585 bzero(sortedList, sizeof(sortedList_t) * sortedListLen);
586
587 // Unpack the mers into the sorting array
588 //
589 if (args->positionsEnabled)
590 for (uint64 i=st; i<ed; i++)
591 sortedList[i-st]._p = merPosnArray[i];
592
593 #if SORTED_LIST_WIDTH == 1
594 for (uint64 i=st, J=st*args->merDataWidth; i<ed; i++, J += args->merDataWidth)
595 sortedList[i-st]._w = getDecodedValue(merDataArray[0], J, args->merDataWidth);
596 #else
597 for (uint64 i=st; i<ed; i++) {
598 for (uint64 mword=0, width=args->merDataWidth; width>0; ) {
599 if (width >= 64) {
600 sortedList[i-st]._w[mword] = merDataArray[mword][i];
601 width -= 64;
602 mword++;
603 } else {
604 sortedList[i-st]._w[mword] = getDecodedValue(merDataArray[mword], i * width, width);
605 width = 0;
606 }
607 }
608 }
609 #endif
610
611 // Sort if there is more than one item
612 //
613 if (sortedListLen > 1) {
614 for (int64 t=(sortedListLen-2)/2; t>=0; t--)
615 adjustHeap(sortedList, t, sortedListLen);
616
617 for (int64 t=sortedListLen-1; t>0; t--) {
618 sortedList_t tv = sortedList[t];
619 sortedList[t] = sortedList[0];
620 sortedList[0] = tv;
621
622 adjustHeap(sortedList, 0, t);
623 }
624 }
625
626 // Dump the list of mers to the file.
627 //
628 kMer mer(args->merSize);
629
630 for (uint32 t=0; t<sortedListLen; t++) {
631 C->tick();
632
633 // Build the complete mer
634 //
635 #if SORTED_LIST_WIDTH == 1
636 mer.setWord(0, sortedList[t]._w);
637 #else
638 for (uint64 mword=0; mword < SORTED_LIST_WIDTH; mword++)
639 mer.setWord(mword, sortedList[t]._w[mword]);
640 #endif
641 mer.setBits(args->merDataWidth, args->numBuckets_log2, bucket);
642
643 // Add it
644 if (args->positionsEnabled)
645 W->addMer(mer, 1, &sortedList[t]._p);
646 else
647 W->addMer(mer, 1, 0L);
648
649 }
650 }
651
652 delete [] sortedList;
653
654 delete C;
655 delete W;
656
657 delete [] batchOutputFile;
658
659 for (uint32 x=0; x<SORTED_LIST_WIDTH; x++)
660 delete [] merDataArray[x];
661
662 delete [] merPosnArray;
663
664 delete [] bucketPointers;
665
666 if (args->beVerbose)
667 fprintf(stderr, "Segment "uint64FMT" finished.\n", segment);
668 }
669
670
671
672 void
673 build(merylArgs *args) {
674
675 if (!args->countBatch && !args->mergeBatch)
676 prepareBatch(args);
677
678 // Three choices:
679 //
680 // threaded -- start threads, launch pieces in each thread. This
681 // thread waits for completion and then merges the results.
682 //
683 // batched -- write info file and exit. Compute and merge is done
684 // on separate invocations.
685 //
686 // segmented -- write info file, then do each piece sequentially.
687 // After all pieces finished, do a merge.
688 //
689 //
690
691 bool doMerge = false;
692
693 if (args->configBatch) {
694
695 // Write out our configuration and exit if we are -configbatch
696 //
697 args->writeConfig();
698
699 if (args->sgeJobName) {
700 fprintf(stdout, "Batch prepared. Submitting to the grid.\n");
701 submitCountBatches(args);
702 } else {
703 fprintf(stdout, "Batch prepared. Please run:\n");
704 for (uint64 s=0; s<args->segmentLimit; s++)
705 fprintf(stdout, "%s -countbatch "uint64FMT" -o %s\n", args->execName, s, args->outputFile);
706 fprintf(stdout, "%s -mergebatch -o %s\n", args->execName, args->outputFile);
707 }
708 } else if (args->countBatch) {
709
710 // Read back the configuration, run the segment and exit if we
711 // are -countbatch
712 //
713 merylArgs *savedArgs = new merylArgs(args->outputFile);
714 savedArgs->beVerbose = args->beVerbose;
715 runSegment(savedArgs, args->batchNumber);
716 delete savedArgs;
717 } else if (args->mergeBatch) {
718
719 // Check that all the files exist if we are -mergebatch and
720 // continue with execution
721 //
722 // MEMORY LEAK! We should delete this at the end of the
723 // function, but it's a pain, and who cares?
724 //
725 merylArgs *savedArgs = new merylArgs(args->outputFile);
726 savedArgs->beVerbose = args->beVerbose;
727
728 args = savedArgs;
729
730 doMerge = true;
731 } else {
732
733 if (args->numThreads > 1)
734
735 // Run, using threads. There is a lot of baloney needed, so it's
736 // all in a separate function.
737 //
738 runThreaded(args);
739 else
740 // No special options given, do all the work here and now
741 //
742 for (uint64 s=0; s<args->segmentLimit; s++)
743 runSegment(args, s);
744
745 // Either case, we want to merge now.
746 //
747 doMerge = true;
748 }
749
750
751 // If there is more than one segment, merge them to get the output.
752 //
753 // We do this by contructing a meryl command line and recursively
754 // (effectively) calling meryl.
755 //
756 // The command line is
757 //
758 // ./meryl -M merge [-v] -s batch1 -s batch2 ... -s batchN -o outputFile
759 //
760 if ((doMerge) && (args->segmentLimit > 1)) {
761
762 if (args->beVerbose)
763 fprintf(stderr, "Merge results.\n");
764
765 int argc = 0;
766 char **argv = new char* [7 + 2 * args->segmentLimit];
767 bool *arga = new bool [7 + 2 * args->segmentLimit];
768
769 arga[argc] = false; argv[argc++] = "meryl-build-merge";
770 arga[argc] = false; argv[argc++] = "-M";
771 arga[argc] = false; argv[argc++] = "merge";
772
773 if (args->beVerbose) {
774 arga[argc] = false;
775 argv[argc++] = "-v";
776 }
777
778 for (uint32 i=0; i<args->segmentLimit; i++) {
779 arga[argc] = false;
780 argv[argc++] = "-s";
781 arga[argc] = true;
782 argv[argc] = new char [strlen(args->outputFile) + 33];
783 sprintf(argv[argc], "%s.batch"uint32FMT, args->outputFile, i);
784 argc++;
785 }
786
787 arga[argc] = false; argv[argc++] = "-o";
788 arga[argc] = false; argv[argc++] = args->outputFile;
789
790 merylArgs *addArgs = new merylArgs(argc, argv);
791 multipleOperations(addArgs);
792
793 // Cleanup the memory leak.
794 //
795 delete addArgs;
796 for (int i=0; i<argc; i++)
797 if (arga[i])
798 delete [] argv[i];
799 delete [] argv;
800 delete [] arga;
801
802 // Remove temporary files
803 //
804 char *filename = new char [strlen(args->outputFile) + 17];
805
806 for (uint32 i=0; i<args->segmentLimit; i++) {
807 sprintf(filename, "%s.batch"uint32FMT".mcidx", args->outputFile, i);
808 unlink(filename);
809 sprintf(filename, "%s.batch"uint32FMT".mcdat", args->outputFile, i);
810 unlink(filename);
811 sprintf(filename, "%s.batch"uint32FMT".mcpos", args->outputFile, i);
812 unlink(filename);
813 }
814
815 delete [] filename;
816 }
817
818 // If we just merged, delete the merstream file
819 //
820 if (doMerge) {
821 char *filename = new char [strlen(args->outputFile) + 17];
822
823 sprintf(filename, "%s.merStream", args->outputFile);
824 unlink(filename);
825
826 delete [] filename;
827 }
828 }