Add CalledBases to stats.
[lightning.git] / export.go
1 package main
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         "sort"
15         "strings"
16         "sync"
17         "time"
18
19         "git.arvados.org/arvados.git/sdk/go/arvados"
20         "github.com/arvados/lightning/hgvs"
21         log "github.com/sirupsen/logrus"
22 )
23
24 type outputFormat struct {
25         Print   func(out io.Writer, seqname string, varslice []hgvs.Variant)
26         PadLeft bool
27 }
28
29 var (
30         outputFormats = map[string]outputFormat{
31                 "hgvs": outputFormatHGVS,
32                 "vcf":  outputFormatVCF,
33         }
34         outputFormatHGVS = outputFormat{Print: printHGVS}
35         outputFormatVCF  = outputFormat{Print: printVCF, PadLeft: true}
36 )
37
38 type exporter struct {
39         outputFormat outputFormat
40 }
41
42 func (cmd *exporter) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
43         var err error
44         defer func() {
45                 if err != nil {
46                         fmt.Fprintf(stderr, "%s\n", err)
47                 }
48         }()
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 {
63                 err = nil
64                 return 0
65         } else if err != nil {
66                 return 2
67         }
68
69         if f, ok := outputFormats[*outputFormatStr]; !ok {
70                 err = fmt.Errorf("invalid output format %q", *outputFormatStr)
71                 return 2
72         } else {
73                 cmd.outputFormat = f
74         }
75
76         if *pprof != "" {
77                 go func() {
78                         log.Println(http.ListenAndServe(*pprof, nil))
79                 }()
80         }
81
82         if !*runlocal {
83                 if *outputFilename != "-" {
84                         err = errors.New("cannot specify output file in container mode: not implemented")
85                         return 1
86                 }
87                 runner := arvadosContainerRunner{
88                         Name:        "lightning export",
89                         Client:      arvados.NewClientFromEnv(),
90                         ProjectUUID: *projectUUID,
91                         RAM:         240000000000,
92                         VCPUs:       32,
93                         Priority:    *priority,
94                 }
95                 err = runner.TranslatePaths(inputFilename)
96                 if err != nil {
97                         return 1
98                 }
99                 if *outputBed != "" {
100                         if strings.Contains(*outputBed, "/") {
101                                 err = fmt.Errorf("cannot use -output-bed filename %q containing '/' char", *outputBed)
102                                 return 1
103                         }
104                         *outputBed = "/mnt/output/" + *outputBed
105                 }
106                 runner.Args = []string{"export", "-local=true", "-pick", *pick, "-ref", *refname, "-output-format", *outputFormatStr, "-output-bed", *outputBed, "-i", *inputFilename, "-o", "/mnt/output/export.csv"}
107                 var output string
108                 output, err = runner.Run()
109                 if err != nil {
110                         return 1
111                 }
112                 fmt.Fprintln(stdout, output+"/export.csv")
113                 return 0
114         }
115
116         input, err := os.Open(*inputFilename)
117         if err != nil {
118                 return 1
119         }
120         defer input.Close()
121
122         // Error out early if seeking doesn't work on the input file.
123         _, err = input.Seek(0, io.SeekEnd)
124         if err != nil {
125                 return 1
126         }
127         _, err = input.Seek(0, io.SeekStart)
128         if err != nil {
129                 return 1
130         }
131
132         var mtx sync.Mutex
133         var cgs []CompactGenome
134         tilelib := tileLibrary{
135                 includeNoCalls: true,
136         }
137         err = tilelib.LoadGob(context.Background(), input, func(cg CompactGenome) {
138                 if *pick != "" && *pick != cg.Name {
139                         return
140                 }
141                 log.Debugf("export: pick %q", cg.Name)
142                 mtx.Lock()
143                 defer mtx.Unlock()
144                 cgs = append(cgs, cg)
145         })
146         if err != nil {
147                 return 1
148         }
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))
151
152         refseq, ok := tilelib.refseqs[*refname]
153         if !ok {
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)
157                         }
158                         return
159                 }())
160                 return 1
161         }
162
163         _, err = input.Seek(0, io.SeekStart)
164         if err != nil {
165                 return 1
166         }
167
168         var output io.WriteCloser
169         if *outputFilename == "-" {
170                 output = nopCloser{stdout}
171         } else {
172                 output, err = os.OpenFile(*outputFilename, os.O_CREATE|os.O_WRONLY, 0666)
173                 if err != nil {
174                         return 1
175                 }
176                 defer output.Close()
177         }
178         bufw := bufio.NewWriter(output)
179
180         var bedout *os.File
181         var bedbufw *bufio.Writer
182         if *outputBed != "" {
183                 bedout, err = os.OpenFile(*outputBed, os.O_CREATE|os.O_WRONLY, 0666)
184                 if err != nil {
185                         return 1
186                 }
187                 defer bedout.Close()
188                 bedbufw = bufio.NewWriter(bedout)
189         }
190
191         err = cmd.export(bufw, bedout, input, tilelib.taglib.keylen, refseq, cgs)
192         if err != nil {
193                 return 1
194         }
195         err = bufw.Flush()
196         if err != nil {
197                 return 1
198         }
199         err = output.Close()
200         if err != nil {
201                 return 1
202         }
203         if bedout != nil {
204                 err = bedbufw.Flush()
205                 if err != nil {
206                         return 1
207                 }
208                 err = bedout.Close()
209                 if err != nil {
210                         return 1
211                 }
212         }
213         err = input.Close()
214         if err != nil {
215                 return 1
216         }
217         return 0
218 }
219
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 {
227                                 need[libref] = true
228                         }
229                 }
230         }
231         sort.Strings(seqnames)
232
233         for _, cg := range cgs {
234                 for i, variant := range cg.Variants {
235                         if variant == 0 {
236                                 continue
237                         }
238                         libref := tileLibRef{Tag: tagID(i / 2), Variant: variant}
239                         need[libref] = true
240                 }
241         }
242
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}
248                         if need[libref] {
249                                 tileVariant[libref] = tv
250                         }
251                 }
252                 return nil
253         })
254         if err != nil {
255                 return err
256         }
257
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)
263                 }
264         }
265         if len(missing) > 0 {
266                 if limit := 100; len(missing) > limit {
267                         log.Warnf("first %d missing tiles: %v", limit, missing[:limit])
268                 } else {
269                         log.Warnf("missing tiles: %v", missing)
270                 }
271                 return fmt.Errorf("%d needed tiles are missing from library", len(missing))
272         }
273
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 {
279                 seqname := seqname
280                 outbuf := &outbuf[seqidx]
281                 bedbuf := &bedbuf[seqidx]
282                 if bedout == nil {
283                         bedbuf = nil
284                 }
285                 // TODO: limit number of goroutines and unflushed bufs to ncpus
286                 wg.Add(1)
287                 go func() {
288                         defer wg.Done()
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())
291                 }()
292         }
293         wg.Wait()
294
295         wg.Add(1)
296         go func() {
297                 defer wg.Done()
298                 for i, seqname := range seqnames {
299                         log.Infof("writing outbuf %s", seqname)
300                         io.Copy(out, &outbuf[i])
301                 }
302         }()
303         if bedout != nil {
304                 wg.Add(1)
305                 go func() {
306                         defer wg.Done()
307                         for i, seqname := range seqnames {
308                                 log.Infof("writing bedbuf %s", seqname)
309                                 io.Copy(bedout, &bedbuf[i])
310                         }
311                 }()
312         }
313         wg.Wait()
314         return nil
315 }
316
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) {
320         refpos := 0
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 {
328                                         continue
329                                 }
330                                 variant := cg.Variants[int(libref.Tag)*2+phase]
331                                 if variant == 0 {
332                                         continue
333                                 }
334                                 tagcoverage++
335                                 genometile := tileVariant[tileLibRef{Tag: libref.Tag, Variant: variant}]
336                                 if variant == libref.Variant {
337                                         continue
338                                 }
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...)
347                                         }
348                                         refSequence = append(refSequence, tileVariant[reftiles[refstepend]].Sequence...)
349                                         refstepend++
350                                 }
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 {
355                                                 v = v.PadLeft()
356                                         }
357                                         v.Position += refpos
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]
360                                         if varslice == nil {
361                                                 varslice = make([]hgvs.Variant, len(cgs)*2)
362                                                 variantAt[v.Position] = varslice
363                                         }
364                                         varslice[cgidx*2+phase] = v
365                                 }
366                         }
367                 }
368                 refpos += len(reftile.Sequence) - taglen
369
370                 // Flush entries from variantAt that are behind
371                 // refpos. Flush all entries if this is the last
372                 // reftile of the path/chromosome.
373                 var flushpos []int
374                 lastrefstep := refstep == len(reftiles)-1
375                 for pos := range variantAt {
376                         if lastrefstep || pos <= refpos {
377                                 flushpos = append(flushpos, pos)
378                         }
379                 }
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
387                                 }
388                         }
389                         cmd.outputFormat.Print(outw, seqname, varslice)
390                 }
391                 if bedw != nil && len(reftile.Sequence) > 0 {
392                         tilestart := refpos - len(reftile.Sequence) + taglen
393                         tileend := refpos
394                         if !lastrefstep {
395                                 tileend += taglen
396                         }
397                         thickstart := tilestart + taglen
398                         if refstep == 0 {
399                                 thickstart = 0
400                         }
401                         thickend := refpos
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,
406                                 libref.Tag,
407                                 score,
408                                 thickstart, thickend)
409                 }
410         }
411 }
412
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 == "" {
417                         continue
418                 }
419                 alts := refs[v.Ref]
420                 if alts == nil {
421                         alts = map[string]int{}
422                         refs[v.Ref] = alts
423                 }
424                 alts[v.New] = 0
425         }
426         for ref, alts := range refs {
427                 var altslice []string
428                 for alt := range alts {
429                         altslice = append(altslice, alt)
430                 }
431                 sort.Strings(altslice)
432                 for i, a := range altslice {
433                         alts[a] = i + 1
434                 }
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]
439                         if v1.Ref != ref {
440                                 a1 = 0
441                         }
442                         if v2.Ref != ref {
443                                 a2 = 0
444                         }
445                         fmt.Fprintf(out, "\t%d/%d", a1, a2)
446                 }
447                 out.Write([]byte{'\n'})
448         }
449 }
450
451 func printHGVS(out io.Writer, seqname string, varslice []hgvs.Variant) {
452         for i := 0; i < len(varslice)/2; i++ {
453                 if i > 0 {
454                         out.Write([]byte{'\t'})
455                 }
456                 var1, var2 := varslice[i*2], varslice[i*2+1]
457                 if var1 == var2 {
458                         if var1.Ref == var1.New {
459                                 out.Write([]byte{'.'})
460                         } else {
461                                 fmt.Fprintf(out, "%s:g.%s", seqname, var1.String())
462                         }
463                 } else {
464                         fmt.Fprintf(out, "%s:g.[%s];[%s]", seqname, var1.String(), var2.String())
465                 }
466         }
467         out.Write([]byte{'\n'})
468 }