1 // Copyright (C) The Lightning Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
31 "github.com/klauspost/pgzip"
32 log "github.com/sirupsen/logrus"
35 type importer struct {
45 saveIncompleteTiles bool
47 matchChromosome *regexp.Regexp
49 retainAfterEncoding bool // keep imported genomes/refseqs in memory after writing to disk
53 func (cmd *importer) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
57 fmt.Fprintf(stderr, "%s\n", err)
60 flags := flag.NewFlagSet("", flag.ContinueOnError)
61 flags.SetOutput(stderr)
62 flags.StringVar(&cmd.tagLibraryFile, "tag-library", "", "tag library fasta `file`")
63 flags.StringVar(&cmd.refFile, "ref", "", "reference fasta `file`")
64 flags.StringVar(&cmd.outputFile, "o", "-", "output `file`")
65 flags.StringVar(&cmd.projectUUID, "project", "", "project `UUID` for output data")
66 flags.BoolVar(&cmd.runLocal, "local", false, "run on local host (default: run in an arvados container)")
67 flags.BoolVar(&cmd.skipOOO, "skip-ooo", false, "skip out-of-order tags")
68 flags.BoolVar(&cmd.outputTiles, "output-tiles", false, "include tile variant sequences in output file")
69 flags.BoolVar(&cmd.saveIncompleteTiles, "save-incomplete-tiles", false, "treat tiles with no-calls as regular tiles")
70 flags.StringVar(&cmd.outputStats, "output-stats", "", "output stats to `file` (json)")
71 cmd.batchArgs.Flags(flags)
72 matchChromosome := flags.String("match-chromosome", "^(chr)?([0-9]+|X|Y|MT?)$", "import chromosomes that match the given `regexp`")
73 flags.IntVar(&cmd.priority, "priority", 500, "container request priority")
74 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
75 flags.StringVar(&cmd.loglevel, "loglevel", "info", "logging threshold (trace, debug, info, warn, error, fatal, or panic)")
76 err = flags.Parse(args)
77 if err == flag.ErrHelp {
80 } else if err != nil {
82 } else if cmd.tagLibraryFile == "" {
83 fmt.Fprintln(os.Stderr, "cannot import without -tag-library argument")
85 } else if flags.NArg() == 0 {
92 log.Println(http.ListenAndServe(*pprof, nil))
96 lvl, err := log.ParseLevel(cmd.loglevel)
102 cmd.matchChromosome, err = regexp.Compile(*matchChromosome)
108 err = cmd.runBatches(stdout, flags.Args())
115 infiles, err := listInputFiles(flags.Args())
119 infiles = cmd.batchArgs.Slice(infiles)
121 taglib, err := cmd.loadTagLibrary()
126 var outw, outf io.WriteCloser
127 if cmd.outputFile == "-" {
128 outw = nopCloser{stdout}
130 outf, err = os.OpenFile(cmd.outputFile, os.O_CREATE|os.O_WRONLY, 0777)
135 if strings.HasSuffix(cmd.outputFile, ".gz") {
136 outw = pgzip.NewWriter(outf)
141 bufw := bufio.NewWriterSize(outw, 64*1024*1024)
142 cmd.encoder = gob.NewEncoder(bufw)
144 tilelib := &tileLibrary{taglib: taglib, retainNoCalls: cmd.saveIncompleteTiles, skipOOO: cmd.skipOOO}
146 cmd.encoder.Encode(LibraryEntry{TagSet: taglib.Tags()})
147 tilelib.encoder = cmd.encoder
150 for range time.Tick(10 * time.Minute) {
151 log.Printf("tilelib.Len() == %d", tilelib.Len())
155 err = cmd.tileInputs(tilelib, infiles)
167 if outf != nil && outf != outw {
176 func (cmd *importer) runBatches(stdout io.Writer, inputs []string) error {
177 if cmd.outputFile != "-" {
178 // Not yet implemented, but this should write
179 // the collection to an existing collection,
180 // possibly even an in-place update.
181 return errors.New("cannot specify output file in container mode: not implemented")
183 runner := arvadosContainerRunner{
184 Name: "lightning import",
185 Client: arvadosClientFromEnv,
186 ProjectUUID: cmd.projectUUID,
190 Priority: cmd.priority,
193 err := runner.TranslatePaths(&cmd.tagLibraryFile, &cmd.refFile, &cmd.outputFile)
197 for i := range inputs {
198 err = runner.TranslatePaths(&inputs[i])
204 outputs, err := cmd.batchArgs.RunBatches(context.Background(), func(ctx context.Context, batch int) (string, error) {
207 runner.Name += fmt.Sprintf(" (batch %d of %d)", batch, cmd.batches)
209 runner.Args = []string{"import",
211 "-loglevel=" + cmd.loglevel,
213 fmt.Sprintf("-skip-ooo=%v", cmd.skipOOO),
214 fmt.Sprintf("-output-tiles=%v", cmd.outputTiles),
215 fmt.Sprintf("-save-incomplete-tiles=%v", cmd.saveIncompleteTiles),
216 "-match-chromosome", cmd.matchChromosome.String(),
217 "-output-stats", "/mnt/output/stats.json",
218 "-tag-library", cmd.tagLibraryFile,
220 "-o", "/mnt/output/library.gob.gz",
222 runner.Args = append(runner.Args, cmd.batchArgs.Args(batch)...)
223 runner.Args = append(runner.Args, inputs...)
224 return runner.RunContext(ctx)
229 var outfiles []string
230 for _, o := range outputs {
231 outfiles = append(outfiles, o+"/library.gob.gz")
233 fmt.Fprintln(stdout, strings.Join(outfiles, " "))
237 func (cmd *importer) tileFasta(tilelib *tileLibrary, infile string, isRef bool) (tileSeq, []importStats, error) {
238 var input io.ReadCloser
239 input, err := open(infile)
244 input = ioutil.NopCloser(bufio.NewReaderSize(input, 8*1024*1024))
245 if strings.HasSuffix(infile, ".gz") {
246 input, err = pgzip.NewReader(input)
252 return tilelib.TileFasta(infile, input, cmd.matchChromosome, isRef)
255 func (cmd *importer) loadTagLibrary() (*tagLibrary, error) {
256 log.Printf("tag library %s load starting", cmd.tagLibraryFile)
257 f, err := open(cmd.tagLibraryFile)
262 rdr := ioutil.NopCloser(bufio.NewReaderSize(f, 64*1024*1024))
263 if strings.HasSuffix(cmd.tagLibraryFile, ".gz") {
264 rdr, err = gzip.NewReader(rdr)
266 return nil, fmt.Errorf("%s: gzip: %s", cmd.tagLibraryFile, err)
270 var taglib tagLibrary
271 err = taglib.Load(rdr)
275 if taglib.Len() < 1 {
276 return nil, fmt.Errorf("cannot tile: tag library is empty")
278 log.Printf("tag library %s load done", cmd.tagLibraryFile)
283 vcfFilenameRe = regexp.MustCompile(`\.vcf(\.gz)?$`)
284 fasta1FilenameRe = regexp.MustCompile(`\.1\.fa(sta)?(\.gz)?$`)
285 fasta2FilenameRe = regexp.MustCompile(`\.2\.fa(sta)?(\.gz)?$`)
286 fastaFilenameRe = regexp.MustCompile(`\.fa(sta)?(\.gz)?$`)
289 func listInputFiles(paths []string) (files []string, err error) {
290 for _, path := range paths {
291 if fi, err := os.Stat(path); err != nil {
292 return nil, fmt.Errorf("%s: stat failed: %s", path, err)
293 } else if !fi.IsDir() {
294 if !fasta2FilenameRe.MatchString(path) {
295 files = append(files, path)
299 d, err := os.Open(path)
301 return nil, fmt.Errorf("%s: open failed: %s", path, err)
304 names, err := d.Readdirnames(0)
306 return nil, fmt.Errorf("%s: readdir failed: %s", path, err)
309 for _, name := range names {
310 if vcfFilenameRe.MatchString(name) {
311 files = append(files, filepath.Join(path, name))
312 } else if fastaFilenameRe.MatchString(name) && !fasta2FilenameRe.MatchString(name) {
313 files = append(files, filepath.Join(path, name))
318 for _, file := range files {
319 if fastaFilenameRe.MatchString(file) {
321 } else if vcfFilenameRe.MatchString(file) {
322 if _, err := os.Stat(file + ".csi"); err == nil {
324 } else if _, err = os.Stat(file + ".tbi"); err == nil {
327 return nil, fmt.Errorf("%s: cannot read without .tbi or .csi index file", file)
330 return nil, fmt.Errorf("don't know how to handle filename %s", file)
336 func (cmd *importer) tileInputs(tilelib *tileLibrary, infiles []string) error {
337 starttime := time.Now()
338 errs := make(chan error, 1)
339 todo := make(chan func() error, len(infiles)*2)
340 allstats := make([][]importStats, len(infiles)*2)
341 var encodeJobs sync.WaitGroup
342 for idx, infile := range infiles {
343 idx, infile := idx, infile
344 var phases sync.WaitGroup
346 variants := make([][]tileVariantID, 2)
347 if fasta1FilenameRe.MatchString(infile) {
348 todo <- func() error {
350 log.Printf("%s starting", infile)
351 defer log.Printf("%s done", infile)
352 tseqs, stats, err := cmd.tileFasta(tilelib, infile, false)
353 allstats[idx*2] = stats
354 var kept, dropped int
355 variants[0], kept, dropped = tseqs.Variants()
356 log.Printf("%s found %d unique tags plus %d repeats", infile, kept, dropped)
359 infile2 := fasta1FilenameRe.ReplaceAllString(infile, `.2.fa$1$2`)
360 todo <- func() error {
362 log.Printf("%s starting", infile2)
363 defer log.Printf("%s done", infile2)
364 tseqs, stats, err := cmd.tileFasta(tilelib, infile2, false)
365 allstats[idx*2+1] = stats
366 var kept, dropped int
367 variants[1], kept, dropped = tseqs.Variants()
368 log.Printf("%s found %d unique tags plus %d repeats", infile2, kept, dropped)
371 } else if fastaFilenameRe.MatchString(infile) {
372 todo <- func() error {
375 log.Printf("%s starting", infile)
376 defer log.Printf("%s done", infile)
377 tseqs, stats, err := cmd.tileFasta(tilelib, infile, true)
378 allstats[idx*2] = stats
383 for _, tseq := range tseqs {
386 log.Printf("%s tiled %d seqs, total len %d", infile, len(tseqs), totlen)
388 if cmd.retainAfterEncoding {
390 if tilelib.refseqs == nil {
391 tilelib.refseqs = map[string]map[string][]tileLibRef{}
393 tilelib.refseqs[infile] = tseqs
397 return cmd.encoder.Encode(LibraryEntry{
398 CompactSequences: []CompactSequence{{Name: infile, TileSequences: tseqs}},
401 // Don't write out a CompactGenomes entry
403 } else if vcfFilenameRe.MatchString(infile) {
404 for phase := 0; phase < 2; phase++ {
406 todo <- func() error {
408 log.Printf("%s phase %d starting", infile, phase+1)
409 defer log.Printf("%s phase %d done", infile, phase+1)
410 tseqs, stats, err := cmd.tileGVCF(tilelib, infile, phase)
411 allstats[idx*2] = stats
412 var kept, dropped int
413 variants[phase], kept, dropped = tseqs.Variants()
414 log.Printf("%s phase %d found %d unique tags plus %d repeats", infile, phase+1, kept, dropped)
419 panic(fmt.Sprintf("bug: unhandled filename %q", infile))
423 defer encodeJobs.Done()
428 variants := flatten(variants)
429 err := cmd.encoder.Encode(LibraryEntry{
430 CompactGenomes: []CompactGenome{{Name: infile, Variants: variants}},
438 if cmd.retainAfterEncoding {
440 if tilelib.compactGenomes == nil {
441 tilelib.compactGenomes = make(map[string][]tileVariantID)
443 tilelib.compactGenomes[infile] = variants
449 var tileJobs sync.WaitGroup
451 for i := 0; i < runtime.GOMAXPROCS(-1)*2; i++ {
453 atomic.AddInt64(&running, 1)
455 defer tileJobs.Done()
456 defer atomic.AddInt64(&running, -1)
457 for fn := range todo {
468 remain := len(todo) + int(atomic.LoadInt64(&running)) - 1
469 if remain < cap(todo) {
470 ttl := time.Now().Sub(starttime) * time.Duration(remain) / time.Duration(cap(todo)-remain)
471 eta := time.Now().Add(ttl)
472 log.Printf("progress %d/%d, eta %v (%v)", cap(todo)-remain, cap(todo), eta, ttl)
479 // Must not wait on encodeJobs in this case. If the
480 // tileJobs goroutines exited early, some funcs in
481 // todo haven't been called, so the corresponding
482 // encodeJobs will wait forever.
493 if cmd.outputStats != "" {
494 f, err := os.OpenFile(cmd.outputStats, os.O_CREATE|os.O_WRONLY, 0666)
498 var flatstats []importStats
499 for _, stats := range allstats {
500 flatstats = append(flatstats, stats...)
502 err = json.NewEncoder(f).Encode(flatstats)
511 func (cmd *importer) tileGVCF(tilelib *tileLibrary, infile string, phase int) (tileseq tileSeq, stats []importStats, err error) {
512 if cmd.refFile == "" {
513 err = errors.New("cannot import vcf: reference data (-ref) not specified")
516 args := []string{"bcftools", "consensus", "--fasta-ref", cmd.refFile, "-H", fmt.Sprint(phase + 1), infile}
517 indexsuffix := ".tbi"
518 if _, err := os.Stat(infile + ".csi"); err == nil {
521 if out, err := exec.Command("docker", "image", "ls", "-q", "lightning-runtime").Output(); err == nil && len(out) > 0 {
522 args = append([]string{
523 "docker", "run", "--rm",
525 "--volume=" + infile + ":" + infile + ":ro",
526 "--volume=" + infile + indexsuffix + ":" + infile + indexsuffix + ":ro",
527 "--volume=" + cmd.refFile + ":" + cmd.refFile + ":ro",
531 consensus := exec.Command(args[0], args[1:]...)
532 consensus.Stderr = os.Stderr
533 stdout, err := consensus.StdoutPipe()
538 err = consensus.Start()
542 defer consensus.Wait()
543 tileseq, stats, err = tilelib.TileFasta(fmt.Sprintf("%s phase %d", infile, phase+1), stdout, cmd.matchChromosome, false)
551 err = consensus.Wait()
553 err = fmt.Errorf("%s phase %d: bcftools: %s", infile, phase, err)
559 func flatten(variants [][]tileVariantID) []tileVariantID {
561 for _, v := range variants {
566 flat := make([]tileVariantID, ntags*2)
567 for i := 0; i < ntags; i++ {
568 for hap := 0; hap < 2; hap++ {
569 if i < len(variants[hap]) {
570 flat[i*2+hap] = variants[hap][i]