23 "github.com/kshedden/gonpy"
26 type gvcf2numpy struct {
32 func (cmd *gvcf2numpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
36 fmt.Fprintf(stderr, "%s\n", err)
39 flags := flag.NewFlagSet("", flag.ContinueOnError)
40 flags.SetOutput(stderr)
41 flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
42 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
43 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
44 err = flags.Parse(args)
45 if err == flag.ErrHelp {
48 } else if err != nil {
50 } else if cmd.refFile == "" || cmd.tagLibraryFile == "" {
51 fmt.Fprintln(os.Stderr, "cannot run without -tag-library and -ref arguments")
53 } else if flags.NArg() == 0 {
61 log.Println(http.ListenAndServe(*pprof, nil))
65 infiles, err := listInputFiles(flags.Args())
70 tilelib, err := cmd.loadTileLibrary()
75 for range time.Tick(10 * time.Second) {
76 log.Printf("tilelib.Len() == %d", tilelib.Len())
79 variants, err := cmd.tileGVCFs(tilelib, infiles)
83 err = cmd.printVariants(variants)
90 func (cmd *gvcf2numpy) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, error) {
91 var input io.ReadCloser
92 input, err := os.Open(infile)
97 if strings.HasSuffix(infile, ".gz") {
98 input, err = gzip.NewReader(input)
104 return tilelib.TileFasta(infile, input)
107 func (cmd *gvcf2numpy) loadTileLibrary() (*tileLibrary, error) {
108 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
109 f, err := os.Open(cmd.tagLibraryFile)
114 var rdr io.ReadCloser = f
115 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
116 rdr, err = gzip.NewReader(f)
118 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
122 var taglib tagLibrary
123 err = taglib.Load(rdr)
127 if taglib.Len() < 1 {
128 return nil, fmt.Errorf("cannot tile: tag library is empty")
130 log.Printf("tag library %s load done", cmd.tagLibraryFile)
131 return &tileLibrary{taglib: &taglib}, nil
134 func listInputFiles(paths []string) (files []string, err error) {
135 for _, path := range paths {
136 if fi, err := os.Stat(path); err != nil {
137 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
138 } else if !fi.IsDir() {
139 if !strings.HasSuffix(path, ".2.fasta") || strings.HasSuffix(path, ".2.fasta.gz") {
140 files = append(files, path)
144 d, err := os.Open(path)
146 return nil, fmt.Errorf("%s: open failed: %s", path, err)
149 names, err := d.Readdirnames(0)
151 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
154 for _, name := range names {
155 if strings.HasSuffix(name, ".vcf") || strings.HasSuffix(name, ".vcf.gz") {
156 files = append(files, filepath.Join(path, name))
157 } else if strings.HasSuffix(name, ".1.fasta") || strings.HasSuffix(name, ".1.fasta.gz") {
158 files = append(files, filepath.Join(path, name))
163 for _, file := range files {
164 if strings.HasSuffix(file, ".1.fasta") || strings.HasSuffix(file, ".1.fasta.gz") {
166 } else if _, err := os.Stat(file + ".csi"); err == nil {
168 } else if _, err = os.Stat(file + ".tbi"); err == nil {
171 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
177 func (cmd *gvcf2numpy) tileGVCFs(tilelib *tileLibrary, infiles []string) ([][]tileVariantID, error) {
178 starttime := time.Now()
179 errs := make(chan error, 1)
180 variants := make([][]tileVariantID, len(infiles)*2)
181 todo := make(chan func() error, len(infiles)*2)
182 var wg sync.WaitGroup
183 for i, infile := range infiles {
184 i, infile := i, infile
185 if strings.HasSuffix(infile, ".1.fasta") || strings.HasSuffix(infile, ".1.fasta.gz") {
186 todo <- func() error {
187 log.Printf("%s starting", infile)
188 defer log.Printf("%s done", infile)
189 tseqs, err := cmd.tileFasta(tilelib, infile)
190 variants[i*2] = tseqs.Variants()
193 infile2 := regexp.MustCompile(`\.1\.fasta(\.gz)?$`).ReplaceAllString(infile, `.2.fasta$1`)
194 todo <- func() error {
195 log.Printf("%s starting", infile2)
196 defer log.Printf("%s done", infile2)
197 tseqs, err := cmd.tileFasta(tilelib, infile2)
198 variants[i*2+1] = tseqs.Variants()
202 for phase := 0; phase < 2; phase++ {
204 todo <- func() error {
205 log.Printf("%s phase %d starting", infile, phase+1)
206 defer log.Printf("%s phase %d done", infile, phase+1)
207 tseqs, err := cmd.tileGVCF(tilelib, infile, phase)
208 variants[i*2+phase] = tseqs.Variants()
215 running := int64(runtime.NumCPU())
216 for i := 0; i < runtime.NumCPU(); i++ {
220 defer atomic.AddInt64(&running, -1)
221 for fn := range todo {
232 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
233 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
234 eta := time.Now().Add(ttl)
235 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
241 return variants, <-errs
244 func (cmd *gvcf2numpy) printVariants(variants [][]tileVariantID) error {
246 for _, v := range variants {
251 rows := len(variants) / 2
253 out := make([]uint16, rows*cols)
254 for row := 0; row < len(variants)/2; row++ {
255 for phase := 0; phase < 2; phase++ {
256 for tag, variant := range variants[row*2+phase] {
257 out[row*cols+2*int(tag)+phase] = uint16(variant)
261 w := bufio.NewWriter(cmd.output)
262 npw, err := gonpy.NewWriter(nopCloser{w})
266 npw.Shape = []int{rows, cols}
271 type nopCloser struct {
275 func (nopCloser) Close() error { return nil }
277 func (cmd *gvcf2numpy) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, err error) {
278 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
279 indexsuffix := ".tbi"
280 if _, err := os.Stat(infile + ".csi"); err == nil {
283 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
284 args = append([]string{
285 "docker", "run", "--rm",
287 "--volume=" + infile + ":" + infile + ":ro",
288 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
289 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
293 consensus := exec.Command(args[0], args[1:]...)
294 consensus.Stderr = os.Stderr
295 stdout, err := consensus.StdoutPipe()
300 err = consensus.Start()
304 defer consensus.Wait()
305 tileseq, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout)
313 err = consensus.Wait()
315 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)