Debian Codegraph @

eutils/fasta.go

raw
1 // ===========================================================================
2 //
3 // PUBLIC DOMAIN NOTICE
4 // National Center for Biotechnology Information (NCBI)
5 //
6 // This software/database is a "United States Government Work" under the
7 // terms of the United States Copyright Act. It was written as part of
8 // the author's official duties as a United States Government employee and
9 // thus cannot be copyrighted. This software/database is freely available
10 // to the public for use. The National Library of Medicine and the U.S.
11 // Government do not place any restriction on its use or reproduction.
12 // We would, however, appreciate having the NCBI and the author cited in
13 // any work or product based on this material.
14 //
15 // Although all reasonable efforts have been taken to ensure the accuracy
16 // and reliability of the software and data, the NLM and the U.S.
17 // Government do not and cannot warrant the performance or results that
18 // may be obtained by using this software or data. The NLM and the U.S.
19 // Government disclaim all warranties, express or implied, including
20 // warranties of performance, merchantability or fitness for any particular
21 // purpose.
22 //
23 // ===========================================================================
24 //
25 // File Name: fasta.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "fmt"
36 "io"
37 "os"
38 "strconv"
39 "strings"
40 )
41
42 // FASTARecord contains parsed data from a FASTA format record
43 type FASTARecord struct {
44 SeqID string
45 Title string
46 Sequence string
47 Length int
48 }
49
50 // FASTAConverter reads a concatenated FASTA stream and sends individual records down a channel
51 func FASTAConverter(inp io.Reader, caseSensitive bool) <-chan FASTARecord {
52
53 if inp == nil {
54 return nil
55 }
56
57 // internal channel sends either definition line or combined sequence lines
58 lns := make(chan string, chanDepth)
59
60 // second channel send assembled FASTA records to the caller one at a time
61 out := make(chan FASTARecord, chanDepth)
62
63 if lns == nil || out == nil {
64 DisplayWarning("Unable to create FASTA converter channels")
65 os.Exit(1)
66 }
67
68 // fastaSplitter partitions FASTA input stream into a full definition line or a sequence segment
69 fastaSplitter := func(inp io.Reader, lns chan<- string) {
70
71 // close channel when all strings have been sent
72 defer close(lns)
73
74 const FASTABUFSIZE = 65536
75
76 buffer := make([]byte, FASTABUFSIZE)
77 isClosed := false
78
79 // read the next large block of characters from input stream
80 nextBuffer := func() string {
81
82 if isClosed {
83 return ""
84 }
85
86 n, err := inp.Read(buffer[:])
87
88 if err != nil {
89 if err != io.EOF {
90 // real error
91 DisplayWarning("%s", err.Error())
92
93 // ignore bytes - non-conforming implementations of io.Reader may
94 // return mangled data on non-EOF errors
95 isClosed = true
96
97 return ""
98 }
99
100 // end of file
101 isClosed = true
102
103 if n == 0 {
104 // if EOF and no more data
105 return ""
106 }
107 }
108
109 if n < 0 {
110 // reality check - non-conforming implementations of io.Reader may return -1
111 DisplayWarning("io.Reader returned negative count %d", n)
112
113 // treat as n == 0
114 return ""
115 }
116
117 // slice of actual characters read
118 bufr := buffer[:n]
119
120 return string(bufr[:])
121 }
122
123 line := ""
124
125 for {
126
127 if line == "" {
128 line = nextBuffer()
129 if line == "" {
130 break
131 }
132 }
133
134 // look for start of FASTA defline
135 pos := strings.Index(line, ">")
136
137 if pos < 0 {
138 // no angle bracket in buffer, send remainder as sequence
139 lns <- line
140 line = ""
141 continue
142 }
143
144 if pos > 0 {
145 // send sequence buffer up to angle bracket
146 str := line[:pos]
147 lns <- str
148 // shrink buffer to start at angle bracket
149 line = line[pos:]
150 continue
151 }
152
153 // look for end of FASTA defline
154 pos = strings.Index(line, "\n")
155
156 if pos > 0 {
157 // send full defline within buffer
158 str := line[:pos]
159 lns <- str
160 // shrink buffer to start after defline and newline character
161 line = line[pos+1:]
162 continue
163 }
164
165 // defline continues into next buffer, look for next newline
166 defln := line
167
168 for {
169
170 // read next buffer
171 line = nextBuffer()
172 if line == "" {
173 // file ends in defline
174 lns <- defln
175 break
176 }
177
178 pos = strings.Index(line, "\n")
179
180 if pos < 0 {
181 // add full buffer to defline
182 defln += line
183 // continue with next buffer
184 continue
185 }
186
187 // found newline, send constructed defline
188 defln += line[:pos]
189 lns <- defln
190 line = line[pos+1:]
191 break
192 }
193 }
194 }
195
196 // fastaStreamer sends FASTA records down a channel
197 fastaStreamer := func(lns <-chan string, out chan<- FASTARecord) {
198
199 // close channel when all records have been processed
200 defer close(out)
201
202 seqid := ""
203 title := ""
204
205 var fasta []string
206
207 sendFasta := func() {
208
209 seq := strings.Join(fasta, "")
210 seqlen := len(seq)
211
212 if seqlen > 0 {
213 out <- FASTARecord{SeqID: seqid, Title: title, Sequence: seq[:], Length: seqlen}
214 }
215
216 seqid = ""
217 title = ""
218
219 // reset sequence accumulator
220 fasta = nil
221 }
222
223 for line := range lns {
224
225 if strings.HasPrefix(line, ">") {
226
227 // send current record, clear sequence buffer
228 sendFasta()
229
230 // parse next defline
231 line = line[1:]
232 seqid, title = SplitInTwoLeft(line, " ")
233
234 continue
235 }
236
237 if !caseSensitive {
238 // optionally convert FASTA letters to upper case
239 line = strings.ToUpper(line)
240 }
241
242 // leave only letters, asterisk, or hyphen
243 line = strings.Map(func(c rune) rune {
244 if c >= 'A' && c <= 'Z' {
245 return c
246 }
247 if c >= 'a' && c <= 'z' {
248 return c
249 }
250 if c == '*' || c == '-' {
251 return c
252 }
253 return -1
254 }, line)
255
256 // append current line
257 fasta = append(fasta, line)
258 }
259
260 // send final record
261 sendFasta()
262 }
263
264 // launch single fasta splitter goroutine
265 go fastaSplitter(inp, lns)
266
267 // launch single fasta streamer goroutine
268 go fastaStreamer(lns, out)
269
270 return out
271 }
272
273 // FormatFASTA sends lines of specified width to Stdout
274 func FormatFASTA(inp io.Reader, width int, requireHeader, caseSensitive bool) {
275
276 if inp == nil {
277 return
278 }
279
280 fcnv := FASTAConverter(inp, caseSensitive)
281 if fcnv == nil {
282 DisplayError("Unable to create FASTA converter")
283 return
284 }
285
286 if width < 1 || width > 100 {
287 // default width is 70 characters per line
288 width = 70
289 }
290
291 var buffer strings.Builder
292 count := 0
293 recordCount := 0
294
295 wrtr := bufio.NewWriter(os.Stdout)
296
297 for fsa := range fcnv {
298
299 seqid, title, sequence := fsa.SeqID, fsa.Title, fsa.Sequence
300
301 recordCount++
302
303 if seqid != "" || title != "" || requireHeader {
304 sep := ""
305 buffer.WriteString(">")
306
307 if seqid == "" {
308 seqid = fmt.Sprintf("lcl|%d", recordCount)
309 }
310 if seqid != "" {
311 buffer.WriteString(seqid)
312 sep = " "
313 }
314 if title != "" {
315 buffer.WriteString(sep)
316 buffer.WriteString(title)
317 }
318
319 buffer.WriteString("\n")
320 }
321
322 for sequence != "" {
323
324 mx := len(sequence)
325 if mx > width {
326 mx = width
327 }
328 item := sequence[:mx]
329 sequence = sequence[mx:]
330 item = strings.ToUpper(item)
331 buffer.WriteString(item)
332 buffer.WriteString("\n")
333
334 count++
335
336 if count >= 1000 {
337 count = 0
338 txt := buffer.String()
339 if txt != "" {
340 // print current buffer
341 wrtr.WriteString(txt[:])
342 }
343 buffer.Reset()
344 }
345 }
346 }
347
348 txt := buffer.String()
349 if txt != "" {
350 // print last buffer
351 wrtr.WriteString(txt[:])
352 }
353 buffer.Reset()
354
355 wrtr.Flush()
356 }
357
358 // FASTAtoXML converts a FASTA flatfile to an XML string
359 func FASTAtoXML(fasta string, caseSensitive bool) string {
360
361 if fasta == "" {
362 return ""
363 }
364
365 fcnv := FASTAConverter(strings.NewReader(fasta), caseSensitive)
366 if fcnv == nil {
367 DisplayError("Unable to create FASTA converter")
368 return ""
369 }
370
371 var buffer strings.Builder
372
373 for fsa := range fcnv {
374
375 buffer.WriteString("<FASTA>\n")
376 if fsa.SeqID != "" {
377 buffer.WriteString(" <ID>")
378 buffer.WriteString(fsa.SeqID)
379 buffer.WriteString("</ID>\n")
380 }
381 if fsa.Title != "" {
382 buffer.WriteString(" <Title>")
383 buffer.WriteString(fsa.Title)
384 buffer.WriteString("</Title>\n")
385 }
386 if fsa.Length != 0 {
387 buffer.WriteString(" <Length>")
388 buffer.WriteString(strconv.Itoa(fsa.Length))
389 buffer.WriteString("</Length>\n")
390 }
391 if fsa.Sequence != "" {
392 buffer.WriteString(" <Seq>")
393 buffer.WriteString(fsa.Sequence)
394 buffer.WriteString("</Seq>\n")
395 }
396 buffer.WriteString("</FASTA>\n")
397 }
398
399 res := buffer.String()
400
401 buffer.Reset()
402
403 return res
404 }