27 "github.com/klauspost/pgzip"
28 log "github.com/sirupsen/logrus"
31 type importer struct {
41 saveIncompleteTiles bool
43 matchChromosome *regexp.Regexp
45 retainAfterEncoding bool // keep imported genomes/refseqs in memory after writing to disk
49 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
53 fmt.Fprintf(stderr, "%s\n", err)
56 flags := flag.NewFlagSet("", flag.ContinueOnError)
57 flags.SetOutput(stderr)
58 flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
59 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
60 flags.StringVar(&cmd.outputFile, "o", "-", "output `file`")
61 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for output data")
62 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
63 flags.BoolVar(&cmd.skipOOO, "skip-ooo", false, "skip out-of-order tags")
64 flags.BoolVar(&cmd.outputTiles, "output-tiles", false, "include tile variant sequences in output file")
65 flags.BoolVar(&cmd.saveIncompleteTiles, "save-incomplete-tiles", false, "treat tiles with no-calls as regular tiles")
66 flags.StringVar(&cmd.outputStats, "output-stats", "", "output stats to `file` (json)")
67 cmd.batchArgs.Flags(flags)
68 matchChromosome := flags.String("match-chromosome", "^(chr)?([0-9]+|X|Y|MT?)$", "import chromosomes that match the given `regexp`")
69 flags.IntVar(&cmd.priority, "priority", 500, "container request priority")
70 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
71 flags.StringVar(&cmd.loglevel, "loglevel", "info", "logging threshold (trace, debug, info, warn, error, fatal, or panic)")
72 err = flags.Parse(args)
73 if err == flag.ErrHelp {
76 } else if err != nil {
78 } else if cmd.tagLibraryFile == "" {
79 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
81 } else if flags.NArg() == 0 {
88 log.Println(http.ListenAndServe(*pprof, nil))
92 lvl, err := log.ParseLevel(cmd.loglevel)
98 cmd.matchChromosome, err = regexp.Compile(*matchChromosome)
104 err = cmd.runBatches(stdout, flags.Args())
111 infiles, err := listInputFiles(flags.Args())
115 infiles = cmd.batchArgs.Slice(infiles)
117 taglib, err := cmd.loadTagLibrary()
122 var outw, outf io.WriteCloser
123 if cmd.outputFile == "-" {
124 outw = nopCloser{stdout}
126 outf, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
131 if strings.HasSuffix(cmd.outputFile, ".gz") {
132 outw = pgzip.NewWriter(outf)
137 bufw := bufio.NewWriterSize(outw, 64*1024*1024)
138 cmd.encoder = gob.NewEncoder(bufw)
140 tilelib := &tileLibrary{taglib: taglib, retainNoCalls: cmd.saveIncompleteTiles, skipOOO: cmd.skipOOO}
142 cmd.encoder.Encode(LibraryEntry{TagSet: taglib.Tags()})
143 tilelib.encoder = cmd.encoder
146 for range time.Tick(10 * time.Minute) {
147 log.Printf("tilelib.Len() == %d", tilelib.Len())
151 err = cmd.tileInputs(tilelib, infiles)
163 if outf != nil && outf != outw {
172 func (cmd *importer) runBatches(stdout io.Writer, inputs []string) error {
173 if cmd.outputFile != "-" {
174 // Not yet implemented, but this should write
175 // the collection to an existing collection,
176 // possibly even an in-place update.
177 return errors.New("cannot specify output file in container mode: not implemented")
179 runner := arvadosContainerRunner{
180 Name: "lightning import",
181 Client: arvadosClientFromEnv,
182 ProjectUUID: cmd.projectUUID,
186 Priority: cmd.priority,
189 err := runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
193 for i := range inputs {
194 err = runner.TranslatePaths(&inputs[i])
200 outputs, err := cmd.batchArgs.RunBatches(context.Background(), func(ctx context.Context, batch int) (string, error) {
203 runner.Name += fmt.Sprintf(" (batch %d of %d)", batch, cmd.batches)
205 runner.Args = []string{"import",
207 "-loglevel=" + cmd.loglevel,
209 fmt.Sprintf("-skip-ooo=%v", cmd.skipOOO),
210 fmt.Sprintf("-output-tiles=%v", cmd.outputTiles),
211 fmt.Sprintf("-save-incomplete-tiles=%v", cmd.saveIncompleteTiles),
212 "-match-chromosome", cmd.matchChromosome.String(),
213 "-output-stats", "/mnt/output/stats.json",
214 "-tag-library", cmd.tagLibraryFile,
216 "-o", "/mnt/output/library.gob.gz",
218 runner.Args = append(runner.Args, cmd.batchArgs.Args(batch)...)
219 runner.Args = append(runner.Args, inputs...)
220 return runner.RunContext(ctx)
225 var outfiles []string
226 for _, o := range outputs {
227 outfiles = append(outfiles, o+"/library.gob.gz")
229 fmt.Fprintln(stdout, strings.Join(outfiles, " "))
233 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string) (tileSeq, []importStats, error) {
234 var input io.ReadCloser
235 input, err := open(infile)
240 input = ioutil.NopCloser(bufio.NewReaderSize(input, 8*1024*1024))
241 if strings.HasSuffix(infile, ".gz") {
242 input, err = pgzip.NewReader(input)
248 return tilelib.TileFasta(infile, input, cmd.matchChromosome)
251 func (cmd *importer) loadTagLibrary() (*tagLibrary, error) {
252 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
253 f, err := open(cmd.tagLibraryFile)
258 rdr := ioutil.NopCloser(bufio.NewReaderSize(f, 64*1024*1024))
259 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
260 rdr, err = gzip.NewReader(rdr)
262 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
266 var taglib tagLibrary
267 err = taglib.Load(rdr)
271 if taglib.Len() < 1 {
272 return nil, fmt.Errorf("cannot tile: tag library is empty")
274 log.Printf("tag library %s load done", cmd.tagLibraryFile)
279 vcfFilenameRe = regexp.MustCompile(`\.vcf(\.gz)?$`)
280 fasta1FilenameRe = regexp.MustCompile(`\.1\.fa(sta)?(\.gz)?$`)
281 fasta2FilenameRe = regexp.MustCompile(`\.2\.fa(sta)?(\.gz)?$`)
282 fastaFilenameRe = regexp.MustCompile(`\.fa(sta)?(\.gz)?$`)
285 func listInputFiles(paths []string) (files []string, err error) {
286 for _, path := range paths {
287 if fi, err := os.Stat(path); err != nil {
288 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
289 } else if !fi.IsDir() {
290 if !fasta2FilenameRe.MatchString(path) {
291 files = append(files, path)
295 d, err := os.Open(path)
297 return nil, fmt.Errorf("%s: open failed: %s", path, err)
300 names, err := d.Readdirnames(0)
302 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
305 for _, name := range names {
306 if vcfFilenameRe.MatchString(name) {
307 files = append(files, filepath.Join(path, name))
308 } else if fastaFilenameRe.MatchString(name) && !fasta2FilenameRe.MatchString(name) {
309 files = append(files, filepath.Join(path, name))
314 for _, file := range files {
315 if fastaFilenameRe.MatchString(file) {
317 } else if vcfFilenameRe.MatchString(file) {
318 if _, err := os.Stat(file + ".csi"); err == nil {
320 } else if _, err = os.Stat(file + ".tbi"); err == nil {
323 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
326 return nil, fmt.Errorf("don't know how to handle filename %s", file)
332 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
333 starttime := time.Now()
334 errs := make(chan error, 1)
335 todo := make(chan func() error, len(infiles)*2)
336 allstats := make([][]importStats, len(infiles)*2)
337 var encodeJobs sync.WaitGroup
338 for idx, infile := range infiles {
339 idx, infile := idx, infile
340 var phases sync.WaitGroup
342 variants := make([][]tileVariantID, 2)
343 if fasta1FilenameRe.MatchString(infile) {
344 todo <- func() error {
346 log.Printf("%s starting", infile)
347 defer log.Printf("%s done", infile)
348 tseqs, stats, err := cmd.tileFasta(tilelib, infile)
349 allstats[idx*2] = stats
350 var kept, dropped int
351 variants[0], kept, dropped = tseqs.Variants()
352 log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
355 infile2 := fasta1FilenameRe.ReplaceAllString(infile, `.2.fa$1$2`)
356 todo <- func() error {
358 log.Printf("%s starting", infile2)
359 defer log.Printf("%s done", infile2)
360 tseqs, stats, err := cmd.tileFasta(tilelib, infile2)
361 allstats[idx*2+1] = stats
362 var kept, dropped int
363 variants[1], kept, dropped = tseqs.Variants()
364 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)
384 if cmd.retainAfterEncoding {
386 if tilelib.refseqs == nil {
387 tilelib.refseqs = map[string]map[string][]tileLibRef{}
389 tilelib.refseqs[infile] = tseqs
393 return cmd.encoder.Encode(LibraryEntry{
394 CompactSequences: []CompactSequence{{Name: infile, TileSequences: tseqs}},
397 // Don't write out a CompactGenomes entry
399 } else if vcfFilenameRe.MatchString(infile) {
400 for phase := 0; phase < 2; phase++ {
402 todo <- func() error {
404 log.Printf("%s phase %d starting", infile, phase+1)
405 defer log.Printf("%s phase %d done", infile, phase+1)
406 tseqs, stats, err := cmd.tileGVCF(tilelib, infile, phase)
407 allstats[idx*2] = stats
408 var kept, dropped int
409 variants[phase], kept, dropped = tseqs.Variants()
410 log.Printf("%s phase %d found %d unique tags plus %d repeats", infile, phase+1, kept, dropped)
415 panic(fmt.Sprintf("bug: unhandled filename %q", infile))
419 defer encodeJobs.Done()
424 variants := flatten(variants)
425 err := cmd.encoder.Encode(LibraryEntry{
426 CompactGenomes: []CompactGenome{{Name: infile, Variants: variants}},
434 if cmd.retainAfterEncoding {
436 if tilelib.compactGenomes == nil {
437 tilelib.compactGenomes = make(map[string][]tileVariantID)
439 tilelib.compactGenomes[infile] = variants
445 var tileJobs sync.WaitGroup
447 for i := 0; i < runtime.GOMAXPROCS(-1)*2; i++ {
449 atomic.AddInt64(&running, 1)
451 defer tileJobs.Done()
452 defer atomic.AddInt64(&running, -1)
453 for fn := range todo {
464 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
465 if remain < cap(todo) {
466 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
467 eta := time.Now().Add(ttl)
468 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
475 // Must not wait on encodeJobs in this case. If the
476 // tileJobs goroutines exited early, some funcs in
477 // todo haven't been called, so the corresponding
478 // encodeJobs will wait forever.
489 if cmd.outputStats != "" {
490 f, err := os.OpenFile(cmd.outputStats, os.O_CREATE|os.O_WRONLY, 0666)
494 var flatstats []importStats
495 for _, stats := range allstats {
496 flatstats = append(flatstats, stats...)
498 err = json.NewEncoder(f).Encode(flatstats)
507 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, stats []importStats, err error) {
508 if cmd.refFile == "" {
509 err = errors.New("cannot import vcf: reference data (-ref) not specified")
512 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
513 indexsuffix := ".tbi"
514 if _, err := os.Stat(infile + ".csi"); err == nil {
517 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
518 args = append([]string{
519 "docker", "run", "--rm",
521 "--volume=" + infile + ":" + infile + ":ro",
522 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
523 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
527 consensus := exec.Command(args[0], args[1:]...)
528 consensus.Stderr = os.Stderr
529 stdout, err := consensus.StdoutPipe()
534 err = consensus.Start()
538 defer consensus.Wait()
539 tileseq, stats, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout, cmd.matchChromosome)
547 err = consensus.Wait()
549 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)
555 func flatten(variants [][]tileVariantID) []tileVariantID {
557 for _, v := range variants {
562 flat := make([]tileVariantID, ntags*2)
563 for i := 0; i < ntags; i++ {
564 for hap := 0; hap < 2; hap++ {
565 if i < len(variants[hap]) {
566 flat[i*2+hap] = variants[hap][i]