Debian Codegraph @

bam/reader.go

raw symbols SCIP
1 // Copyright ©2012 The bíogo Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package bam
6
7 import (
8 "bytes"
9 "encoding/binary"
10 "errors"
11 "fmt"
12 "io"
13 "unsafe"
14
15 "github.com/biogo/hts/bgzf"
16 "github.com/biogo/hts/sam"
17 )
18
19 // Reader implements BAM data reading.
20 type Reader struct {
21 r *bgzf.Reader
22 h *sam.Header
23 c *bgzf.Chunk
24
25 // references is cached header
26 // reference count.
27 references int32
28
29 // omit specifies how much of the
30 // record should be omitted during
31 // a read of the BAM input.
32 omit int
33
34 lastChunk bgzf.Chunk
35
36 // buf is used to read the block data for each record.
37 // The size is chosen to be small, but large enough to
38 // be able to contain the majority of reasonable BAM
39 // records when serialised as byte data.
40 buf [0x1000]byte
41 }
42
43 // NewReader returns a new Reader using the given io.Reader
44 // and setting the read concurrency to rd. If rd is zero
45 // concurrency is set to GOMAXPROCS. The returned Reader
46 // should be closed after use to avoid leaking resources.
47 func NewReader(r io.Reader, rd int) (*Reader, error) {
48 bg, err := bgzf.NewReader(r, rd)
49 if err != nil {
50 return nil, err
51 }
52 h, _ := sam.NewHeader(nil, nil)
53 br := &Reader{
54 r: bg,
55 h: h,
56
57 references: int32(len(h.Refs())),
58 }
59 err = br.h.DecodeBinary(br.r)
60 if err != nil {
61 return nil, err
62 }
63 br.lastChunk.End = br.r.LastChunk().End
64 return br, nil
65 }
66
67 // Header returns the SAM Header held by the Reader.
68 func (br *Reader) Header() *sam.Header {
69 return br.h
70 }
71
72 // BAM record layout.
73 type bamRecordFixed struct {
74 blockSize int32
75 refID int32
76 pos int32
77 nLen uint8
78 mapQ uint8
79 bin uint16
80 nCigar uint16
81 flags sam.Flags
82 lSeq int32
83 nextRefID int32
84 nextPos int32
85 tLen int32
86 }
87
88 var (
89 lenFieldSize = binary.Size(bamRecordFixed{}.blockSize)
90 bamFixedRemainder = binary.Size(bamRecordFixed{}) - lenFieldSize
91 )
92
93 func vOffset(o bgzf.Offset) int64 {
94 return o.File<<16 | int64(o.Block)
95 }
96
97 // Omit specifies what portions of the Record to omit reading.
98 // When o is None, a full sam.Record is returned by Read, when o
99 // is AuxTags the auxiliary tag data is omitted and when o is
100 // AllVariableLengthData, sequence, quality and auxiliary data
101 // is omitted.
102 func (br *Reader) Omit(o int) {
103 br.omit = o
104 }
105
106 // None, AuxTags and AllVariableLengthData are values taken
107 // by the Reader Omit method.
108 const (
109 None = iota // Omit no field data from the record.
110 AuxTags // Omit auxiliary tag data.
111 AllVariableLengthData // Omit sequence, quality and auxiliary data.
112 )
113
114 // Read returns the next sam.Record in the BAM stream.
115 //
116 // The sam.Record returned will not contain the sequence, quality or
117 // auxiliary tag data if Omit(AllVariableLengthData) has been called
118 // prior to the Read call and will not contain the auxiliary tag data
119 // if Omit(AuxTags) has been called.
120 func (br *Reader) Read() (*sam.Record, error) {
121 if br.c != nil && vOffset(br.r.LastChunk().End) >= vOffset(br.c.End) {
122 return nil, io.EOF
123 }
124
125 b, err := newBuffer(br)
126 if err != nil {
127 return nil, err
128 }
129
130 var rec sam.Record
131 refID := b.readInt32()
132 rec.Pos = int(b.readInt32())
133 nLen := b.readUint8()
134 rec.MapQ = b.readUint8()
135 b.discard(2)
136 nCigar := b.readUint16()
137 rec.Flags = sam.Flags(b.readUint16())
138 lSeq := int(b.readInt32())
139 nextRefID := b.readInt32()
140 rec.MatePos = int(b.readInt32())
141 rec.TempLen = int(b.readInt32())
142
143 // Read variable length data.
144 if nLen < 1 {
145 return nil, fmt.Errorf("bam: invalid read name length: %d", nLen)
146 }
147 rec.Name = string(b.unsafeBytes(int(nLen) - 1))
148 b.discard(1)
149
150 // bytes are safe since readCigarOps does not retain the returned buffer.
151 rec.Cigar = readCigarOps(b.unsafeBytes(int(nCigar) * 4))
152
153 var seq, auxTags []byte
154 if br.omit >= AllVariableLengthData {
155 goto done
156 }
157
158 if lSeq < 0 {
159 return nil, fmt.Errorf("bam: invalid sequence length: %d", lSeq)
160 }
161 seq = b.bytes((lSeq >> 1) + (lSeq & 0x1))
162 rec.Seq = sam.Seq{Length: lSeq, Seq: *(*doublets)(unsafe.Pointer(&seq))}
163 rec.Qual = b.bytes(lSeq)
164
165 if br.omit >= AuxTags {
166 goto done
167 }
168 auxTags = b.bytes(b.len())
169 rec.AuxFields, err = parseAux(auxTags)
170 if err != nil {
171 return nil, err
172 }
173
174 done:
175 refs := int32(len(br.h.Refs()))
176 if refID != -1 {
177 if refID < -1 || refID >= refs {
178 return nil, errors.New("bam: reference id out of range")
179 }
180 rec.Ref = br.h.Refs()[refID]
181 }
182 if nextRefID != -1 {
183 if refID == nextRefID {
184 rec.MateRef = rec.Ref
185 return &rec, nil
186 }
187 if nextRefID < -1 || nextRefID >= refs {
188 return nil, errors.New("bam: mate reference id out of range")
189 }
190 rec.MateRef = br.h.Refs()[nextRefID]
191 }
192
193 return &rec, nil
194 }
195
196 // SetCache sets the cache to be used by the Reader.
197 func (bg *Reader) SetCache(c bgzf.Cache) {
198 bg.r.SetCache(c)
199 }
200
201 // Seek performs a seek to the specified bgzf.Offset.
202 func (br *Reader) Seek(off bgzf.Offset) error {
203 return br.r.Seek(off)
204 }
205
206 // SetChunk sets a limited range of the underlying BGZF file to read, after
207 // seeking to the start of the given chunk. It may be used to iterate over
208 // a defined genomic interval.
209 func (br *Reader) SetChunk(c *bgzf.Chunk) error {
210 if c != nil {
211 err := br.r.Seek(c.Begin)
212 if err != nil {
213 return err
214 }
215 }
216 br.c = c
217 return nil
218 }
219
220 // LastChunk returns the bgzf.Chunk corresponding to the last Read operation.
221 // The bgzf.Chunk returned is only valid if the last Read operation returned a
222 // nil error.
223 func (br *Reader) LastChunk() bgzf.Chunk {
224 return br.lastChunk
225 }
226
227 // Close closes the Reader.
228 func (br *Reader) Close() error {
229 return br.r.Close()
230 }
231
232 // Iterator wraps a Reader to provide a convenient loop interface for reading BAM data.
233 // Successive calls to the Next method will step through the features of the provided
234 // Reader. Iteration stops unrecoverably at EOF or the first error.
235 type Iterator struct {
236 r *Reader
237
238 chunks []bgzf.Chunk
239
240 rec *sam.Record
241 err error
242 }
243
244 // NewIterator returns a Iterator to read from r, limiting the reads to the provided
245 // chunks.
246 //
247 // chunks, err := idx.Chunks(ref, beg, end)
248 // if err != nil {
249 // return err
250 // }
251 // i, err := NewIterator(r, chunks)
252 // if err != nil {
253 // return err
254 // }
255 // for i.Next() {
256 // fn(i.Record())
257 // }
258 // return i.Close()
259 func NewIterator(r *Reader, chunks []bgzf.Chunk) (*Iterator, error) {
260 if len(chunks) == 0 {
261 return &Iterator{r: r}, nil
262 }
263 err := r.SetChunk(&chunks[0])
264 if err != nil {
265 return nil, err
266 }
267 chunks = chunks[1:]
268 return &Iterator{r: r, chunks: chunks}, nil
269 }
270
271 // Next advances the Iterator past the next record, which will then be available through
272 // the Record method. It returns false when the iteration stops, either by reaching the end of the
273 // input or an error. After Next returns false, the Error method will return any error that
274 // occurred during iteration, except that if it was io.EOF, Error will return nil.
275 func (i *Iterator) Next() bool {
276 if i.err != nil {
277 return false
278 }
279 i.rec, i.err = i.r.Read()
280 if len(i.chunks) != 0 && i.err == io.EOF {
281 i.err = i.r.SetChunk(&i.chunks[0])
282 i.chunks = i.chunks[1:]
283 return i.Next()
284 }
285 return i.err == nil
286 }
287
288 // Error returns the first non-EOF error that was encountered by the Iterator.
289 func (i *Iterator) Error() error {
290 if i.err == io.EOF {
291 return nil
292 }
293 return i.err
294 }
295
296 // Record returns the most recent record read by a call to Next.
297 func (i *Iterator) Record() *sam.Record { return i.rec }
298
299 // Close releases the underlying Reader.
300 func (i *Iterator) Close() error {
301 i.r.SetChunk(nil)
302 return i.Error()
303 }
304
305 // len(cb) must be a multiple of 4.
306 func readCigarOps(cb []byte) []sam.CigarOp {
307 co := make([]sam.CigarOp, len(cb)/4)
308 for i := range co {
309 co[i] = sam.CigarOp(binary.LittleEndian.Uint32(cb[i*4 : (i+1)*4]))
310 }
311 return co
312 }
313
314 var jumps = [256]int{
315 'A': 1,
316 'c': 1, 'C': 1,
317 's': 2, 'S': 2,
318 'i': 4, 'I': 4,
319 'f': 4,
320 'Z': -1,
321 'H': -1,
322 'B': -1,
323 }
324
325 // parseAux examines the data of a SAM record's OPT fields,
326 // returning a slice of sam.Aux that are backed by the original data.
327 func parseAux(aux []byte) ([]sam.Aux, error) {
328 if len(aux) == 0 {
329 return nil, nil
330 }
331
332 // Heuristically pre-allocate enough slots for the byte data.
333 // Value chosen by experimentation and will not fit all inputs,
334 // with the cost being over-allocation.
335 aa := make([]sam.Aux, 0, len(aux)/4)
336
337 for i := 0; i+2 < len(aux); {
338 t := aux[i+2]
339 switch j := jumps[t]; {
340 case j > 0:
341 j += 3
342 aa = append(aa, sam.Aux(aux[i:i+j:i+j]))
343 i += j
344 case j < 0:
345 switch t {
346 case 'Z', 'H':
347 j := bytes.IndexByte(aux[i:], 0)
348 if j == -1 {
349 return nil, errors.New("bam: invalid zero terminated data: no zero")
350 }
351 aa = append(aa, sam.Aux(aux[i:i+j:i+j]))
352 i += j + 1
353 case 'B':
354 length := binary.LittleEndian.Uint32(aux[i+4 : i+8])
355 j = int(length)*jumps[aux[i+3]] + int(unsafe.Sizeof(length)) + 4
356 if j < 0 || i+j < 0 || i+j > len(aux) {
357 return nil, fmt.Errorf("bam: invalid array length for aux data: %d", length)
358 }
359 aa = append(aa, sam.Aux(aux[i:i+j:i+j]))
360 i += j
361 }
362 default:
363 return nil, fmt.Errorf("bam: unrecognised optional field type: %q", t)
364 }
365 }
366 return aa, nil
367 }
368
369 // buffer is light-weight read buffer.
370 type buffer struct {
371 off int
372 data []byte
373 shared bool
374 err error
375 }
376
377 // bytes returns the next n bytes in the buffer. It is safe for the caller
378 // to retain the byte slice.
379 func (b *buffer) bytes(n int) []byte {
380 data := b.unsafeBytes(n)
381 if !b.shared {
382 return data
383 }
384 // TODO(kortschak): Replace this with bytes.Clone when available.
385 // See https://github.com/golang/go/issues/45038 for bytes.Clone.
386 return append(data[:0:0], data...)
387 }
388
389 // unsafeBytes returns the next n bytes of the buffer. The caller must not
390 // retain the returned byte slice without copying it.
391 func (b *buffer) unsafeBytes(n int) []byte {
392 if b.err != nil {
393 return nil
394 }
395 if b.len() < n {
396 b.err = io.ErrUnexpectedEOF
397 return nil
398 }
399 s := b.off
400 b.off += n
401 return b.data[s:b.off]
402 }
403
404 func (b *buffer) len() int {
405 return len(b.data) - b.off
406 }
407
408 func (b *buffer) discard(n int) {
409 if b.err != nil {
410 return
411 }
412 if b.len() < n {
413 b.err = io.ErrUnexpectedEOF
414 return
415 }
416 b.off += n
417 }
418
419 func (b *buffer) readUint8() uint8 {
420 if b.err != nil {
421 return 0
422 }
423 if b.len() < 1 {
424 b.err = io.ErrUnexpectedEOF
425 return 0
426 }
427 b.off++
428 return b.data[b.off-1]
429 }
430
431 func (b *buffer) readUint16() uint16 {
432 if b.err != nil {
433 return 0
434 }
435 if b.len() < 2 {
436 b.err = io.ErrUnexpectedEOF
437 return 0
438 }
439 return binary.LittleEndian.Uint16(b.unsafeBytes(2))
440 }
441
442 func (b *buffer) readInt32() int32 {
443 if b.err != nil {
444 return 0
445 }
446 if b.len() < 4 {
447 b.err = io.ErrUnexpectedEOF
448 return 0
449 }
450 return int32(binary.LittleEndian.Uint32(b.unsafeBytes(4)))
451 }
452
453 // newBuffer returns a new buffer reading from the Reader's underlying bgzf.Reader and
454 // updates the Reader's lastChunk field.
455 func newBuffer(br *Reader) (*buffer, error) {
456 n, err := io.ReadFull(br.r, br.buf[:4])
457 // br.r.Chunk() is only valid after the call the Read(), so this
458 // must come after the first read in the record.
459 tx := br.r.Begin()
460 defer func() {
461 br.lastChunk = tx.End()
462 }()
463 if err != nil {
464 return nil, err
465 }
466 if n != 4 {
467 return nil, errors.New("bam: invalid record: short block size")
468 }
469 b := &buffer{data: br.buf[:4]}
470 size := int(b.readInt32())
471 if size == 0 {
472 return nil, io.EOF
473 }
474 if size < 0 {
475 return nil, errors.New("bam: invalid record: invalid block size")
476 }
477 if size > cap(br.buf) {
478 b.off, b.data = 0, make([]byte, size)
479 } else {
480 b.off, b.data = 0, br.buf[:size]
481 b.shared = true
482 }
483 n, err = io.ReadFull(br.r, b.data)
484 if err != nil {
485 return nil, err
486 }
487 if n != size {
488 return nil, errors.New("bam: truncated record")
489 }
490 return b, nil
491 }
492
493 // buildAux constructs a single byte slice that represents a slice of sam.Aux.
494 func buildAux(aa []sam.Aux) (aux []byte) {
495 for _, a := range aa {
496 // TODO: validate each 'a'
497 aux = append(aux, []byte(a)...)
498 switch a.Type() {
499 case 'Z', 'H':
500 aux = append(aux, 0)
501 }
502 }
503 return
504 }
505
506 type doublets []sam.Doublet
507
508 func (np doublets) Bytes() []byte { return *(*[]byte)(unsafe.Pointer(&np)) }