-
Notifications
You must be signed in to change notification settings - Fork 157
/
seq.go
391 lines (352 loc) · 11.7 KB
/
seq.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
// Copyright © 2016-2019 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 (
"bytes"
"fmt"
"io"
"os"
"runtime"
"syscall"
// "runtime/debug"
"github.com/shenwei356/bio/seq"
"github.com/shenwei356/bio/seqio/fastx"
"github.com/shenwei356/util/byteutil"
"github.com/spf13/cobra"
)
// seqCmd represents the seq command
var seqCmd = &cobra.Command{
Use: "seq",
Short: "transform sequences (revserse, complement, extract ID...)",
Long: `transform sequences (revserse, complement, extract ID...)
Attentions:
1. This command outputs plain text even when out file ends with ".gz".
`,
Run: func(cmd *cobra.Command, args []string) {
config := getConfigs(cmd)
alphabet := config.Alphabet
idRegexp := config.IDRegexp
lineWidth := config.LineWidth
outFile := config.OutFile
quiet := config.Quiet
seq.AlphabetGuessSeqLengthThreshold = config.AlphabetGuessSeqLength
runtime.GOMAXPROCS(config.Threads)
reverse := getFlagBool(cmd, "reverse")
complement := getFlagBool(cmd, "complement")
onlyName := getFlagBool(cmd, "name")
onlySeq := getFlagBool(cmd, "seq")
onlyQual := getFlagBool(cmd, "qual")
onlyID := getFlagBool(cmd, "only-id")
removeGaps := getFlagBool(cmd, "remove-gaps")
gapLetters := getFlagString(cmd, "gap-letters")
lowerCase := getFlagBool(cmd, "lower-case")
upperCase := getFlagBool(cmd, "upper-case")
dna2rna := getFlagBool(cmd, "dna2rna")
rna2dna := getFlagBool(cmd, "rna2dna")
color := getFlagBool(cmd, "color")
validateSeq := getFlagBool(cmd, "validate-seq")
validateSeqLength := getFlagValidateSeqLength(cmd, "validate-seq-length")
minLen := getFlagInt(cmd, "min-len")
maxLen := getFlagInt(cmd, "max-len")
qBase := getFlagPositiveInt(cmd, "qual-ascii-base")
minQual := getFlagFloat64(cmd, "min-qual")
maxQual := getFlagFloat64(cmd, "max-qual")
if gapLetters == "" {
checkError(fmt.Errorf("value of flag -G (--gap-letters) should not be empty"))
}
for _, c := range gapLetters {
if c > 127 {
checkError(fmt.Errorf("value of -G (--gap-letters) contains non-ASCII characters"))
}
}
if minLen >= 0 && maxLen >= 0 && minLen > maxLen {
checkError(fmt.Errorf("value of flag -m (--min-len) should be >= value of flag -M (--max-len)"))
}
if minQual >= 0 && maxQual >= 0 && minQual > maxQual {
checkError(fmt.Errorf("value of flag -Q (--min-qual) should be <= value of flag -R (--max-qual)"))
}
// if minLen >= 0 || maxLen >= 0 {
// removeGaps = true
// if !quiet {
// log.Infof("flag -g (--remove-gaps) is switched on when using -m (--min-len) or -M (--max-len)")
// }
// }
if (minLen >= 0 || maxLen >= 0) && !removeGaps {
log.Warning("you may switch on flag -g/--remove-gaps to remove spaces")
}
seq.ValidateSeq = validateSeq
seq.ValidateWholeSeq = false
seq.ValidSeqLengthThreshold = validateSeqLength
seq.ValidSeqThreads = config.Threads
seq.ComplementThreads = config.Threads
if complement && (alphabet == nil || alphabet == seq.Protein) {
log.Warningf("flag -t (--seq-type) (DNA/RNA) is recommended for computing complement sequences")
}
if !validateSeq && !(alphabet == nil || alphabet == seq.Unlimit) {
if !quiet {
log.Info("when flag -t (--seq-type) given, flag -v (--validate-seq) is automatically switched on")
}
validateSeq = true
seq.ValidateSeq = true
}
if lowerCase && upperCase {
checkError(fmt.Errorf("could not give both flags -l (--lower-case) and -u (--upper-case)"))
}
files := getFileListFromArgsAndFile(cmd, args, true, "infile-list", true)
var seqCol *SeqColorizer
if color {
switch alphabet {
case seq.DNA, seq.DNAredundant, seq.RNA, seq.RNAredundant:
seqCol = NewSeqColorizer("nucleic")
case seq.Protein:
seqCol = NewSeqColorizer("amino")
default:
seqCol = NewSeqColorizer("nucleic")
}
}
var outfh *os.File
var err error
if outFile == "-" {
outfh = os.Stdout
} else {
outfh, err = os.Create(outFile)
checkError(err)
}
defer outfh.Close()
var outbw io.Writer
outbw = outfh
if color {
outbw = seqCol.WrapWriter(outfh)
}
var checkSeqType bool
var isFastq bool
var printName, printSeq, printQual bool
var head []byte
var sequence *seq.Seq
var text []byte
var b *bytes.Buffer
var record *fastx.Record
var fastxReader *fastx.Reader
for _, file := range files {
fastxReader, err = fastx.NewReader(alphabet, file, idRegexp)
checkError(err)
checkSeqType = true
printQual = false
once := true
if onlySeq || onlyQual {
config.LineWidth = 0
}
for {
record, err = fastxReader.Read()
if err != nil {
if err == io.EOF {
break
}
checkError(err)
break
}
if checkSeqType {
isFastq = fastxReader.IsFastq
if isFastq {
config.LineWidth = 0
printQual = true
}
checkSeqType = false
}
if removeGaps {
record.Seq.RemoveGapsInplace(gapLetters)
}
if minLen >= 0 && len(record.Seq.Seq) < minLen {
continue
}
if maxLen >= 0 && len(record.Seq.Seq) > maxLen {
continue
}
if minQual > 0 || maxQual > 0 {
avgQual := record.Seq.AvgQual(qBase)
if minQual > 0 && avgQual < minQual {
continue
}
if maxQual > 0 && avgQual >= maxQual {
continue
}
}
printName, printSeq = true, true
if onlyName && onlySeq {
printName, printSeq = true, true
} else if onlyName {
printName, printSeq, printQual = true, false, false
} else if onlySeq {
printName, printSeq, printQual = false, true, false
} else if onlyQual {
if !isFastq {
checkError(fmt.Errorf("FASTA format has no quality. So do not just use flag -q (--qual)"))
}
printName, printSeq, printQual = false, false, true
}
if printName {
if onlyID {
head = record.ID
} else {
head = record.Name
}
if printSeq {
if isFastq {
outbw.Write([]byte("@"))
outbw.Write(head)
outbw.Write([]byte("\n"))
} else {
outbw.Write([]byte(">"))
outbw.Write(head)
outbw.Write([]byte("\n"))
}
} else {
outbw.Write(head)
outbw.Write([]byte("\n"))
}
}
sequence = record.Seq
if reverse {
sequence = sequence.ReverseInplace()
}
if complement {
if !config.Quiet && record.Seq.Alphabet == seq.Protein || record.Seq.Alphabet == seq.Unlimit {
log.Warning("complement does no take effect on protein/unlimit sequence")
}
sequence = sequence.ComplementInplace()
}
if printSeq {
if dna2rna {
ab := fastxReader.Alphabet()
if ab == seq.RNA || ab == seq.RNAredundant {
if once {
log.Warningf("it's already RNA, no need to convert")
once = false
}
} else {
for i, b := range sequence.Seq {
switch b {
case 't':
sequence.Seq[i] = 'u'
case 'T':
sequence.Seq[i] = 'U'
}
}
}
}
if rna2dna {
ab := fastxReader.Alphabet()
if ab == seq.DNA || ab == seq.DNAredundant {
if once {
log.Warningf("it's already DNA, no need to convert")
once = false
}
} else {
for i, b := range sequence.Seq {
switch b {
case 'u':
sequence.Seq[i] = 't'
case 'U':
sequence.Seq[i] = 'T'
}
}
}
}
if lowerCase {
sequence.Seq = bytes.ToLower(sequence.Seq)
} else if upperCase {
sequence.Seq = bytes.ToUpper(sequence.Seq)
}
if len(sequence.Seq) <= pageSize {
text := byteutil.WrapByteSlice(sequence.Seq, config.LineWidth)
if color {
if sequence.Qual != nil {
text = seqCol.ColorWithQuals(text, sequence.Qual)
} else {
text = seqCol.Color(text)
}
}
outbw.Write(text)
} else {
if bufferedByteSliceWrapper == nil {
bufferedByteSliceWrapper = byteutil.NewBufferedByteSliceWrapper2(1, len(sequence.Seq), config.LineWidth)
}
text, b = bufferedByteSliceWrapper.Wrap(sequence.Seq, config.LineWidth)
if color {
text = seqCol.Color(text)
}
outbw.Write(text)
bufferedByteSliceWrapper.Recycle(b)
}
outbw.Write([]byte("\n"))
}
if printQual {
if !onlyQual {
outbw.Write([]byte("+\n"))
}
if len(sequence.Qual) <= pageSize {
if color {
outbw.Write(byteutil.WrapByteSlice(seqCol.ColorQuals(sequence.Qual), config.LineWidth))
} else {
outbw.Write(byteutil.WrapByteSlice(sequence.Qual, config.LineWidth))
}
} else {
if bufferedByteSliceWrapper == nil {
bufferedByteSliceWrapper = byteutil.NewBufferedByteSliceWrapper2(1, len(sequence.Qual), config.LineWidth)
}
text, b = bufferedByteSliceWrapper.Wrap(sequence.Qual, config.LineWidth)
if color {
text = seqCol.ColorQuals(text)
}
outbw.Write(text)
bufferedByteSliceWrapper.Recycle(b)
}
outbw.Write([]byte("\n"))
}
}
config.LineWidth = lineWidth
}
outfh.Close()
},
}
var pageSize = syscall.Getpagesize()
func init() {
RootCmd.AddCommand(seqCmd)
seqCmd.Flags().BoolP("reverse", "r", false, "reverse sequence")
seqCmd.Flags().BoolP("complement", "p", false, "complement sequence, flag '-v' is recommended to switch on")
seqCmd.Flags().BoolP("name", "n", false, "only print names")
seqCmd.Flags().BoolP("seq", "s", false, "only print sequences")
seqCmd.Flags().BoolP("qual", "q", false, "only print qualities")
seqCmd.Flags().BoolP("only-id", "i", false, "print ID instead of full head")
seqCmd.Flags().BoolP("remove-gaps", "g", false, "remove gaps")
seqCmd.Flags().StringP("gap-letters", "G", "- .", "gap letters")
seqCmd.Flags().BoolP("lower-case", "l", false, "print sequences in lower case")
seqCmd.Flags().BoolP("upper-case", "u", false, "print sequences in upper case")
seqCmd.Flags().BoolP("dna2rna", "", false, "DNA to RNA")
seqCmd.Flags().BoolP("rna2dna", "", false, "RNA to DNA")
seqCmd.Flags().BoolP("color", "k", false, "colorize sequences - to be piped into \"less -R\"")
seqCmd.Flags().BoolP("validate-seq", "v", false, "validate bases according to the alphabet")
seqCmd.Flags().IntP("validate-seq-length", "V", 10000, "length of sequence to validate (0 for whole seq)")
seqCmd.Flags().IntP("min-len", "m", -1, "only print sequences longer than the minimum length (-1 for no limit)")
seqCmd.Flags().IntP("max-len", "M", -1, "only print sequences shorter than the maximum length (-1 for no limit)")
seqCmd.Flags().IntP("qual-ascii-base", "b", 33, "ASCII BASE, 33 for Phred+33")
seqCmd.Flags().Float64P("min-qual", "Q", -1, "only print sequences with average quality qreater or equal than this limit (-1 for no limit)")
seqCmd.Flags().Float64P("max-qual", "R", -1, "only print sequences with average quality less than this limit (-1 for no limit)")
}