/
vcf-subset.go
123 lines (105 loc) · 2.64 KB
/
vcf-subset.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
package main
import (
"bufio"
"errors"
"fmt"
"github.com/codegangsta/cli"
"github.com/knmkr/go-vcf-tools/lib"
"io"
"log"
"os"
"strconv"
"strings"
)
func doSubset(c *cli.Context) {
arg_keep_id := c.String("keep-id")
arg_keep_ids := c.String("keep-ids")
arg_keep_index := c.String("keep-index")
reader := bufio.NewReaderSize(os.Stdin, 64*1024)
// Parse header lines
var sample_ids []string
line, err := lib.Readln(reader)
for err == nil {
if strings.HasPrefix(line, "##") {
fmt.Println(line)
} else if strings.HasPrefix(line, "#CHROM") {
fields := strings.Split(line, "\t")
fmt.Print(strings.Join(fields[0:9], "\t"))
fmt.Print("\t")
sample_ids = fields[9:]
break
} else {
err = errors.New("Invalid VCF header")
break
}
line, err = lib.Readln(reader)
}
if err != nil && err != io.EOF {
panic(err)
}
// Get indices of sample IDs to be kept
keep_ids := []string{}
keep_idxs := []int{}
if arg_keep_id != "" || arg_keep_ids != "" {
if arg_keep_id != "" {
// A sample ID to be kept. E.g., NA00001
keep_ids = append(keep_ids, arg_keep_id)
} else {
// Path to a file of sample IDs to be kept. Each line contains one sample ID.
fp, err := os.Open(arg_keep_ids)
if err != nil {
panic(err)
}
defer fp.Close()
ids_reader := bufio.NewReaderSize(fp, 128*1024)
ids_line, err := lib.Readln(ids_reader)
for err == nil {
keep_ids = append(keep_ids, ids_line)
ids_line, err = lib.Readln(ids_reader)
}
if err != nil && err != io.EOF {
panic(err)
}
}
for i := range keep_ids {
for j := range sample_ids {
if keep_ids[i] == sample_ids[j] {
keep_idxs = append(keep_idxs, j)
break
}
}
}
if len(keep_idxs) == 0 {
fmt.Println()
log.Fatal("No sample IDs matched.")
}
} else if arg_keep_index != "" {
// An index of sample ID field to be kept. E.g., to keep 1st sample, set: 0
_keep_idx, _ := strconv.Atoi(arg_keep_index)
if _keep_idx > len(sample_ids) {
fmt.Println()
log.Fatal("No sample IDs matched.")
}
keep_idxs = append(keep_idxs, _keep_idx)
}
fmt.Println(strings.Join(subset(sample_ids, keep_idxs), "\t"))
line, err = lib.Readln(reader)
for err == nil {
records := strings.Split(line, "\t")
result := []string{}
result = append(result, records[0:9]...)
result = append(result, subset(records[9:], keep_idxs)...)
fmt.Println(strings.Join(result, "\t"))
line, err = lib.Readln(reader)
}
if err != nil && err != io.EOF {
panic(err)
}
}
func subset(records []string, keep_idxs []int) []string {
result := []string{}
for i := range keep_idxs {
result = append(result, records[keep_idxs[i]])
}
return result
}