21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "github.com/arvados/lightning/hgvs"
23 log "github.com/sirupsen/logrus"
26 type outputFormat struct {
27 Print func(out io.Writer, seqname string, varslice []hgvs.Variant)
32 outputFormats = map[string]outputFormat{
33 "hgvs-onehot": outputFormatHGVSOneHot,
34 "hgvs": outputFormatHGVS,
35 "vcf": outputFormatVCF,
37 outputFormatHGVS = outputFormat{Print: printHGVS}
38 outputFormatHGVSOneHot = outputFormat{Print: printHGVSOneHot}
39 outputFormatVCF = outputFormat{Print: printVCF, PadLeft: true}
42 type exporter struct {
43 outputFormat outputFormat
47 func (cmd *exporter) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
51 fmt.Fprintf(stderr, "%s\n", err)
54 flags := flag.NewFlagSet("", flag.ContinueOnError)
55 flags.SetOutput(stderr)
56 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
57 pprofdir := flags.String("pprof-dir", "", "write Go profile data to `directory` periodically")
58 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
59 projectUUID := flags.String("project", "", "project `UUID` for output data")
60 priority := flags.Int("priority", 500, "container request priority")
61 refname := flags.String("ref", "", "reference genome `name`")
62 inputFilename := flags.String("i", "-", "input `file` (library)")
63 outputFilename := flags.String("o", "-", "output `file`")
64 outputFormatStr := flags.String("output-format", "hgvs", "output `format`: hgvs or vcf")
65 outputBed := flags.String("output-bed", "", "also output bed `file`")
66 labelsFilename := flags.String("output-labels", "", "also output genome labels csv `file`")
67 flags.IntVar(&cmd.maxTileSize, "max-tile-size", 50000, "don't try to make annotations for tiles bigger than given `size`")
68 err = flags.Parse(args)
69 if err == flag.ErrHelp {
72 } else if err != nil {
76 if f, ok := outputFormats[*outputFormatStr]; !ok {
77 err = fmt.Errorf("invalid output format %q", *outputFormatStr)
85 log.Println(http.ListenAndServe(*pprof, nil))
89 go writeProfilesPeriodically(*pprofdir)
93 if *outputFilename != "-" {
94 err = errors.New("cannot specify output file in container mode: not implemented")
97 runner := arvadosContainerRunner{
98 Name: "lightning export",
99 Client: arvados.NewClientFromEnv(),
100 ProjectUUID: *projectUUID,
105 err = runner.TranslatePaths(inputFilename)
109 if *outputBed != "" {
110 if strings.Contains(*outputBed, "/") {
111 err = fmt.Errorf("cannot use -output-bed filename %q containing '/' char", *outputBed)
114 *outputBed = "/mnt/output/" + *outputBed
116 runner.Args = []string{"export", "-local=true",
118 "-pprof-dir", "/mnt/output",
120 "-output-format", *outputFormatStr,
121 "-output-bed", *outputBed,
122 "-output-labels", "/mnt/output/labels.csv",
123 "-max-tile-size", fmt.Sprintf("%d", cmd.maxTileSize),
124 "-i", *inputFilename,
125 "-o", "/mnt/output/export.csv",
128 output, err = runner.Run()
132 fmt.Fprintln(stdout, output+"/export.csv")
136 in, err := open(*inputFilename)
141 input, ok := in.(io.ReadSeeker)
143 err = fmt.Errorf("%s: %T cannot seek", *inputFilename, in)
147 // Error out early if seeking doesn't work on the input file.
148 _, err = input.Seek(0, io.SeekEnd)
152 _, err = input.Seek(0, io.SeekStart)
157 var cgs []CompactGenome
158 tilelib := &tileLibrary{
160 compactGenomes: map[string][]tileVariantID{},
162 err = tilelib.LoadGob(context.Background(), input, strings.HasSuffix(*inputFilename, ".gz"), nil)
167 refseq, ok := tilelib.refseqs[*refname]
169 err = fmt.Errorf("reference name %q not found in input; have %v", *refname, func() (names []string) {
170 for name := range tilelib.refseqs {
171 names = append(names, name)
178 names := cgnames(tilelib)
179 for _, name := range names {
180 cgs = append(cgs, CompactGenome{Name: name, Variants: tilelib.compactGenomes[name]})
182 if *labelsFilename != "" {
183 log.Infof("writing labels to %s", *labelsFilename)
185 f, err = os.OpenFile(*labelsFilename, os.O_CREATE|os.O_WRONLY, 0777)
190 _, outBasename := path.Split(*outputFilename)
191 for i, name := range names {
192 _, err = fmt.Fprintf(f, "%d,%q,%q\n", i, trimFilenameForLabel(name), outBasename)
194 err = fmt.Errorf("write %s: %w", *labelsFilename, err)
200 err = fmt.Errorf("close %s: %w", *labelsFilename, err)
205 _, err = input.Seek(0, io.SeekStart)
210 var output io.WriteCloser
211 if *outputFilename == "-" {
212 output = nopCloser{stdout}
214 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0666)
220 bufw := bufio.NewWriter(output)
223 var bedbufw *bufio.Writer
224 if *outputBed != "" {
225 bedout, err = os.OpenFile(*outputBed, os.O_CREATE|os.O_WRONLY, 0666)
230 bedbufw = bufio.NewWriter(bedout)
233 err = cmd.export(bufw, bedout, input, strings.HasSuffix(*inputFilename, ".gz"), tilelib, refseq, cgs)
246 err = bedbufw.Flush()
262 func (cmd *exporter) export(out, bedout io.Writer, librdr io.Reader, gz bool, tilelib *tileLibrary, refseq map[string][]tileLibRef, cgs []CompactGenome) error {
263 need := map[tileLibRef]bool{}
264 var seqnames []string
265 for seqname, librefs := range refseq {
266 seqnames = append(seqnames, seqname)
267 for _, libref := range librefs {
268 if libref.Variant != 0 {
273 sort.Strings(seqnames)
275 for _, cg := range cgs {
276 for i, variant := range cg.Variants {
280 libref := tileLibRef{Tag: tagID(i / 2), Variant: variant}
285 log.Infof("export: loading %d tile variants", len(need))
286 tileVariant := map[tileLibRef]TileVariant{}
287 err := DecodeLibrary(librdr, gz, func(ent *LibraryEntry) error {
288 for _, tv := range ent.TileVariants {
289 libref := tilelib.getRef(tv.Tag, tv.Sequence)
291 tileVariant[libref] = tv
300 log.Infof("export: loaded %d tile variants", len(tileVariant))
301 var missing []tileLibRef
302 for libref := range need {
303 if _, ok := tileVariant[libref]; !ok {
304 missing = append(missing, libref)
307 if len(missing) > 0 {
308 if limit := 100; len(missing) > limit {
309 log.Warnf("first %d missing tiles: %v", limit, missing[:limit])
311 log.Warnf("missing tiles: %v", missing)
313 return fmt.Errorf("%d needed tiles are missing from library", len(missing))
316 outw := make([]io.WriteCloser, len(seqnames))
317 bedw := make([]io.WriteCloser, len(seqnames))
319 var merges sync.WaitGroup
320 merge := func(dst io.Writer, src []io.WriteCloser, label string) {
322 for i, seqname := range seqnames {
329 log.Infof("writing %s %s", seqname, label)
330 scanner := bufio.NewScanner(pr)
333 dst.Write(scanner.Bytes())
334 dst.Write([]byte{'\n'})
337 log.Infof("writing %s %s done", seqname, label)
341 merge(out, outw, "output")
343 merge(bedout, bedw, "bed")
346 throttle := throttle{Max: runtime.NumCPU()}
347 log.Infof("assembling %d sequences in %d goroutines", len(seqnames), throttle.Max)
348 for seqidx, seqname := range seqnames {
349 seqidx, seqname := seqidx, seqname
354 defer throttle.Release()
359 outwb := bufio.NewWriter(outw)
361 cmd.exportSeq(outwb, bedw, tilelib.taglib.keylen, seqname, refseq[seqname], tileVariant, cgs)
369 // Align genome tiles to reference tiles, write diffs to outw, and (if
370 // bedw is not nil) write tile coverage to bedw.
371 func (cmd *exporter) exportSeq(outw, bedw io.Writer, taglen int, seqname string, reftiles []tileLibRef, tileVariant map[tileLibRef]TileVariant, cgs []CompactGenome) {
373 variantAt := map[int][]hgvs.Variant{} // variantAt[chromOffset][genomeIndex*2+phase]
374 for refstep, libref := range reftiles {
375 reftile := tileVariant[libref]
376 tagcoverage := 0 // number of times the start tag was found in genomes -- max is len(cgs)*2
377 for cgidx, cg := range cgs {
378 for phase := 0; phase < 2; phase++ {
379 if len(cg.Variants) <= int(libref.Tag)*2+phase {
382 variant := cg.Variants[int(libref.Tag)*2+phase]
387 if variant == libref.Variant {
390 genometile := tileVariant[tileLibRef{Tag: libref.Tag, Variant: variant}]
391 if len(genometile.Sequence) == 0 {
392 // Hash is known but sequence
393 // is not, e.g., retainNoCalls
394 // was false during import
397 if len(genometile.Sequence) > cmd.maxTileSize {
400 refSequence := reftile.Sequence
401 // If needed, extend the reference
402 // sequence up to the tag at the end
403 // of the genometile sequence.
404 refstepend := refstep + 1
405 for refstepend < len(reftiles) && len(refSequence) >= taglen && !bytes.EqualFold(refSequence[len(refSequence)-taglen:], genometile.Sequence[len(genometile.Sequence)-taglen:]) && len(refSequence) <= cmd.maxTileSize {
406 if &refSequence[0] == &reftile.Sequence[0] {
407 refSequence = append([]byte(nil), refSequence...)
409 refSequence = append(refSequence, tileVariant[reftiles[refstepend]].Sequence...)
412 // (TODO: handle no-calls)
413 vars, _ := hgvs.Diff(strings.ToUpper(string(refSequence)), strings.ToUpper(string(genometile.Sequence)), time.Second)
414 for _, v := range vars {
415 if cmd.outputFormat.PadLeft {
419 varslice := variantAt[v.Position]
421 varslice = make([]hgvs.Variant, len(cgs)*2)
422 variantAt[v.Position] = varslice
424 varslice[cgidx*2+phase] = v
428 refpos += len(reftile.Sequence) - taglen
430 // Flush entries from variantAt that are behind
431 // refpos. Flush all entries if this is the last
432 // reftile of the path/chromosome.
434 lastrefstep := refstep == len(reftiles)-1
435 for pos := range variantAt {
436 if lastrefstep || pos <= refpos {
437 flushpos = append(flushpos, pos)
440 sort.Slice(flushpos, func(i, j int) bool { return flushpos[i] < flushpos[j] })
441 for _, pos := range flushpos {
442 varslice := variantAt[pos]
443 delete(variantAt, pos)
444 for i := range varslice {
445 if varslice[i].Position == 0 {
446 varslice[i].Position = pos
449 cmd.outputFormat.Print(outw, seqname, varslice)
451 if bedw != nil && len(reftile.Sequence) > 0 {
452 tilestart := refpos - len(reftile.Sequence) + taglen
457 thickstart := tilestart + taglen
463 // coverage score, 0 to 1000
466 score = 1000 * tagcoverage / len(cgs) / 2
469 fmt.Fprintf(bedw, "%s %d %d %d %d . %d %d\n",
470 seqname, tilestart, tileend,
473 thickstart, thickend)
478 func printVCF(out io.Writer, seqname string, varslice []hgvs.Variant) {
479 refs := map[string]map[string]int{}
480 for _, v := range varslice {
481 if v.Ref == "" && v.New == "" {
486 alts = map[string]int{}
491 for ref, alts := range refs {
492 var altslice []string
493 for alt := range alts {
494 altslice = append(altslice, alt)
496 sort.Strings(altslice)
497 for i, a := range altslice {
500 fmt.Fprintf(out, "%s\t%d\t%s\t%s", seqname, varslice[0].Position, ref, strings.Join(altslice, ","))
501 for i := 0; i < len(varslice); i += 2 {
502 v1, v2 := varslice[i], varslice[i+1]
503 a1, a2 := alts[v1.New], alts[v2.New]
510 fmt.Fprintf(out, "\t%d/%d", a1, a2)
512 out.Write([]byte{'\n'})
516 func printHGVS(out io.Writer, seqname string, varslice []hgvs.Variant) {
517 for i := 0; i < len(varslice)/2; i++ {
519 out.Write([]byte{'\t'})
521 var1, var2 := varslice[i*2], varslice[i*2+1]
523 if var1.Ref == var1.New {
524 out.Write([]byte{'.'})
526 fmt.Fprintf(out, "%s:g.%s", seqname, var1.String())
529 fmt.Fprintf(out, "%s:g.[%s];[%s]", seqname, var1.String(), var2.String())
532 out.Write([]byte{'\n'})
535 func printHGVSOneHot(out io.Writer, seqname string, varslice []hgvs.Variant) {
536 vars := map[hgvs.Variant]bool{}
537 for _, v := range varslice {
543 // sort variants to ensure output is deterministic
544 sorted := make([]hgvs.Variant, 0, len(vars))
545 for v := range vars {
546 sorted = append(sorted, v)
548 sort.Slice(sorted, func(a, b int) bool { return hgvs.Less(sorted[a], sorted[b]) })
550 for _, v := range sorted {
551 fmt.Fprintf(out, "%s.%s", seqname, v.String())
552 for i := 0; i < len(varslice); i += 2 {
553 if varslice[i] == v || varslice[i+1] == v {
554 out.Write([]byte("\t1"))
556 out.Write([]byte("\t0"))
559 out.Write([]byte{'\n'})