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{
135 includeNoCalls: true,
137 err = tilelib.LoadGob(context.Background(), input, 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, tilelib.taglib.keylen, refseq, cgs)
204 err = bedbufw.Flush()
220 func (cmd *exporter) export(out, bedout io.Writer, librdr io.Reader, 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, 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 genometile := tileVariant[tileLibRef{Tag: libref.Tag, Variant: variant}]
336 if variant == libref.Variant {
339 refSequence := reftile.Sequence
340 // If needed, extend the reference
341 // sequence up to the tag at the end
342 // of the genometile sequence.
343 refstepend := refstep + 1
344 for refstepend < len(reftiles) && len(refSequence) >= taglen && !bytes.EqualFold(refSequence[len(refSequence)-taglen:], genometile.Sequence[len(genometile.Sequence)-taglen:]) {
345 if &refSequence[0] == &reftile.Sequence[0] {
346 refSequence = append([]byte(nil), refSequence...)
348 refSequence = append(refSequence, tileVariant[reftiles[refstepend]].Sequence...)
351 // (TODO: handle no-calls)
352 vars, _ := hgvs.Diff(strings.ToUpper(string(refSequence)), strings.ToUpper(string(genometile.Sequence)), time.Second)
353 for _, v := range vars {
354 if cmd.outputFormat.PadLeft {
358 log.Debugf("%s seq %s phase %d tag %d tile diff %s\n", cg.Name, seqname, phase, libref.Tag, v.String())
359 varslice := variantAt[v.Position]
361 varslice = make([]hgvs.Variant, len(cgs)*2)
362 variantAt[v.Position] = varslice
364 varslice[cgidx*2+phase] = v
368 refpos += len(reftile.Sequence) - taglen
370 // Flush entries from variantAt that are behind
371 // refpos. Flush all entries if this is the last
372 // reftile of the path/chromosome.
374 lastrefstep := refstep == len(reftiles)-1
375 for pos := range variantAt {
376 if lastrefstep || pos <= refpos {
377 flushpos = append(flushpos, pos)
380 sort.Slice(flushpos, func(i, j int) bool { return flushpos[i] < flushpos[j] })
381 for _, pos := range flushpos {
382 varslice := variantAt[pos]
383 delete(variantAt, pos)
384 for i := range varslice {
385 if varslice[i].Position == 0 {
386 varslice[i].Position = pos
389 cmd.outputFormat.Print(outw, seqname, varslice)
391 if bedw != nil && len(reftile.Sequence) > 0 {
392 tilestart := refpos - len(reftile.Sequence) + taglen
397 thickstart := tilestart + taglen
402 // coverage score, 0 to 1000
403 score := 1000 * tagcoverage / len(cgs) / 2
404 fmt.Fprintf(bedw, "%s %d %d %d %d . %d %d\n",
405 seqname, tilestart, tileend,
408 thickstart, thickend)
413 func printVCF(out io.Writer, seqname string, varslice []hgvs.Variant) {
414 refs := map[string]map[string]int{}
415 for _, v := range varslice {
416 if v.Ref == "" && v.New == "" {
421 alts = map[string]int{}
426 for ref, alts := range refs {
427 var altslice []string
428 for alt := range alts {
429 altslice = append(altslice, alt)
431 sort.Strings(altslice)
432 for i, a := range altslice {
435 fmt.Fprintf(out, "%s\t%d\t%s\t%s", seqname, varslice[0].Position, ref, strings.Join(altslice, ","))
436 for i := 0; i < len(varslice); i += 2 {
437 v1, v2 := varslice[i], varslice[i+1]
438 a1, a2 := alts[v1.New], alts[v2.New]
445 fmt.Fprintf(out, "\t%d/%d", a1, a2)
447 out.Write([]byte{'\n'})
451 func printHGVS(out io.Writer, seqname string, varslice []hgvs.Variant) {
452 for i := 0; i < len(varslice)/2; i++ {
454 out.Write([]byte{'\t'})
456 var1, var2 := varslice[i*2], varslice[i*2+1]
458 if var1.Ref == var1.New {
459 out.Write([]byte{'.'})
461 fmt.Fprintf(out, "%s:g.%s", seqname, var1.String())
464 fmt.Fprintf(out, "%s:g.[%s];[%s]", seqname, var1.String(), var2.String())
467 out.Write([]byte{'\n'})