Adjust memory.
[lightning.git] / export.go
1 package lightning
2
3 import (
4         "bufio"
5         "bytes"
6         "context"
7         "errors"
8         "flag"
9         "fmt"
10         "io"
11         "net/http"
12         _ "net/http/pprof"
13         "os"
14         "path"
15         "runtime"
16         "sort"
17         "strings"
18         "sync"
19         "time"
20
21         "git.arvados.org/arvados.git/sdk/go/arvados"
22         "github.com/arvados/lightning/hgvs"
23         log "github.com/sirupsen/logrus"
24 )
25
26 type outputFormat struct {
27         Print   func(out io.Writer, seqname string, varslice []hgvs.Variant)
28         PadLeft bool
29 }
30
31 var (
32         outputFormats = map[string]outputFormat{
33                 "hgvs-onehot": outputFormatHGVSOneHot,
34                 "hgvs":        outputFormatHGVS,
35                 "vcf":         outputFormatVCF,
36         }
37         outputFormatHGVS       = outputFormat{Print: printHGVS}
38         outputFormatHGVSOneHot = outputFormat{Print: printHGVSOneHot}
39         outputFormatVCF        = outputFormat{Print: printVCF, PadLeft: true}
40 )
41
42 type exporter struct {
43         outputFormat outputFormat
44         maxTileSize  int
45 }
46
47 func (cmd *exporter) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
48         var err error
49         defer func() {
50                 if err != nil {
51                         fmt.Fprintf(stderr, "%s\n", err)
52                 }
53         }()
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 {
70                 err = nil
71                 return 0
72         } else if err != nil {
73                 return 2
74         }
75
76         if f, ok := outputFormats[*outputFormatStr]; !ok {
77                 err = fmt.Errorf("invalid output format %q", *outputFormatStr)
78                 return 2
79         } else {
80                 cmd.outputFormat = f
81         }
82
83         if *pprof != "" {
84                 go func() {
85                         log.Println(http.ListenAndServe(*pprof, nil))
86                 }()
87         }
88         if *pprofdir != "" {
89                 go writeProfilesPeriodically(*pprofdir)
90         }
91
92         if !*runlocal {
93                 if *outputFilename != "-" {
94                         err = errors.New("cannot specify output file in container mode: not implemented")
95                         return 1
96                 }
97                 runner := arvadosContainerRunner{
98                         Name:        "lightning export",
99                         Client:      arvados.NewClientFromEnv(),
100                         ProjectUUID: *projectUUID,
101                         RAM:         700000000000,
102                         VCPUs:       64,
103                         Priority:    *priority,
104                 }
105                 err = runner.TranslatePaths(inputFilename)
106                 if err != nil {
107                         return 1
108                 }
109                 if *outputBed != "" {
110                         if strings.Contains(*outputBed, "/") {
111                                 err = fmt.Errorf("cannot use -output-bed filename %q containing '/' char", *outputBed)
112                                 return 1
113                         }
114                         *outputBed = "/mnt/output/" + *outputBed
115                 }
116                 runner.Args = []string{"export", "-local=true",
117                         "-pprof", ":6000",
118                         "-pprof-dir", "/mnt/output",
119                         "-ref", *refname,
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",
126                 }
127                 var output string
128                 output, err = runner.Run()
129                 if err != nil {
130                         return 1
131                 }
132                 fmt.Fprintln(stdout, output+"/export.csv")
133                 return 0
134         }
135
136         in, err := open(*inputFilename)
137         if err != nil {
138                 return 1
139         }
140         defer in.Close()
141         input, ok := in.(io.ReadSeeker)
142         if !ok {
143                 err = fmt.Errorf("%s: %T cannot seek", *inputFilename, in)
144                 return 1
145         }
146
147         // Error out early if seeking doesn't work on the input file.
148         _, err = input.Seek(0, io.SeekEnd)
149         if err != nil {
150                 return 1
151         }
152         _, err = input.Seek(0, io.SeekStart)
153         if err != nil {
154                 return 1
155         }
156
157         var cgs []CompactGenome
158         tilelib := &tileLibrary{
159                 retainNoCalls:  true,
160                 compactGenomes: map[string][]tileVariantID{},
161         }
162         err = tilelib.LoadGob(context.Background(), input, strings.HasSuffix(*inputFilename, ".gz"), nil)
163         if err != nil {
164                 return 1
165         }
166
167         refseq, ok := tilelib.refseqs[*refname]
168         if !ok {
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)
172                         }
173                         return
174                 }())
175                 return 1
176         }
177
178         names := cgnames(tilelib)
179         for _, name := range names {
180                 cgs = append(cgs, CompactGenome{Name: name, Variants: tilelib.compactGenomes[name]})
181         }
182         if *labelsFilename != "" {
183                 log.Infof("writing labels to %s", *labelsFilename)
184                 var f *os.File
185                 f, err = os.OpenFile(*labelsFilename, os.O_CREATE|os.O_WRONLY, 0777)
186                 if err != nil {
187                         return 1
188                 }
189                 defer f.Close()
190                 _, outBasename := path.Split(*outputFilename)
191                 for i, name := range names {
192                         _, err = fmt.Fprintf(f, "%d,%q,%q\n", i, trimFilenameForLabel(name), outBasename)
193                         if err != nil {
194                                 err = fmt.Errorf("write %s: %w", *labelsFilename, err)
195                                 return 1
196                         }
197                 }
198                 err = f.Close()
199                 if err != nil {
200                         err = fmt.Errorf("close %s: %w", *labelsFilename, err)
201                         return 1
202                 }
203         }
204
205         _, err = input.Seek(0, io.SeekStart)
206         if err != nil {
207                 return 1
208         }
209
210         var output io.WriteCloser
211         if *outputFilename == "-" {
212                 output = nopCloser{stdout}
213         } else {
214                 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0666)
215                 if err != nil {
216                         return 1
217                 }
218                 defer output.Close()
219         }
220         bufw := bufio.NewWriter(output)
221
222         var bedout *os.File
223         var bedbufw *bufio.Writer
224         if *outputBed != "" {
225                 bedout, err = os.OpenFile(*outputBed, os.O_CREATE|os.O_WRONLY, 0666)
226                 if err != nil {
227                         return 1
228                 }
229                 defer bedout.Close()
230                 bedbufw = bufio.NewWriter(bedout)
231         }
232
233         err = cmd.export(bufw, bedout, input, strings.HasSuffix(*inputFilename, ".gz"), tilelib, refseq, cgs)
234         if err != nil {
235                 return 1
236         }
237         err = bufw.Flush()
238         if err != nil {
239                 return 1
240         }
241         err = output.Close()
242         if err != nil {
243                 return 1
244         }
245         if bedout != nil {
246                 err = bedbufw.Flush()
247                 if err != nil {
248                         return 1
249                 }
250                 err = bedout.Close()
251                 if err != nil {
252                         return 1
253                 }
254         }
255         err = in.Close()
256         if err != nil {
257                 return 1
258         }
259         return 0
260 }
261
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 {
269                                 need[libref] = true
270                         }
271                 }
272         }
273         sort.Strings(seqnames)
274
275         for _, cg := range cgs {
276                 for i, variant := range cg.Variants {
277                         if variant == 0 {
278                                 continue
279                         }
280                         libref := tileLibRef{Tag: tagID(i / 2), Variant: variant}
281                         need[libref] = true
282                 }
283         }
284
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)
290                         if need[libref] {
291                                 tileVariant[libref] = tv
292                         }
293                 }
294                 return nil
295         })
296         if err != nil {
297                 return err
298         }
299
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)
305                 }
306         }
307         if len(missing) > 0 {
308                 if limit := 100; len(missing) > limit {
309                         log.Warnf("first %d missing tiles: %v", limit, missing[:limit])
310                 } else {
311                         log.Warnf("missing tiles: %v", missing)
312                 }
313                 return fmt.Errorf("%d needed tiles are missing from library", len(missing))
314         }
315
316         outw := make([]io.WriteCloser, len(seqnames))
317         bedw := make([]io.WriteCloser, len(seqnames))
318
319         var merges sync.WaitGroup
320         merge := func(dst io.Writer, src []io.WriteCloser, label string) {
321                 var mtx sync.Mutex
322                 for i, seqname := range seqnames {
323                         pr, pw := io.Pipe()
324                         src[i] = pw
325                         merges.Add(1)
326                         seqname := seqname
327                         go func() {
328                                 defer merges.Done()
329                                 log.Infof("writing %s %s", seqname, label)
330                                 scanner := bufio.NewScanner(pr)
331                                 for scanner.Scan() {
332                                         mtx.Lock()
333                                         dst.Write(scanner.Bytes())
334                                         dst.Write([]byte{'\n'})
335                                         mtx.Unlock()
336                                 }
337                                 log.Infof("writing %s %s done", seqname, label)
338                         }()
339                 }
340         }
341         merge(out, outw, "output")
342         if bedout != nil {
343                 merge(bedout, bedw, "bed")
344         }
345
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
350                 outw := outw[seqidx]
351                 bedw := bedw[seqidx]
352                 throttle.Acquire()
353                 go func() {
354                         defer throttle.Release()
355                         if bedw != nil {
356                                 defer bedw.Close()
357                         }
358                         defer outw.Close()
359                         outwb := bufio.NewWriter(outw)
360                         defer outwb.Flush()
361                         cmd.exportSeq(outwb, bedw, tilelib.taglib.keylen, seqname, refseq[seqname], tileVariant, cgs)
362                 }()
363         }
364
365         merges.Wait()
366         return nil
367 }
368
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) {
372         refpos := 0
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 {
380                                         continue
381                                 }
382                                 variant := cg.Variants[int(libref.Tag)*2+phase]
383                                 if variant == 0 {
384                                         continue
385                                 }
386                                 tagcoverage++
387                                 if variant == libref.Variant {
388                                         continue
389                                 }
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
395                                         continue
396                                 }
397                                 if len(genometile.Sequence) > cmd.maxTileSize {
398                                         continue
399                                 }
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...)
408                                         }
409                                         refSequence = append(refSequence, tileVariant[reftiles[refstepend]].Sequence...)
410                                         refstepend++
411                                 }
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 {
416                                                 v = v.PadLeft()
417                                         }
418                                         v.Position += refpos
419                                         varslice := variantAt[v.Position]
420                                         if varslice == nil {
421                                                 varslice = make([]hgvs.Variant, len(cgs)*2)
422                                                 variantAt[v.Position] = varslice
423                                         }
424                                         varslice[cgidx*2+phase] = v
425                                 }
426                         }
427                 }
428                 refpos += len(reftile.Sequence) - taglen
429
430                 // Flush entries from variantAt that are behind
431                 // refpos. Flush all entries if this is the last
432                 // reftile of the path/chromosome.
433                 var flushpos []int
434                 lastrefstep := refstep == len(reftiles)-1
435                 for pos := range variantAt {
436                         if lastrefstep || pos <= refpos {
437                                 flushpos = append(flushpos, pos)
438                         }
439                 }
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
447                                 }
448                         }
449                         cmd.outputFormat.Print(outw, seqname, varslice)
450                 }
451                 if bedw != nil && len(reftile.Sequence) > 0 {
452                         tilestart := refpos - len(reftile.Sequence) + taglen
453                         tileend := refpos
454                         if !lastrefstep {
455                                 tileend += taglen
456                         }
457                         thickstart := tilestart + taglen
458                         if refstep == 0 {
459                                 thickstart = 0
460                         }
461                         thickend := refpos
462
463                         // coverage score, 0 to 1000
464                         score := 1000
465                         if len(cgs) > 0 {
466                                 score = 1000 * tagcoverage / len(cgs) / 2
467                         }
468
469                         fmt.Fprintf(bedw, "%s %d %d %d %d . %d %d\n",
470                                 seqname, tilestart, tileend,
471                                 libref.Tag,
472                                 score,
473                                 thickstart, thickend)
474                 }
475         }
476 }
477
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 == "" {
482                         continue
483                 }
484                 alts := refs[v.Ref]
485                 if alts == nil {
486                         alts = map[string]int{}
487                         refs[v.Ref] = alts
488                 }
489                 alts[v.New] = 0
490         }
491         for ref, alts := range refs {
492                 var altslice []string
493                 for alt := range alts {
494                         altslice = append(altslice, alt)
495                 }
496                 sort.Strings(altslice)
497                 for i, a := range altslice {
498                         alts[a] = i + 1
499                 }
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]
504                         if v1.Ref != ref {
505                                 a1 = 0
506                         }
507                         if v2.Ref != ref {
508                                 a2 = 0
509                         }
510                         fmt.Fprintf(out, "\t%d/%d", a1, a2)
511                 }
512                 out.Write([]byte{'\n'})
513         }
514 }
515
516 func printHGVS(out io.Writer, seqname string, varslice []hgvs.Variant) {
517         for i := 0; i < len(varslice)/2; i++ {
518                 if i > 0 {
519                         out.Write([]byte{'\t'})
520                 }
521                 var1, var2 := varslice[i*2], varslice[i*2+1]
522                 if var1 == var2 {
523                         if var1.Ref == var1.New {
524                                 out.Write([]byte{'.'})
525                         } else {
526                                 fmt.Fprintf(out, "%s:g.%s", seqname, var1.String())
527                         }
528                 } else {
529                         fmt.Fprintf(out, "%s:g.[%s];[%s]", seqname, var1.String(), var2.String())
530                 }
531         }
532         out.Write([]byte{'\n'})
533 }
534
535 func printHGVSOneHot(out io.Writer, seqname string, varslice []hgvs.Variant) {
536         vars := map[hgvs.Variant]bool{}
537         for _, v := range varslice {
538                 if v.Ref != v.New {
539                         vars[v] = true
540                 }
541         }
542
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)
547         }
548         sort.Slice(sorted, func(a, b int) bool { return hgvs.Less(sorted[a], sorted[b]) })
549
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"))
555                         } else {
556                                 out.Write([]byte("\t0"))
557                         }
558                 }
559                 out.Write([]byte{'\n'})
560         }
561 }