forked from shenwei356/seqkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grep.go
259 lines (232 loc) · 7.44 KB
/
grep.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
// Copyright © 2016 Wei Shen <shenwei356@gmail.com>
//
// 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 (
"fmt"
"regexp"
"runtime"
"sync"
"github.com/brentp/xopen"
"github.com/shenwei356/bio/seq"
"github.com/shenwei356/bio/seqio/fasta"
"github.com/shenwei356/breader"
"github.com/spf13/cobra"
)
// grepCmd represents the extract command
var grepCmd = &cobra.Command{
Use: "grep",
Short: "grep sequences by pattern(s) of name or sequence motifs",
Long: `grep sequences by pattern(s) of name or sequence motifs
`,
Run: func(cmd *cobra.Command, args []string) {
alphabet := getAlphabet(cmd, "seq-type")
idRegexp := getFlagString(cmd, "id-regexp")
chunkSize := getFlagPositiveInt(cmd, "chunk-size")
threads := getFlagPositiveInt(cmd, "threads")
lineWidth := getFlagNonNegativeInt(cmd, "line-width")
outFile := getFlagString(cmd, "out-file")
seq.AlphabetGuessSeqLenghtThreshold = getFlagalphabetGuessSeqLength(cmd, "alphabet-guess-seq-length")
seq.ValidateSeq = false
runtime.GOMAXPROCS(threads)
pattern := getFlagStringSlice(cmd, "pattern")
patternFile := getFlagString(cmd, "pattern-file")
useRegexp := getFlagBool(cmd, "use-regexp")
deleteMatched := getFlagBool(cmd, "delete-matched")
invertMatch := getFlagBool(cmd, "invert-match")
bySeq := getFlagBool(cmd, "by-seq")
byName := getFlagBool(cmd, "by-name")
ignoreCase := getFlagBool(cmd, "ignore-case")
degenerate := getFlagBool(cmd, "degenerate")
if len(pattern) == 0 && patternFile == "" {
checkError(fmt.Errorf("one of flags -p (--pattern) and -f (--pattern-file) needed"))
}
if useRegexp && degenerate {
checkError(fmt.Errorf("could not give both flags -d (--degenerat) and -r (--use-regexp)"))
}
files := getFileList(args)
// prepare pattern
patterns := make(map[string]*regexp.Regexp)
if patternFile != "" {
reader, err := breader.NewDefaultBufferedReader(patternFile)
checkError(err)
for chunk := range reader.Ch {
checkError(chunk.Err)
for _, data := range chunk.Data {
p := data.(string)
if degenerate || useRegexp {
if degenerate {
pattern2seq, err := seq.NewSeq(alphabet, []byte(p))
if err != nil {
checkError(fmt.Errorf("it seems that flag -d is given, "+
"but you provide regular expression instead of available %s sequence", alphabet))
}
p = pattern2seq.Degenerate2Regexp()
}
if ignoreCase {
p = "(?i)" + p
}
r, err := regexp.Compile(p)
checkError(err)
patterns[p] = r
} else {
patterns[p] = nil
}
}
}
} else {
if degenerate || useRegexp {
for _, p := range pattern {
if degenerate {
pattern2seq, err := seq.NewSeq(alphabet, []byte(p))
if err != nil {
checkError(fmt.Errorf("it seems that flag -d is given, "+
"but you provide regular expression instead of available %s sequence", alphabet))
}
p = pattern2seq.Degenerate2Regexp()
}
if ignoreCase {
p = "(?i)" + p
}
re, err := regexp.Compile(p)
checkError(err)
patterns[p] = re
}
} else {
for _, p := range pattern {
patterns[p] = nil
}
}
}
outfh, err := xopen.Wopen(outFile)
checkError(err)
defer outfh.Close()
for _, file := range files {
ch := make(chan fasta.FastaRecordChunk, threads)
done := make(chan int)
// receiver
go func() {
var id uint64 = 0
chunks := make(map[uint64]fasta.FastaRecordChunk)
for chunk := range ch {
checkError(chunk.Err)
if chunk.ID == id {
for _, record := range chunk.Data {
outfh.WriteString(fmt.Sprintf(">%s\n%s\n", record.Name, record.FormatSeq(lineWidth)))
}
id++
} else { // check bufferd result
for true {
if chunk, ok := chunks[id]; ok {
for _, record := range chunk.Data {
outfh.WriteString(fmt.Sprintf(">%s\n%s\n", record.Name, record.FormatSeq(lineWidth)))
}
id++
delete(chunks, chunk.ID)
} else {
break
}
}
chunks[chunk.ID] = chunk
}
}
if len(chunks) > 0 {
sortedIDs := sortFastaRecordChunkMapID(chunks)
for _, id := range sortedIDs {
chunk := chunks[id]
for _, record := range chunk.Data {
outfh.WriteString(fmt.Sprintf(">%s\n%s\n", record.Name, record.FormatSeq(lineWidth)))
}
}
}
done <- 1
}()
// producer and worker
var wg sync.WaitGroup
tokens := make(chan int, threads)
fastaReader, err := fasta.NewFastaReader(alphabet, file, threads, chunkSize, idRegexp)
checkError(err)
for chunk := range fastaReader.Ch {
checkError(chunk.Err)
tokens <- 1
wg.Add(1)
go func(chunk fasta.FastaRecordChunk) {
defer func() {
wg.Done()
<-tokens
}()
var subject []byte
var hit bool
var chunkData []*fasta.FastaRecord
for _, record := range chunk.Data {
if byName {
subject = record.Name
} else if bySeq {
subject = record.Seq.Seq
} else {
subject = record.ID
}
hit = false
if degenerate || useRegexp {
for pattern, re := range patterns {
if re.Match(subject) {
hit = true
if deleteMatched {
delete(patterns, pattern)
}
break
}
}
} else {
if _, ok := patterns[string(subject)]; ok {
hit = true
}
}
if invertMatch {
if hit {
continue
}
} else {
if !hit {
continue
}
}
chunkData = append(chunkData, record)
}
ch <- fasta.FastaRecordChunk{chunk.ID, chunkData, nil}
}(chunk)
}
wg.Wait()
close(ch)
<-done
}
},
}
func init() {
RootCmd.AddCommand(grepCmd)
grepCmd.Flags().StringSliceP("pattern", "p", []string{""}, "search pattern (multiple values supported)")
grepCmd.Flags().StringP("pattern-file", "f", "", "pattern file")
grepCmd.Flags().BoolP("use-regexp", "r", false, "patterns are regular expression")
grepCmd.Flags().BoolP("delete-matched", "", false, "delete matched pattern to speedup")
grepCmd.Flags().BoolP("invert-match", "v", false, "invert the sense of matching, to select non-matching records")
grepCmd.Flags().BoolP("by-name", "n", false, "match by full name instead of just id")
grepCmd.Flags().BoolP("by-seq", "s", false, "match by seq")
grepCmd.Flags().BoolP("ignore-case", "i", false, "ignore case")
grepCmd.Flags().BoolP("degenerate", "d", false, "pattern/motif contains degenerate base")
}