-
Notifications
You must be signed in to change notification settings - Fork 24
/
covstats.go
285 lines (249 loc) · 6.97 KB
/
covstats.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
package covstats
import (
"fmt"
"io"
"log"
"math"
"os"
"sort"
"strconv"
"strings"
arg "github.com/alexflint/go-arg"
"github.com/biogo/hts/bam"
"github.com/biogo/hts/sam"
"github.com/brentp/goleft/samplename"
"github.com/brentp/smoove/shared"
"github.com/brentp/xopen"
)
var cli = struct {
N int `arg:"-n,help:number of reads to sample for length"`
Regions string `arg:"-r,help:optional bed file to specify target regions"`
Fasta string `arg:"-f,help:fasta file. required for cram format"`
Bams []string `arg:"positional,required,help:bams/crams for which to estimate coverage"`
}{N: 1000000}
func pcheck(e error) {
if e != nil {
panic(e)
}
}
const N_MADS = 10
func readCoverage(path string) int {
fh, err := xopen.Ropen(path)
pcheck(err)
cov := 0
for {
line, err := fh.ReadString('\n')
if err == io.EOF {
break
}
line = strings.TrimSuffix(line, "\n")
toks := strings.SplitN(line, "\t", 5)
s, err := strconv.Atoi(toks[1])
pcheck(err)
e, err := strconv.Atoi(toks[2])
pcheck(err)
cov += e - s
}
return cov
}
func madFilter(arr []int, nmads int) []int {
if !sort.IntsAreSorted(arr) {
sort.Ints(arr)
}
med := arr[len(arr)/2]
upper_mads := make([]int, 0, len(arr))
for _, a := range arr[len(arr)/2+1:] {
upper_mads = append(upper_mads, a-med)
}
sort.Ints(upper_mads)
umad := upper_mads[len(upper_mads)/2]
upper := med + nmads*umad
var i, a int
for i, a = range arr {
if a > upper {
break
}
}
return arr[:i]
}
func meanStd(arr []int) (mean, std float64) {
// first remove things that are more than 10 mads above the median.
l := float64(len(arr))
for _, a := range arr {
mean += float64(a) / l
}
for _, a := range arr {
std += math.Pow(float64(a)-mean, 2) / l
}
return mean, math.Sqrt(std)
}
// Stats hold info about a bam returned from `BamStats`
type Stats struct {
InsertMean float64
InsertSD float64
// 5th percentile of insert size
InsertPct5 int
// 95th percentile of insert size
InsertPct95 int
TemplateMean float64
TemplateSD float64
ReadLengthMean float64
ReadLengthMedian float64
// ProportionBad is the proportion of reads that were Dup|QCFail
ProportionBad float64
ProportionUnmapped float64
ProportionProperlyPaired float64
ProportionDuplicate float64
MaxReadLength int
H []float64
}
func (s Stats) String() string {
return fmt.Sprintf("%.2f\t%.2f\t%d\t%d\t%.2f\t%.2f", s.InsertMean, s.InsertSD, s.InsertPct5, s.InsertPct95, s.TemplateMean, s.TemplateSD)
}
// number of reads to skip to avoid crap at start of chrom
const skipReads = 100000
// BamStats takes bam reader sample N well-behaved sites and return the coverage and insert-size info
func BamStats(br *bam.Reader, n int, skipReads int) Stats {
br.Omit(bam.AllVariableLengthData)
sizes := make([]int, 0, 2*n)
insertSizes := make([]int, 0, n)
templateLengths := make([]int, 0, n)
var nBad, nUnmapped int
for i := 0; i < skipReads; i++ {
_, err := br.Read()
if err == io.EOF {
log.Println("covmed: not enough reads to sample for bam stats")
break
}
}
s := Stats{}
var k int
for len(insertSizes) < n {
rec, err := br.Read()
if err == io.EOF {
break
}
pcheck(err)
if rec.Flags&sam.Unmapped != 0 {
nUnmapped++
continue
}
k++
if rec.Flags&(sam.Duplicate|sam.QCFail) != 0 {
if rec.Flags&sam.Duplicate != 0 {
s.ProportionDuplicate++
}
nBad++
continue
}
if rec.Flags&sam.ProperPair != 0 {
s.ProportionProperlyPaired++
}
if len(sizes) < 2*n {
_, read := rec.Cigar.Lengths()
sizes = append(sizes, read)
} else {
// single end reads have no pairs so we have to skip.
if len(insertSizes) == 0 {
break
}
}
if rec.Pos < rec.MatePos && rec.Flags&sam.ProperPair == sam.ProperPair && len(rec.Cigar) == 1 && rec.Cigar[0].Type() == sam.CigarMatch {
insertSizes = append(insertSizes, rec.MatePos-rec.End())
templateLengths = append(templateLengths, rec.TempLen)
}
}
sort.Ints(sizes)
if len(sizes) > 0 {
s.ProportionBad = float64(nBad) / float64(k)
s.ProportionDuplicate = s.ProportionDuplicate / float64(k)
s.ProportionProperlyPaired = s.ProportionProperlyPaired / float64(k)
s.ProportionUnmapped = float64(nUnmapped) / float64(k)
s.ReadLengthMedian = float64(sizes[(len(sizes)-1)/2]) - 1
s.ReadLengthMean, _ = meanStd(sizes)
sort.Ints(sizes)
s.MaxReadLength = sizes[len(sizes)-1]
}
if len(insertSizes) > 0 {
sort.Ints(insertSizes)
l := float64(len(insertSizes) - 1)
s.InsertPct5 = insertSizes[int(0.05*l+0.5)]
s.InsertPct95 = insertSizes[int(0.95*l+0.5)]
insertSizes = madFilter(insertSizes, N_MADS)
s.InsertMean, s.InsertSD = meanStd(insertSizes)
templateLengths = madFilter(templateLengths, N_MADS)
s.TemplateMean, s.TemplateSD = meanStd(templateLengths)
// taken from lumpy/scripts/pairend_distro.py
start := float64(s.MaxReadLength)
stop := float64(s.TemplateMean + s.TemplateSD*4)
s.H = make([]float64, int(stop-start+1))
cnt := float64(0)
for _, t := range templateLengths {
x := float64(t)
if x < start || x > stop {
continue
}
j := int(x - start)
s.H[j] += 1
cnt += 1
}
for i := range s.H {
s.H[i] /= cnt
}
}
return s
}
// Main is called from the dispatcher
func Main() {
fmt.Fprintln(os.Stdout, "coverage\tinsert_mean\tinsert_sd\tinsert_5th\tinsert_95th\ttemplate_mean\ttemplate_sd\tpct_unmapped\tpct_bad_reads\tpct_duplicate\tpct_proper_pair\tread_length\tbam\tsample")
arg.MustParse(&cli)
for _, bamPath := range cli.Bams {
brdr, err := shared.NewReader(bamPath, 2, cli.Fasta)
pcheck(err)
names := strings.Join(samplename.Names(brdr.Header()), ",")
if names == "" {
names = "<no-read-groups>"
}
var idx *bam.Index
if strings.HasSuffix(bamPath, ".bam") {
ifh, ierr := os.Open(bamPath + ".bai")
if ierr != nil {
// if .bam.bai didn't exist, check .bai
ifh, err = os.Open(bamPath[:len(bamPath)-4] + ".bai")
}
pcheck(err)
idx, err = bam.ReadIndex(ifh)
pcheck(err)
}
genomeBases := 0
mapped := uint64(0)
sizes := BamStats(brdr, cli.N, skipReads)
var notFound []string
for _, ref := range brdr.Header().Refs() {
genomeBases += ref.Len()
if idx != nil {
stats, ok := idx.ReferenceStats(ref.ID())
if !ok {
if !strings.Contains(ref.Name(), "random") && ref.Len() > 10000 {
notFound = append(notFound, ref.Name())
}
continue
}
mapped += stats.Mapped
}
}
if len(notFound) > 0 {
fmt.Fprintf(os.Stderr, "chromosomes: %s not found in %s\n", strings.Join(notFound, ","), bamPath)
}
if cli.Regions != "" {
genomeBases = readCoverage(cli.Regions)
}
// TODO: check that reads are from coverage regions.
coverage := (1 - sizes.ProportionBad) * float64(mapped) * sizes.ReadLengthMean / float64(genomeBases)
fmt.Fprintf(os.Stdout, "%.2f\t%s\t%.2f\t%.1f\t%.1f\t%.1f\t%d\t%s\t%s\n", coverage, sizes.String(), 100*sizes.ProportionUnmapped,
100*sizes.ProportionBad,
100*sizes.ProportionDuplicate,
100*sizes.ProportionProperlyPaired,
sizes.MaxReadLength, bamPath, names)
}
}