22 "git.arvados.org/arvados.git/sdk/go/arvados"
23 "github.com/arvados/lightning/hgvs"
24 "github.com/klauspost/pgzip"
25 "github.com/kshedden/gonpy"
26 "github.com/sirupsen/logrus"
27 log "github.com/sirupsen/logrus"
30 type tvVariant struct {
32 librefs map[tileLibRef]bool
35 type outputFormat interface {
38 Head(out io.Writer, cgs []CompactGenome) error
39 Print(out io.Writer, seqname string, varslice []tvVariant) error
40 Finish(outdir string, out io.Writer, seqname string) error
44 var outputFormats = map[string]func() outputFormat{
45 "hgvs-numpy": func() outputFormat {
46 return &formatHGVSNumpy{alleles: map[string][][]bool{}}
48 "hgvs-onehot": func() outputFormat { return formatHGVSOneHot{} },
49 "hgvs": func() outputFormat { return formatHGVS{} },
50 "pvcf": func() outputFormat { return formatPVCF{} },
51 "vcf": func() outputFormat { return formatVCF{} },
54 type exporter struct {
55 outputFormat outputFormat
61 func (cmd *exporter) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
65 fmt.Fprintf(stderr, "%s\n", err)
68 flags := flag.NewFlagSet("", flag.ContinueOnError)
69 flags.SetOutput(stderr)
70 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
71 pprofdir := flags.String("pprof-dir", "", "write Go profile data to `directory` periodically")
72 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
73 projectUUID := flags.String("project", "", "project `UUID` for output data")
74 priority := flags.Int("priority", 500, "container request priority")
75 refname := flags.String("ref", "", "reference genome `name`")
76 inputDir := flags.String("input-dir", ".", "input `directory`")
77 outputDir := flags.String("output-dir", ".", "output `directory`")
78 outputFormatStr := flags.String("output-format", "hgvs", "output `format`: hgvs, pvcf, or vcf")
79 outputBed := flags.String("output-bed", "", "also output bed `file`")
80 flags.BoolVar(&cmd.outputPerChrom, "output-per-chromosome", true, "output one file per chromosome")
81 flags.BoolVar(&cmd.compress, "z", false, "write gzip-compressed output files")
82 labelsFilename := flags.String("output-labels", "", "also output genome labels csv `file`")
83 flags.IntVar(&cmd.maxTileSize, "max-tile-size", 50000, "don't try to make annotations for tiles bigger than given `size`")
84 err = flags.Parse(args)
85 if err == flag.ErrHelp {
88 } else if err != nil {
92 err = fmt.Errorf("extra unparsed command line arguments: %q", flag.Args())
96 if f, ok := outputFormats[*outputFormatStr]; !ok {
97 err = fmt.Errorf("invalid output format %q", *outputFormatStr)
100 cmd.outputFormat = f()
105 log.Println(http.ListenAndServe(*pprof, nil))
109 go writeProfilesPeriodically(*pprofdir)
113 if *outputDir != "." {
114 err = errors.New("cannot specify output directory in container mode: not implemented")
117 runner := arvadosContainerRunner{
118 Name: "lightning export",
119 Client: arvados.NewClientFromEnv(),
120 ProjectUUID: *projectUUID,
126 err = runner.TranslatePaths(inputDir)
130 if *outputBed != "" {
131 if strings.Contains(*outputBed, "/") {
132 err = fmt.Errorf("cannot use -output-bed filename %q containing '/' char", *outputBed)
135 *outputBed = "/mnt/output/" + *outputBed
137 runner.Args = []string{"export", "-local=true",
139 "-pprof-dir", "/mnt/output",
141 "-output-format", *outputFormatStr,
142 "-output-bed", *outputBed,
143 "-output-labels", "/mnt/output/labels.csv",
144 "-output-per-chromosome=" + fmt.Sprintf("%v", cmd.outputPerChrom),
145 "-max-tile-size", fmt.Sprintf("%d", cmd.maxTileSize),
146 "-input-dir", *inputDir,
147 "-output-dir", "/mnt/output",
148 "-z=" + fmt.Sprintf("%v", cmd.compress),
151 output, err = runner.Run()
155 fmt.Fprintln(stdout, output)
159 var cgs []CompactGenome
160 tilelib := &tileLibrary{
162 retainTileSequences: true,
163 compactGenomes: map[string][]tileVariantID{},
165 err = tilelib.LoadDir(context.Background(), *inputDir, nil)
170 refseq, ok := tilelib.refseqs[*refname]
172 err = fmt.Errorf("reference name %q not found in input; have %v", *refname, func() (names []string) {
173 for name := range tilelib.refseqs {
174 names = append(names, name)
181 names := cgnames(tilelib)
182 for _, name := range names {
183 cgs = append(cgs, CompactGenome{Name: name, Variants: tilelib.compactGenomes[name]})
185 if *labelsFilename != "" {
186 log.Infof("writing labels to %s", *labelsFilename)
188 f, err = os.OpenFile(*labelsFilename, os.O_CREATE|os.O_WRONLY, 0777)
193 for i, name := range names {
194 _, err = fmt.Fprintf(f, "%d,%q,%q\n", i, trimFilenameForLabel(name), cmd.outputFormat.Filename())
196 err = fmt.Errorf("write %s: %w", *labelsFilename, err)
202 err = fmt.Errorf("close %s: %w", *labelsFilename, err)
209 var bedbufw *bufio.Writer
210 if *outputBed != "" {
211 bedfile, err = os.OpenFile(*outputBed, os.O_CREATE|os.O_WRONLY, 0666)
215 defer bedfile.Close()
216 bedbufw = bufio.NewWriterSize(bedfile, 16*1024*1024)
220 err = cmd.export(*outputDir, bedout, tilelib, refseq, cgs)
225 err = bedbufw.Flush()
229 err = bedfile.Close()
237 func (cmd *exporter) export(outdir string, bedout io.Writer, tilelib *tileLibrary, refseq map[string][]tileLibRef, cgs []CompactGenome) error {
238 var seqnames []string
239 var missing []tileLibRef
240 for seqname, librefs := range refseq {
241 seqnames = append(seqnames, seqname)
242 for _, libref := range librefs {
243 if libref.Variant != 0 && tilelib.TileVariantSequence(libref) == nil {
244 missing = append(missing, libref)
248 sort.Strings(seqnames)
250 if len(missing) > 0 {
251 if limit := 100; len(missing) > limit {
252 log.Warnf("first %d missing tiles: %v", limit, missing[:limit])
254 log.Warnf("missing tiles: %v", missing)
256 return fmt.Errorf("%d needed tiles are missing from library", len(missing))
259 outw := make([]io.WriteCloser, len(seqnames))
260 bedw := make([]io.WriteCloser, len(seqnames))
262 var merges sync.WaitGroup
263 merge := func(dst io.Writer, src []io.WriteCloser, label string) {
265 for i, seqname := range seqnames {
272 log.Infof("writing %s %s", seqname, label)
273 scanner := bufio.NewScanner(pr)
276 dst.Write(scanner.Bytes())
277 dst.Write([]byte{'\n'})
280 log.Infof("writing %s %s done", seqname, label)
284 if cmd.outputPerChrom {
285 for i, seqname := range seqnames {
286 fnm := filepath.Join(outdir, strings.Replace(cmd.outputFormat.Filename(), ".", "."+seqname+".", 1))
290 f, err := os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
295 log.Infof("writing %q", f.Name())
298 z := pgzip.NewWriter(f)
302 err = cmd.outputFormat.Head(outw[i], cgs)
308 fnm := filepath.Join(outdir, cmd.outputFormat.Filename())
312 f, err := os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
317 log.Infof("writing %q", fnm)
318 var out io.Writer = f
320 z := pgzip.NewWriter(out)
324 cmd.outputFormat.Head(out, cgs)
325 merge(out, outw, "output")
328 merge(bedout, bedw, "bed")
331 throttle := throttle{Max: runtime.NumCPU()}
332 if max := cmd.outputFormat.MaxGoroutines(); max > 0 {
335 log.Infof("assembling %d sequences in %d goroutines", len(seqnames), throttle.Max)
336 for seqidx, seqname := range seqnames {
337 seqidx, seqname := seqidx, seqname
342 defer throttle.Release()
346 outwb := bufio.NewWriterSize(outw, 8*1024*1024)
347 eachVariant(bedw, tilelib.taglib.keylen, seqname, refseq[seqname], tilelib, cgs, cmd.outputFormat.PadLeft(), cmd.maxTileSize, func(varslice []tvVariant) {
348 err := cmd.outputFormat.Print(outwb, seqname, varslice)
351 err := cmd.outputFormat.Finish(outdir, outwb, seqname)
362 return throttle.Err()
365 // Align genome tiles to reference tiles, call callback func on each
366 // variant, and (if bedw is not nil) write tile coverage to bedw.
367 func eachVariant(bedw io.Writer, taglen int, seqname string, reftiles []tileLibRef, tilelib *tileLibrary, cgs []CompactGenome, padLeft bool, maxTileSize int, callback func(varslice []tvVariant)) {
369 progressbar := time.NewTicker(time.Minute)
370 defer progressbar.Stop()
371 var outmtx sync.Mutex
374 variantAt := map[int][]tvVariant{} // variantAt[chromOffset][genomeIndex*2+phase]
375 for refstep, libref := range reftiles {
377 case <-progressbar.C:
380 fin := t0.Add(time.Duration(float64(time.Now().Sub(t0)) * float64(len(reftiles)) / float64(refstep)))
381 eta = fmt.Sprintf("%v (%v)", fin.Format(time.RFC3339), fin.Sub(time.Now()))
385 log.Printf("exportSeq: %s: refstep %d of %d, %.0f/s, ETA %v", seqname, refstep, len(reftiles), float64(refstep)/time.Now().Sub(t0).Seconds(), eta)
388 diffs := map[tileLibRef][]hgvs.Variant{}
389 refseq := tilelib.TileVariantSequence(libref)
390 tagcoverage := 0 // number of times the start tag was found in genomes -- max is len(cgs)*2
391 for cgidx, cg := range cgs {
392 for phase := 0; phase < 2; phase++ {
393 if len(cg.Variants) <= int(libref.Tag)*2+phase {
396 variant := cg.Variants[int(libref.Tag)*2+phase]
401 if variant == libref.Variant {
404 glibref := tileLibRef{Tag: libref.Tag, Variant: variant}
405 vars, ok := diffs[glibref]
407 genomeseq := tilelib.TileVariantSequence(glibref)
408 if len(genomeseq) == 0 {
409 // Hash is known but sequence
410 // is not, e.g., retainNoCalls
411 // was false during import
414 if len(genomeseq) > maxTileSize {
417 refSequence := refseq
418 // If needed, extend the
419 // reference sequence up to
420 // the tag at the end of the
421 // genomeseq sequence.
422 refstepend := refstep + 1
423 for refstepend < len(reftiles) && len(refSequence) >= taglen && !bytes.EqualFold(refSequence[len(refSequence)-taglen:], genomeseq[len(genomeseq)-taglen:]) && len(refSequence) <= maxTileSize {
424 if &refSequence[0] == &refseq[0] {
425 refSequence = append([]byte(nil), refSequence...)
427 refSequence = append(refSequence, tilelib.TileVariantSequence(reftiles[refstepend])...)
430 // (TODO: handle no-calls)
431 if len(refSequence) <= maxTileSize {
432 refstr := strings.ToUpper(string(refSequence))
433 genomestr := strings.ToUpper(string(genomeseq))
434 vars, _ = hgvs.Diff(refstr, genomestr, time.Second)
436 diffs[glibref] = vars
438 for _, v := range vars {
443 varslice := variantAt[v.Position]
445 varslice = make([]tvVariant, len(cgs)*2)
446 variantAt[v.Position] = varslice
448 varslice[cgidx*2+phase].Variant = v
449 if varslice[cgidx*2+phase].librefs == nil {
450 varslice[cgidx*2+phase].librefs = map[tileLibRef]bool{glibref: true}
452 varslice[cgidx*2+phase].librefs[glibref] = true
457 refpos += len(refseq) - taglen
459 // Flush entries from variantAt that are behind
460 // refpos. Flush all entries if this is the last
461 // reftile of the path/chromosome.
462 flushpos := make([]int, 0, len(variantAt))
463 lastrefstep := refstep == len(reftiles)-1
464 for pos := range variantAt {
465 if lastrefstep || pos <= refpos {
466 flushpos = append(flushpos, pos)
469 sort.Slice(flushpos, func(i, j int) bool { return flushpos[i] < flushpos[j] })
470 flushvariants := make([][]tvVariant, len(flushpos))
471 for i, pos := range flushpos {
472 varslice := variantAt[pos]
473 delete(variantAt, pos)
474 for i := range varslice {
475 if varslice[i].Position == 0 {
476 varslice[i].Position = pos
479 flushvariants[i] = varslice
483 defer outmtx.Unlock()
484 for _, varslice := range flushvariants {
488 if bedw != nil && len(refseq) > 0 {
489 tilestart := refpos - len(refseq) + taglen
494 thickstart := tilestart + taglen
500 // coverage score, 0 to 1000
503 score = 1000 * tagcoverage / len(cgs) / 2
506 fmt.Fprintf(bedw, "%s %d %d %d %d . %d %d\n",
507 seqname, tilestart, tileend,
510 thickstart, thickend)
515 func bucketVarsliceByRef(varslice []tvVariant) map[string]map[string]int {
516 byref := map[string]map[string]int{}
517 for _, v := range varslice {
518 if v.Ref == "" && v.New == "" {
523 alts = map[string]int{}
531 type formatVCF struct{}
533 func (formatVCF) MaxGoroutines() int { return 0 }
534 func (formatVCF) Filename() string { return "out.vcf" }
535 func (formatVCF) PadLeft() bool { return true }
536 func (formatVCF) Finish(string, io.Writer, string) error { return nil }
537 func (formatVCF) Head(out io.Writer, cgs []CompactGenome) error {
538 _, err := fmt.Fprint(out, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n")
541 func (formatVCF) Print(out io.Writer, seqname string, varslice []tvVariant) error {
542 for ref, alts := range bucketVarsliceByRef(varslice) {
543 altslice := make([]string, 0, len(alts))
544 for alt := range alts {
545 altslice = append(altslice, alt)
547 sort.Strings(altslice)
550 for i, a := range altslice {
554 info += strconv.Itoa(alts[a])
556 _, err := fmt.Fprintf(out, "%s\t%d\t.\t%s\t%s\t.\t.\t%s\n", seqname, varslice[0].Position, ref, strings.Join(altslice, ","), info)
564 type formatPVCF struct{}
566 func (formatPVCF) MaxGoroutines() int { return 0 }
567 func (formatPVCF) Filename() string { return "out.vcf" }
568 func (formatPVCF) PadLeft() bool { return true }
569 func (formatPVCF) Finish(string, io.Writer, string) error { return nil }
570 func (formatPVCF) Head(out io.Writer, cgs []CompactGenome) error {
571 fmt.Fprintln(out, `##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">`)
572 fmt.Fprintf(out, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT")
573 for _, cg := range cgs {
574 fmt.Fprintf(out, "\t%s", cg.Name)
576 _, err := fmt.Fprintf(out, "\n")
580 func (formatPVCF) Print(out io.Writer, seqname string, varslice []tvVariant) error {
581 for ref, alts := range bucketVarsliceByRef(varslice) {
582 altslice := make([]string, 0, len(alts))
583 for alt := range alts {
584 altslice = append(altslice, alt)
586 sort.Strings(altslice)
587 for i, a := range altslice {
590 _, err := fmt.Fprintf(out, "%s\t%d\t.\t%s\t%s\t.\t.\t.\tGT", seqname, varslice[0].Position, ref, strings.Join(altslice, ","))
594 for i := 0; i < len(varslice); i += 2 {
595 v1, v2 := varslice[i], varslice[i+1]
596 a1, a2 := alts[v1.New], alts[v2.New]
598 // variant on allele 0 belongs on a
599 // different output line -- same
600 // chr,pos but different "ref" length
606 _, err := fmt.Fprintf(out, "\t%d/%d", a1, a2)
611 _, err = out.Write([]byte{'\n'})
619 type formatHGVS struct{}
621 func (formatHGVS) MaxGoroutines() int { return 0 }
622 func (formatHGVS) Filename() string { return "out.tsv" }
623 func (formatHGVS) PadLeft() bool { return false }
624 func (formatHGVS) Head(out io.Writer, cgs []CompactGenome) error { return nil }
625 func (formatHGVS) Finish(string, io.Writer, string) error { return nil }
626 func (formatHGVS) Print(out io.Writer, seqname string, varslice []tvVariant) error {
627 for i := 0; i < len(varslice)/2; i++ {
629 out.Write([]byte{'\t'})
631 var1, var2 := varslice[i*2], varslice[i*2+1]
632 if var1.Variant == var2.Variant {
633 if var1.Ref == var1.New {
634 _, err := out.Write([]byte{'.'})
639 _, err := fmt.Fprintf(out, "%s:g.%s", seqname, var1.String())
645 _, err := fmt.Fprintf(out, "%s:g.[%s];[%s]", seqname, var1.String(), var2.String())
651 _, err := out.Write([]byte{'\n'})
655 type formatHGVSOneHot struct{}
657 func (formatHGVSOneHot) MaxGoroutines() int { return 0 }
658 func (formatHGVSOneHot) Filename() string { return "out.tsv" }
659 func (formatHGVSOneHot) PadLeft() bool { return false }
660 func (formatHGVSOneHot) Head(out io.Writer, cgs []CompactGenome) error { return nil }
661 func (formatHGVSOneHot) Finish(string, io.Writer, string) error { return nil }
662 func (formatHGVSOneHot) Print(out io.Writer, seqname string, varslice []tvVariant) error {
663 vars := map[hgvs.Variant]bool{}
664 for _, v := range varslice {
666 vars[v.Variant] = true
670 // sort variants to ensure output is deterministic
671 sorted := make([]hgvs.Variant, 0, len(vars))
672 for v := range vars {
673 sorted = append(sorted, v)
675 sort.Slice(sorted, func(a, b int) bool { return hgvs.Less(sorted[a], sorted[b]) })
677 for _, v := range sorted {
678 fmt.Fprintf(out, "%s.%s", seqname, v.String())
679 for i := 0; i < len(varslice); i += 2 {
680 if varslice[i].Variant == v || varslice[i+1].Variant == v {
681 out.Write([]byte("\t1"))
683 out.Write([]byte("\t0"))
686 _, err := out.Write([]byte{'\n'})
694 type formatHGVSNumpy struct {
696 alleles map[string][][]bool // alleles[seqname][variantidx][genomeidx*2+phase]
699 func (*formatHGVSNumpy) MaxGoroutines() int { return 8 }
700 func (*formatHGVSNumpy) Filename() string { return "annotations.csv" }
701 func (*formatHGVSNumpy) PadLeft() bool { return false }
702 func (*formatHGVSNumpy) Head(out io.Writer, cgs []CompactGenome) error { return nil }
703 func (f *formatHGVSNumpy) Print(outw io.Writer, seqname string, varslice []tvVariant) error {
704 // sort variants to ensure output is deterministic
705 sorted := make([]hgvs.Variant, 0, len(varslice))
706 for _, v := range varslice {
707 sorted = append(sorted, v.Variant)
709 sort.Slice(sorted, func(a, b int) bool { return hgvs.Less(sorted[a], sorted[b]) })
712 seqalleles := f.alleles[seqname]
715 // append a row to seqvariants and seqalleles for each unique
716 // non-ref variant in varslice.
717 var previous hgvs.Variant
718 for _, v := range sorted {
719 if previous == v || v.Ref == v.New {
723 newrow := make([]bool, len(varslice))
724 for i, allele := range varslice {
725 if allele.Variant == v {
729 seqalleles = append(seqalleles, newrow)
730 _, err := fmt.Fprintf(outw, "%d,%q\n", len(seqalleles)-1, seqname+"."+v.String())
737 f.alleles[seqname] = seqalleles
741 func (f *formatHGVSNumpy) Finish(outdir string, _ io.Writer, seqname string) error {
742 // Write seqname's data to a .npy matrix with one row per
743 // genome and 2 columns per variant.
744 seqalleles := f.alleles[seqname]
746 delete(f.alleles, seqname)
748 if len(seqalleles) == 0 {
751 out := make([]int8, len(seqalleles)*len(seqalleles[0]))
752 rows := len(seqalleles[0]) / 2
753 cols := len(seqalleles) * 2
754 // copy seqalleles[varidx][genome*2+phase] to
755 // out[genome*nvars*2 + varidx*2 + phase]
756 for varidx, alleles := range seqalleles {
757 for g := 0; g < len(alleles)/2; g++ {
758 aa, ab := alleles[g*2], alleles[g*2+1]
761 out[g*cols+varidx*2] = 1
764 out[g*cols+varidx*2+1] = 1
768 outf, err := os.OpenFile(outdir+"/matrix."+seqname+".npy", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0777)
773 bufw := bufio.NewWriter(outf)
774 npw, err := gonpy.NewWriter(nopCloser{bufw})
778 log.WithFields(logrus.Fields{
782 }).Info("writing numpy")
783 npw.Shape = []int{rows, cols}