27 "github.com/klauspost/pgzip"
28 log "github.com/sirupsen/logrus"
31 type importer struct {
41 saveIncompleteTiles bool
43 matchChromosome *regexp.Regexp
48 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
52 fmt.Fprintf(stderr, "%s\n", err)
55 flags := flag.NewFlagSet("", flag.ContinueOnError)
56 flags.SetOutput(stderr)
57 flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
58 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
59 flags.StringVar(&cmd.outputFile, "o", "-", "output `file`")
60 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for output data")
61 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
62 flags.BoolVar(&cmd.skipOOO, "skip-ooo", false, "skip out-of-order tags")
63 flags.BoolVar(&cmd.outputTiles, "output-tiles", false, "include tile variant sequences in output file")
64 flags.BoolVar(&cmd.saveIncompleteTiles, "save-incomplete-tiles", false, "treat tiles with no-calls as regular tiles")
65 flags.StringVar(&cmd.outputStats, "output-stats", "", "output stats to `file` (json)")
66 cmd.batchArgs.Flags(flags)
67 matchChromosome := flags.String("match-chromosome", "^(chr)?([0-9]+|X|Y|MT?)$", "import chromosomes that match the given `regexp`")
68 flags.IntVar(&cmd.priority, "priority", 500, "container request priority")
69 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
70 flags.StringVar(&cmd.loglevel, "loglevel", "info", "logging threshold (trace, debug, info, warn, error, fatal, or panic)")
71 err = flags.Parse(args)
72 if err == flag.ErrHelp {
75 } else if err != nil {
77 } else if cmd.tagLibraryFile == "" {
78 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
80 } else if flags.NArg() == 0 {
87 log.Println(http.ListenAndServe(*pprof, nil))
91 lvl, err := log.ParseLevel(cmd.loglevel)
97 cmd.matchChromosome, err = regexp.Compile(*matchChromosome)
103 err = cmd.runBatches(stdout, flags.Args())
110 infiles, err := listInputFiles(flags.Args())
114 infiles = cmd.batchArgs.Slice(infiles)
116 taglib, err := cmd.loadTagLibrary()
121 var outw, outf io.WriteCloser
122 if cmd.outputFile == "-" {
123 outw = nopCloser{stdout}
125 outf, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
130 if strings.HasSuffix(cmd.outputFile, ".gz") {
131 outw = pgzip.NewWriter(outf)
136 bufw := bufio.NewWriterSize(outw, 64*1024*1024)
137 cmd.encoder = gob.NewEncoder(bufw)
139 tilelib := &tileLibrary{taglib: taglib, retainNoCalls: cmd.saveIncompleteTiles, skipOOO: cmd.skipOOO}
141 cmd.encoder.Encode(LibraryEntry{TagSet: taglib.Tags()})
142 tilelib.encoder = cmd.encoder
145 for range time.Tick(10 * time.Minute) {
146 log.Printf("tilelib.Len() == %d", tilelib.Len())
150 err = cmd.tileInputs(tilelib, infiles)
162 if outf != nil && outf != outw {
171 func (cmd *importer) runBatches(stdout io.Writer, inputs []string) error {
172 if cmd.outputFile != "-" {
173 // Not yet implemented, but this should write
174 // the collection to an existing collection,
175 // possibly even an in-place update.
176 return errors.New("cannot specify output file in container mode: not implemented")
178 runner := arvadosContainerRunner{
179 Name: "lightning import",
180 Client: arvadosClientFromEnv,
181 ProjectUUID: cmd.projectUUID,
185 Priority: cmd.priority,
188 err := runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
192 for i := range inputs {
193 err = runner.TranslatePaths(&inputs[i])
199 outputs, err := cmd.batchArgs.RunBatches(context.Background(), func(ctx context.Context, batch int) (string, error) {
202 runner.Name += fmt.Sprintf(" (batch %d of %d)", batch, cmd.batches)
204 runner.Args = []string{"import",
206 "-loglevel=" + cmd.loglevel,
208 fmt.Sprintf("-skip-ooo=%v", cmd.skipOOO),
209 fmt.Sprintf("-output-tiles=%v", cmd.outputTiles),
210 fmt.Sprintf("-save-incomplete-tiles=%v", cmd.saveIncompleteTiles),
211 "-match-chromosome", cmd.matchChromosome.String(),
212 "-output-stats", "/mnt/output/stats.json",
213 "-tag-library", cmd.tagLibraryFile,
215 "-o", "/mnt/output/library.gob.gz",
217 runner.Args = append(runner.Args, cmd.batchArgs.Args(batch)...)
218 runner.Args = append(runner.Args, inputs...)
219 return runner.RunContext(ctx)
224 var outfiles []string
225 for _, o := range outputs {
226 outfiles = append(outfiles, o+"/library.gob.gz")
228 fmt.Fprintln(stdout, strings.Join(outfiles, " "))
232 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, []importStats, error) {
233 var input io.ReadCloser
234 input, err := open(infile)
239 input = ioutil.NopCloser(bufio.NewReaderSize(input, 8*1024*1024))
240 if strings.HasSuffix(infile, ".gz") {
241 input, err = pgzip.NewReader(input)
247 return tilelib.TileFasta(infile, input, cmd.matchChromosome)
250 func (cmd *importer) loadTagLibrary() (*tagLibrary, error) {
251 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
252 f, err := open(cmd.tagLibraryFile)
257 rdr := ioutil.NopCloser(bufio.NewReaderSize(f, 64*1024*1024))
258 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
259 rdr, err = gzip.NewReader(rdr)
261 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
265 var taglib tagLibrary
266 err = taglib.Load(rdr)
270 if taglib.Len() < 1 {
271 return nil, fmt.Errorf("cannot tile: tag library is empty")
273 log.Printf("tag library %s load done", cmd.tagLibraryFile)
278 vcfFilenameRe = regexp.MustCompile(`\.vcf(\.gz)?$`)
279 fasta1FilenameRe = regexp.MustCompile(`\.1\.fa(sta)?(\.gz)?$`)
280 fasta2FilenameRe = regexp.MustCompile(`\.2\.fa(sta)?(\.gz)?$`)
281 fastaFilenameRe = regexp.MustCompile(`\.fa(sta)?(\.gz)?$`)
284 func listInputFiles(paths []string) (files []string, err error) {
285 for _, path := range paths {
286 if fi, err := os.Stat(path); err != nil {
287 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
288 } else if !fi.IsDir() {
289 if !fasta2FilenameRe.MatchString(path) {
290 files = append(files, path)
294 d, err := os.Open(path)
296 return nil, fmt.Errorf("%s: open failed: %s", path, err)
299 names, err := d.Readdirnames(0)
301 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
304 for _, name := range names {
305 if vcfFilenameRe.MatchString(name) {
306 files = append(files, filepath.Join(path, name))
307 } else if fastaFilenameRe.MatchString(name) && !fasta2FilenameRe.MatchString(name) {
308 files = append(files, filepath.Join(path, name))
313 for _, file := range files {
314 if fastaFilenameRe.MatchString(file) {
316 } else if vcfFilenameRe.MatchString(file) {
317 if _, err := os.Stat(file + ".csi"); err == nil {
319 } else if _, err = os.Stat(file + ".tbi"); err == nil {
322 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
325 return nil, fmt.Errorf("don't know how to handle filename %s", file)
331 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
332 starttime := time.Now()
333 errs := make(chan error, 1)
334 todo := make(chan func() error, len(infiles)*2)
335 allstats := make([][]importStats, len(infiles)*2)
336 var encodeJobs sync.WaitGroup
337 for idx, infile := range infiles {
338 idx, infile := idx, infile
339 var phases sync.WaitGroup
341 variants := make([][]tileVariantID, 2)
342 if fasta1FilenameRe.MatchString(infile) {
343 todo <- func() error {
345 log.Printf("%s starting", infile)
346 defer log.Printf("%s done", infile)
347 tseqs, stats, err := cmd.tileFasta(tilelib, infile)
348 allstats[idx*2] = stats
349 var kept, dropped int
350 variants[0], kept, dropped = tseqs.Variants()
351 log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
354 infile2 := fasta1FilenameRe.ReplaceAllString(infile, `.2.fa$1$2`)
355 todo <- func() error {
357 log.Printf("%s starting", infile2)
358 defer log.Printf("%s done", infile2)
359 tseqs, stats, err := cmd.tileFasta(tilelib, infile2)
360 allstats[idx*2+1] = stats
361 var kept, dropped int
362 variants[1], kept, dropped = tseqs.Variants()
363 log.Printf("%s found %d unique tags plus %d repeats", infile2, kept, dropped)
367 } else if fastaFilenameRe.MatchString(infile) {
368 todo <- func() error {
371 log.Printf("%s starting", infile)
372 defer log.Printf("%s done", infile)
373 tseqs, stats, err := cmd.tileFasta(tilelib, infile)
374 allstats[idx*2] = stats
379 for _, tseq := range tseqs {
382 log.Printf("%s tiled %d seqs, total len %d", infile, len(tseqs), totlen)
383 return cmd.encoder.Encode(LibraryEntry{
384 CompactSequences: []CompactSequence{{Name: infile, TileSequences: tseqs}},
387 // Don't write out a CompactGenomes entry
389 } else if vcfFilenameRe.MatchString(infile) {
390 for phase := 0; phase < 2; phase++ {
392 todo <- func() error {
394 log.Printf("%s phase %d starting", infile, phase+1)
395 defer log.Printf("%s phase %d done", infile, phase+1)
396 tseqs, stats, err := cmd.tileGVCF(tilelib, infile, phase)
397 allstats[idx*2] = stats
398 var kept, dropped int
399 variants[phase], kept, dropped = tseqs.Variants()
400 log.Printf("%s phase %d found %d unique tags plus %d repeats", infile, phase+1, kept, dropped)
405 panic(fmt.Sprintf("bug: unhandled filename %q", infile))
409 defer encodeJobs.Done()
414 err := cmd.encoder.Encode(LibraryEntry{
415 CompactGenomes: []CompactGenome{{Name: infile, Variants: flatten(variants)}},
426 var tileJobs sync.WaitGroup
428 for i := 0; i < runtime.GOMAXPROCS(-1)*2; i++ {
430 atomic.AddInt64(&running, 1)
432 defer tileJobs.Done()
433 defer atomic.AddInt64(&running, -1)
434 for fn := range todo {
445 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
446 if remain < cap(todo) {
447 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
448 eta := time.Now().Add(ttl)
449 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
456 // Must not wait on encodeJobs in this case. If the
457 // tileJobs goroutines exited early, some funcs in
458 // todo haven't been called, so the corresponding
459 // encodeJobs will wait forever.
470 if cmd.outputStats != "" {
471 f, err := os.OpenFile(cmd.outputStats, os.O_CREATE|os.O_WRONLY, 0666)
475 var flatstats []importStats
476 for _, stats := range allstats {
477 flatstats = append(flatstats, stats...)
479 err = json.NewEncoder(f).Encode(flatstats)
488 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, stats []importStats, err error) {
489 if cmd.refFile == "" {
490 err = errors.New("cannot import vcf: reference data (-ref) not specified")
493 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
494 indexsuffix := ".tbi"
495 if _, err := os.Stat(infile + ".csi"); err == nil {
498 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
499 args = append([]string{
500 "docker", "run", "--rm",
502 "--volume=" + infile + ":" + infile + ":ro",
503 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
504 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
508 consensus := exec.Command(args[0], args[1:]...)
509 consensus.Stderr = os.Stderr
510 stdout, err := consensus.StdoutPipe()
515 err = consensus.Start()
519 defer consensus.Wait()
520 tileseq, stats, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout, cmd.matchChromosome)
528 err = consensus.Wait()
530 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)
536 func flatten(variants [][]tileVariantID) []tileVariantID {
538 for _, v := range variants {
543 flat := make([]tileVariantID, ntags*2)
544 for i := 0; i < ntags; i++ {
545 for hap := 0; hap < 2; hap++ {
546 if i < len(variants[hap]) {
547 flat[i*2+hap] = variants[hap][i]