21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 log "github.com/sirupsen/logrus"
25 type vcf2fasta struct {
30 gvcfRegionsPyData []byte
39 func (cmd *vcf2fasta) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
43 fmt.Fprintf(stderr, "%s\n", err)
46 flags := flag.NewFlagSet("", flag.ContinueOnError)
47 flags.SetOutput(stderr)
48 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
49 flags.StringVar(&cmd.genomeFile, "genome", "", "reference genome `file`")
50 flags.BoolVar(&cmd.mask, "mask", false, "mask uncalled regions (default: output hom ref)")
51 flags.StringVar(&cmd.gvcfRegionsPy, "gvcf-regions.py", "https://raw.githubusercontent.com/lijiayong/gvcf_regions/master/gvcf_regions.py", "source of gvcf_regions.py")
52 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for containers and output data")
53 flags.StringVar(&cmd.outputDir, "output-dir", "", "output directory")
54 flags.IntVar(&cmd.vcpus, "vcpus", 0, "number of VCPUs to request for arvados container (default: 2*number of input files, max 32)")
55 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
56 priority := flags.Int("priority", 500, "container request priority")
57 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
58 err = flags.Parse(args)
59 if err == flag.ErrHelp {
62 } else if err != nil {
64 } else if cmd.refFile == "" {
65 err = errors.New("reference data (-ref) not specified")
67 } else if flags.NArg() == 0 {
75 log.Println(http.ListenAndServe(*pprof, nil))
80 err = cmd.loadRegionsPy()
87 if cmd.outputDir != "" {
88 err = errors.New("cannot specify output dir in non-local mode")
93 infiles, err = listInputFiles(flags.Args())
97 if cmd.vcpus = len(infiles) * 2; cmd.vcpus > 32 {
101 runner := arvadosContainerRunner{
102 Name: "lightning vcf2fasta",
103 Client: arvados.NewClientFromEnv(),
104 ProjectUUID: cmd.projectUUID,
105 RAM: 2<<30 + int64(cmd.vcpus)<<28,
108 Mounts: map[string]map[string]interface{}{
109 "/gvcf_regions.py": map[string]interface{}{
111 "content": string(cmd.gvcfRegionsPyData),
115 err = runner.TranslatePaths(&cmd.refFile, &cmd.genomeFile)
119 inputs := flags.Args()
120 for i := range inputs {
121 err = runner.TranslatePaths(&inputs[i])
126 runner.Args = append([]string{"vcf2fasta",
128 "-ref", cmd.refFile, fmt.Sprintf("-mask=%v", cmd.mask),
129 "-genome", cmd.genomeFile,
130 "-gvcf-regions.py", "/gvcf_regions.py",
131 "-output-dir", "/mnt/output"}, inputs...)
133 output, err = runner.Run()
137 fmt.Fprintln(stdout, output)
141 infiles, err := listInputFiles(flags.Args())
150 todo := make(chan job)
152 for _, infile := range infiles {
153 for phase := 1; phase <= 2; phase++ {
154 todo <- job{vcffile: infile, phase: phase}
160 done := make(chan error, runtime.NumCPU()*2)
161 var wg sync.WaitGroup
162 for i := 0; i < runtime.NumCPU(); i++ {
166 for job := range todo {
168 // a different worker encountered an error
171 err := cmd.vcf2fasta(job.vcffile, job.phase)
173 done <- fmt.Errorf("%s phase %d: %s", job.vcffile, job.phase, err)
191 func maybeInDocker(args, mountfiles []string) []string {
192 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err != nil || len(out) == 0 {
195 dockerrun := []string{
196 "docker", "run", "--rm", "-i",
199 for _, f := range mountfiles {
200 dockerrun = append(dockerrun, "--volume="+f+":"+f+":ro")
202 dockerrun = append(dockerrun, "lightning-runtime")
203 dockerrun = append(dockerrun, args...)
207 func (cmd *vcf2fasta) vcf2fasta(infile string, phase int) error {
208 _, basename := filepath.Split(infile)
209 outfile := filepath.Join(cmd.outputDir, fmt.Sprintf("%s.%d.fasta.gz", basename, phase))
210 outf, err := os.OpenFile(outfile, os.O_CREATE|os.O_WRONLY, 0777)
212 return fmt.Errorf("error opening output file: %s", err)
215 gzipw := gzip.NewWriter(outf)
218 var maskfifo string // filename of mask fifo if we're running bedtools, otherwise ""
220 var wg sync.WaitGroup
221 errs := make(chan error, 2)
223 if cmd.genomeFile == "" {
224 return errors.New("cannot apply mask without -genome argument")
226 var regions bytes.Buffer
227 bedargs := []string{"python", "-", "--gvcf_type", "gatk", infile}
228 bed := exec.Command(bedargs[0], bedargs[1:]...)
229 bed.Stdin = bytes.NewBuffer(cmd.gvcfRegionsPyData)
230 bed.Stdout = ®ions
231 bed.Stderr = cmd.stderr
232 log.Printf("running %v", bed.Args)
234 log.Printf("exited %v", bed.Args)
236 return fmt.Errorf("gvcf_regions: %s", err)
239 // The bcftools --mask argument needs to end in ".bed"
240 // in order to be parsed as a BED file, so we need to
241 // use a named pipe instead of stdin.
242 tempdir, err := ioutil.TempDir("", "")
244 return fmt.Errorf("TempDir: %s", err)
246 defer os.RemoveAll(tempdir)
247 maskfifo = filepath.Join(tempdir, "fifo.bed")
248 err = syscall.Mkfifo(maskfifo, 0600)
250 return fmt.Errorf("mkfifo: %s", err)
256 maskfifow, err := os.OpenFile(maskfifo, os.O_WRONLY, 0)
261 defer maskfifow.Close()
263 bedcompargs := []string{"bedtools", "complement", "-i", "/dev/stdin", "-g", cmd.genomeFile}
264 bedcompargs = maybeInDocker(bedcompargs, []string{cmd.genomeFile})
265 bedcomp := exec.Command(bedcompargs[0], bedcompargs[1:]...)
266 bedcomp.Stdin = ®ions
267 bedcomp.Stdout = maskfifow
268 bedcomp.Stderr = cmd.stderr
269 log.Printf("running %v", bedcomp.Args)
271 log.Printf("exited %v", bedcomp.Args)
273 errs <- fmt.Errorf("bedtools complement: %s", err)
276 err = maskfifow.Close()
287 consargs := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase)}
289 consargs = append(consargs, "--mask", maskfifo)
291 consargs = append(consargs, infile)
292 indexsuffix := ".tbi"
293 if _, err := os.Stat(infile + ".csi"); err == nil {
296 mounts := []string{infile, infile + indexsuffix, cmd.refFile}
298 mounts = append(mounts, maskfifo)
300 consargs = maybeInDocker(consargs, mounts)
302 consensus := exec.Command(consargs[0], consargs[1:]...)
303 consensus.Stderr = os.Stderr
304 consensus.Stdout = gzipw
305 consensus.Stderr = cmd.stderr
306 log.Printf("running %v", consensus.Args)
307 err = consensus.Run()
309 errs <- fmt.Errorf("bcftools consensus: %s", err)
325 for err := range errs {
334 func (cmd *vcf2fasta) loadRegionsPy() error {
335 if strings.HasPrefix(cmd.gvcfRegionsPy, "http") {
336 resp, err := http.Get(cmd.gvcfRegionsPy)
340 if resp.StatusCode != http.StatusOK {
341 return fmt.Errorf("get %q: http status %d", cmd.gvcfRegionsPy, resp.StatusCode)
343 buf, err := ioutil.ReadAll(resp.Body)
345 return fmt.Errorf("get %q: read body: %s", cmd.gvcfRegionsPy, err)
347 cmd.gvcfRegionsPyData = buf
350 buf, err := ioutil.ReadFile(cmd.gvcfRegionsPy)
354 cmd.gvcfRegionsPyData = buf