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 == "complete_genomics_pass_all" {
289 bedargs = append(bedargs,
290 "--ignore_phrases", "CNV", "INS:ME",
291 "--unreported_is_called",
293 } else if cmd.gvcfType != "" {
294 bedargs = append(bedargs, "--gvcf_type", cmd.gvcfType)
296 bedargs = append(bedargs, infile)
297 bed := exec.CommandContext(ctx, bedargs[0], bedargs[1:]...)
298 bed.Stdin = bytes.NewBuffer(cmd.gvcfRegionsPyData)
299 bed.Stdout = ®ions
300 bed.Stderr = cmd.stderr
301 log.Printf("running %v", bed.Args)
303 log.Printf("exited %v", bed.Args)
305 return fmt.Errorf("gvcf_regions: %s", err)
308 if cmd.genomeFile != "" {
309 // Read chromosome sizes from genome file in
310 // case any weren't specified in the VCF
312 genomeFile, err := open(cmd.genomeFile)
314 return fmt.Errorf("error opening genome file %q: %s", cmd.genomeFile, err)
316 scanner := bufio.NewScanner(genomeFile)
320 _, err := fmt.Sscanf(scanner.Text(), "%s\t%d", &chr, &size)
322 return fmt.Errorf("error parsing genome file %q: %s", cmd.genomeFile, err)
324 if chrSize[chr] == 0 {
328 if err = scanner.Err(); err != nil {
329 return fmt.Errorf("error scanning genome file %q: %s", cmd.genomeFile, err)
333 // "bedtools complement" expects the chromosome sizes
334 // ("genome file") to appear in the same order as the
335 // chromosomes in the input vcf, so we need to sort
337 scanner = bufio.NewScanner(bytes.NewBuffer(append([]byte(nil), regions.Bytes()...)))
338 var sortedGenomeFile bytes.Buffer
342 _, err := fmt.Sscanf(scanner.Text(), "%s\t%d", &chr, &size)
344 return fmt.Errorf("error parsing gvcf_regions output: %s", err)
346 if size, ok := chrSize[chr]; ok {
347 fmt.Fprintf(&sortedGenomeFile, "%s\t%d\n", chr, size)
352 // The bcftools --mask argument needs to end in ".bed"
353 // in order to be parsed as a BED file, so we need to
354 // use a named pipe instead of stdin.
355 tempdir, err := ioutil.TempDir("", "")
357 return fmt.Errorf("TempDir: %s", err)
359 defer os.RemoveAll(tempdir)
360 maskfifo = filepath.Join(tempdir, "fifo.bed")
361 err = syscall.Mkfifo(maskfifo, 0600)
363 return fmt.Errorf("mkfifo: %s", err)
366 // bedtools complement can't seem to read from a pipe
367 // reliably -- "Error: line number 1 of file
368 // /dev/stdin has 1 fields, but 3 were expected." --
369 // so we stage to a temp file.
370 regionsFile := filepath.Join(tempdir, "gvcf_regions.bed")
371 err = ioutil.WriteFile(regionsFile, regions.Bytes(), 0644)
380 maskfifow, err := os.OpenFile(maskfifo, os.O_WRONLY, 0)
385 defer maskfifow.Close()
387 bedcompargs := []string{"bedtools", "complement", "-i", regionsFile, "-g", "/dev/stdin"}
388 bedcompargs = maybeInDocker(bedcompargs, []string{cmd.genomeFile})
389 bedcomp := exec.CommandContext(ctx, bedcompargs[0], bedcompargs[1:]...)
390 bedcomp.Stdin = &sortedGenomeFile
391 bedcomp.Stdout = maskfifow
392 bedcomp.Stderr = cmd.stderr
393 log.Printf("running %v", bedcomp.Args)
395 log.Printf("exited %v", bedcomp.Args)
397 errs <- fmt.Errorf("bedtools complement: %s", err)
400 err = maskfifow.Close()
411 consargs := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase)}
413 consargs = append(consargs, "--mask", maskfifo)
415 consargs = append(consargs, infile)
416 indexsuffix := ".tbi"
417 if _, err := os.Stat(infile + ".csi"); err == nil {
420 mounts := []string{infile, infile + indexsuffix, cmd.refFile}
422 mounts = append(mounts, maskfifo)
424 consargs = maybeInDocker(consargs, mounts)
426 consensus := exec.CommandContext(ctx, consargs[0], consargs[1:]...)
427 consensus.Stderr = os.Stderr
428 consensus.Stdout = gzipw
429 consensus.Stderr = cmd.stderr
430 log.Printf("running %v", consensus.Args)
431 err = consensus.Run()
433 errs <- fmt.Errorf("bcftools consensus: %s", err)
436 log.Printf("exited %v", consensus.Args)
455 for err := range errs {
465 func (cmd *vcf2fasta) loadRegionsPy() error {
466 if strings.HasPrefix(cmd.gvcfRegionsPy, "http") {
467 resp, err := http.Get(cmd.gvcfRegionsPy)
471 if resp.StatusCode != http.StatusOK {
472 return fmt.Errorf("get %q: http status %d", cmd.gvcfRegionsPy, resp.StatusCode)
474 buf, err := ioutil.ReadAll(resp.Body)
476 return fmt.Errorf("get %q: read body: %s", cmd.gvcfRegionsPy, err)
478 cmd.gvcfRegionsPyData = buf
481 buf, err := ioutil.ReadFile(cmd.gvcfRegionsPy)
485 cmd.gvcfRegionsPyData = buf