-
Notifications
You must be signed in to change notification settings - Fork 18
/
variant.go
425 lines (391 loc) · 10.9 KB
/
variant.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package vcfgo
import (
"errors"
"fmt"
"log"
"strconv"
"strings"
"github.com/brentp/irelate/interfaces"
)
// Variant holds the information about a single site. It is analagous to a row in a VCF file.
type Variant struct {
Chromosome string
Pos uint64
Id_ string
Reference string
Alternate []string
Quality float32
Filter string
Info_ interfaces.Info
Format []string
Samples []*SampleGenotype
// if lazy parsing, then just save the sample strings here.
sampleString string
Header *Header
LineNumber int64
}
func (v *Variant) Info() interfaces.Info {
return v.Info_
}
func (v *Variant) Id() string {
return v.Id_
}
func (v *Variant) Ref() string {
return v.Reference
}
func (v *Variant) Alt() []string {
return v.Alternate
}
// Chrom returns the chromosome name.
func (v *Variant) Chrom() string {
return v.Chromosome
}
// Start returns the 0-based start
func (v *Variant) Start() uint32 {
return uint32(v.Pos - 1)
}
// CIPos reports the Left and Right end of an SV using the CIPOS tag. It is in
// bed format so the end is +1'ed. E.g. If there is not CIPOS, the return value
// is v.Start(), v.Start() + 1
func (v *Variant) CIPos() (uint32, uint32, bool) {
if v.Header == nil {
v.Header = NewHeader()
}
s := v.Start()
v.Header.RLock()
if _, ok := v.Header.Infos["CIPOS"]; !ok {
v.Header.RUnlock()
v.Header.Lock()
v.Header.Infos["CIPOS"] = &Info{Id: "CIPOS", Number: "2", Description: "CIPOS", Type: "Integer"}
v.Header.Unlock()
} else {
v.Header.RUnlock()
}
ipair, err := v.Info().Get("CIPOS")
if ipair == nil && err != nil {
return s, s + 1, false
}
pair, ok := ipair.([]int)
if !ok {
return s, s + 1, false
}
left := pair[0]
right := pair[1]
return uint32(int(s) + left), uint32(int(s) + right + 1), true
}
// CIEnd reports the Left and Right end of an SV using the CIEND tag. It is in
// bed format so the end is +1'ed. E.g. If there is no CIEND, the return value
// is v.End() - 1, v.End()
func (v *Variant) CIEnd() (uint32, uint32, bool) {
if v.Header == nil {
v.Header = NewHeader()
}
e := v.End()
v.Header.RLock()
if _, ok := v.Header.Infos["CIEND"]; !ok {
v.Header.RUnlock()
v.Header.Lock()
v.Header.Infos["CIEND"] = &Info{Id: "CIEND", Number: "2", Description: "CIEND", Type: "Integer"}
v.Header.Unlock()
} else {
v.Header.RUnlock()
}
ipair, err := v.Info().Get("CIEND")
if ipair == nil && err != nil {
return e - 1, e, false
}
pair, ok := ipair.([]int)
if !ok {
return e - 1, e, false
}
left := pair[0]
right := pair[1]
return uint32(int(e)+left) - 1, uint32(int(e) + right), true
}
// End returns the 0-based start + the length of the reference allele.
func (v *Variant) End() uint32 {
/*
if len(v.Alt()[0]) == 0 {
log.Println(v.Chrom(), v.Start()+1, v.Ref(), v.Alt())
}*/
a := v.Alt()[0]
if len(a) == 0 || a[0] != '<' {
return uint32(v.Pos-1) + uint32(len(v.Ref()))
}
if strings.HasPrefix(v.Alt()[0], "<DEL") || strings.HasPrefix(v.Alt()[0], "<DUP") || strings.HasPrefix(v.Alt()[0], "<IN") || strings.HasPrefix(v.Alt()[0], "<CN") {
if svlen, err := v.Info().Get("SVLEN"); err == nil || (strings.Contains(err.Error(), "not found in header") && svlen != nil) {
var slen int
err = nil
switch svlen.(type) {
case int:
slen = svlen.(int)
case string:
var e error
if svlen.(string) == "" {
return uint32(v.Pos)
}
slen, e = strconv.Atoi(svlen.(string))
if e != nil {
log.Fatalf("bad value for svlen: %s\n", svlen)
}
case float64:
slen = int(svlen.(float64))
case float32:
slen = int(svlen.(float32))
case []interface{}:
slen = svlen.([]interface{})[0].(int)
case interface{}:
slen = svlen.(int)
default:
log.Printf("non int type for SVLEN:%s at %s:%d\n", svlen, v.Chrom(), v.Pos)
slen = 1
}
if slen < 0 {
slen = -slen
}
return uint32(int(v.Pos) + slen)
} else if end, err := v.Info().Get("END"); err == nil || end != nil {
if end == nil || end == "" {
if a != "<CN0>" {
log.Printf("non int type for END and SVLEN:%s at %s:%d\n", svlen, v.Chrom(), v.Pos)
}
return uint32(v.Pos + 1)
}
if e, ok := end.(int); ok {
return uint32(e)
}
if s, ok := end.(string); ok {
if v, err := strconv.Atoi(s); err == nil {
return uint32(v)
} else {
log.Printf("error parsing INFO/END: %s", err)
}
}
}
log.Printf("no svlen for variant %s:%d\n%s\nUsing %d", v.Chromosome, v.Pos, v, v.Pos+1)
}
// <INS and BND's get handled by this.
return uint32(v.Pos-1) + uint32(len(v.Ref()))
}
func fmtFloat32(v float32) string {
var val string
if v > 0.02 || v < -0.02 {
val = fmt.Sprintf("%.4f", v)
} else {
val = fmt.Sprintf("%.5g", v)
}
val = strings.TrimRight(strings.TrimRight(val, "0"), ".")
if val == "" || val == "-" {
val = "0"
}
return val
}
func fmtFloat64(v float64) string {
var val string
if v > 0.02 || v < -0.02 {
val = fmt.Sprintf("%.4f", v)
} else {
val = fmt.Sprintf("%.5g", v)
}
val = strings.TrimRight(strings.TrimRight(val, "0"), ".")
if val == "" || val == "-" {
val = "0"
}
return val
}
// SampleGenotype holds the information about a sample. Several fields are pre-parsed, but
// all fields are kept in Fields as well.
type SampleGenotype struct {
Phased bool
GT []int
DP int
GL []float64
GQ int
MQ int
Fields map[string]string
}
// String returns the string representation of the sample field.
func (s *SampleGenotype) String() string {
return fmt.Sprintf("GT: %v, DP: %d, GL: %v, GQ: %d, MQ: %d, Fields: %v", s.GT, s.DP, s.GL, s.GQ, s.MQ, s.Fields)
}
// RefDepth returns the depths of the alternates for this sample
func (s *SampleGenotype) RefDepth() (int, error) {
if ad, ok := s.Fields["AD"]; ok {
idx := strings.Index(ad, ",")
return strconv.Atoi(ad[:idx])
}
if ro, ok := s.Fields["RO"]; ok {
return strconv.Atoi(ro)
}
return 0, errors.New("only freebayes and gatk depths supported at this time")
}
// AltDepths returns the depths of the alternates for this sample
func (s *SampleGenotype) AltDepths() ([]int, error) {
var svals []string
if ad, ok := s.Fields["AD"]; ok {
idx := strings.Index(ad, ",")
svals = strings.Split(ad[idx+1:], ",")
} else if ro, ok := s.Fields["AO"]; ok {
svals = strings.Split(ro, ",")
} else {
return []int{}, errors.New("only freebayes and GATK supported for ref/alt depths")
}
vals := make([]int, len(svals))
for i := range svals {
v, err := strconv.Atoi(svals[i])
if err != nil {
return []int{}, err
}
vals[i] = v
}
return vals, nil
}
// ToString returns the string representation of the sample field.
func (sg *SampleGenotype) ToString(fields []string) string {
if len(fields) == 0 {
return "."
}
s := make([]string, len(fields))
for i, f := range fields {
s[i] = sg.Fields[f]
}
return strings.Join(s, ":")
}
// NewSampleGenotype allocates the internals and returns a *SampleGenotype
func NewSampleGenotype() *SampleGenotype {
s := &SampleGenotype{}
s.GT = make([]int, 0, 2)
s.GL = make([]float64, 0, 3)
s.Fields = make(map[string]string)
return s
}
// String gives a string representation of a variant
func (v *Variant) String() string {
var qual string
if v.Quality == MISSING_VAL {
qual = "."
} else {
qual = fmt.Sprintf("%.1f", v.Quality)
}
s := fmt.Sprintf("%s\t%d\t%s\t%s\t%s\t%s\t%s\t%s", v.Chromosome, v.Pos, v.Id_, v.Ref(), strings.Join(v.Alt(), ","), qual, v.Filter, v.Info())
if len(v.Samples) > 0 {
samps := make([]string, len(v.Samples))
for i, s := range v.Samples {
samps[i] = s.ToString(v.Format)
}
s += fmt.Sprintf("\t%s\t%s", strings.Join(v.Format, ":"), strings.Join(samps, "\t"))
} else if v.sampleString != "" {
s += fmt.Sprintf("\t%s\t%s", strings.Join(v.Format, ":"), v.sampleString)
}
return s
}
// GetGenotypeField uses the information from the header to parse the correct time from a genotype field.
// It returns an interface that can be asserted to the expected type.
func (v *Variant) GetGenotypeField(g *SampleGenotype, field string, missing interface{}) (interface{}, error) {
if g == nil {
return missing, fmt.Errorf("GetGenotypeField: empty genotype when requesting %s", field)
}
h := v.Header
format, ok := h.SampleFormats[field]
if !ok {
return nil, fmt.Errorf("GetGenotypeField: field not found in formats: %s", field)
}
value, ok := g.Fields[field]
if !ok {
return nil, fmt.Errorf("GetGenotypeField: field not found in genotypes: %s", field)
}
switch format.Type {
case "Integer":
var mv int
var ok bool
if mv, ok = missing.(int); !ok {
return nil, fmt.Errorf("GetGenotypeField: bad non-int missing value: %v", missing)
}
return handleNumberType(format.Number, value, len(v.Alt()), len(g.GT), true, mv)
case "Float":
var mv float32
var ok bool
if mv, ok = missing.(float32); !ok {
return nil, fmt.Errorf("GetGenotypeField: bad non-float missing value: %v", missing)
}
return handleNumberType(format.Number, value, len(v.Alt()), len(g.GT), false, mv)
case "String", "Character", "Unknown":
return value, nil
case "Flag":
return field, nil
}
return nil, fmt.Errorf("unknown format: %s", format.Type)
}
func handleNumberType(number string, value string, nAlts int, nGTs int, isInt bool, mv interface{}) (interface{}, error) {
if number == "1" || !strings.Contains(value, ",") || number == "." || number == "" {
if isInt {
if value == "" || value == "." {
return (mv).(int), nil
}
return strconv.Atoi(value)
}
if value == "" || value == "." {
return (mv).(float32), nil
}
return strconv.ParseFloat(value, 32)
}
if count, err := strconv.Atoi(number); err == nil || number == "G" || number == "A" || number == "R" {
if err != nil {
switch number {
case "G":
count = nGTs * (nGTs + 1) / 2
case "A":
count = nAlts
case "R":
count = nAlts + 1
}
err = nil
}
var ret interface{}
split := strings.Split(value, ",")
if isInt {
ret = make([]int, len(split), len(split))
} else {
ret = make([]float32, len(split), len(split))
}
var countErr error
// caller can ignore error if they want, we still fill what we can.
if len(split) != count {
countErr = fmt.Errorf("number of fields (%d) does not match expected (%d) in '%s'", len(split), count, value)
}
for i, s := range split {
if isInt {
ri, err := strconv.Atoi(s) //, 10, 32)
if err != nil {
// if it's an error, we allow empty
if s == "" || s == "." {
ret.([]int)[i] = mv.(int)
err = nil
} else {
return nil, fmt.Errorf("non integer type: %s", s)
}
} else {
ret.([]int)[i] = int(ri)
}
} else {
rf, err := strconv.ParseFloat(s, 32)
if err != nil {
// if it's an error, we allow empty
if s == "" || s == "." {
ret.([]float32)[i] = mv.(float32)
err = nil
} else {
return nil, fmt.Errorf("non float type: %s", s)
}
} else {
ret.([]float32)[i] = float32(rf)
}
}
}
return ret, countErr
} else if number == "." || number == "" {
return value, nil
} else {
return nil, fmt.Errorf("unknown number field: %s", number)
}
}