25 "git.arvados.org/arvados.git/sdk/go/arvados"
26 log "github.com/sirupsen/logrus"
29 type vcf2fasta struct {
34 gvcfRegionsPyData []byte
43 func (cmd *vcf2fasta) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
47 fmt.Fprintf(stderr, "%s\n", err)
50 flags := flag.NewFlagSet("", flag.ContinueOnError)
51 flags.SetOutput(stderr)
52 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
53 flags.StringVar(&cmd.genomeFile, "genome", "", "reference genome `file`")
54 flags.BoolVar(&cmd.mask, "mask", false, "mask uncalled regions (default: output hom ref)")
55 flags.StringVar(&cmd.gvcfRegionsPy, "gvcf-regions.py", "https://raw.githubusercontent.com/lijiayong/gvcf_regions/master/gvcf_regions.py", "source of gvcf_regions.py")
56 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for containers and output data")
57 flags.StringVar(&cmd.outputDir, "output-dir", "", "output directory")
58 flags.IntVar(&cmd.vcpus, "vcpus", 0, "number of VCPUs to request for arvados container (default: 2*number of input files, max 32)")
59 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
60 priority := flags.Int("priority", 500, "container request priority")
61 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
62 err = flags.Parse(args)
63 if err == flag.ErrHelp {
66 } else if err != nil {
68 } else if cmd.refFile == "" {
69 err = errors.New("reference data (-ref) not specified")
71 } else if flags.NArg() == 0 {
79 log.Println(http.ListenAndServe(*pprof, nil))
84 err = cmd.loadRegionsPy()
91 if cmd.outputDir != "" {
92 err = errors.New("cannot specify output dir in non-local mode")
97 infiles, err = listInputFiles(flags.Args())
101 if cmd.vcpus = len(infiles) * 2; cmd.vcpus > 32 {
105 runner := arvadosContainerRunner{
106 Name: "lightning vcf2fasta",
107 Client: arvados.NewClientFromEnv(),
108 ProjectUUID: cmd.projectUUID,
109 RAM: 2<<30 + int64(cmd.vcpus)<<28,
112 Mounts: map[string]map[string]interface{}{
113 "/gvcf_regions.py": map[string]interface{}{
115 "content": string(cmd.gvcfRegionsPyData),
120 runner.RAM += int64(cmd.vcpus) << 31
122 err = runner.TranslatePaths(&cmd.refFile, &cmd.genomeFile)
126 inputs := flags.Args()
127 for i := range inputs {
128 err = runner.TranslatePaths(&inputs[i])
133 runner.Args = append([]string{"vcf2fasta",
135 "-ref", cmd.refFile, fmt.Sprintf("-mask=%v", cmd.mask),
136 "-genome", cmd.genomeFile,
137 "-gvcf-regions.py", "/gvcf_regions.py",
138 "-output-dir", "/mnt/output"}, inputs...)
140 output, err = runner.Run()
144 fmt.Fprintln(stdout, output)
148 infiles, err := listInputFiles(flags.Args())
157 todo := make(chan job)
159 for _, infile := range infiles {
160 for phase := 1; phase <= 2; phase++ {
161 todo <- job{vcffile: infile, phase: phase}
167 done := make(chan error, runtime.NumCPU()*2)
168 var wg sync.WaitGroup
169 for i := 0; i < runtime.NumCPU(); i++ {
173 for job := range todo {
175 // a different worker encountered an error
178 err := cmd.vcf2fasta(job.vcffile, job.phase)
180 done <- fmt.Errorf("%s phase %d: %s", job.vcffile, job.phase, err)
198 func maybeInDocker(args, mountfiles []string) []string {
199 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err != nil || len(out) == 0 {
202 dockerrun := []string{
203 "docker", "run", "--rm", "-i",
206 for _, f := range mountfiles {
207 dockerrun = append(dockerrun, "--volume="+f+":"+f+":ro")
209 dockerrun = append(dockerrun, "lightning-runtime")
210 dockerrun = append(dockerrun, args...)
214 func (cmd *vcf2fasta) vcf2fasta(infile string, phase int) error {
215 ctx, cancel := context.WithCancel(context.Background())
218 _, basename := filepath.Split(infile)
219 outfile := filepath.Join(cmd.outputDir, fmt.Sprintf("%s.%d.fasta.gz", basename, phase))
220 outf, err := os.OpenFile(outfile, os.O_CREATE|os.O_WRONLY, 0777)
222 return fmt.Errorf("error opening output file: %s", err)
225 gzipw := gzip.NewWriter(outf)
228 var maskfifo string // filename of mask fifo if we're running bedtools, otherwise ""
230 var wg sync.WaitGroup
231 errs := make(chan error, 2)
233 chrSize := map[string]int{}
235 vcffile, err := os.Open(infile)
239 defer vcffile.Close()
240 var rdr io.Reader = vcffile
241 if strings.HasSuffix(infile, ".gz") {
242 rdr, err = gzip.NewReader(vcffile)
247 contigre := regexp.MustCompile(`([^=,]*)=([^>,]*)`)
248 scanner := bufio.NewScanner(rdr)
250 if s := scanner.Text(); !strings.HasPrefix(s, "##") {
252 } else if !strings.HasPrefix(s, "##contig=<") {
255 kv := map[string]string{}
256 for _, m := range contigre.FindAllStringSubmatch(s[10:], -1) {
259 if kv["ID"] != "" && kv["length"] != "" {
260 chrSize[kv["ID"]], _ = strconv.Atoi(kv["length"])
264 if err = scanner.Err(); err != nil {
265 return fmt.Errorf("error scanning input file %q: %s", infile, err)
267 var regions bytes.Buffer
268 bedargs := []string{"python2", "-", "--gvcf_type", "gatk", infile}
269 bed := exec.CommandContext(ctx, bedargs[0], bedargs[1:]...)
270 bed.Stdin = bytes.NewBuffer(cmd.gvcfRegionsPyData)
271 bed.Stdout = ®ions
272 bed.Stderr = cmd.stderr
273 log.Printf("running %v", bed.Args)
275 log.Printf("exited %v", bed.Args)
277 return fmt.Errorf("gvcf_regions: %s", err)
280 if cmd.genomeFile != "" {
281 // Read chromosome sizes from genome file in
282 // case any weren't specified in the VCF
284 genomeFile, err := os.Open(cmd.genomeFile)
286 return fmt.Errorf("error opening genome file %q: %s", cmd.genomeFile, err)
288 scanner := bufio.NewScanner(genomeFile)
292 _, err := fmt.Sscanf(scanner.Text(), "%s\t%d", &chr, &size)
294 return fmt.Errorf("error parsing genome file %q: %s", cmd.genomeFile, err)
296 if chrSize[chr] == 0 {
300 if err = scanner.Err(); err != nil {
301 return fmt.Errorf("error scanning genome file %q: %s", cmd.genomeFile, err)
305 // "bedtools complement" expects the chromosome sizes
306 // ("genome file") to appear in the same order as the
307 // chromosomes in the input vcf, so we need to sort
309 scanner = bufio.NewScanner(bytes.NewBuffer(append([]byte(nil), regions.Bytes()...)))
310 var sortedGenomeFile bytes.Buffer
314 _, err := fmt.Sscanf(scanner.Text(), "%s\t%d", &chr, &size)
316 return fmt.Errorf("error parsing gvcf_regions output: %s", err)
318 if size, ok := chrSize[chr]; ok {
319 fmt.Fprintf(&sortedGenomeFile, "%s\t%d\n", chr, size)
324 // The bcftools --mask argument needs to end in ".bed"
325 // in order to be parsed as a BED file, so we need to
326 // use a named pipe instead of stdin.
327 tempdir, err := ioutil.TempDir("", "")
329 return fmt.Errorf("TempDir: %s", err)
331 defer os.RemoveAll(tempdir)
332 maskfifo = filepath.Join(tempdir, "fifo.bed")
333 err = syscall.Mkfifo(maskfifo, 0600)
335 return fmt.Errorf("mkfifo: %s", err)
338 // bedtools complement can't seem to read from a pipe
339 // reliably -- "Error: line number 1 of file
340 // /dev/stdin has 1 fields, but 3 were expected." --
341 // so we stage to a temp file.
342 regionsFile := filepath.Join(tempdir, "gvcf_regions.bed")
343 err = ioutil.WriteFile(regionsFile, regions.Bytes(), 0644)
352 maskfifow, err := os.OpenFile(maskfifo, os.O_WRONLY, 0)
357 defer maskfifow.Close()
359 bedcompargs := []string{"bedtools", "complement", "-i", regionsFile, "-g", "/dev/stdin"}
360 bedcompargs = maybeInDocker(bedcompargs, []string{cmd.genomeFile})
361 bedcomp := exec.CommandContext(ctx, bedcompargs[0], bedcompargs[1:]...)
362 bedcomp.Stdin = &sortedGenomeFile
363 bedcomp.Stdout = maskfifow
364 bedcomp.Stderr = cmd.stderr
365 log.Printf("running %v", bedcomp.Args)
367 log.Printf("exited %v", bedcomp.Args)
369 errs <- fmt.Errorf("bedtools complement: %s", err)
372 err = maskfifow.Close()
383 consargs := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase)}
385 consargs = append(consargs, "--mask", maskfifo)
387 consargs = append(consargs, infile)
388 indexsuffix := ".tbi"
389 if _, err := os.Stat(infile + ".csi"); err == nil {
392 mounts := []string{infile, infile + indexsuffix, cmd.refFile}
394 mounts = append(mounts, maskfifo)
396 consargs = maybeInDocker(consargs, mounts)
398 consensus := exec.CommandContext(ctx, consargs[0], consargs[1:]...)
399 consensus.Stderr = os.Stderr
400 consensus.Stdout = gzipw
401 consensus.Stderr = cmd.stderr
402 log.Printf("running %v", consensus.Args)
403 err = consensus.Run()
405 errs <- fmt.Errorf("bcftools consensus: %s", err)
421 for err := range errs {
431 func (cmd *vcf2fasta) loadRegionsPy() error {
432 if strings.HasPrefix(cmd.gvcfRegionsPy, "http") {
433 resp, err := http.Get(cmd.gvcfRegionsPy)
437 if resp.StatusCode != http.StatusOK {
438 return fmt.Errorf("get %q: http status %d", cmd.gvcfRegionsPy, resp.StatusCode)
440 buf, err := ioutil.ReadAll(resp.Body)
442 return fmt.Errorf("get %q: read body: %s", cmd.gvcfRegionsPy, err)
444 cmd.gvcfRegionsPyData = buf
447 buf, err := ioutil.ReadFile(cmd.gvcfRegionsPy)
451 cmd.gvcfRegionsPyData = buf