19 "git.arvados.org/arvados.git/sdk/go/arvados"
20 "github.com/arvados/lightning/hgvs"
21 log "github.com/sirupsen/logrus"
24 type outputFormat struct {
25 Print func(out io.Writer, seqname string, varslice []hgvs.Variant)
30 outputFormats = map[string]outputFormat{
31 "hgvs": outputFormatHGVS,
32 "vcf": outputFormatVCF,
34 outputFormatHGVS = outputFormat{Print: printHGVS}
35 outputFormatVCF = outputFormat{Print: printVCF, PadLeft: true}
38 type exporter struct {
39 outputFormat outputFormat
42 func (cmd *exporter) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
46 fmt.Fprintf(stderr, "%s\n", err)
49 flags := flag.NewFlagSet("", flag.ContinueOnError)
50 flags.SetOutput(stderr)
51 pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
52 runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
53 projectUUID := flags.String("project", "", "project `UUID` for output data")
54 priority := flags.Int("priority", 500, "container request priority")
55 refname := flags.String("ref", "", "reference genome `name`")
56 inputFilename := flags.String("i", "-", "input `file` (library)")
57 outputFilename := flags.String("o", "-", "output `file`")
58 outputFormatStr := flags.String("output-format", "hgvs", "output `format`: hgvs or vcf")
59 outputBed := flags.String("output-bed", "", "also output bed `file`")
60 pick := flags.String("pick", "", "`name` of single genome to export")
61 err = flags.Parse(args)
62 if err == flag.ErrHelp {
65 } else if err != nil {
69 if f, ok := outputFormats[*outputFormatStr]; !ok {
70 err = fmt.Errorf("invalid output format %q", *outputFormatStr)
78 log.Println(http.ListenAndServe(*pprof, nil))
83 if *outputFilename != "-" {
84 err = errors.New("cannot specify output file in container mode: not implemented")
87 runner := arvadosContainerRunner{
88 Name: "lightning export",
89 Client: arvados.NewClientFromEnv(),
90 ProjectUUID: *projectUUID,
95 err = runner.TranslatePaths(inputFilename)
100 if strings.Contains(*outputBed, "/") {
101 err = fmt.Errorf("cannot use -output-bed filename %q containing '/' char", *outputBed)
104 *outputBed = "/mnt/output/" + *outputBed
106 runner.Args = []string{"export", "-local=true", "-pick", *pick, "-ref", *refname, "-output-format", *outputFormatStr, "-output-bed", *outputBed, "-i", *inputFilename, "-o", "/mnt/output/export.csv"}
108 output, err = runner.Run()
112 fmt.Fprintln(stdout, output+"/export.csv")
116 input, err := os.Open(*inputFilename)
122 // Error out early if seeking doesn't work on the input file.
123 _, err = input.Seek(0, io.SeekEnd)
127 _, err = input.Seek(0, io.SeekStart)
133 var cgs []CompactGenome
134 tilelib := tileLibrary{
137 err = tilelib.LoadGob(context.Background(), input, strings.HasSuffix(*inputFilename, ".gz"), func(cg CompactGenome) {
138 if *pick != "" && *pick != cg.Name {
141 log.Debugf("export: pick %q", cg.Name)
144 cgs = append(cgs, cg)
149 sort.Slice(cgs, func(i, j int) bool { return cgs[i].Name < cgs[j].Name })
150 log.Printf("export: pick %q => %d genomes", *pick, len(cgs))
152 refseq, ok := tilelib.refseqs[*refname]
154 err = fmt.Errorf("reference name %q not found in input; have %v", *refname, func() (names []string) {
155 for name := range tilelib.refseqs {
156 names = append(names, name)
163 _, err = input.Seek(0, io.SeekStart)
168 var output io.WriteCloser
169 if *outputFilename == "-" {
170 output = nopCloser{stdout}
172 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0666)
178 bufw := bufio.NewWriter(output)
181 var bedbufw *bufio.Writer
182 if *outputBed != "" {
183 bedout, err = os.OpenFile(*outputBed, os.O_CREATE|os.O_WRONLY, 0666)
188 bedbufw = bufio.NewWriter(bedout)
191 err = cmd.export(bufw, bedout, input, strings.HasSuffix(*inputFilename, ".gz"), tilelib.taglib.keylen, refseq, cgs)
204 err = bedbufw.Flush()
220 func (cmd *exporter) export(out, bedout io.Writer, librdr io.Reader, gz bool, taglen int, refseq map[string][]tileLibRef, cgs []CompactGenome) error {
221 need := map[tileLibRef]bool{}
222 var seqnames []string
223 for seqname, librefs := range refseq {
224 seqnames = append(seqnames, seqname)
225 for _, libref := range librefs {
226 if libref.Variant != 0 {
231 sort.Strings(seqnames)
233 for _, cg := range cgs {
234 for i, variant := range cg.Variants {
238 libref := tileLibRef{Tag: tagID(i / 2), Variant: variant}
243 log.Infof("export: loading %d tile variants", len(need))
244 tileVariant := map[tileLibRef]TileVariant{}
245 err := DecodeLibrary(librdr, gz, func(ent *LibraryEntry) error {
246 for _, tv := range ent.TileVariants {
247 libref := tileLibRef{Tag: tv.Tag, Variant: tv.Variant}
249 tileVariant[libref] = tv
258 log.Infof("export: loaded %d tile variants", len(tileVariant))
259 var missing []tileLibRef
260 for libref := range need {
261 if _, ok := tileVariant[libref]; !ok {
262 missing = append(missing, libref)
265 if len(missing) > 0 {
266 if limit := 100; len(missing) > limit {
267 log.Warnf("first %d missing tiles: %v", limit, missing[:limit])
269 log.Warnf("missing tiles: %v", missing)
271 return fmt.Errorf("%d needed tiles are missing from library", len(missing))
274 log.Infof("assembling %d sequences concurrently", len(seqnames))
275 var wg sync.WaitGroup
276 outbuf := make([]bytes.Buffer, len(seqnames))
277 bedbuf := make([]bytes.Buffer, len(seqnames))
278 for seqidx, seqname := range seqnames {
280 outbuf := &outbuf[seqidx]
281 bedbuf := &bedbuf[seqidx]
285 // TODO: limit number of goroutines and unflushed bufs to ncpus
289 cmd.exportSeq(outbuf, bedbuf, taglen, seqname, refseq[seqname], tileVariant, cgs)
290 log.Infof("assembled %q to outbuf %d bedbuf %d", seqname, outbuf.Len(), bedbuf.Len())
298 for i, seqname := range seqnames {
299 log.Infof("writing outbuf %s", seqname)
300 io.Copy(out, &outbuf[i])
307 for i, seqname := range seqnames {
308 log.Infof("writing bedbuf %s", seqname)
309 io.Copy(bedout, &bedbuf[i])
317 // Align genome tiles to reference tiles, write diffs to outw, and (if
318 // bedw is not nil) write tile coverage to bedw.
319 func (cmd *exporter) exportSeq(outw, bedw io.Writer, taglen int, seqname string, reftiles []tileLibRef, tileVariant map[tileLibRef]TileVariant, cgs []CompactGenome) {
321 variantAt := map[int][]hgvs.Variant{} // variantAt[chromOffset][genomeIndex*2+phase]
322 for refstep, libref := range reftiles {
323 reftile := tileVariant[libref]
324 tagcoverage := 0 // number of times the start tag was found in genomes -- max is len(cgs)*2
325 for cgidx, cg := range cgs {
326 for phase := 0; phase < 2; phase++ {
327 if len(cg.Variants) <= int(libref.Tag)*2+phase {
330 variant := cg.Variants[int(libref.Tag)*2+phase]
335 if variant == libref.Variant {
338 genometile := tileVariant[tileLibRef{Tag: libref.Tag, Variant: variant}]
339 if len(genometile.Sequence) == 0 {
340 // Hash is known but sequence
341 // is not, e.g., retainNoCalls
342 // was false during import
345 refSequence := reftile.Sequence
346 // If needed, extend the reference
347 // sequence up to the tag at the end
348 // of the genometile sequence.
349 refstepend := refstep + 1
350 for refstepend < len(reftiles) && len(refSequence) >= taglen && !bytes.EqualFold(refSequence[len(refSequence)-taglen:], genometile.Sequence[len(genometile.Sequence)-taglen:]) {
351 if &refSequence[0] == &reftile.Sequence[0] {
352 refSequence = append([]byte(nil), refSequence...)
354 refSequence = append(refSequence, tileVariant[reftiles[refstepend]].Sequence...)
357 // (TODO: handle no-calls)
358 vars, _ := hgvs.Diff(strings.ToUpper(string(refSequence)), strings.ToUpper(string(genometile.Sequence)), time.Second)
359 for _, v := range vars {
360 if cmd.outputFormat.PadLeft {
364 log.Debugf("%s seq %s phase %d tag %d tile diff %s\n", cg.Name, seqname, phase, libref.Tag, v.String())
365 varslice := variantAt[v.Position]
367 varslice = make([]hgvs.Variant, len(cgs)*2)
368 variantAt[v.Position] = varslice
370 varslice[cgidx*2+phase] = v
374 refpos += len(reftile.Sequence) - taglen
376 // Flush entries from variantAt that are behind
377 // refpos. Flush all entries if this is the last
378 // reftile of the path/chromosome.
380 lastrefstep := refstep == len(reftiles)-1
381 for pos := range variantAt {
382 if lastrefstep || pos <= refpos {
383 flushpos = append(flushpos, pos)
386 sort.Slice(flushpos, func(i, j int) bool { return flushpos[i] < flushpos[j] })
387 for _, pos := range flushpos {
388 varslice := variantAt[pos]
389 delete(variantAt, pos)
390 for i := range varslice {
391 if varslice[i].Position == 0 {
392 varslice[i].Position = pos
395 cmd.outputFormat.Print(outw, seqname, varslice)
397 if bedw != nil && len(reftile.Sequence) > 0 {
398 tilestart := refpos - len(reftile.Sequence) + taglen
403 thickstart := tilestart + taglen
409 // coverage score, 0 to 1000
412 score = 1000 * tagcoverage / len(cgs) / 2
415 fmt.Fprintf(bedw, "%s %d %d %d %d . %d %d\n",
416 seqname, tilestart, tileend,
419 thickstart, thickend)
424 func printVCF(out io.Writer, seqname string, varslice []hgvs.Variant) {
425 refs := map[string]map[string]int{}
426 for _, v := range varslice {
427 if v.Ref == "" && v.New == "" {
432 alts = map[string]int{}
437 for ref, alts := range refs {
438 var altslice []string
439 for alt := range alts {
440 altslice = append(altslice, alt)
442 sort.Strings(altslice)
443 for i, a := range altslice {
446 fmt.Fprintf(out, "%s\t%d\t%s\t%s", seqname, varslice[0].Position, ref, strings.Join(altslice, ","))
447 for i := 0; i < len(varslice); i += 2 {
448 v1, v2 := varslice[i], varslice[i+1]
449 a1, a2 := alts[v1.New], alts[v2.New]
456 fmt.Fprintf(out, "\t%d/%d", a1, a2)
458 out.Write([]byte{'\n'})
462 func printHGVS(out io.Writer, seqname string, varslice []hgvs.Variant) {
463 for i := 0; i < len(varslice)/2; i++ {
465 out.Write([]byte{'\t'})
467 var1, var2 := varslice[i*2], varslice[i*2+1]
469 if var1.Ref == var1.New {
470 out.Write([]byte{'.'})
472 fmt.Fprintf(out, "%s:g.%s", seqname, var1.String())
475 fmt.Fprintf(out, "%s:g.[%s];[%s]", seqname, var1.String(), var2.String())
478 out.Write([]byte{'\n'})