25 "github.com/klauspost/pgzip"
26 log "github.com/sirupsen/logrus"
29 type vcf2fasta struct {
34 gvcfRegionsPyData []byte
45 func (cmd *vcf2fasta) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
49 fmt.Fprintf(stderr, "%s\n", err)
52 flags := flag.NewFlagSet("", flag.ContinueOnError)
53 flags.SetOutput(stderr)
54 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
55 flags.StringVar(&cmd.genomeFile, "genome", "", "reference genome `file`")
56 flags.BoolVar(&cmd.mask, "mask", false, "mask uncalled regions (default: output hom ref)")
57 flags.StringVar(&cmd.gvcfRegionsPy, "gvcf-regions.py", "https://raw.githubusercontent.com/lijiayong/gvcf_regions/master/gvcf_regions.py", "source of gvcf_regions.py")
58 flags.StringVar(&cmd.gvcfType, "gvcf-type", "gatk", "gvcf_type argument to gvcf_regions.py: gatk, complete_genomics, freebayes")
59 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for containers and output data")
60 flags.StringVar(&cmd.outputDir, "output-dir", "", "output directory")
61 flags.IntVar(&cmd.vcpus, "vcpus", 0, "number of VCPUs to request for arvados container (default: 2*number of input files, max 32)")
62 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
63 cmd.batchArgs.Flags(flags)
64 priority := flags.Int("priority", 500, "container request priority")
65 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
66 err = flags.Parse(args)
67 if err == flag.ErrHelp {
70 } else if err != nil {
72 } else if cmd.refFile == "" {
73 err = errors.New("reference data (-ref) not specified")
75 } else if flags.NArg() == 0 {
83 log.Println(http.ListenAndServe(*pprof, nil))
88 err = cmd.loadRegionsPy()
95 if cmd.outputDir != "" {
96 err = errors.New("cannot specify output dir in non-local mode")
101 infiles, err = listInputFiles(flags.Args())
105 batchsize := (len(infiles) + cmd.batchArgs.batches - 1) / cmd.batchArgs.batches
106 if cmd.vcpus = batchsize * 2; cmd.vcpus > 32 {
110 runner := arvadosContainerRunner{
111 Name: "lightning vcf2fasta",
112 Client: arvadosClientFromEnv,
113 ProjectUUID: cmd.projectUUID,
114 RAM: 2<<30 + int64(cmd.vcpus)<<28,
119 Mounts: map[string]map[string]interface{}{
120 "/gvcf_regions.py": map[string]interface{}{
122 "content": string(cmd.gvcfRegionsPyData),
126 err = runner.TranslatePaths(&cmd.refFile, &cmd.genomeFile)
130 inputs := flags.Args()
131 for i := range inputs {
132 err = runner.TranslatePaths(&inputs[i])
138 outputs, err = cmd.batchArgs.RunBatches(context.Background(), func(ctx context.Context, batch int) (string, error) {
141 runner.RAM += int64(cmd.vcpus) << 31
143 runner.Args = []string{"vcf2fasta",
145 "-ref", cmd.refFile, fmt.Sprintf("-mask=%v", cmd.mask),
146 "-genome", cmd.genomeFile,
147 "-gvcf-regions.py", "/gvcf_regions.py",
148 "-gvcf-type", cmd.gvcfType,
149 "-output-dir", "/mnt/output",
151 runner.Args = append(runner.Args, cmd.batchArgs.Args(batch)...)
152 runner.Args = append(runner.Args, inputs...)
153 log.Printf("batch %d: %v", batch, runner.Args)
154 return runner.RunContext(ctx)
159 fmt.Fprintln(stdout, strings.Join(outputs, " "))
163 infiles, err := listInputFiles(flags.Args())
167 infiles = cmd.batchArgs.Slice(infiles)
173 todo := make(chan job)
175 for _, infile := range infiles {
176 for phase := 1; phase <= 2; phase++ {
177 todo <- job{vcffile: infile, phase: phase}
183 done := make(chan error, runtime.NumCPU()*2)
184 var wg sync.WaitGroup
185 for i := 0; i < runtime.NumCPU(); i++ {
189 for job := range todo {
191 // a different worker encountered an error
194 err := cmd.vcf2fasta(job.vcffile, job.phase)
196 done <- fmt.Errorf("%s phase %d: %s", job.vcffile, job.phase, err)
214 func maybeInDocker(args, mountfiles []string) []string {
215 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err != nil || len(out) == 0 {
218 dockerrun := []string{
219 "docker", "run", "--rm", "-i",
222 for _, f := range mountfiles {
223 dockerrun = append(dockerrun, "--volume="+f+":"+f+":ro")
225 dockerrun = append(dockerrun, "lightning-runtime")
226 dockerrun = append(dockerrun, args...)
230 func (cmd *vcf2fasta) vcf2fasta(infile string, phase int) error {
231 ctx, cancel := context.WithCancel(context.Background())
234 _, basename := filepath.Split(infile)
235 outfile := filepath.Join(cmd.outputDir, fmt.Sprintf("%s.%d.fasta.gz", basename, phase))
236 outf, err := os.OpenFile(outfile, os.O_CREATE|os.O_WRONLY, 0777)
238 return fmt.Errorf("error opening output file: %s", err)
241 bufw := bufio.NewWriterSize(outf, 8*1024*1024)
242 gzipw := pgzip.NewWriter(bufw)
245 var maskfifo string // filename of mask fifo if we're running bedtools, otherwise ""
247 var wg sync.WaitGroup
248 errs := make(chan error, 2)
250 chrSize := map[string]int{}
252 vcffile, err := open(infile)
256 defer vcffile.Close()
257 var rdr io.Reader = vcffile
258 rdr = bufio.NewReaderSize(rdr, 8*1024*1024)
259 if strings.HasSuffix(infile, ".gz") {
260 rdr, err = gzip.NewReader(vcffile)
265 contigre := regexp.MustCompile(`([^=,]*)=([^>,]*)`)
266 scanner := bufio.NewScanner(rdr)
268 if s := scanner.Text(); !strings.HasPrefix(s, "##") {
270 } else if !strings.HasPrefix(s, "##contig=<") {
273 kv := map[string]string{}
274 for _, m := range contigre.FindAllStringSubmatch(s[10:], -1) {
277 if kv["ID"] != "" && kv["length"] != "" {
278 chrSize[kv["ID"]], _ = strconv.Atoi(kv["length"])
282 if err = scanner.Err(); err != nil {
283 return fmt.Errorf("error scanning input file %q: %s", infile, err)
286 var regions bytes.Buffer
287 bedargs := []string{"python2", "-"}
288 if cmd.gvcfType != "" {
289 bedargs = append(bedargs, "--gvcf_type", cmd.gvcfType)
291 bedargs = append(bedargs, infile)
292 bed := exec.CommandContext(ctx, bedargs[0], bedargs[1:]...)
293 bed.Stdin = bytes.NewBuffer(cmd.gvcfRegionsPyData)
294 bed.Stdout = ®ions
295 bed.Stderr = cmd.stderr
296 log.Printf("running %v", bed.Args)
298 log.Printf("exited %v", bed.Args)
300 return fmt.Errorf("gvcf_regions: %s", err)
303 if cmd.genomeFile != "" {
304 // Read chromosome sizes from genome file in
305 // case any weren't specified in the VCF
307 genomeFile, err := open(cmd.genomeFile)
309 return fmt.Errorf("error opening genome file %q: %s", cmd.genomeFile, err)
311 scanner := bufio.NewScanner(genomeFile)
315 _, err := fmt.Sscanf(scanner.Text(), "%s\t%d", &chr, &size)
317 return fmt.Errorf("error parsing genome file %q: %s", cmd.genomeFile, err)
319 if chrSize[chr] == 0 {
323 if err = scanner.Err(); err != nil {
324 return fmt.Errorf("error scanning genome file %q: %s", cmd.genomeFile, err)
328 // "bedtools complement" expects the chromosome sizes
329 // ("genome file") to appear in the same order as the
330 // chromosomes in the input vcf, so we need to sort
332 scanner = bufio.NewScanner(bytes.NewBuffer(append([]byte(nil), regions.Bytes()...)))
333 var sortedGenomeFile bytes.Buffer
337 _, err := fmt.Sscanf(scanner.Text(), "%s\t%d", &chr, &size)
339 return fmt.Errorf("error parsing gvcf_regions output: %s", err)
341 if size, ok := chrSize[chr]; ok {
342 fmt.Fprintf(&sortedGenomeFile, "%s\t%d\n", chr, size)
347 // The bcftools --mask argument needs to end in ".bed"
348 // in order to be parsed as a BED file, so we need to
349 // use a named pipe instead of stdin.
350 tempdir, err := ioutil.TempDir("", "")
352 return fmt.Errorf("TempDir: %s", err)
354 defer os.RemoveAll(tempdir)
355 maskfifo = filepath.Join(tempdir, "fifo.bed")
356 err = syscall.Mkfifo(maskfifo, 0600)
358 return fmt.Errorf("mkfifo: %s", err)
361 // bedtools complement can't seem to read from a pipe
362 // reliably -- "Error: line number 1 of file
363 // /dev/stdin has 1 fields, but 3 were expected." --
364 // so we stage to a temp file.
365 regionsFile := filepath.Join(tempdir, "gvcf_regions.bed")
366 err = ioutil.WriteFile(regionsFile, regions.Bytes(), 0644)
375 maskfifow, err := os.OpenFile(maskfifo, os.O_WRONLY, 0)
380 defer maskfifow.Close()
382 bedcompargs := []string{"bedtools", "complement", "-i", regionsFile, "-g", "/dev/stdin"}
383 bedcompargs = maybeInDocker(bedcompargs, []string{cmd.genomeFile})
384 bedcomp := exec.CommandContext(ctx, bedcompargs[0], bedcompargs[1:]...)
385 bedcomp.Stdin = &sortedGenomeFile
386 bedcomp.Stdout = maskfifow
387 bedcomp.Stderr = cmd.stderr
388 log.Printf("running %v", bedcomp.Args)
390 log.Printf("exited %v", bedcomp.Args)
392 errs <- fmt.Errorf("bedtools complement: %s", err)
395 err = maskfifow.Close()
406 consargs := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase)}
408 consargs = append(consargs, "--mask", maskfifo)
410 consargs = append(consargs, infile)
411 indexsuffix := ".tbi"
412 if _, err := os.Stat(infile + ".csi"); err == nil {
415 mounts := []string{infile, infile + indexsuffix, cmd.refFile}
417 mounts = append(mounts, maskfifo)
419 consargs = maybeInDocker(consargs, mounts)
421 consensus := exec.CommandContext(ctx, consargs[0], consargs[1:]...)
422 consensus.Stderr = os.Stderr
423 consensus.Stdout = gzipw
424 consensus.Stderr = cmd.stderr
425 log.Printf("running %v", consensus.Args)
426 err = consensus.Run()
428 errs <- fmt.Errorf("bcftools consensus: %s", err)
431 log.Printf("exited %v", consensus.Args)
450 for err := range errs {
460 func (cmd *vcf2fasta) loadRegionsPy() error {
461 if strings.HasPrefix(cmd.gvcfRegionsPy, "http") {
462 resp, err := http.Get(cmd.gvcfRegionsPy)
466 if resp.StatusCode != http.StatusOK {
467 return fmt.Errorf("get %q: http status %d", cmd.gvcfRegionsPy, resp.StatusCode)
469 buf, err := ioutil.ReadAll(resp.Body)
471 return fmt.Errorf("get %q: read body: %s", cmd.gvcfRegionsPy, err)
473 cmd.gvcfRegionsPyData = buf
476 buf, err := ioutil.ReadFile(cmd.gvcfRegionsPy)
480 cmd.gvcfRegionsPyData = buf