forked from EddyRivasLab/easel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
esl_dsqdata.c
1810 lines (1599 loc) · 81 KB
/
esl_dsqdata.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* esl_dsqdata : faster sequence input
*
* Implements a predigitized binary file format for biological
* sequences. Sequence data are packed bitwise into 32-bit packets,
* where each packet contains either six 5-bit residues or fifteen
* 2-bit residues, plus two control bits. Input is asynchronous,
* using POSIX threads, with a "loader" thread doing disk reads and
* "unpacker" thread(s) preparing chunks of sequences for
* analysis. Sequence data and metadata are stored in separate files,
* which may allow further input acceleration by deferring
* metadata accesses until they're actually needed.
*
* All thread synchronization is handled internally. A caller does not
* need to worry about the internal parallelism; it just calls
* <esl_dsqdata_Read()>. Caller can create multiple threads, each
* calling <esl_dsqdata_Read()>.
*
* A DSQDATA database <basename> is stored in four files:
* - basename : a human-readable stub
* - basename.dsqi : index file, enabling random access & parallel chunking
* - basename.dsqm : metadata including names, accessions, descs, taxonomy
* - basename.dsqs : sequences, in a packed binary format
*
* Contents:
* 1. ESL_DSQDATA: reading dsqdata format
* 2. Creating dsqdata format from a sequence file
* 3. ESL_DSQDATA_CHUNK, a chunk of input sequence data
* 4. Loader and unpacker, the input threads
* 5. Packing sequences and unpacking chunks
* 6. Notes and references
* 7. Unit tests
* 8. Test driver
* 9. Examples
*/
#include <esl_config.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <pthread.h>
#include "easel.h"
#include "esl_alphabet.h"
#include "esl_random.h"
#include "esl_sq.h"
#include "esl_sqio.h"
#include "esl_dsqdata.h"
static ESL_DSQDATA_CHUNK *dsqdata_chunk_Create (ESL_DSQDATA *dd);
static void dsqdata_chunk_Destroy(ESL_DSQDATA_CHUNK *chu);
static void *dsqdata_loader_thread (void *p);
static void *dsqdata_unpacker_thread(void *p);
static int dsqdata_unpack_chunk(ESL_DSQDATA_CHUNK *chu, int do_pack5);
static int dsqdata_unpack5(uint32_t *psq, ESL_DSQ *dsq, int *ret_L, int *ret_P);
static int dsqdata_unpack2(uint32_t *psq, ESL_DSQ *dsq, int *ret_L, int *ret_P);
static int dsqdata_pack5 (ESL_DSQ *dsq, int L, uint32_t *psq, int *ret_P);
static int dsqdata_pack2 (ESL_DSQ *dsq, int L, uint32_t *psq, int *ret_P);
/* Embedded magic numbers allow us to validate the correct binary
* format, with version (if needed in the future), and to detect
* byteswapping.
*/
static uint32_t eslDSQDATA_MAGIC_V1 = 0xc4d3d1b1; // "dsq1" + 0x80808080
static uint32_t eslDSQDATA_MAGIC_V1SWAP = 0xb1d1d3c4; // ... as above, but byteswapped.
/*****************************************************************
*# 1. <ESL_DSQDATA>: reading dsqdata format
*****************************************************************/
/* Function: esl_dsqdata_Open()
* Synopsis: Open a digital sequence database for reading
* Incept: SRE, Wed Jan 20 09:50:00 2016 [Amtrak 2150, NYP-BOS]
*
* Purpose: Open dsqdata database <basename> for reading. The file
* <basename> is a stub describing the database. The bulk
* of the data are in three accompanying binary files: the
* index file <basename>.dsqi, the metadata file
* <basename>.dsqm, and the sequence file <basename>.dsqs.
*
* <nconsumers> is an upper bound on the number of threads
* in which the caller plans to be calling
* <esl_dsqdata_Read()> -- or, more precisely, the maximum
* number of data chunks that the caller could be working
* on at any given instant. This is a hint, not a
* commitment. The dsqdata loader uses it to determine the
* maximum number of data chunks that can be in play at
* once (including chunks it is juggling internally, plus
* if all the caller's reader threads are busy on
* theirs). If <nconsumers> is set too small, the loader
* may stall waiting for chunks to come back for recycling.
*
* Reading digital sequence data requires a digital
* alphabet. You can either provide one (in which case we
* validate that it matches the alphabet used by the
* dsqdata) or, as a convenience, <esl_dsqdata_Open()> can
* create one for you. Either way, you pass a pointer to an
* <ESL_ALPHABET> structure <abc>, in <byp_abc>. <byp_abc>
* uses a partial Easel "bypass" idiom: if <*byp_abc> is
* NULL, we allocate and return a new alphabet; if
* <*byp_abc> is a ptr to an existing alphabet, we use it
* for validation. That is, you have two choices:
*
* ```
* ESL_ALPHABET *abc = NULL;
* esl_dsqdata_Open(&abc, basename...)
* // <abc> is now the alphabet of <basename>;
* // now you're responsible for Destroy'ing it
* ```
*
* or:
*
* ```
* ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO);
* status = esl_dsqdata_Open(&abc, basename);
* // if status == eslEINCOMPAT, alphabet in basename
* // doesn't match caller's expectation
* ```
*
* Args: byp_abc : expected or created alphabet; pass &abc, abc=NULL or abc=expected alphabet
* basename : data are in files <basename> and <basename.dsq[ism]>
* nconsumers : upper bound on number of consumer threads caller is going to Read() with
* ret_dd : RETURN : the new ESL_DSQDATA object.
*
* Returns: <eslOK> on success.
*
* <eslENOTFOUND> if one or more of the expected datafiles
* aren't there or can't be opened.
*
* <eslEFORMAT> if something looks wrong in parsing file
* formats. Includes problems in headers, and also the
* case where caller provides a digital alphabet in
* <*byp_abc> and it doesn't match the database's alphabet.
*
* On any normal error, <*ret_dd> is still returned, but in
* an error state, and <dd->errbuf> is a user-directed
* error message that the caller can relay to the user. Other
* than the <errbuf>, the rest of the contents are undefined.
*
* Caller is responsible for destroying <*byp_abc>.
*
* Throws: <eslEMEM> on allocation error.
* <eslESYS> on system call failure.
* <eslEUNIMPLEMENTED> if data are byteswapped
* TODO: handle byteswapping
*
* On any thrown exception, <*ret_dd> is returned NULL.
*
* On <eslESYS> exceptions, some thread resources may
* not be fully freed, leading to some memory leakage.
*/
int
esl_dsqdata_Open(ESL_ALPHABET **byp_abc, char *basename, int nconsumers, ESL_DSQDATA **ret_dd)
{
ESL_DSQDATA *dd = NULL;
int bufsize = 4096;
uint32_t magic = 0;
uint32_t tag = 0;
uint32_t alphatype = eslUNKNOWN;
int ndd;
char *p; // used for strtok() parsing of fields on a line
char buf[4096];
int u;
int status;
ESL_DASSERT1(( nconsumers > 0 ));
ESL_DASSERT1(( byp_abc != NULL )); // either *byp_abc == NULL or *byp_abc = the caller's expected alphabet.
ESL_ALLOC(dd, sizeof(ESL_DSQDATA));
dd->stubfp = NULL;
dd->ifp = NULL;
dd->sfp = NULL;
dd->mfp = NULL;
dd->abc_r = *byp_abc; // This may be NULL; if so, we create it later.
dd->magic = 0;
dd->uniquetag = 0;
dd->flags = 0;
dd->max_namelen = 0;
dd->max_acclen = 0;
dd->max_desclen = 0;
dd->max_seqlen = 0;
dd->nseq = 0;
dd->nres = 0;
dd->chunk_maxseq = eslDSQDATA_CHUNK_MAXSEQ; // someday we may want to allow tuning these
dd->chunk_maxpacket = eslDSQDATA_CHUNK_MAXPACKET;
dd->do_byteswap = FALSE;
dd->pack5 = FALSE;
dd->nconsumers = nconsumers;
dd->n_unpackers = eslDSQDATA_UNPACKERS; // we'll want to allow tuning this too
dd->errbuf[0] = '\0';
/* Open the four files.
*/
ndd = strlen(basename) + 6; // +5 for .dsqx; +1 for \0
ESL_ALLOC( dd->basename, ndd);
if ( snprintf(dd->basename, ndd, "%s.dsqi", basename) <= 0) ESL_XEXCEPTION_SYS(eslESYS, "sprintf() failure");
if (( dd->ifp = fopen(dd->basename, "rb")) == NULL) ESL_XFAIL(eslENOTFOUND, dd->errbuf, "Failed to find or open index file %s\n", dd->basename);
if ( snprintf(dd->basename, ndd, "%s.dsqm", basename) <= 0) ESL_XEXCEPTION_SYS(eslESYS, "sprintf() failure");
if (( dd->mfp = fopen(dd->basename, "rb")) == NULL) ESL_XFAIL(eslENOTFOUND, dd->errbuf, "Failed to find or open metadata file %s\n", dd->basename);
if ( snprintf(dd->basename, ndd, "%s.dsqs", basename) <= 0) ESL_XEXCEPTION_SYS(eslESYS, "sprintf() failure");
if (( dd->sfp = fopen(dd->basename, "rb")) == NULL) ESL_XFAIL(eslENOTFOUND, dd->errbuf, "Failed to find or open sequence file %s\n", dd->basename);
strcpy(dd->basename, basename);
if (( dd->stubfp = fopen(dd->basename, "r")) == NULL) ESL_XFAIL(eslENOTFOUND, dd->errbuf, "Failed to find or open stub file %s\n", dd->basename);
/* The stub file is unparsed, intended to be human readable, with one exception:
* The first line contains the unique tag that we use to validate linkage of the 4 files.
* The format of that first line is:
* Easel dsqdata v123 x0000000000
*/
if ( fgets(buf, bufsize, dd->stubfp) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file is empty - no tag line found");
if (( p = strtok(buf, " \t\n\r")) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format: tag line has no data");
if ( strcmp(p, "Easel") != 0) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
if (( p = strtok(NULL, " \t\n\r")) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
if ( strcmp(p, "dsqdata") != 0) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
if (( p = strtok(NULL, " \t\n\r")) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
if ( *p != 'v') ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format: no v on version");
if ( ! esl_str_IsInteger(p+1)) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file had bad format: no version number");
// version number is currently unused: there's only 1
if (( p = strtok(NULL, " \t\n\r")) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
if ( *p != 'x') ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format: no x on tag");
if ( ! esl_str_IsInteger(p+1)) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file had bad format: no integer tag");
dd->uniquetag = strtoul(p+1, NULL, 10);
/* Index file has a header of 7 uint32's, 3 uint64's */
if ( fread(&(dd->magic), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file has no header - is empty?");
if ( fread(&tag, sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no tag");
if ( fread(&alphatype, sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no alphatype");
if ( fread(&(dd->flags), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no flags");
if ( fread(&(dd->max_namelen), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no max name len");
if ( fread(&(dd->max_acclen), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no max accession len");
if ( fread(&(dd->max_desclen), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no max description len");
if ( fread(&(dd->max_seqlen), sizeof(uint64_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no max seq len");
if ( fread(&(dd->nseq), sizeof(uint64_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no nseq");
if ( fread(&(dd->nres), sizeof(uint64_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no nres");
/* Check the magic and the tag */
if (tag != dd->uniquetag) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file has bad tag, doesn't go with stub file");
// Eventually we would set dd->do_byteswap = TRUE; below.
if (dd->magic == eslDSQDATA_MAGIC_V1SWAP) ESL_XEXCEPTION(eslEUNIMPLEMENTED, "dsqdata cannot yet read data in different byte orders");
else if (dd->magic != eslDSQDATA_MAGIC_V1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file has bad magic");
/* Either validate, or create the alphabet */
if (dd->abc_r)
{
if (alphatype != dd->abc_r->type)
ESL_XFAIL(eslEFORMAT, dd->errbuf, "data files use %s alphabet; expected %s alphabet",
esl_abc_DecodeType(alphatype),
esl_abc_DecodeType(dd->abc_r->type));
}
else
{
if ( esl_abc_ValidateType(alphatype) != eslOK) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file has invalid alphabet type %d", alphatype);
if (( dd->abc_r = esl_alphabet_Create(alphatype)) == NULL) ESL_XEXCEPTION(eslEMEM, "alphabet creation failed");
}
/* If it's protein, flip the switch to expect all 5-bit packing */
if (dd->abc_r->type == eslAMINO) dd->pack5 = TRUE;
/* Metadata file has a header of 2 uint32's, magic and uniquetag */
if (( fread(&magic, sizeof(uint32_t), 1, dd->mfp)) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "metadata file has no header - is empty?");
if (( fread(&tag, sizeof(uint32_t), 1, dd->mfp)) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "metadata file header truncated - no tag?");
if ( magic != dd->magic) ESL_XFAIL(eslEFORMAT, dd->errbuf, "metadata file has bad magic");
if ( tag != dd->uniquetag) ESL_XFAIL(eslEFORMAT, dd->errbuf, "metadata file has bad tag, doesn't match stub");
/* Sequence file also has a header of 2 uint32's, magic and uniquetag */
if (( fread(&magic, sizeof(uint32_t), 1, dd->sfp)) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "sequence file has no header - is empty?");
if (( fread(&tag, sizeof(uint32_t), 1, dd->sfp)) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "sequence file header truncated - no tag?");
if ( magic != dd->magic) ESL_XFAIL(eslEFORMAT, dd->errbuf, "sequence file has bad magic");
if ( tag != dd->uniquetag) ESL_XFAIL(eslEFORMAT, dd->errbuf, "sequence file has bad tag, doesn't match stub");
/* unpacker inboxes and outboxes */
for (u = 0; u < dd->n_unpackers; u++)
{
dd->inbox[u] = NULL;
if ( pthread_mutex_init(&(dd->inbox_mutex[u]), NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed");
if ( pthread_cond_init (&(dd->inbox_cv[u]), NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_init() failed");
dd->inbox_eod[u] = FALSE;
dd->outbox[u] = NULL;
if ( pthread_mutex_init(&(dd->outbox_mutex[u]), NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed");
if ( pthread_cond_init (&(dd->outbox_cv[u]), NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_init() failed");
dd->outbox_eod[u] = FALSE;
}
/* consumers share access to <nchunk> counter */
dd->nchunk = 0;
if ( pthread_mutex_init(&dd->nchunk_mutex, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed");
/* chunk recycling stack */
dd->recycling = NULL;
if ( pthread_mutex_init(&dd->recycling_mutex, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed");
if ( pthread_cond_init(&dd->recycling_cv, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_init() failed");
/* Create the "initialization is complete" signaling mechanism
* before creating any threads, and lock the initialization mutex
* while we're creating them. The issue here is that unpackers
* identify their [u] index by comparing their self thread id to the
* master list of thread ids, so make sure that master list actually
* exists.
*/
dd->go = FALSE;
if ( pthread_mutex_init(&dd->go_mutex, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed on go_mutex");
if ( pthread_cond_init( &dd->go_cv, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_init() failed on go_cv");
if ( pthread_mutex_lock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_lock() failed on go_mutex");
/* Create the loader and the unpackers.
* They will wait to start until we signal through go->cv.
*/
if ( pthread_create(&dd->loader_t, NULL, dsqdata_loader_thread, dd) != 0) ESL_XEXCEPTION(eslESYS, "pthread_create() failed");
for (u = 0; u < dd->n_unpackers; u++)
if ( pthread_create(&(dd->unpacker_t[u]), NULL, dsqdata_unpacker_thread, dd) != 0) ESL_XEXCEPTION(eslESYS, "pthread_create() failed");
/* All threads started, initialization complete - broadcast "go" signal to all threads */
dd->go = TRUE;
if ( pthread_mutex_unlock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_unlock() failed on go_mutex");
if ( pthread_cond_broadcast(&dd->go_cv) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_broadcast() failed on go_cv");
*ret_dd = dd;
*byp_abc = dd->abc_r; // If caller provided <*byp_abc> this is a no-op, because we set abc_r = *byp_abc.
return eslOK; // .. otherwise we're passing the created <abc> back to caller, caller's
// responsibility, we just keep the reference to it.
ERROR:
if (status == eslENOTFOUND || status == eslEFORMAT || status == eslEINCOMPAT)
{ /* on normal errors, we return <dd> with its <errbuf>, don't change *byp_abc */
*ret_dd = dd;
if (*byp_abc == NULL && dd->abc_r) esl_alphabet_Destroy(dd->abc_r);
return status;
}
else if (status != eslESYS)
{ /* on most exceptions, we free <dd>, return it NULL, don't change *byp_abc */
esl_dsqdata_Close(dd);
*ret_dd = NULL;
if (*byp_abc == NULL && dd->abc_r) esl_alphabet_Destroy(dd->abc_r);
return status;
}
else
{ /* on eslESYS exceptions - pthread initializations failing - we can't assume we can _Close() correctly. */
*ret_dd = NULL;
if (*byp_abc == NULL && dd->abc_r) esl_alphabet_Destroy(dd->abc_r);
return status;
}
}
/* Function: esl_dsqdata_Read()
* Synopsis: Read next chunk of sequence data.
* Incept: SRE, Thu Jan 21 11:21:38 2016 [Harvard]
*
* Purpose: Read the next chunk from <dd>, return a pointer to it in
* <*ret_chu>, and return <eslOK>. When data are exhausted,
* return <eslEOF>, and <*ret_chu> is <NULL>.
*
* Threadsafe. All thread operations in the dsqdata reader
* are handled internally. Caller does not have to worry
* about wrapping this in a mutex. Multiple caller threads
* can call <esl_dsqdata_Read()>.
*
* All chunk allocation and deallocation is handled
* internally. After using a chunk, caller gives it back to
* the reader using <esl_dsqdata_Recycle()>.
*
* Args: dd : open dsqdata object to read from
* ret_chu : RETURN : next chunk of seq data
*
* Returns: <eslOK> on success. <*ret_chu> is a chunk of seq data.
* Caller must call <esl_dsqdata_Recycle()> on each chunk
* that it Read()'s.
*
* <eslEOF> if we've reached the end of the input file;
* <*ret_chu> is NULL.
*
* Throws: <eslESYS> if a pthread call fails.
* Caller should treat this as disastrous. Without correctly
* working pthread calls, we cannot read, and we may not be able
* to correctly clean up and close the reader. Caller should
* treat <dd> as toxic, clean up whatever else it may need to,
* and exit.
*/
int
esl_dsqdata_Read(ESL_DSQDATA *dd, ESL_DSQDATA_CHUNK **ret_chu)
{
ESL_DSQDATA_CHUNK *chu = NULL;
int u;
/* First, determine which slot the next chunk is in, using the consumer-shared <nchunk> counter */
if ( pthread_mutex_lock(&dd->nchunk_mutex) != 0) ESL_EXCEPTION(eslESYS, "failed to lock reader mutex");
u = (int) (dd->nchunk % dd->n_unpackers);
/* Acquire a lock that outbox, wait for it to be in full or EOD state */
if ( pthread_mutex_lock(&(dd->outbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "failed to lock outbox[u] mutex");
while (! dd->outbox_eod[u] && dd->outbox[u] == NULL) {
if ( pthread_cond_wait(&(dd->outbox_cv[u]), &(dd->outbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "failed to wait on outbox[u] signal");
}
/* Get the chunk from outbox. */
chu = dd->outbox[u];
dd->outbox[u] = NULL;
if (chu) dd->nchunk++; // chu==NULL if we're EOD. (and eod flag is up too, but we already know that by getting here)
/* Release the outbox lock and signal back to unpacker (skip signalling if we're EOD; unpacker[u] is done) */
if ( pthread_mutex_unlock(&(dd->outbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "failed to unlock outbox[u] mutex");
if ( chu && pthread_cond_signal (&(dd->outbox_cv[u])) != 0) ESL_EXCEPTION(eslESYS, "failed to signal outbox[u] is empty");
/* Release the reader lock that protects dd->nchunk counter */
if ( pthread_mutex_unlock(&dd->nchunk_mutex) != 0) ESL_EXCEPTION(eslESYS, "failed to unlock reader mutex");
*ret_chu = chu;
return (chu ? eslOK : eslEOF);
}
/* Function: esl_dsqdata_Recycle()
* Synopsis: Give a chunk back to the reader.
* Incept: SRE, Thu Feb 11 19:24:33 2016
*
* Purpose: Recycle chunk <chu> back to the reader <dd>. The reader
* is responsible for all allocation and deallocation of
* chunks. The reader will either reuse the chunk's memory
* if more chunks remain to be read, or it will free it.
*
* Args: dd : dsqdata reader
* chu : chunk to recycle
*
* Returns: <eslOK> on success.
*
* Throws: <eslESYS> on a pthread call failure. Caller should regard
* such an error as disastrous; if pthread calls are
* failing, you cannot depend on the reader to be working
* at all, and you should treat <dd> as toxic. Do whatever
* desperate things you need to do and exit.
*/
int
esl_dsqdata_Recycle(ESL_DSQDATA *dd, ESL_DSQDATA_CHUNK *chu)
{
if (chu)
{
if ( pthread_mutex_lock(&dd->recycling_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex lock failed");
chu->nxt = dd->recycling; // Push chunk onto head of recycling stack
dd->recycling = chu;
if ( pthread_mutex_unlock(&dd->recycling_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex unlock failed");
if ( pthread_cond_signal(&dd->recycling_cv) != 0) ESL_EXCEPTION(eslESYS, "pthread cond signal failed"); // loader may wait for this signal
}
return eslOK;
}
/* Function: esl_dsqdata_Close()
* Synopsis: Close a dsqdata reader.
* Incept: SRE, Thu Feb 11 19:32:54 2016
*
* Purpose: Close a dsqdata reader.
*
* Returns: <eslOK> on success.
* Throws: <eslESYS> on a system call failure, including pthread
* calls and fclose(). Caller should regard such a failure
* as disastrous: treat <dd> as toxic and exit as soon as
* possible without making any other system calls, if possible.
*
* Note: Normally Easel would call _Close() not only on a correctly
* opened object (after the Open returns) but also from
* within the Open call to clean up on failure. This relies
* on being able to tell which parts of an incomplete
* object have been initialized; this is why Easel sets
* ptrs to NULL before allocating them, for example. POSIX
* threads doesn't seem to give us a way to check whether a
* mutex, condition variable, or thread has been
* initialized; and destroying an uninitialized mutex or CV
* results in undefined behavior. We could include a
* boolean flag for each pthreads component -- or one for
* all of them -- but instead, we simply say that a failure
* of pthreads initialization in the Open function is so
* catastrophic and unexpected that we exit that function
* without cleaning up the incomplete ESL_DSQDATA
* structure. We expect that the caller is simply going to
* have to quit anyway, so we don't need to worry about
* memory leakage.
*/
int
esl_dsqdata_Close(ESL_DSQDATA *dd)
{
int u;
if (dd)
{
/* out of abundance of caution - wait for threads to join before breaking down <dd> */
if ( pthread_join(dd->loader_t, NULL) != 0) ESL_EXCEPTION(eslESYS, "pthread join failed");
for (u = 0; u < dd->n_unpackers; u++)
if ( pthread_join(dd->unpacker_t[u], NULL) != 0) ESL_EXCEPTION(eslESYS, "pthread join failed");
if (dd->basename) free(dd->basename);
if (dd->stubfp) { if ( fclose(dd->stubfp) != 0) ESL_EXCEPTION(eslESYS, "fclose failed"); }
if (dd->ifp) { if ( fclose(dd->ifp) != 0) ESL_EXCEPTION(eslESYS, "fclose failed"); }
if (dd->sfp) { if ( fclose(dd->sfp) != 0) ESL_EXCEPTION(eslESYS, "fclose failed"); }
if (dd->mfp) { if ( fclose(dd->mfp) != 0) ESL_EXCEPTION(eslESYS, "fclose failed"); }
for (u = 0; u < dd->n_unpackers; u++)
{
if ( pthread_mutex_destroy(&(dd->inbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
if ( pthread_cond_destroy(&(dd->inbox_cv[u])) != 0) ESL_EXCEPTION(eslESYS, "pthread cond destroy failed");
if ( pthread_mutex_destroy(&(dd->outbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
if ( pthread_cond_destroy(&(dd->outbox_cv[u])) != 0) ESL_EXCEPTION(eslESYS, "pthread cond destroy failed");
}
if ( pthread_mutex_destroy(&dd->nchunk_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
if ( pthread_mutex_destroy(&dd->recycling_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
if ( pthread_cond_destroy(&dd->recycling_cv) != 0) ESL_EXCEPTION(eslESYS, "pthread cond destroy failed");
if ( pthread_mutex_destroy(&dd->go_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
if ( pthread_cond_destroy(&dd->go_cv) != 0) ESL_EXCEPTION(eslESYS, "pthread cond destroy failed");
/* Loader thread is responsible for freeing all chunks it created, even on error. */
#if (eslDEBUGLEVEL >= 1)
for (u = 0; u < dd->n_unpackers; u++) {
assert( dd->inbox[u] == NULL );
assert( dd->outbox[u] == NULL );
}
assert(dd->recycling == NULL );
#endif
free(dd);
}
return eslOK;
}
/*****************************************************************
*# 2. Creating dsqdata format from a sequence file
*****************************************************************/
/* Function: esl_dsqdata_Write()
* Synopsis: Create a dsqdata database
* Incept: SRE, Sat Feb 13 07:33:30 2016 [AGBT 2016, Orlando]
*
* Purpose: Caller has just opened <sqfp>, in digital mode.
* Create a dsqdata database <basename> from the sequence
* data in <sqfp>.
*
* <sqfp> must be protein, DNA, or RNA sequence data. It
* must be rewindable (i.e. a file), because we have to
* read it twice. It must be newly opened (i.e. positioned
* at the start).
*
* Args: sqfp - newly opened sequence data file
* basename - base name of dsqdata files to create
* errbuf - user-directed error message on normal errors
*
* Returns: <eslOK> on success.
*
* <eslEWRITE> if an output file can't be opened. <errbuf>
* contains user-directed error message.
*
* <eslEFORMAT> if a parse error is encountered while
* reading <sqfp>.
*
*
* Throws: <eslESYS> A system call failed, such as fwrite().
* <eslEINVAL> Sequence handle <sqfp> isn't digital and rewindable.
* <eslEMEM> Allocation failure
* <eslEUNIMPLEMENTED> Sequence is too long to be encoded.
* (TODO: chromosome-scale DNA sequences)
*/
int
esl_dsqdata_Write(ESL_SQFILE *sqfp, char *basename, char *errbuf)
{
ESL_RANDOMNESS *rng = NULL;
ESL_SQ *sq = NULL;
FILE *stubfp = NULL;
FILE *ifp = NULL;
FILE *mfp = NULL;
FILE *sfp = NULL;
char *outfile = NULL;
uint32_t magic = eslDSQDATA_MAGIC_V1;
uint32_t uniquetag;
uint32_t alphatype;
uint32_t flags = 0;
uint32_t max_namelen = 0;
uint32_t max_acclen = 0;
uint32_t max_desclen = 0;
uint64_t max_seqlen = 0;
uint64_t nseq = 0;
uint64_t nres = 0;
int do_pack5 = FALSE;
uint32_t *psq;
ESL_DSQDATA_RECORD idx; // one index record to write
int plen;
int64_t spos = 0;
int64_t mpos = 0;
int n;
int na;
int status;
if (! esl_sqfile_IsRewindable(sqfp)) ESL_EXCEPTION(eslEINVAL, "sqfp must be rewindable (e.g. an open file)");
if (! sqfp->abc) ESL_EXCEPTION(eslEINVAL, "sqfp must be digital");
// Could also check that it's positioned at the start.
if ( (sq = esl_sq_CreateDigital(sqfp->abc)) == NULL) { status = eslEMEM; goto ERROR; }
/* First pass over the sequence file, to get statistics.
* Read it now, before opening any files, in case we find any parse errors.
*/
while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
{
if (sq->n >= 6 * eslDSQDATA_CHUNK_MAXPACKET) // guaranteed limit
ESL_EXCEPTION(eslEUNIMPLEMENTED, "dsqdata cannot currently deal with large sequences");
nseq++;
nres += sq->n;
if (sq->n > max_seqlen) max_seqlen = sq->n;
n = strlen(sq->name); if (n > max_namelen) max_namelen = n;
n = strlen(sq->acc); if (n > max_acclen) max_acclen = n;
n = strlen(sq->desc); if (n > max_desclen) max_desclen = n;
esl_sq_Reuse(sq);
}
if (status == eslEFORMAT) ESL_XFAIL(eslEFORMAT, errbuf, sqfp->get_error(sqfp));
else if (status != eslEOF) return status;
if ((status = esl_sqfile_Position(sqfp, 0)) != eslOK) return status;
if (( rng = esl_randomness_Create(0) ) == NULL) { status = eslEMEM; goto ERROR; }
uniquetag = esl_random_uint32(rng);
alphatype = sqfp->abc->type;
if (alphatype == eslAMINO) do_pack5 = TRUE;
else if (alphatype != eslDNA && alphatype != eslRNA) ESL_EXCEPTION(eslEINVAL, "alphabet must be protein or nucleic");
na = strlen(basename) + 6; // '.dsq?' + '\0'
ESL_ALLOC(outfile, na);
if ( snprintf(outfile, na, "%s.dsqi", basename) < 0) ESL_EXCEPTION(eslESYS, "sprintf failed");
if (( ifp = fopen(outfile, "wb")) == NULL) ESL_XFAIL(eslEWRITE, errbuf, "failed to open dsqdata index file %s for writing", outfile);
if ( snprintf(outfile, na, "%s.dsqm", basename) < 0) ESL_EXCEPTION(eslESYS, "sprintf failed");
if (( mfp = fopen(outfile, "wb")) == NULL) ESL_XFAIL(eslEWRITE, errbuf, "failed to open dsqdata metadata file %s for writing", outfile);
if ( snprintf(outfile, na, "%s.dsqs", basename) < 0) ESL_EXCEPTION(eslESYS, "sprintf failed");
if (( sfp = fopen(outfile, "wb")) == NULL) ESL_XFAIL(eslEWRITE, errbuf, "failed to open dsqdata sequence file %s for writing", outfile);
if (( stubfp = fopen(basename, "w")) == NULL) ESL_XFAIL(eslEWRITE, errbuf, "failed to open dsqdata stub file %s for writing", basename);
/* Header: index file */
if (fwrite(&magic, sizeof(uint32_t), 1, ifp) != 1 ||
fwrite(&uniquetag, sizeof(uint32_t), 1, ifp) != 1 ||
fwrite(&alphatype, sizeof(uint32_t), 1, ifp) != 1 ||
fwrite(&flags, sizeof(uint32_t), 1, ifp) != 1 ||
fwrite(&max_namelen, sizeof(uint32_t), 1, ifp) != 1 ||
fwrite(&max_acclen, sizeof(uint32_t), 1, ifp) != 1 ||
fwrite(&max_desclen, sizeof(uint32_t), 1, ifp) != 1 ||
fwrite(&max_seqlen, sizeof(uint64_t), 1, ifp) != 1 ||
fwrite(&nseq, sizeof(uint64_t), 1, ifp) != 1 ||
fwrite(&nres, sizeof(uint64_t), 1, ifp) != 1)
ESL_XEXCEPTION_SYS(eslESYS, "fwrite() failed, index file header");
/* Header: metadata file */
if (fwrite(&magic, sizeof(uint32_t), 1, mfp) != 1 ||
fwrite(&uniquetag, sizeof(uint32_t), 1, mfp) != 1)
ESL_XEXCEPTION_SYS(eslESYS, "fwrite() failed, metadata file header");
/* Header: sequence file */
if (fwrite(&magic, sizeof(uint32_t), 1, sfp) != 1 ||
fwrite(&uniquetag, sizeof(uint32_t), 1, sfp) != 1)
ESL_XEXCEPTION_SYS(eslESYS, "fwrite() failed, metadata file header");
/* Second pass: index, metadata, and sequence files */
while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
{
/* Packed sequence */
psq = (uint32_t *) sq->dsq; // pack-in-place
ESL_DASSERT1(( sq->salloc >= 4 )); // required min space for pack-in-place
if (do_pack5) dsqdata_pack5(sq->dsq, sq->n, psq, &plen);
else dsqdata_pack2(sq->dsq, sq->n, psq, &plen);
if ( fwrite(psq, sizeof(uint32_t), plen, sfp) != plen)
ESL_XEXCEPTION(eslESYS, "fwrite() failed, packed seq");
spos += plen;
/* Metadata */
n = strlen(sq->name);
if ( fwrite(sq->name, sizeof(char), n+1, mfp) != n+1)
ESL_XEXCEPTION(eslESYS, "fwrite () failed, metadata, name");
mpos += n+1;
n = strlen(sq->acc);
if ( fwrite(sq->acc, sizeof(char), n+1, mfp) != n+1)
ESL_XEXCEPTION(eslESYS, "fwrite () failed, metadata, accession");
mpos += n+1;
n = strlen(sq->desc);
if ( fwrite(sq->desc, sizeof(char), n+1, mfp) != n+1)
ESL_XEXCEPTION(eslESYS, "fwrite () failed, metadata, description");
mpos += n+1;
if ( fwrite( &(sq->tax_id), sizeof(int32_t), 1, mfp) != 1)
ESL_XEXCEPTION(eslESYS, "fwrite () failed, metadata, taxonomy id");
mpos += sizeof(int32_t);
/* Index file */
idx.psq_end = spos-1; // could be -1, on 1st seq, if 1st seq L=0.
idx.metadata_end = mpos-1;
if ( fwrite(&idx, sizeof(ESL_DSQDATA_RECORD), 1, ifp) != 1)
ESL_XEXCEPTION(eslESYS, "fwrite () failed, index file");
esl_sq_Reuse(sq);
}
/* Stub file */
fprintf(stubfp, "Easel dsqdata v1 x%" PRIu32 "\n", uniquetag);
fprintf(stubfp, "\n");
fprintf(stubfp, "Original file: %s\n", sqfp->filename);
fprintf(stubfp, "Original format: %s\n", esl_sqio_DecodeFormat(sqfp->format));
fprintf(stubfp, "Type: %s\n", esl_abc_DecodeType(sqfp->abc->type));
fprintf(stubfp, "Sequences: %" PRIu64 "\n", nseq);
fprintf(stubfp, "Residues: %" PRIu64 "\n", nres);
esl_sq_Destroy(sq);
esl_randomness_Destroy(rng);
free(outfile);
fclose(stubfp);
fclose(ifp);
fclose(mfp);
fclose(sfp);
return eslOK;
ERROR:
if (sq) esl_sq_Destroy(sq);
if (rng) esl_randomness_Destroy(rng);
if (outfile) free(outfile);
if (stubfp) fclose(stubfp);
if (ifp) fclose(ifp);
if (mfp) fclose(mfp);
if (sfp) fclose(sfp);
return status;
}
/*****************************************************************
* 3. ESL_DSQDATA_CHUNK: a chunk of input sequence data
*****************************************************************/
static ESL_DSQDATA_CHUNK *
dsqdata_chunk_Create(ESL_DSQDATA *dd)
{
ESL_DSQDATA_CHUNK *chu = NULL;
int U; // max size of unpacked seq data, in bytes (smem allocation)
int status;
ESL_ALLOC(chu, sizeof(ESL_DSQDATA_CHUNK));
chu->i0 = 0;
chu->N = 0;
chu->pn = 0;
chu->dsq = NULL;
chu->name = NULL;
chu->acc = NULL;
chu->desc = NULL;
chu->taxid = NULL;
chu->L = NULL;
chu->metadata = NULL;
chu->smem = NULL;
chu->nxt = NULL;
/* dsq, name, acc, desc are arrays of pointers into smem, metadata.
* taxid is cast to int, from the metadata.
* L is figured out by the unpacker.
* All of these are set by the unpacker.
*/
ESL_ALLOC(chu->dsq, dd->chunk_maxseq * sizeof(ESL_DSQ *));
ESL_ALLOC(chu->name, dd->chunk_maxseq * sizeof(char *));
ESL_ALLOC(chu->acc, dd->chunk_maxseq * sizeof(char *));
ESL_ALLOC(chu->desc, dd->chunk_maxseq * sizeof(char *));
ESL_ALLOC(chu->taxid, dd->chunk_maxseq * sizeof(int));
ESL_ALLOC(chu->L, dd->chunk_maxseq * sizeof(int64_t));
/* On the <smem> allocation, and the <dsq> and <psq> pointers into it:
*
* <maxpacket> (in uint32's) sets the maximum single fread() size:
* one load of a new chunk of packed sequence, up to maxpacket*4
* bytes. <smem> needs to be able to hold both that and the fully
* unpacked sequence, because we unpack in place. Each packet
* unpacks to at most 6 or 15 residues (5-bit or 2-bit packing) We
* don't pack sentinels, so the maximum unpacked size includes
* <maxseq>+1 sentinels... because we concat the digital seqs so
* that the trailing sentinel of seq i is the leading sentinel of
* seq i+1.
*
* The packed seq (max of P bytes) loads overlap with the unpacked
* data (max of U bytes):
* psq
* v[ P bytes ]
* smem: 0........0........0..........0
* ^[ U bytes ]
* ^dsq[0] ^dsq[1] ^dsq[2]
*
* and as long as we unpack psq left to right -- and as long as we
* read the last packet before we write the last unpacked residues
* to smem - we're guaranteed that the unpacking works without
* overwriting any unpacked data.
*/
U = (dd->pack5 ? 6 * dd->chunk_maxpacket : 15 * dd->chunk_maxpacket);
U += dd->chunk_maxseq + 1;
ESL_ALLOC(chu->smem, sizeof(ESL_DSQ) * U);
chu->psq = (uint32_t *) (chu->smem + U - 4*dd->chunk_maxpacket);
/* We don't have any guarantees about the amount of metadata
* associated with the N sequences, so <metadata> has to be a
* reallocatable space. We make a lowball guess for the initial
* alloc, on the off chance that the metadata size is small (names
* only, no acc/desc): minimally, say 12 bytes of name, 3 \0's, and
* 4 bytes for the taxid integer: call it 20.
*/
chu->mdalloc = 20 * dd->chunk_maxseq;
ESL_ALLOC(chu->metadata, sizeof(char) * chu->mdalloc);
return chu;
ERROR:
dsqdata_chunk_Destroy(chu);
return NULL;
}
static void
dsqdata_chunk_Destroy(ESL_DSQDATA_CHUNK *chu)
{
if (chu)
{
if (chu->metadata) free(chu->metadata);
if (chu->smem) free(chu->smem);
if (chu->L) free(chu->L);
if (chu->taxid) free(chu->taxid);
if (chu->desc) free(chu->desc);
if (chu->acc) free(chu->acc);
if (chu->name) free(chu->name);
if (chu->dsq) free(chu->dsq);
free(chu);
}
}
/*****************************************************************
* 4. Loader and unpacker, the input threads
*****************************************************************/
static void *
dsqdata_loader_thread(void *p)
{
ESL_DSQDATA *dd = (ESL_DSQDATA *) p;
ESL_DSQDATA_RECORD *idx = NULL;
ESL_DSQDATA_CHUNK *chu = NULL;
int64_t nchunk = 0; // total number of chunks loaded (including empty EOF)
int nalloc = 0; // number of chunks we create, and need to destroy.
int nidx = 0; // how many records in <idx>: usually MAXSEQ, until end
int nload = 0; // how many sequences we load: >=1, <=nidx
int ncarried = 0; // how many records carry over to next iteration: nidx-nload
int nread = 0; // fread()'s return value
int nmeta = 0; // how many bytes of metadata we want to read for this chunk
int i0 = 0; // absolute index of first record in <idx>, 0-offset
int64_t psq_last = -1; // psq_end for record i0-1
int64_t meta_last = -1; // metadata_end for record i0-1
int u; // which unpacker outbox we put this chunk in
int status;
/* Don't use <dd> until we get the structure-is-ready signal */
if ( pthread_mutex_lock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_lock failed on go_mutex");
while (! dd->go) {
if ( pthread_cond_wait(&dd->go_cv, &dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_wait failed on go_cv");
}
if ( pthread_mutex_unlock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_lock failed on go_mutex");
/* We can begin. */
ESL_ALLOC(idx, sizeof(ESL_DSQDATA_RECORD) * dd->chunk_maxseq);
while (1)
{
//printf("loader: working on chunk %d\n", (int) nchunk+1);
/* Get a chunk structure we can use - either by creating it, or recycling it.
* We probably don't benefit from having more than <nconsumers> + 3*<n_unpackers> + 2,
* which is enough to have all threads working, all in/outboxes full, and at least 1
* waiting in recycling.
* SRE TODO: test, how many is optimal, does it matter?
* the two limits below perform comparably in `esl_dsqdata_example -n`, but that
* doesn't have high-cpu reader threads.
*/
//if (nalloc < dd->nconsumers + dd->n_unpackers + 1)
if (nalloc < dd->nconsumers + 3 * dd->n_unpackers + 2)
{
//printf("loader: creating a new chunk\n");
if ( (chu = dsqdata_chunk_Create(dd)) == NULL) { status = eslEMEM; goto ERROR; }
nalloc++;
}
else
{
//printf("loader: getting a new chunk from recycling...\n");
if ( pthread_mutex_lock(&dd->recycling_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex lock failed");
while (dd->recycling == NULL) {
if ( pthread_cond_wait(&dd->recycling_cv, &dd->recycling_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond wait failed");
}
chu = dd->recycling; // pop one off recycling stack
dd->recycling = chu->nxt;
if ( pthread_mutex_unlock(&dd->recycling_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex unlock failed");
if ( pthread_cond_signal(&dd->recycling_cv) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond signal failed"); // signal *after* unlocking mutex
//printf("loader: ... done, have new chunk from recycling.\n");
}
/* Refill index. (The memmove is avoidable. Alt strategy: we could load in 2 frames)
* The previous loop loaded packed sequence for <nload'> of the <nidx'> entries,
* where the 's indicate the variable has carried over from prev iteration:
* |----- nload' ----||--- (ncarried) ---|
* |-------------- nidx' ----------------|
* Now we're going to shift the remainder ncarried = nidx-nload to the left, then refill:
* |---- ncarried ----||--- (MAXSEQ-ncarried) ---|
* |-------------- MAXSEQ -----------------------|
* while watching out for the terminal case where we run out of
* data, loading less than (MAXSEQ-ncarried) records:
* |---- ncarried ----||--- nidx* ---|
* |------------- nidx --------------|
* where the <nidx*> is what fread() returns to us.
*/
i0 += nload; // this chunk starts with seq #<i0>
ncarried = (nidx - nload);
memmove(idx, idx + nload, sizeof(ESL_DSQDATA_RECORD) * ncarried);
nidx = fread(idx + ncarried, sizeof(ESL_DSQDATA_RECORD), dd->chunk_maxseq - ncarried, dd->ifp);
nidx += ncarried; // usually, this'll be MAXSEQ, unless we're near EOF.
if (nidx == 0) // then we're EOD.
{
//printf("loader: reached EOD.\n");
dsqdata_chunk_Destroy(chu);
nalloc--; // we'd counted that chunk towards <nalloc>.
break; // this is the only way out of loader's main loop
}
/* Figure out how many sequences we're going to load: <nload>
* nload = max i : i <= MAXSEQ && idx[i].psq_end - psq_last <= CHUNK_MAX
*/
ESL_DASSERT1(( idx[0].psq_end - psq_last <= dd->chunk_maxpacket ));
if (idx[nidx-1].psq_end - psq_last <= dd->chunk_maxpacket)
nload = nidx;
else
{ // Binary search for nload = max_i idx[i-1].psq_end - lastend <= MAX
int righti = nidx;
int mid;
nload = 1;
while (righti - nload > 1)
{
mid = nload + (righti - nload) / 2;
if (idx[mid-1].psq_end - psq_last <= dd->chunk_maxpacket) nload = mid;
else righti = mid;
}
}
/* Read packed sequence. */
//printf("loader: loading chunk %d from disk.\n", (int) nchunk+1);
chu->pn = idx[nload-1].psq_end - psq_last;
nread = fread(chu->psq, sizeof(uint32_t), chu->pn, dd->sfp);
//printf("Read %d packed ints from seq file\n", nread);
if ( nread != chu->pn ) ESL_XEXCEPTION(eslEOD, "dsqdata packet loader: expected %d, got %d", chu->pn, nread);
/* Read metadata, reallocating if needed */
nmeta = idx[nload-1].metadata_end - meta_last;
if (nmeta > chu->mdalloc) {
ESL_REALLOC(chu->metadata, sizeof(char) * nmeta); // should be realloc by doubling instead?
chu->mdalloc = nmeta;
}
nread = fread(chu->metadata, sizeof(char), nmeta, dd->mfp);
if ( nread != nmeta ) ESL_XEXCEPTION(eslEOD, "dsqdata metadata loader: expected %d, got %d", nmeta, nread);
chu->i0 = i0;
chu->N = nload;
psq_last = idx[nload-1].psq_end;
meta_last = idx[nload-1].metadata_end;
/* Put chunk in appropriate outbox.
*/
u = nchunk % dd->n_unpackers; // note this is the loader's own private <nchunk> counter, not the consumer-shared one in <dd>
//printf("loader: about to put chunk %d into inbox %d\n", (int) nchunk+1, u);
if ( pthread_mutex_lock(&(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex lock failed");
while (dd->inbox[u] != NULL) {
if (pthread_cond_wait(&(dd->inbox_cv[u]), &(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond wait failed");
}
dd->inbox[u] = chu;
if ( pthread_mutex_unlock(&(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex unlock failed");
if ( pthread_cond_signal(&(dd->inbox_cv[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond signal failed");
//printf("loader: finished putting chunk %d into inbox %d\n", (int) nchunk+1, u);
nchunk++;
}
/* Cleanup time. First, set all unpacker inboxes to EOD state. (We overwrite <u> here.)
*/