-
Notifications
You must be signed in to change notification settings - Fork 157
/
bam_toolbox.go
812 lines (736 loc) · 18.5 KB
/
bam_toolbox.go
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
// Copyright © 2020 Oxford Nanopore Technologies, 2020 Botond Sipos.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cmd
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"regexp"
"sort"
"github.com/biogo/hts/bam"
"github.com/biogo/hts/sam"
"github.com/shenwei356/bio/seq"
"github.com/shenwei356/bio/seqio/fai"
"github.com/shenwei356/bio/seqio/fastx"
syaml "github.com/smallfish/simpleyaml"
)
type BamTool struct {
Name string
Desc string
Use func(params *BamToolParams)
}
type BamToolParams struct {
Yaml *syaml.Yaml
InChan chan *sam.Record
OutChan chan *sam.Record
Quiet bool
Silent bool
Threads int
Rank int
Shed Toolshed
}
type Toolshed map[string]BamTool
func (s Toolshed) String() string {
tools := make([]string, 0, len(s))
for t := range s {
tools = append(tools, t)
}
sort.Strings(tools)
res := "Tool\tDescription\n"
res += "----\t-----------\n"
for _, t := range tools {
res += fmt.Sprintf("%s\t%s\n", s[t].Name, s[t].Desc)
}
return res
}
func NewToolshed() Toolshed {
ts := map[string]BamTool{
"AlnContext": BamTool{Name: "AlnContext", Desc: "filter records by the sequence context at start and end", Use: BamToolAlnContext},
"AccStats": BamTool{Name: "AccStats", Desc: "calculates mean accuracy weighted by aligment lengths", Use: BamToolAccStats},
"Dump": BamTool{Name: "Dump", Desc: "dump various record properties in TSV format", Use: BamToolDump},
"help": BamTool{Name: "help", Desc: "list all tools with description", Use: ListTools},
}
return ts
}
func NewBamReaderChan(inFile string, cp int, buff int, threads int) (chan *sam.Record, *bam.Reader) {
outChan := make(chan *sam.Record, cp)
fh, err := os.Stdin, error(nil)
if inFile != "-" {
fh, err = os.Open(inFile)
checkError(err)
}
r, err := bam.NewReader(bufio.NewReaderSize(fh, buff), threads)
go func() {
for {
rec, err := r.Read()
if err == io.EOF {
close(outChan)
return
}
if err != nil {
close(outChan)
}
checkError(err)
outChan <- rec
}
}()
return outChan, r
}
func NewBamSinkChan(cp int) (chan *sam.Record, chan bool) {
outChan := make(chan *sam.Record, cp)
doneChan := make(chan bool, 0)
go func() {
for rec := range outChan {
_ = rec
}
doneChan <- true
}()
return outChan, doneChan
}
func NewBamWriterChan(inFile string, head *sam.Header, cp int, buff int, threads int) (chan *sam.Record, chan bool) {
outChan := make(chan *sam.Record, buff)
doneChan := make(chan bool, 0)
fh, err := os.Stdout, error(nil)
if inFile != "-" {
fh, err = os.Open(inFile)
checkError(err)
}
bio := bufio.NewWriterSize(fh, buff)
w, err := bam.NewWriter(bio, head, threads)
go func() {
for rec := range outChan {
err := w.Write(rec)
checkError(err)
}
w.Close()
bio.Flush()
fh.Close()
doneChan <- true
}()
return outChan, doneChan
}
func BamToolbox(toolYaml string, inFile string, outFile string, quiet bool, silent bool, threads int) {
if toolYaml == "help" {
toolYaml = "help: true"
}
y, err := syaml.NewYaml([]byte(toolYaml))
checkError(err)
ty, err := y.GetMapKeys()
checkError(err)
if ty[0] == "Yaml" {
conf, err := y.Get("Yaml").String()
checkError(err)
cb, err := ioutil.ReadFile(conf)
checkError(err)
y, err = syaml.NewYaml(cb)
checkError(err)
}
chanCap := 5000
ioBuff := 1024 * 128
paramFields := map[string]bool{
"Sink": true,
}
switch len(ty) {
case 0:
log.Fatal("toolbox: not tool specified!")
default:
tkeys, err := y.GetMapKeys()
checkError(err)
shed := NewToolshed()
var inChan, outChan, lastOut chan *sam.Record
var bamReader *bam.Reader
var doneChan chan bool
var sink bool
if tkeys[0] != "help" {
inChan, bamReader = NewBamReaderChan(inFile, chanCap, ioBuff, threads)
sink, err = y.Get("Sink").Bool()
if err == nil && sink {
lastOut, doneChan = NewBamSinkChan(chanCap)
} else {
lastOut, doneChan = NewBamWriterChan(outFile, bamReader.Header(), chanCap, ioBuff, threads)
}
}
outChan = make(chan *sam.Record, chanCap)
nextIn, nextOut := inChan, outChan
clearKeys := make([]string, 0)
for _, k := range tkeys {
if !paramFields[k] {
clearKeys = append(clearKeys, k)
}
}
for rank, tool := range clearKeys {
var wt BamTool
var ok bool
if wt, ok = shed[tool]; !ok {
log.Fatal("Unknown tool:", tool)
}
if rank == (len(clearKeys) - 1) {
nextOut = lastOut
}
params := &BamToolParams{
Yaml: y.Get(tool),
InChan: nextIn,
OutChan: nextOut,
Quiet: quiet,
Silent: silent,
Threads: threads,
Rank: rank,
Shed: shed,
}
nextIn = nextOut
nextOut = make(chan *sam.Record, chanCap)
go wt.Use(params)
}
<-doneChan
}
}
func ListTools(p *BamToolParams) {
os.Stderr.WriteString(p.Shed.String())
os.Exit(0)
}
func BamToolAlnContext(p *BamToolParams) {
ref, err := p.Yaml.Get("Ref").String()
checkError(err)
idx := NewRefWitdFaidx(ref, false, p.Silent)
leftShift, err := p.Yaml.Get("LeftShift").Int()
checkError(err)
rightShift, err := p.Yaml.Get("RightShift").Int()
checkError(err)
var regStart *regexp.Regexp
var regEnd *regexp.Regexp
checkError(err)
regStrStart, err := p.Yaml.Get("RegexStart").String()
if err == nil {
regStart = regexp.MustCompile(regStrStart)
}
regStrEnd, err := p.Yaml.Get("RegexEnd").String()
if err == nil {
regEnd = regexp.MustCompile(regStrEnd)
}
stranded, invert := false, false
_ = invert
stranded, _ = p.Yaml.Get("Stranded").Bool()
invert, _ = p.Yaml.Get("Invert").Bool()
tsvFh := os.Stderr
tsvFile, err := p.Yaml.Get("Tsv").String()
if err == nil && tsvFile != "-" {
tsvFh, err = os.Create(tsvFile)
}
head := fmt.Sprintf("Read\tRef\tStrand\tStartSeq\tStartMatch\tEndSeq\tEndMatch\n")
tsvFh.WriteString(head)
for r := range p.InChan {
chrom := r.Ref.Name()
startPos, endPos := r.Pos, r.End()
startSeq, err := idx.IdxSubSeq(chrom, startPos+leftShift, startPos+rightShift)
checkError(err)
endSeq, err := idx.IdxSubSeq(chrom, endPos+leftShift, endPos+rightShift)
checkError(err)
strand := 1
if GetSamReverse(r) {
strand = -1
if stranded {
startSeq, endSeq = RevCompDNA(endSeq), RevCompDNA(startSeq)
}
}
yes, no := -1, 1
if invert {
no, yes = yes, no
}
startMatch := no
endMatch := no
if regStart != nil {
if regStart.MatchString(startSeq) {
startMatch = yes
}
}
if regEnd != nil {
if regEnd.MatchString(endSeq) {
endMatch = yes
}
}
match := (startMatch == yes) || (endMatch == yes)
info := fmt.Sprintf("%s\t%s\t%d\t%s\t%d\t%s\t%d\n", GetSamName(r), GetSamRef(r), strand, startSeq, startMatch, endSeq, endMatch)
if match && !invert {
p.OutChan <- r
tsvFh.WriteString(info)
} else if !match && invert {
p.OutChan <- r
} else {
tsvFh.WriteString(info)
}
}
close(p.OutChan)
tsvFh.Close()
}
type RefWithFaidx struct {
Fasta string
IdxFile string
idx fai.Index
faidx *fai.Faidx
Cache bool
}
func (idx *RefWithFaidx) IdxSubSeq(chrom string, start, end int) (string, error) {
b, err := idx.faidx.SubSeq(chrom, start, end)
return string(b), err
}
func NewRefWitdFaidx(file string, cache bool, quiet bool) *RefWithFaidx {
fileFai := file + ".seqkit.fai"
idRegexp := fastx.DefaultIDRegexp
var idx fai.Index
var err error
if fileNotExists(fileFai) {
if !quiet {
log.Infof("create FASTA index for %s", file)
}
idx, err = fai.CreateWithIDRegexp(file, fileFai, idRegexp)
checkError(err)
} else {
idx, err = fai.Read(fileFai)
checkError(err)
}
var faidx *fai.Faidx
faidx, err = fai.NewWithIndex(file, idx)
checkError(err)
i := &RefWithFaidx{
Fasta: file,
IdxFile: fileFai,
idx: idx,
faidx: faidx,
Cache: cache,
}
return i
}
func BamToolAccStats(p *BamToolParams) {
totalLen := 0
accSum := 0.0
wAccSum := 0.0
nr := 0.0
tsvFh := os.Stderr
tsvFile, err := p.Yaml.Get("Tsv").String()
if err == nil && tsvFile != "-" {
tsvFh, err = os.Create(tsvFile)
}
for r := range p.InChan {
if GetSamMapped(r) {
info := GetSamAlnDetails(r)
totalLen += info.Len
wAccSum += info.WAcc
accSum += info.Acc
nr++
}
p.OutChan <- r
}
WeightedAcc := wAccSum / float64(totalLen)
MeanAcc := accSum / nr
tsvFh.WriteString("AccMean\tWeightedAccMean\n")
tsvFh.WriteString(fmt.Sprintf("%.3f\t%.3f\n", MeanAcc, WeightedAcc))
close(p.OutChan)
}
type AlnDetails struct {
Match int
Mismatch int
MatchMismatch int
Insertion int
Deletion int
Skip int
Len int
Acc float64
WAcc float64
}
func GetSamAlnDetails(r *sam.Record) *AlnDetails {
var mismatch int
res := new(AlnDetails)
aux, ok := r.Tag([]byte("NM"))
if !ok {
panic("no NM tag")
}
var mm int
var ins int
var del int
var skip int
switch aux.Value().(type) {
case int:
mismatch = int(aux.Value().(int))
case int8:
mismatch = int(aux.Value().(int8))
case int16:
mismatch = int(aux.Value().(int16))
case int32:
mismatch = int(aux.Value().(int32))
case int64:
mismatch = int(aux.Value().(int64))
case uint:
mismatch = int(aux.Value().(uint))
case uint8:
mismatch = int(aux.Value().(uint8))
case uint16:
mismatch = int(aux.Value().(uint16))
case uint32:
mismatch = int(aux.Value().(uint32))
case uint64:
mismatch = int(aux.Value().(uint64))
default:
panic("Could not parse NM tag: " + aux.String())
}
for _, op := range r.Cigar {
switch op.Type() {
case sam.CigarMatch, sam.CigarEqual, sam.CigarMismatch:
mm += op.Len()
case sam.CigarInsertion:
ins += op.Len()
case sam.CigarDeletion:
del += op.Len()
case sam.CigarSkipped:
skip += op.Len()
default:
//fmt.Println(op)
}
}
res.MatchMismatch = mm
res.Mismatch = mismatch
res.Insertion = ins
res.Deletion = del
res.Skip = skip
res.Len = mm + ins + del
res.Match = res.MatchMismatch - res.Mismatch
res.Acc = (1.0 - float64(mismatch)/float64(mm+ins+del)) * 100
res.WAcc = res.Acc * float64(res.Len)
return res
}
func BamToolDump(p *BamToolParams) {
validFields := []string{"Read", "Ref", "Pos", "EndPos", "MapQual", "Acc", "Match", "Mismatch", "Ins", "Del", "AlnLen", "ReadLen", "RefLen", "RefAln", "RefCov", "ReadAln", "ReadCov", "Strand", "MeanQual", "LeftClip", "RightClip", "Flags", "IsSec", "IsSup", "ReadSeq", "ReadAlnSeq", "LeftSoftClipSeq", "RightSoftClipSeq", "RightSoftClip", "LeftHardClip", "RightHardClip"}
tsvFh := os.Stderr
tsvFile, err := p.Yaml.Get("Tsv").String()
if err == nil && tsvFile != "-" {
tsvFh, err = os.Create(tsvFile)
}
arr, err := p.Yaml.Get("Fields").Array()
checkError(err)
keys := []string{}
for _, k := range arr {
s, ok := k.(string)
if ok {
found := false
for _, x := range validFields {
if s == x {
found = true
continue
}
}
if found {
keys = append(keys, s)
}
}
}
if len(arr) == 1 {
tmp, ok := arr[0].(string)
if ok {
if tmp == "*" {
keys = validFields
}
}
}
tsvFh.WriteString(PrintTsvLine(keys))
for r := range p.InChan {
if GetSamMapped(r) {
tsvFh.WriteString(PrintTsvLine(SamDumper(keys, r)))
}
p.OutChan <- r
}
close(p.OutChan)
tsvFh.Close()
}
func SamDumper(fields []string, r *sam.Record) []string {
res := make([]string, len(fields))
for i, f := range fields {
res[i] = GetSamDump(f, r)
}
return res
}
func GetSamDump(field string, r *sam.Record) string {
acc := GetSamAlnDetails(r)
switch field {
case "Read":
return fmt.Sprintf("%s", GetSamName(r))
case "Ref":
return fmt.Sprintf("%s", GetSamRef(r))
case "Pos":
return fmt.Sprintf("%d", GetSamPos(r))
case "EndPos":
return fmt.Sprintf("%d", GetSamEndPos(r))
case "MapQual":
return fmt.Sprintf("%d", GetSamMapQual(r))
case "Acc":
return fmt.Sprintf("%.3f", acc.Acc)
case "Match":
return fmt.Sprintf("%d", acc.Match)
case "Mismatch":
return fmt.Sprintf("%d", acc.Mismatch)
case "Ins":
return fmt.Sprintf("%d", acc.Insertion)
case "Del":
return fmt.Sprintf("%d", acc.Deletion)
case "AlnLen":
return fmt.Sprintf("%d", acc.Len)
case "ReadLen":
return fmt.Sprintf("%d", GetSamReadLen(r))
case "RefLen":
return fmt.Sprintf("%d", GetSamRefLen(r))
case "RefAln":
return fmt.Sprintf("%d", GetSamRefAln(r))
case "RefCov":
return fmt.Sprintf("%.3f", GetSamRefCov(r))
case "ReadAln":
return fmt.Sprintf("%d", GetSamReadAln(r))
case "ReadCov":
return fmt.Sprintf("%.3f", GetSamReadCov(r))
case "Strand":
return fmt.Sprintf("%d", GetSamStrand(r))
case "MeanQual":
return fmt.Sprintf("%d", GetSamReadAln(r))
case "LeftClip":
return fmt.Sprintf("%d", GetSamLeftClip(r))
case "RightClip":
return fmt.Sprintf("%d", GetSamRightClip(r))
case "Flags":
return fmt.Sprintf("%d", r.Flags)
case "IsSec":
return fmt.Sprintf("%d", GetSamIsSec(r))
case "IsSup":
return fmt.Sprintf("%d", GetSamIsSup(r))
case "ReadSeq":
return fmt.Sprintf("%s", GetSamReadSeq(r))
case "ReadAlnSeq":
return fmt.Sprintf("%s", GetSamReadAlnSeq(r))
case "LeftSoftClipSeq":
return fmt.Sprintf("%s", GetSamLeftSoftClipSeq(r))
case "RightSoftClipSeq":
return fmt.Sprintf("%s", GetSamRightSoftClipSeq(r))
case "LeftSoftClip":
return fmt.Sprintf("%d", GetSamLeftSoftClip(r))
case "RightSoftClip":
return fmt.Sprintf("%d", GetSamRightSoftClip(r))
case "LeftHardClip":
return fmt.Sprintf("%d", GetSamLeftHardClip(r))
case "RightHardClip":
return fmt.Sprintf("%d", GetSamRightHardClip(r))
default:
return "<!INVALID_FIELD!>"
}
return ""
}
func GetSamMapped(r *sam.Record) bool {
return (r.Flags&sam.Unmapped == 0)
}
func GetSamReverse(r *sam.Record) bool {
return (r.Flags&sam.Reverse == 0)
}
func GetSamRef(r *sam.Record) string {
return r.Ref.Name()
}
func GetSamName(r *sam.Record) string {
return r.Name
}
func GetSamReadAlnSeq(r *sam.Record) string {
return r.Name
}
func GetSamReadSeq(r *sam.Record) string {
if r.Seq.Length > 0 {
return string(r.Seq.Expand())
}
return ""
}
func GetSamLeftSoftClipSeq(r *sam.Record) string {
seq := GetSamReadSeq(r)
if len(seq) > 0 {
return seq[:GetSamLeftSoftClip(r)]
}
return ""
}
func GetSamRightSoftClipSeq(r *sam.Record) string {
seq := GetSamReadSeq(r)
if len(seq) > 0 {
return seq[(len(seq) - GetSamRightSoftClip(r)):]
}
return ""
}
func GetSamMapQual(r *sam.Record) int {
return int(r.MapQ)
}
func GetSamHardClipped(r *sam.Record) int {
var hc int
last := len(r.Cigar) - 1
if r.Cigar[last].Type() == sam.CigarHardClipped {
hc += r.Cigar[last].Len()
}
if r.Cigar[0].Type() == sam.CigarHardClipped {
hc += r.Cigar[0].Len()
}
return hc
}
func GetSamLeftHardClip(r *sam.Record) int {
var hc int
if r.Cigar[0].Type() == sam.CigarHardClipped {
hc += r.Cigar[0].Len()
}
return hc
}
func GetSamLeftClip(r *sam.Record) int {
return GetSamLeftSoftClip(r) + GetSamLeftHardClip(r)
}
func GetSamRightClip(r *sam.Record) int {
return GetSamRightSoftClip(r) + GetSamRightHardClip(r)
}
func GetSamRightSoftClip(r *sam.Record) int {
var hc int
last := len(r.Cigar) - 1
if r.Cigar[last].Type() == sam.CigarSoftClipped {
hc += r.Cigar[last].Len()
}
return hc
}
func GetSamLeftSoftClip(r *sam.Record) int {
var hc int
if r.Cigar[0].Type() == sam.CigarSoftClipped {
hc += r.Cigar[0].Len()
}
return hc
}
func GetSamRightHardClip(r *sam.Record) int {
var hc int
last := len(r.Cigar) - 1
if r.Cigar[last].Type() == sam.CigarHardClipped {
hc += r.Cigar[last].Len()
}
return hc
}
func GetSamReadLen(r *sam.Record) int {
if r.Seq.Length > 0 {
sl := int(r.Seq.Length) + GetSamHardClipped(r)
return sl
}
var ql int
for _, op := range r.Cigar {
ql += op.Len() * op.Type().Consumes().Query
}
return ql
}
func GetSamRefAln(r *sam.Record) int {
return r.Len()
}
func GetSamRefLen(r *sam.Record) int {
return r.Ref.Len()
}
func GetSamRefCov(r *sam.Record) float64 {
return float64(r.Len()) / float64(r.Ref.Len()) * 100
}
func GetSamReadCov(r *sam.Record) float64 {
sl := float64(GetSamReadLen(r))
return float64(100 * (sl - float64(GetSamLeftClip(r)-GetSamRightClip(r))) / float64(sl))
}
func GetSamReadAln(r *sam.Record) int {
if r.Flags&sam.Unmapped != 0 {
return 0
}
sl := GetSamReadLen(r)
return (sl - GetSamLeftClip(r) - GetSamRightClip(r))
}
func GetSamStrand(r *sam.Record) int {
if GetSamReverse(r) {
return -1
}
return 1
}
func GetSamIsSup(r *sam.Record) int {
if r.Flags&sam.Supplementary != 0 {
return 1
}
return 0
}
func GetSamIsSec(r *sam.Record) int {
if r.Flags&sam.Secondary != 0 {
return 1
}
return 0
}
func GetSamMeanBaseQual(r *sam.Record) float64 {
if len(r.Qual) != r.Seq.Length {
return 0.0
}
s := &seq.Seq{Qual: r.Qual}
return s.AvgQual(0)
}
func GetSamPos(r *sam.Record) int {
return r.Pos
}
func GetSamEndPos(r *sam.Record) int {
return r.Pos + r.Len()
}
func GetSamAcc(r *sam.Record) float64 {
var mismatch int
aux, ok := r.Tag([]byte("NM"))
if !ok {
panic("no NM tag")
}
var mm int
var ins int
var del int
var skip int
switch aux.Value().(type) {
case int:
mismatch = int(aux.Value().(int))
case int8:
mismatch = int(aux.Value().(int8))
case int16:
mismatch = int(aux.Value().(int16))
case int32:
mismatch = int(aux.Value().(int32))
case int64:
mismatch = int(aux.Value().(int64))
case uint:
mismatch = int(aux.Value().(uint))
case uint8:
mismatch = int(aux.Value().(uint8))
case uint16:
mismatch = int(aux.Value().(uint16))
case uint32:
mismatch = int(aux.Value().(uint32))
case uint64:
mismatch = int(aux.Value().(uint64))
default:
panic("Could not parse NM tag: " + aux.String())
}
for _, op := range r.Cigar {
switch op.Type() {
case sam.CigarMatch, sam.CigarEqual, sam.CigarMismatch:
mm += op.Len()
case sam.CigarInsertion:
ins += op.Len()
case sam.CigarDeletion:
del += op.Len()
case sam.CigarSkipped:
skip += op.Len()
default:
//fmt.Println(op)
}
}
return (1.0 - float64(mismatch)/float64(mm+ins+del)) * 100
}