-
Notifications
You must be signed in to change notification settings - Fork 13
/
GCdbYank.cpp
489 lines (459 loc) · 15.1 KB
/
GCdbYank.cpp
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
#include "GCdbYank.h"
#include "GBase.h"
#include <ctype.h>
#define ERR_READ "GCdbYank: error reading from file.\n"
#define ERR_READFMT "GCdbYank read error: incorrect file format.\n"
#define ERR_RANGEFMT "Sequence range parsing error for key '%s'\n"
#define ERR_RANGE_INVALID "Invalid range (%d-%d) specified for sequence '%s' of length %d\n"
// 1MB memory buffer:
#define MAX_MEM_RECSIZE 1048576
#ifndef O_BINARY
#define O_BINARY 0x0000
#endif
//default size of the index record for records stored with 32bit offsets
uint32 irec_size32=8;
#ifdef ENABLE_COMPRESSION
GCdbZFasta::GCdbZFasta(FILE* azf, int zrsize, char* r_delim) {
zrecsize=-1;
zpos=0;
recdelim=Gstrdup(r_delim);
zf=azf;
decomp_start(zrsize);
chrhandler=new GFastaCharHandler(recdelim);
}
GCdbZFasta::~GCdbZFasta() {
//if (zf!=NULL && zf!=stdout && zf!=stdin) fclose(zf);
// FULL_FLUSH method instead of finish
delete chrhandler;
GFREE(recdelim);
decomp_end();
}
void GCdbZFasta::decomp_start(int zrsize) {
zstream.zalloc = (alloc_func)0;
zstream.zfree = (free_func)0;
zstream.opaque = (voidpf)0;
zstream.next_in = (Bytef*)sbuf;
zstream.avail_in = 0;
zstream.next_out = (Bytef*)lbuf;
int err = inflateInit(&zstream);
if (err!=Z_OK)
GMessage("Error at inflateInit()\n");
//-- now read and discard the first record, so we can use random access later
// (needed by zlib)
int bytes_read=fread(sbuf, 1, zrsize, zf);
if (bytes_read<zrsize)
GError("Error reading 1st record from zrec file\n");
zstream.next_in = (Bytef*)sbuf;
zstream.avail_in = bytes_read;
//decompress first chunk
zstream.next_out = (Bytef*)lbuf;
zstream.avail_out = GCDBZ_LBUF_LEN;
err = inflate(&zstream, Z_SYNC_FLUSH);
if (err !=Z_OK && err!=Z_STREAM_END)
GError("GCdbZFasta error: 1st record inflate failed! (err=%d)\n",err);
}
void GCdbZFasta::decomp_end() {
int err = inflateEnd(&zstream);
if (err!=Z_OK)
GError("Error at inflateEnd() (err=%d)\n", err);
}
//fasta record decompress
//returns: the number of bytes decompressed
int GCdbZFasta::decompress(FastaSeq& rec, int csize, int zfofs, charFunc* seqCallBack) {
if (zfofs>=0) {
if (fseeko(zf, zfofs, 0))
GError("GCdbZFasta::decompress: error fseeko() to %d\n", zfofs);
}
else
if (feof(zf)) return 0;
bool in_rec=true;
int err=0;
int total_read=0;
int total_written=0;
chrhandler->init(&rec, seqCallBack);
while (in_rec) { // read loop
int to_read=0;
int bytes_read=0;
if (csize<=0) { //read one byte at a time
to_read=1;
int c;
if ((c =fgetc(zf))!=EOF) {
bytes_read = 1;
sbuf[0]=c;
}
else {
//bytes_read=0;
return 0; //eof
}
total_read+=bytes_read;
}
else {
to_read = csize-total_read>GCDBZ_SBUF_LEN ?
GCDBZ_SBUF_LEN : csize-total_read;
// check for csize vs bytes_read match:
if (to_read==0) return 0;
bytes_read=fread(sbuf, 1, to_read, zf);
if (bytes_read!=to_read)
GError("Error reading from zrec file\n");
total_read+=bytes_read;
in_rec=(total_read<csize);
}
if (bytes_read==0) {
//GMessage("bytes_read = 0\n");
return 0;
}
if (in_rec && bytes_read<to_read) in_rec=false;
zstream.next_in = (Bytef*)sbuf;
zstream.avail_in = bytes_read;
do { //decompression loop
zstream.next_out = (Bytef*)lbuf;
zstream.avail_out = GCDBZ_LBUF_LEN;
uLong t_out=zstream.total_out;
err = inflate(&zstream, Z_SYNC_FLUSH);
uLong toWrite=zstream.total_out-t_out;
if (toWrite>0) {
/* if (fwrite(lbuf, 1, toWrite, outf)<toWrite) {
GError("Error writing inflated chunk!\n");
} */
for (unsigned int i=0;i<toWrite;i++)
chrhandler->processChar(lbuf[i]);
total_written+=toWrite;
}
if (err==Z_STREAM_END) {
in_rec=false;
if (total_written==0) {
GMessage("Z_STREAM_END found but total_written=0!\n");
}
break;
}
else if (err !=Z_OK)
GError("GCdbZFasta error: inflate failed! (err=%d)\n",err);
} while (zstream.avail_in!=0); //decompression loop
} //read loop
chrhandler->done();
/*if (err!=Z_STREAM_END) {
GError("decompress: Z_STREAM_END not found!\n");
}*/
return total_written;
}
GCdbZFasta* GCdbYank::openCdbz(char* p) {
//in case this was not done before:
gcvt_uint=(endian_test())? &uint32_sun : &uint32_x86;
FILE* zf=fopen(p, "rb");
if (zf==NULL) {
GMessage("Error: cannot open compressed file '%s'!\n",p);
return NULL;
}
//check if the file is valid and read the length of the first record
//
char ztag[5];
ztag[4]='\0';
if (fread(ztag, 1, 4, zf)<4) {
GMessage("Error reading header of compressed file '%s'\n",p);
return NULL;
}
if (strcmp(ztag, "CDBZ")!=0) {
GMessage("Error: file '%s' doesn't appear to be a zlib compressed cdb?\n",p);
return NULL;
}
unsigned int zrecsize;
if (fread((void*) &zrecsize,1,4,zf)<4) {
GMessage("Error reading 1st compressed record size for file '%s'!\n",p);
return NULL;
}
zrecsize=gcvt_uint(&zrecsize);
return new GCdbZFasta(zf, zrecsize, recdelim);
}
#else
static const char err_COMPRESSED[]="Error: compression detected but not compiled in!\n";
#endif
//decompression stuff
void inplace_Lower(char* c) {
char *p=c;
while (*p!='\0') { *p=tolower(*p);p++; }
}
void buf_get(GCDBuffer* b, uint32& pos, char *buf, unsigned int len) {
int r;
while (len > 0) {
r = b->get(buf,len);
if (r == -1) GError(ERR_READ);
if (r == 0)
GError(ERR_READFMT);
pos += r;
buf += r;
len -= r;
}
}
void buf_getnum(GCDBuffer* b, uint32& pos, uint32 *num) {
char buf[4];
buf_get(b, pos, buf, 4);
uint32_unpack(buf,num);
}
int read_dbinfo(int fd, char** fnameptr, cdbInfo& dbstat) {
//this is messy due to the need of compatibility with the
//old 32bit file-length
char* dbname=*fnameptr;
//read just the tag first: 4 bytes ID
lseek(fd, -cdbInfoSIZE, SEEK_END);
int r=read(fd, &dbstat, cdbInfoSIZE );
if (r!=cdbInfoSIZE) return 2;
//GMessage("Size of dbstat=%d\n", cdbInfoSIZE);
if (strncmp(dbstat.oldtag, "CIDX", 4)==0) {
//old dbstat structure -- convert it
dbstat.num_keys=gcvt_uint(&dbstat.oldnum[0]);
dbstat.num_records=gcvt_uint(&dbstat.oldnum[1]);
dbstat.dbsize=gcvt_uint(&dbstat.old_dbsize);
dbstat.idxflags = gcvt_uint(&dbstat.old_idxflags);
//position on the dbnamelen entry
dbstat.dbnamelen = gcvt_uint(&dbstat.old_dbnamelen);
//GMessage("dbnamelen=%d\n", dbstat.dbnamelen);
lseek(fd, -(off_t)(cdbInfoSIZE-4+dbstat.dbnamelen), SEEK_END);
}
else if (strncmp(dbstat.tag, "CDBX", 4)!=0) {
GMessage("Error: this doesn't appear to be a cdbfasta created file!\n");
return 1;
}
else { // new CDBX type:
dbstat.dbsize = gcvt_offt(&dbstat.dbsize);
dbstat.num_keys=gcvt_uint(&dbstat.num_keys);
dbstat.num_records=gcvt_uint(&dbstat.num_records);
dbstat.idxflags = gcvt_uint(&dbstat.idxflags);
//position on the dbnamelen entry
dbstat.dbnamelen = gcvt_uint(&dbstat.dbnamelen);
//GMessage("dbnamelen=%d\n", dbstat.dbnamelen);
lseek(fd, -(off_t)(cdbInfoSIZE+dbstat.dbnamelen), SEEK_END);
}
GMALLOC(dbname, dbstat.dbnamelen+1);
dbname[dbstat.dbnamelen]='\0';
r=read(fd, dbname, dbstat.dbnamelen);
*fnameptr=dbname;
if (r!=dbstat.dbnamelen)
return 2;
return 0;
}
int parse_int(char* buf, const char* key, int& e) {
char* p, *q;
while (e!=EOF && isspace(e)) { //skip any spaces
if (e=='\n') GError(ERR_RANGEFMT, key);
e=fgetc(stdin);
}
if (e==EOF) GError(ERR_RANGEFMT, key);
//now e is the first non-space
p=buf;
q=p;
while (e!=EOF && !isspace(e)) {
*q=e;
q++;
e=fgetc(stdin);
}
*q='\0'; //now p is the starting coordinate string
return atoi(p);
//now the file pointer should be on the first space after the parsed value
}
int parse_int(char*& f, const char* key, int& e) {
char* p, *q;
char buf[16];
while (e!='\0' && isspace(e)) { //skip any spaces
if (e=='\n') GError(ERR_RANGEFMT, key);
f++;
e=*f;
}
if (e=='\0') GError(ERR_RANGEFMT, key);
//now e is the first non-space char
p=buf;
q=p;
while (e!='\0' && !isspace(e)) {
*q=e;
q++;
f++;
e=*f;
}
*q='\0';
return atoi(p);
//now f and e should be on the first space after the parsed value (or '\0')
}
GCdbYank::GCdbYank(const char* fidx, const char* recsep) {
is_compressed=false;
fd=-1;
cdb=NULL;
warnings=0;
#ifdef ENABLE_COMPRESSION
cdbz=NULL;
#endif
fdb=-1;
fz=NULL;
dbname=NULL;
recdelim=Gstrdup(recsep);
if (fidx==NULL) GError("GCdbYank Error: NULL index file name!");
idxfile=Gstrdup(fidx);
cdb=new GCdbRead(idxfile);
fd=cdb->getfd();
db_size=0;
dbstat.dbsize=0;
info_dbname=NULL;
int r=read_dbinfo(fd, &info_dbname, dbstat);
lseek(fd, 0, SEEK_SET);
if (r==1) GError("This file does not seem to be a cdbfasta generated file.\n");
else if (r==2)
GError("Error reading info chunk!\n");
/*try to find the database file
rules: if given, only the -d given filename is used
otherwise:
1) the same directory with the given index file(stripping the suffix)
2) the dbstat filepath/name stored by cdbfasta
*/
if (dbname==NULL) {
char* p = rstrchr(idxfile, '.');
if (p!=NULL) {
/*GError("%s\ncdbyank error: cannot use %s as an index file. When no -d is\n\
given, so the database file can be located in the same directory \n\
by removing the index file suffix (.cidx)\n", USAGE, idxfile);*/
int nlen=p-idxfile;
char* namebuf=NULL;
GMALLOC(namebuf, nlen+1);
strncpy(namebuf, idxfile, nlen);
namebuf[nlen]='\0';
if (fileExists(namebuf))
dbname=namebuf;
} // strip the index file extenstion
// 2) try the stored dbstat name
if (dbname==NULL) {
if (fileExists(info_dbname)) dbname=info_dbname;
else GError("Cannot locate the database file for this index\n");
}
}// database name not given
is_compressed=(dbstat.idxflags & CDBMSK_OPT_COMPRESS);
if (is_compressed)
//try to open the dbname as a compressed file
fz=fopen(dbname, "rb");
else fdb=open(dbname, O_RDONLY|O_BINARY);
if (fdb==-1 && fz==NULL)
GError("Error: cannot open database file %s\n",dbname);
if (is_compressed) {
#ifndef ENABLE_COMPRESSION
GError(err_COMPRESSED);
#else
fclose(fz);//just to start fresh here
//determine size:
int ftmp = open(dbname, O_RDONLY|O_BINARY);
if (ftmp == -1) GError("Error reopening db '%s'?\n",dbname);
struct stat fdbstat;
fstat(ftmp, &fdbstat);
db_size=fdbstat.st_size;
close(ftmp);
//-------- reopen here
cdbz=openCdbz(dbname);
if (cdbz==NULL)
GError("Error opening the cdbz file '%s'\n");
fz=cdbz->getZFile();
#endif
}
else {
struct stat fdbstat;
if (stat(dbname, &fdbstat)!=0) {
perror("stat()");
exit(1);
}
db_size=fdbstat.st_size;
}
//abort if the database size was read and it doesn't match the cdbfasta stored size
if (dbstat.dbsize>0 && dbstat.dbsize!=db_size)
GError("Error: invalid %d database size - (%lld vs %lld) please rerun cdbfasta for '%s'\n",
fdb, dbstat.dbsize, db_size, dbname);
fastahandler=new GFastaCharHandler(recdelim);
} //* GCdbYank constructor *//
GCdbYank::~GCdbYank() {
if (is_compressed) {
fclose(fz);
#ifdef ENABLE_COMPRESSION
delete cdbz;
#endif
}
else close(fdb);
GFREE(info_dbname);
delete fastahandler;
GFREE(recdelim);
GFREE(dbname);
GFREE(idxfile);
delete cdb;
close(fd);
}
int GCdbYank::getRecord(const char* key, FastaSeq& rec, charFunc* seqCallBack) {
//assumes fdb is open, cdb was created on the index file
int r=cdb->find(key);
if (r==0) return 0;
if (r==-1)
GError("cdbyank: error searching for key %s in %s\n", key, idxfile);
/* while (r>0) { */
off_t pos = cdb->datapos(); //position of this key's record in the index file
unsigned int len=cdb->datalen(); // length of this key's record
char bytes[32]; // data buffer -- should just accomodate fastarec_pos, fastarec_length
if (cdb->read(bytes,len,pos) == -1)
GError("cdbyank: error at GCbd::read (%s)!\n", idxfile);
off_t fpos; //this will be the fastadb offset
uint32 reclen; //this will be the fasta record offset
if (len>irec_size32) { //64 bit file offset was used
fpos=gcvt_offt(bytes);
reclen=gcvt_uint(&bytes[sizeof(uint32)<<1]);
}
else { //32bit offset used
fpos=gcvt_uint(bytes);
reclen=gcvt_uint(&bytes[sizeof(uint32)]);
}
//GMessage("reclen=%d\n", reclen);
/* if (showQuery)
fprintf(fout, "%c%s%c\t", delimQuery, key, delimQuery);*/
/*========= FETCHING RECORD CONTENT ======= */
if (is_compressed) {
//for now: ignore special retrievals, just print the whole record
#ifdef ENABLE_COMPRESSION
return cdbz->decompress(rec, reclen, fpos, seqCallBack);
#else
GError(err_COMPRESSED);
#endif
}
else { // not compressed -- position into the file and build an ad hoc GFastaFile
lseek(fdb, fpos, SEEK_SET);
// read it char by char and return it as output
char c='\0';
int charsread=0;
fastahandler->init(&rec, seqCallBack);
while (reclen-- && read(fdb, &c, 1)==1) {
fastahandler->processChar(c);
charsread++;
}
fastahandler->done();
return charsread;
} // not compressed
/* if (many) r=cdb->findnext(key, strlen(key));
else r=0;
} */
return 0;
}
off_t GCdbYank::getRecordPos(const char* key, uint32* record_len) {
//assumes fdb is open, cdb was created on the index file
int r=cdb->find(key);
if (r==0 && warnings) {
GMessage("cdbyank: key \"%s\" not found in %s\n", key, idxfile);
return -1;
}
if (r==-1)
GError("cdbyank: error searching for key %s in %s\n", key, idxfile);
off_t pos = cdb->datapos(); //position of this key's record in the index file
unsigned int len=cdb->datalen(); // length of this key's record
char bytes[64]; // data buffer -- should just accomodate fastarec_pos, fastarec_length
if (cdb->read(bytes,len,pos) == -1)
GError("cdbyank: error at GCbd::read (%s)!\n", idxfile);
off_t fpos; //this will be the fastadb offset
uint32 rlen; //this will be the fasta record length
if (len>irec_size32) { //64 bit file offset was used
fpos=gcvt_offt(bytes);
rlen=gcvt_uint(&bytes[offsetof(CIdxData, reclen)]);
}
else { //32bit offset used
fpos=gcvt_uint(bytes);
rlen=gcvt_uint(&bytes[offsetof(CIdxData32, reclen)]);
}
if (record_len!=NULL) *record_len=rlen;
return fpos;
}