-
Notifications
You must be signed in to change notification settings - Fork 59
/
readfq.go
105 lines (94 loc) · 2.48 KB
/
readfq.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
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
)
func main() {
n, sLen, qLen := 0, int64(0), int64(0)
var fqr FqReader
fqr.Reader = bufio.NewReader(os.Stdin)
for r, done := fqr.Iter(); !done; r, done = fqr.Iter() {
n += 1
sLen += int64(len(r.Seq))
qLen += int64(len(r.Qual))
}
fmt.Printf("%v\t%v\t%v\n", n, sLen, qLen)
}
// Record contains the data from a fasta fastq record
type record struct {
Name, Seq, Qual string
}
// FqReader holds all the necessary fields that will be use during the processing
// of a fasta fastq file
type FqReader struct {
Reader *bufio.Reader
last, seq, qual []byte // last line processed, temporary seq and qual values
finished bool
rec record
}
// iterLines iterates over the lines of a reader
func (fq *FqReader) iterLines() ([]byte, bool) {
line, err := fq.Reader.ReadSlice('\n')
if err != nil {
if err == io.EOF {
return line, true
} else {
panic(err)
}
}
return line, false
}
var space = []byte(" ")
func (fq *FqReader) Iter() (record, bool) {
if fq.finished {
return fq.rec, fq.finished
}
// Read the seq id (fasta or fastq)
if fq.last == nil {
for l, done := fq.iterLines(); !done; l, done = fq.iterLines() {
if l[0] == '>' || l[0] == '@' { // read id
fq.last = l[0 : len(l)-1]
break
}
}
if fq.last == nil { // We couldn't find a valid record, no more data in file
fq.finished = true
return fq.rec, fq.finished
}
}
fq.rec.Name = string(bytes.SplitN(fq.last, space, 1)[0])
fq.last = nil
// Now read the sequence
fq.seq = fq.seq[:0]
for l, done := fq.iterLines(); !done; l, done = fq.iterLines() {
c := l[0]
if c == '+' || c == '>' || c == '@' {
fq.last = l[0 : len(l)-1]
break
}
fq.seq = append(fq.seq, l[0:len(l)-1]...)
}
fq.rec.Seq = string(fq.seq)
if fq.last != nil { // There are more lines
if fq.last[0] != '+' { // fasta record
return fq.rec, fq.finished
}
leng := 0
fq.qual = fq.qual[:0]
for l, done := fq.iterLines(); !done; l, done = fq.iterLines() {
fq.qual = append(fq.qual, l[0:len(l)-1]...)
leng += len(l)
if leng >= len(fq.seq) { // we have read enough quality
fq.last = nil
fq.rec.Qual = string(fq.qual)
return fq.rec, fq.finished
}
}
fq.finished = true
fq.rec.Qual = string(fq.qual)
}
return fq.rec, fq.finished // incomplete fastq quality, return what we have
}