Debian Codegraph @

sam/record.go

raw symbols SCIP
1 // Copyright ©2012-2013 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 sam
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "strconv"
12
13 "github.com/biogo/hts/internal"
14 )
15
16 // Record represents a SAM/BAM record.
17 type Record struct {
18 Name string
19 Ref *Reference
20 Pos int
21 MapQ byte
22 Cigar Cigar
23 Flags Flags
24 MateRef *Reference
25 MatePos int
26 TempLen int
27 Seq Seq
28 Qual []byte
29 AuxFields AuxFields
30 }
31
32 // NewRecord returns a Record, checking for consistency of the provided
33 // attributes.
34 func NewRecord(name string, ref, mRef *Reference, p, mPos, tLen int, mapQ byte, co []CigarOp, seq, qual []byte, aux []Aux) (*Record, error) {
35 if !(validPos(p) && validPos(mPos) && validTmpltLen(tLen) && validLen(len(seq)) && (qual == nil || validLen(len(qual)))) {
36 return nil, errors.New("sam: value out of range")
37 }
38 if len(name) == 0 || len(name) > 254 {
39 return nil, errors.New("sam: name absent or too long")
40 }
41 if qual != nil && len(qual) != len(seq) {
42 return nil, errors.New("sam: sequence/quality length mismatch")
43 }
44 if ref != nil {
45 if ref.id < 0 {
46 return nil, errors.New("sam: linking to invalid reference")
47 }
48 } else {
49 if p != -1 {
50 return nil, errors.New("sam: specified position != -1 without reference")
51 }
52 }
53 if mRef != nil {
54 if mRef.id < 0 {
55 return nil, errors.New("sam: linking to invalid mate reference")
56 }
57 } else {
58 if mPos != -1 {
59 return nil, errors.New("sam: specified mate position != -1 without mate reference")
60 }
61 }
62 r := &Record{
63 Name: name,
64 Ref: ref,
65 Pos: p,
66 MapQ: mapQ,
67 Cigar: co,
68 MateRef: mRef,
69 MatePos: mPos,
70 TempLen: tLen,
71 Seq: NewSeq(seq),
72 Qual: qual,
73 AuxFields: aux,
74 }
75 return r, nil
76 }
77
78 // IsValidRecord returns whether the record satisfies the conditions that
79 // it has the Unmapped flag set if it not placed; that the MateUnmapped
80 // flag is set if it paired its mate is unplaced; that the CIGAR length
81 // matches the sequence and quality string lengths if they are non-zero; and
82 // that the Paired, ProperPair, Unmapped and MateUnmapped flags are consistent.
83 func IsValidRecord(r *Record) bool {
84 if (r.Ref == nil || r.Pos == -1) && r.Flags&Unmapped == 0 {
85 return false
86 }
87 if r.Flags&Paired != 0 && (r.MateRef == nil || r.MatePos == -1) && r.Flags&MateUnmapped == 0 {
88 return false
89 }
90 if r.Flags&(Unmapped|ProperPair) == Unmapped|ProperPair {
91 return false
92 }
93 if r.Flags&(Paired|MateUnmapped|ProperPair) == Paired|MateUnmapped|ProperPair {
94 return false
95 }
96 if len(r.Qual) != 0 && r.Seq.Length != len(r.Qual) {
97 return false
98 }
99 if r.Seq.Length != 0 && r.Seq.Length != r.queryLen() {
100 return false
101 }
102 return true
103 }
104
105 func (r *Record) queryLen() int {
106 var l int
107 for _, co := range r.Cigar {
108 l += co.Len() * co.Type().Consumes().Query
109 }
110 return l
111 }
112
113 // Tag returns an Aux tag whose tag ID matches the first two bytes of tag and true.
114 // If no tag matches, nil and false are returned.
115 func (r *Record) Tag(tag []byte) (v Aux, ok bool) {
116 if len(tag) < 2 {
117 panic("sam: tag too short")
118 }
119 for _, aux := range r.AuxFields {
120 if aux.matches(tag) {
121 return aux, true
122 }
123 }
124 return nil, false
125 }
126
127 // RefID returns the reference ID for the Record.
128 func (r *Record) RefID() int {
129 return r.Ref.ID()
130 }
131
132 // Start returns the lower-coordinate end of the alignment.
133 func (r *Record) Start() int {
134 return r.Pos
135 }
136
137 // Bin returns the BAM index bin of the record.
138 func (r *Record) Bin() int {
139 if r.Flags&(Unmapped|MateUnmapped) == Unmapped|MateUnmapped {
140 return 4680 // reg2bin(-1, 0)
141 }
142 return int(internal.BinFor(r.Pos, r.End()))
143 }
144
145 // Len returns the length of the alignment.
146 func (r *Record) Len() int {
147 return r.End() - r.Start()
148 }
149
150 func max(a, b int) int {
151 if a < b {
152 return b
153 }
154 return a
155 }
156
157 // End returns the highest query-consuming coordinate end of the alignment.
158 // The position returned by End is not valid if r.Cigar.IsValid(r.Seq.Length)
159 // is false.
160 func (r *Record) End() int {
161 if r.Flags&Unmapped != 0 || len(r.Cigar) == 0 {
162 return r.Pos + 1
163 }
164 pos := r.Pos
165 end := pos
166 for _, co := range r.Cigar {
167 pos += co.Len() * co.Type().Consumes().Reference
168 end = max(end, pos)
169 }
170 return end
171 }
172
173 // Strand returns an int8 indicating the strand of the alignment. A positive return indicates
174 // alignment in the forward orientation, a negative returns indicates alignment in the reverse
175 // orientation.
176 func (r *Record) Strand() int8 {
177 if r.Flags&Reverse == Reverse {
178 return -1
179 }
180 return 1
181 }
182
183 // LessByName returns true if the receiver sorts by record name before other.
184 func (r *Record) LessByName(other *Record) bool {
185 return r.Name < other.Name
186 }
187
188 // LessByCoordinate returns true if the receiver sorts by coordinate before other
189 // according to the SAM specification.
190 func (r *Record) LessByCoordinate(other *Record) bool {
191 rRefName := r.Ref.Name()
192 oRefName := other.Ref.Name()
193 switch {
194 case oRefName == "*":
195 return true
196 case rRefName == "*":
197 return false
198 }
199 return (rRefName < oRefName) || (rRefName == oRefName && r.Pos < other.Pos)
200 }
201
202 // String returns a string representation of the Record.
203 func (r *Record) String() string {
204 end := r.End()
205 return fmt.Sprintf("%s %v %v %d %s:%d..%d (%d) %d %s:%d %d %s %v %v",
206 r.Name,
207 r.Flags,
208 r.Cigar,
209 r.MapQ,
210 r.Ref.Name(),
211 r.Pos,
212 end,
213 r.Bin(),
214 end-r.Pos,
215 r.MateRef.Name(),
216 r.MatePos,
217 r.TempLen,
218 r.Seq.Expand(),
219 r.Qual,
220 r.AuxFields,
221 )
222 }
223
224 // UnmarshalText implements the encoding.TextUnmarshaler. It calls UnmarshalSAM with
225 // a nil Header.
226 func (r *Record) UnmarshalText(b []byte) error {
227 return r.UnmarshalSAM(nil, b)
228 }
229
230 // UnmarshalSAM parses a SAM format alignment line in the provided []byte, using
231 // references from the provided Header. If a nil Header is passed to UnmarshalSAM
232 // and the SAM data include non-empty refence and mate reference names, fake
233 // references with zero length and an ID of -1 are created to hold the reference
234 // names.
235 func (r *Record) UnmarshalSAM(h *Header, b []byte) error {
236 f := bytes.Split(b, []byte{'\t'})
237 if len(f) < 11 {
238 return errors.New("sam: missing SAM fields")
239 }
240 *r = Record{Name: string(f[0])}
241 // TODO(kortschak): Consider parsing string format flags.
242 flags, err := strconv.ParseUint(string(f[1]), 0, 16)
243 if err != nil {
244 return fmt.Errorf("sam: failed to parse flags: %w", err)
245 }
246 r.Flags = Flags(flags)
247 r.Ref, err = referenceForName(h, string(f[2]))
248 if err != nil {
249 return fmt.Errorf("sam: failed to assign reference: %w", err)
250 }
251 r.Pos, err = strconv.Atoi(string(f[3]))
252 r.Pos--
253 if err != nil {
254 return fmt.Errorf("sam: failed to parse position: %w", err)
255 }
256 mapQ, err := strconv.ParseUint(string(f[4]), 10, 8)
257 if err != nil {
258 return fmt.Errorf("sam: failed to parse map quality: %w", err)
259 }
260 r.MapQ = byte(mapQ)
261 r.Cigar, err = ParseCigar(f[5])
262 if err != nil {
263 return fmt.Errorf("sam: failed to parse cigar string: %w", err)
264 }
265 if bytes.Equal(f[2], f[6]) || bytes.Equal(f[6], []byte{'='}) {
266 r.MateRef = r.Ref
267 } else {
268 r.MateRef, err = referenceForName(h, string(f[6]))
269 if err != nil {
270 return fmt.Errorf("sam: failed to assign mate reference: %w", err)
271 }
272 }
273 r.MatePos, err = strconv.Atoi(string(f[7]))
274 r.MatePos--
275 if err != nil {
276 return fmt.Errorf("sam: failed to parse mate position: %w", err)
277 }
278 r.TempLen, err = strconv.Atoi(string(f[8]))
279 if err != nil {
280 return fmt.Errorf("sam: failed to parse template length: %w", err)
281 }
282 if !bytes.Equal(f[9], []byte{'*'}) {
283 r.Seq = NewSeq(f[9])
284 if len(r.Cigar) != 0 && !r.Cigar.IsValid(r.Seq.Length) {
285 return errors.New("sam: sequence/CIGAR length mismatch")
286 }
287 }
288 if !bytes.Equal(f[10], []byte{'*'}) {
289 r.Qual = append(r.Qual, f[10]...)
290 for i := range r.Qual {
291 r.Qual[i] -= 33
292 }
293 } else if r.Seq.Length != 0 {
294 r.Qual = make([]byte, r.Seq.Length)
295 for i := range r.Qual {
296 r.Qual[i] = 0xff
297 }
298 }
299 if len(r.Qual) != 0 && len(r.Qual) != r.Seq.Length {
300 return errors.New("sam: sequence/quality length mismatch")
301 }
302 if len(f) > 11 {
303 r.AuxFields = make([]Aux, len(f)-11)
304 for i, aux := range f[11:] {
305 a, err := ParseAux(aux)
306 if err != nil {
307 return err
308 }
309 r.AuxFields[i] = a
310 }
311 }
312 return nil
313 }
314
315 func referenceForName(h *Header, name string) (*Reference, error) {
316 if name == "*" {
317 return nil, nil
318 }
319 if h == nil {
320 // If we don't have a Header, return a fake Reference.
321 return &Reference{
322 id: -1,
323 name: name,
324 }, nil
325 }
326
327 for _, r := range h.refs {
328 if r.Name() == name {
329 return r, nil
330 }
331 }
332 return nil, fmt.Errorf("no reference with name %q", name)
333 }
334
335 // MarshalText implements encoding.TextMarshaler. It calls MarshalSAM with FlagDecimal.
336 func (r *Record) MarshalText() ([]byte, error) {
337 return r.MarshalSAM(0)
338 }
339
340 // MarshalSAM formats a Record as SAM using the specified flag format. Acceptable
341 // formats are FlagDecimal, FlagHex and FlagString.
342 func (r *Record) MarshalSAM(flags int) ([]byte, error) {
343 if flags < FlagDecimal || flags > FlagString {
344 return nil, errors.New("sam: flag format option out of range")
345 }
346 if r.Qual != nil && len(r.Qual) != r.Seq.Length {
347 return nil, errors.New("sam: sequence/quality length mismatch")
348 }
349 var buf bytes.Buffer
350 fmt.Fprintf(&buf, "%s\t%v\t%s\t%d\t%d\t%s\t%s\t%d\t%d\t%s\t%s",
351 r.Name,
352 formatFlags(r.Flags, flags),
353 r.Ref.Name(),
354 r.Pos+1,
355 r.MapQ,
356 r.Cigar,
357 formatMate(r.Ref, r.MateRef),
358 r.MatePos+1,
359 r.TempLen,
360 formatSeq(r.Seq),
361 formatQual(r.Qual),
362 )
363 for _, t := range r.AuxFields {
364 fmt.Fprintf(&buf, "\t%v", samAux(t))
365 }
366 return buf.Bytes(), nil
367 }
368
369 // Flag format constants.
370 const (
371 FlagDecimal = iota
372 FlagHex
373 FlagString
374 )
375
376 func formatFlags(f Flags, format int) interface{} {
377 switch format {
378 case FlagDecimal:
379 return uint16(f)
380 case FlagHex:
381 return fmt.Sprintf("0x%x", f)
382 case FlagString:
383 // If 0x01 is unset, no assumptions can be made about 0x02, 0x08, 0x20, 0x40 and 0x80
384 const pairedMask = ProperPair | MateUnmapped | MateReverse | MateReverse | Read1 | Read2
385 if f&1 == 0 {
386 f &^= pairedMask
387 }
388
389 const flags = "pPuUrR12sfdS"
390
391 b := make([]byte, 0, len(flags))
392 for i, c := range flags {
393 if f&(1<<uint(i)) != 0 {
394 b = append(b, byte(c))
395 }
396 }
397
398 return string(b)
399 default:
400 panic("sam: invalid flag format")
401 }
402 }
403
404 func formatMate(ref, mate *Reference) string {
405 if mate != nil && ref == mate {
406 return "="
407 }
408 return mate.Name()
409 }
410
411 func formatSeq(s Seq) []byte {
412 if s.Length == 0 {
413 return []byte{'*'}
414 }
415 return s.Expand()
416 }
417
418 func formatQual(q []byte) []byte {
419 for _, v := range q {
420 if v != 0xff {
421 a := make([]byte, len(q))
422 for i, p := range q {
423 a[i] = p + 33
424 }
425 return a
426 }
427 }
428 return []byte{'*'}
429 }
430
431 // Doublet is a nybble-encode pair of nucleotide bases.
432 type Doublet byte
433
434 // Seq is a nybble-encode pair of nucleotide sequence.
435 type Seq struct {
436 Length int
437 Seq []Doublet
438 }
439
440 var (
441 n16TableRev = [16]byte{'=', 'A', 'C', 'M', 'G', 'R', 'S', 'V', 'T', 'W', 'Y', 'H', 'K', 'D', 'B', 'N'}
442 n16Table = [256]Doublet{
443 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf,
444 0xf, 0xf, 0xf, 0xf, 0xf,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 0xf, 0xf, 0xf,
457 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf,
458 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf,
459 }
460 )
461
462 // NewSeq returns a new Seq based on the given byte slice.
463 func NewSeq(s []byte) Seq {
464 return Seq{
465 Length: len(s),
466 Seq: contract(s),
467 }
468 }
469
470 func contract(s []byte) []Doublet {
471 ns := make([]Doublet, (len(s)+1)>>1)
472 var np Doublet
473 for i, b := range s {
474 if i&1 == 0 {
475 np = n16Table[b] << 4
476 } else {
477 ns[i>>1] = np | n16Table[b]
478 }
479 }
480 // We haven't written the last base if the
481 // sequence was odd length, so do that now.
482 if len(s)&1 != 0 {
483 ns[len(ns)-1] = np
484 }
485 return ns
486 }
487
488 // Expand returns the byte encoded form of the receiver.
489 func (ns Seq) Expand() []byte {
490 s := make([]byte, ns.Length)
491 for i := range s {
492 if i&1 == 0 {
493 s[i] = n16TableRev[ns.Seq[i>>1]>>4]
494 } else {
495 s[i] = n16TableRev[ns.Seq[i>>1]&0xf]
496 }
497 }
498
499 return s
500 }
501
502 // At returns the base at the given position.
503 // At panics unless 0 <= pos < ns.Length.
504 func (ns Seq) At(pos int) byte {
505 if pos%2 == 0 {
506 return n16TableRev[ns.Seq[pos/2]>>4]
507 }
508 return n16TableRev[ns.Seq[pos/2]&0xf]
509 }