| 1 | // Copyright ©2013 The bíogo Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package fai implements FAI fasta sequence file index handling. |
| 6 | package fai |
| 7 | |
| 8 | import ( |
| 9 | "bufio" |
| 10 | "bytes" |
| 11 | "encoding/csv" |
| 12 | "errors" |
| 13 | "fmt" |
| 14 | "io" |
| 15 | "sort" |
| 16 | "strconv" |
| 17 | ) |
| 18 | |
| 19 | const ( |
| 20 | nameField = iota |
| 21 | lengthField |
| 22 | startField |
| 23 | basesField |
| 24 | bytesField |
| 25 | ) |
| 26 | |
| 27 | var ErrNonUnique = errors.New("non-unique record name") |
| 28 | |
| 29 | // Index is an FAI index. |
| 30 | type Index map[string]Record |
| 31 | |
| 32 | // NewIndex returns a new Index constructed from the FASTA sequence |
| 33 | // in the provided io.Reader. |
| 34 | func NewIndex(fasta io.Reader) (Index, error) { |
| 35 | sc := bufio.NewScanner(fasta) |
| 36 | sc.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) { |
| 37 | if atEOF && len(data) == 0 { |
| 38 | return 0, nil, nil |
| 39 | } |
| 40 | if i := bytes.IndexByte(data, '\n'); i >= 0 { |
| 41 | return i + 1, data[:i+1], nil |
| 42 | } |
| 43 | if atEOF { |
| 44 | return len(data), data, nil |
| 45 | } |
| 46 | return 0, nil, nil |
| 47 | }) |
| 48 | |
| 49 | idx := make(Index) |
| 50 | var ( |
| 51 | rec Record |
| 52 | offset int64 |
| 53 | wantDescLine bool |
| 54 | ) |
| 55 | for sc.Scan() { |
| 56 | b := bytes.TrimSpace(sc.Bytes()) |
| 57 | if len(b) == 0 { |
| 58 | continue |
| 59 | } |
| 60 | if bytes.Equal(b, []byte{'>'}) { |
| 61 | return nil, fmt.Errorf("fai: missing sequence name at %d", offset) |
| 62 | } |
| 63 | if b[0] == '>' { |
| 64 | if rec.Name != "" { |
| 65 | idx[rec.Name] = rec |
| 66 | rec = Record{} |
| 67 | } |
| 68 | lenID := bytes.IndexAny(b, " \t") |
| 69 | if lenID < 0 { |
| 70 | rec.Name = string(b[1:]) |
| 71 | } else { |
| 72 | rec.Name = string(b[1:lenID]) |
| 73 | } |
| 74 | if _, exists := idx[rec.Name]; exists { |
| 75 | return nil, fmt.Errorf("fai: duplicate sequence identifier %s at %d", rec.Name, offset) |
| 76 | } |
| 77 | rec.Start = offset + int64(len(sc.Bytes())) |
| 78 | wantDescLine = false |
| 79 | } else { |
| 80 | if wantDescLine { |
| 81 | return nil, fmt.Errorf("fai: unexpected short line before offset %d", offset) |
| 82 | } |
| 83 | switch { |
| 84 | case rec.BytesPerLine == 0: |
| 85 | rec.BytesPerLine = len(sc.Bytes()) |
| 86 | case len(sc.Bytes()) > rec.BytesPerLine: |
| 87 | return nil, fmt.Errorf("fai: unexpected long line at offset %d", offset) |
| 88 | case len(sc.Bytes()) < rec.BytesPerLine: |
| 89 | wantDescLine = true |
| 90 | } |
| 91 | switch { |
| 92 | case len(b) == 0: |
| 93 | // Do nothing. |
| 94 | case rec.BasesPerLine == 0: |
| 95 | rec.BasesPerLine = len(b) |
| 96 | case len(b) > rec.BasesPerLine: |
| 97 | return nil, fmt.Errorf("fai: unexpected long line at offset %d", offset) |
| 98 | case len(b) < rec.BasesPerLine: |
| 99 | wantDescLine = true |
| 100 | } |
| 101 | rec.Length += len(b) |
| 102 | } |
| 103 | offset += int64(len(sc.Bytes())) |
| 104 | } |
| 105 | if rec.Name != "" { |
| 106 | idx[rec.Name] = rec |
| 107 | rec = Record{} |
| 108 | } |
| 109 | return idx, sc.Err() |
| 110 | } |
| 111 | |
| 112 | // Record is a single FAI index record. |
| 113 | type Record struct { |
| 114 | // Name is the name of the sequence. |
| 115 | Name string |
| 116 | // Length is the length of the sequence. |
| 117 | Length int |
| 118 | // Start is the starting seek offset of |
| 119 | // the sequence. |
| 120 | Start int64 |
| 121 | // BasesPerLine is the number of sequences |
| 122 | // bases per line. |
| 123 | BasesPerLine int |
| 124 | // BytesPerLine is the number of bytes |
| 125 | // used to represent each line. |
| 126 | BytesPerLine int |
| 127 | } |
| 128 | |
| 129 | // Position returns the seek offset of the sequence position p for the |
| 130 | // given Record. |
| 131 | func (r Record) Position(p int) int64 { |
| 132 | if p < 0 || r.Length <= p { |
| 133 | panic("fai: index out of range") |
| 134 | } |
| 135 | return r.position(p) |
| 136 | } |
| 137 | |
| 138 | func (r Record) position(p int) int64 { |
| 139 | return r.Start + int64(p/r.BasesPerLine*r.BytesPerLine+p%r.BasesPerLine) |
| 140 | } |
| 141 | |
| 142 | // endOfLineOffset returns the number of bytes until the end of the line |
| 143 | // holding position p. |
| 144 | func (r Record) endOfLineOffset(p int) int { |
| 145 | if p/r.BasesPerLine == r.Length/r.BasesPerLine { |
| 146 | return r.Length - p |
| 147 | } |
| 148 | return r.BasesPerLine - p%r.BasesPerLine |
| 149 | } |
| 150 | |
| 151 | func mustAtoi(fields []string, index, line int) int { |
| 152 | i, err := strconv.ParseInt(fields[index], 10, 0) |
| 153 | if err != nil { |
| 154 | panic(parseError(line, index, err)) |
| 155 | } |
| 156 | return int(i) |
| 157 | } |
| 158 | |
| 159 | func mustAtoi64(fields []string, index, line int) int64 { |
| 160 | i, err := strconv.ParseInt(fields[index], 10, 64) |
| 161 | if err != nil { |
| 162 | panic(parseError(line, index, err)) |
| 163 | } |
| 164 | return i |
| 165 | } |
| 166 | |
| 167 | // ReadFrom returns an Index from the stream provided by an io.Reader or an error. If the input |
| 168 | // contains non-unique records the error is a csv.ParseError identifying the second non-unique |
| 169 | // record. |
| 170 | func ReadFrom(r io.Reader) (idx Index, err error) { |
| 171 | tr := csv.NewReader(r) |
| 172 | tr.Comma = '\t' |
| 173 | tr.FieldsPerRecord = 5 |
| 174 | defer func() { |
| 175 | r := recover() |
| 176 | if r != nil { |
| 177 | e, ok := r.(error) |
| 178 | if !ok { |
| 179 | panic(r) |
| 180 | } |
| 181 | if _, ok = r.(*csv.ParseError); !ok { |
| 182 | panic(r) |
| 183 | } |
| 184 | err = e |
| 185 | idx = nil |
| 186 | } |
| 187 | }() |
| 188 | for line := 1; ; line++ { |
| 189 | rec, err := tr.Read() |
| 190 | if err == io.EOF { |
| 191 | return idx, nil |
| 192 | } |
| 193 | if err != nil { |
| 194 | return nil, err |
| 195 | } |
| 196 | if idx == nil { |
| 197 | idx = make(Index) |
| 198 | } else if _, exists := idx[rec[nameField]]; exists { |
| 199 | return nil, parseError(line, 0, ErrNonUnique) |
| 200 | } |
| 201 | idx[rec[nameField]] = Record{ |
| 202 | Name: rec[nameField], |
| 203 | Length: mustAtoi(rec, lengthField, line), |
| 204 | Start: mustAtoi64(rec, startField, line), |
| 205 | BasesPerLine: mustAtoi(rec, basesField, line), |
| 206 | BytesPerLine: mustAtoi(rec, bytesField, line), |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | func parseError(line, column int, err error) *csv.ParseError { |
| 212 | return &csv.ParseError{ |
| 213 | StartLine: line, |
| 214 | Line: line, |
| 215 | Column: column, |
| 216 | Err: err, |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | // WriteTo writes the given index to w in order of ascending start position. |
| 221 | func WriteTo(w io.Writer, idx Index) error { |
| 222 | recs := make([]Record, 0, len(idx)) |
| 223 | for _, r := range idx { |
| 224 | recs = append(recs, r) |
| 225 | } |
| 226 | sort.Sort(byStart(recs)) |
| 227 | for _, r := range recs { |
| 228 | _, err := fmt.Fprintf(w, "%s\t%d\t%d\t%d\t%d\n", r.Name, r.Length, r.Start, r.BasesPerLine, r.BytesPerLine) |
| 229 | if err != nil { |
| 230 | return err |
| 231 | } |
| 232 | } |
| 233 | return nil |
| 234 | } |
| 235 | |
| 236 | type byStart []Record |
| 237 | |
| 238 | func (r byStart) Len() int { return len(r) } |
| 239 | func (r byStart) Less(i, j int) bool { return r[i].Start < r[j].Start } |
| 240 | func (r byStart) Swap(i, j int) { r[i], r[j] = r[j], r[i] } |