Debian Codegraph @

variant.go

raw
1 package vcfgo
2
3 import (
4 "errors"
5 "fmt"
6 "log"
7 "math"
8 "strconv"
9 "strings"
10
11 "github.com/brentp/irelate/interfaces"
12 )
13
14 // Variant holds the information about a single site. It is analagous to a row in a VCF file.
15 type Variant struct {
16 Chromosome string
17 Pos uint64
18 Id_ string
19 Reference string
20 Alternate []string
21 Quality float32
22 Filter string
23 Info_ interfaces.Info
24 Format []string
25 Samples []*SampleGenotype
26 // if lazy parsing, then just save the sample strings here.
27 sampleString string
28 Header *Header
29 LineNumber int64
30 }
31
32 func (v *Variant) Info() interfaces.Info {
33 return v.Info_
34 }
35
36 func (v *Variant) Id() string {
37 return v.Id_
38 }
39
40 func (v *Variant) Ref() string {
41 return v.Reference
42 }
43
44 func (v *Variant) Alt() []string {
45 return v.Alternate
46 }
47
48 // Chrom returns the chromosome name.
49 func (v *Variant) Chrom() string {
50 return v.Chromosome
51 }
52
53 // Start returns the 0-based start
54 func (v *Variant) Start() uint32 {
55 return uint32(v.Pos - 1)
56 }
57
58 // CIPos reports the Left and Right end of an SV using the CIPOS tag. It is in
59 // bed format so the end is +1'ed. E.g. If there is not CIPOS, the return value
60 // is v.Start(), v.Start() + 1
61 func (v *Variant) CIPos() (uint32, uint32, bool) {
62 if v.Header == nil {
63 v.Header = NewHeader()
64 }
65 s := v.Start()
66 v.Header.RLock()
67 if _, ok := v.Header.Infos["CIPOS"]; !ok {
68 v.Header.RUnlock()
69 v.Header.Lock()
70 v.Header.Infos["CIPOS"] = &Info{Id: "CIPOS", Number: "2", Description: "CIPOS", Type: "Integer"}
71 v.Header.Unlock()
72 } else {
73 v.Header.RUnlock()
74 }
75
76 ipair, err := v.Info().Get("CIPOS")
77 if ipair == nil && err != nil {
78 return s, s + 1, false
79 }
80 pair, ok := ipair.([]int)
81 if !ok {
82 return s, s + 1, false
83 }
84 left := pair[0]
85 right := pair[1]
86 return uint32(int(s) + left), uint32(int(s) + right + 1), true
87 }
88
89 // CIEnd reports the Left and Right end of an SV using the CIEND tag. It is in
90 // bed format so the end is +1'ed. E.g. If there is no CIEND, the return value
91 // is v.End() - 1, v.End()
92 func (v *Variant) CIEnd() (uint32, uint32, bool) {
93 if v.Header == nil {
94 v.Header = NewHeader()
95 }
96 e := v.End()
97 v.Header.RLock()
98 if _, ok := v.Header.Infos["CIEND"]; !ok {
99 v.Header.RUnlock()
100 v.Header.Lock()
101 v.Header.Infos["CIEND"] = &Info{Id: "CIEND", Number: "2", Description: "CIEND", Type: "Integer"}
102 v.Header.Unlock()
103 } else {
104 v.Header.RUnlock()
105 }
106 ipair, err := v.Info().Get("CIEND")
107 if ipair == nil && err != nil {
108 return e - 1, e, false
109 }
110 pair, ok := ipair.([]int)
111 if !ok {
112 return e - 1, e, false
113 }
114 left := pair[0]
115 right := pair[1]
116 return uint32(int(e)+left) - 1, uint32(int(e) + right), true
117 }
118
119 // End returns the 0-based start + the length of the reference allele.
120 func (v *Variant) End() uint32 {
121 /*
122 if len(v.Alt()[0]) == 0 {
123 log.Println(v.Chrom(), v.Start()+1, v.Ref(), v.Alt())
124 }*/
125 a := v.Alt()[0]
126 if len(a) == 0 || a[0] != '<' {
127 return uint32(v.Pos-1) + uint32(len(v.Ref()))
128 }
129 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") {
130 if svlenValue, err := v.Info().Get("SVLEN"); err == nil || (strings.Contains(err.Error(), "not found in header") && svlenValue != nil) {
131 var slen int
132 err = nil
133 switch svlen := svlenValue.(type) {
134 case int:
135 slen = svlen
136 case string:
137 var e error
138 if svlen == "" {
139 return uint32(v.Pos)
140 }
141 slen, e = strconv.Atoi(svlen)
142 if e != nil {
143 log.Fatalf("bad value for svlen: %s\n", svlen)
144 }
145 case float64:
146 slen = int(svlen)
147 case float32:
148 slen = int(svlen)
149 case []interface{}:
150 slen = svlen[0].(int)
151 case []int:
152 slen = svlen[0]
153 default:
154 log.Printf("non int type for SVLEN:%s at %s:%d\n", svlen, v.Chrom(), v.Pos)
155 slen = 1
156 }
157 if slen < 0 {
158 slen = -slen
159 }
160 return uint32(int(v.Pos) + slen)
161
162 } else if end, err := v.Info().Get("END"); err == nil || end != nil {
163 if end == nil || end == "" {
164 if a != "<CN0>" {
165 log.Printf("non int type for END and SVLEN:%s at %s:%d\n", svlenValue, v.Chrom(), v.Pos)
166 }
167 return uint32(v.Pos + 1)
168 }
169
170 if e, ok := end.(int); ok {
171 return uint32(e)
172 }
173 if s, ok := end.(string); ok {
174 if v, err := strconv.Atoi(s); err == nil {
175 return uint32(v)
176 } else {
177 log.Printf("error parsing INFO/END: %s", err)
178 }
179 }
180 }
181 log.Printf("no svlen for variant %s:%d\n%s\nUsing %d", v.Chromosome, v.Pos, v, v.Pos+1)
182 }
183 // <INS and BND's get handled by this.
184 return uint32(v.Pos-1) + uint32(len(v.Ref()))
185 }
186
187 func fmtFloat32(v float32) string {
188 var val string
189 if v > 0.02 || v < -0.02 {
190 val = fmt.Sprintf("%.4f", v)
191 } else {
192 val = fmt.Sprintf("%.5g", v)
193 }
194 val = strings.TrimRight(strings.TrimRight(val, "0"), ".")
195 if val == "" || val == "-" {
196 val = "0"
197 }
198 return val
199 }
200
201 func fmtFloat64(v float64) string {
202 var val string
203 if v > 0.02 || v < -0.02 {
204 val = fmt.Sprintf("%.4f", v)
205 } else {
206 val = fmt.Sprintf("%.5g", v)
207 }
208 val = strings.TrimRight(strings.TrimRight(val, "0"), ".")
209 if val == "" || val == "-" {
210 val = "0"
211 }
212 return val
213 }
214
215 // SampleGenotype holds the information about a sample. Several fields are pre-parsed, but
216 // all fields are kept in Fields as well.
217 type SampleGenotype struct {
218 Phased bool
219 GT []int
220 DP int
221 GL []float64
222 GQ int
223 MQ int
224 Fields map[string]string
225 }
226
227 // String returns the string representation of the sample field.
228 func (s *SampleGenotype) String() string {
229 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)
230 }
231
232 // RefDepth returns the depths of the alternates for this sample
233 func (s *SampleGenotype) RefDepth() (int, error) {
234 if ad, ok := s.Fields["AD"]; ok {
235 idx := strings.Index(ad, ",")
236 return strconv.Atoi(ad[:idx])
237 }
238 if ro, ok := s.Fields["RO"]; ok {
239 return strconv.Atoi(ro)
240 }
241 return 0, errors.New("only freebayes and gatk depths supported at this time")
242 }
243
244 // AltDepths returns the depths of the alternates for this sample
245 func (s *SampleGenotype) AltDepths() ([]int, error) {
246 var svals []string
247 if ad, ok := s.Fields["AD"]; ok {
248 idx := strings.Index(ad, ",")
249 svals = strings.Split(ad[idx+1:], ",")
250 } else if ro, ok := s.Fields["AO"]; ok {
251 svals = strings.Split(ro, ",")
252 } else {
253 return []int{}, errors.New("only freebayes and GATK supported for ref/alt depths")
254 }
255 vals := make([]int, len(svals))
256 for i := range svals {
257 v, err := strconv.Atoi(svals[i])
258 if err != nil {
259 return []int{}, err
260 }
261 vals[i] = v
262 }
263 return vals, nil
264 }
265
266 // ToString returns the string representation of the sample field.
267 func (sg *SampleGenotype) ToString(fields []string) string {
268 if len(fields) == 0 {
269 return "."
270 }
271
272 s := make([]string, len(fields))
273 for i, f := range fields {
274 s[i] = sg.Fields[f]
275 }
276 return strings.Join(s, ":")
277 }
278
279 // NewSampleGenotype allocates the internals and returns a *SampleGenotype
280 func NewSampleGenotype() *SampleGenotype {
281 s := &SampleGenotype{}
282 s.GT = make([]int, 0, 2)
283 s.GL = make([]float64, 0, 3)
284 s.Fields = make(map[string]string)
285 return s
286 }
287
288 // String gives a string representation of a variant
289 func (v *Variant) String() string {
290 var qual string
291
292 if math.Float32bits(v.Quality) == missingBits {
293 qual = "."
294 } else {
295 qual = fmt.Sprintf("%.1f", v.Quality)
296 }
297
298 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())
299 if len(v.Samples) > 0 {
300 samps := make([]string, len(v.Samples))
301 for i, s := range v.Samples {
302 samps[i] = s.ToString(v.Format)
303 }
304 s += fmt.Sprintf("\t%s\t%s", strings.Join(v.Format, ":"), strings.Join(samps, "\t"))
305 } else if v.sampleString != "" {
306 s += fmt.Sprintf("\t%s\t%s", strings.Join(v.Format, ":"), v.sampleString)
307 }
308 return s
309 }
310
311 // GetGenotypeField uses the information from the header to parse the correct time from a genotype field.
312 // It returns an interface that can be asserted to the expected type.
313 func (v *Variant) GetGenotypeField(g *SampleGenotype, field string, missing interface{}) (interface{}, error) {
314 if g == nil {
315 return missing, fmt.Errorf("GetGenotypeField: empty genotype when requesting %s", field)
316 }
317 h := v.Header
318 format, ok := h.SampleFormats[field]
319 if !ok {
320 return nil, fmt.Errorf("GetGenotypeField: field not found in formats: %s", field)
321 }
322 value, ok := g.Fields[field]
323 if !ok {
324 return nil, fmt.Errorf("GetGenotypeField: field not found in genotypes: %s", field)
325 }
326 switch format.Type {
327 case "Integer":
328 var mv int
329 var ok bool
330 if mv, ok = missing.(int); !ok {
331 return nil, fmt.Errorf("GetGenotypeField: bad non-int missing value: %v", missing)
332 }
333 return handleNumberType(format.Number, value, len(v.Alt()), len(g.GT), true, mv)
334
335 case "Float":
336 var mv float32
337 var ok bool
338 if mv, ok = missing.(float32); !ok {
339 return nil, fmt.Errorf("GetGenotypeField: bad non-float missing value: %v", missing)
340 }
341 return handleNumberType(format.Number, value, len(v.Alt()), len(g.GT), false, mv)
342
343 case "String", "Character", "Unknown":
344 return value, nil
345
346 case "Flag":
347 return field, nil
348
349 }
350
351 return nil, fmt.Errorf("unknown format: %s", format.Type)
352 }
353
354 func handleNumberType(number string, value string, nAlts int, nGTs int, isInt bool, mv interface{}) (interface{}, error) {
355 if number == "1" || !strings.Contains(value, ",") || number == "." || number == "" {
356 if isInt {
357 if value == "" || value == "." {
358 return (mv).(int), nil
359 }
360 return strconv.Atoi(value)
361 }
362 if value == "" || value == "." {
363 return (mv).(float32), nil
364 }
365 return strconv.ParseFloat(value, 32)
366 }
367 if count, err := strconv.Atoi(number); err == nil || number == "G" || number == "A" || number == "R" {
368 if err != nil {
369 switch number {
370 case "G":
371 count = nGTs * (nGTs + 1) / 2
372 case "A":
373 count = nAlts
374 case "R":
375 count = nAlts + 1
376 }
377 err = nil
378 }
379 var ret interface{}
380 split := strings.Split(value, ",")
381 if isInt {
382 ret = make([]int, len(split), len(split))
383 } else {
384 ret = make([]float32, len(split), len(split))
385 }
386
387 var countErr error
388
389 // caller can ignore error if they want, we still fill what we can.
390 if len(split) != count {
391 countErr = fmt.Errorf("number of fields (%d) does not match expected (%d) in '%s'", len(split), count, value)
392 }
393 for i, s := range split {
394 if isInt {
395 ri, err := strconv.Atoi(s) //, 10, 32)
396 if err != nil {
397 // if it's an error, we allow empty
398 if s == "" || s == "." {
399 ret.([]int)[i] = mv.(int)
400 err = nil
401 } else {
402 return nil, fmt.Errorf("non integer type: %s", s)
403 }
404 } else {
405 ret.([]int)[i] = int(ri)
406 }
407 } else {
408 rf, err := strconv.ParseFloat(s, 32)
409 if err != nil {
410 // if it's an error, we allow empty
411 if s == "" || s == "." {
412 ret.([]float32)[i] = mv.(float32)
413 err = nil
414 } else {
415 return nil, fmt.Errorf("non float type: %s", s)
416 }
417 } else {
418 ret.([]float32)[i] = float32(rf)
419 }
420 }
421 }
422 return ret, countErr
423 } else if number == "." || number == "" {
424 return value, nil
425 } else {
426 return nil, fmt.Errorf("unknown number field: %s", number)
427 }
428 }