More memory + direct Keep access for merge and exportnumpy.
[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                 retainNoCalls: true,
136         }
137         err = tilelib.LoadGob(context.Background(), input, strings.HasSuffix(*inputFilename, ".gz"), 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, strings.HasSuffix(*inputFilename, ".gz"), 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, 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 {
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, gz, 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                                 if variant == libref.Variant {
336                                         continue
337                                 }
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
343                                         continue
344                                 }
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...)
353                                         }
354                                         refSequence = append(refSequence, tileVariant[reftiles[refstepend]].Sequence...)
355                                         refstepend++
356                                 }
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 {
361                                                 v = v.PadLeft()
362                                         }
363                                         v.Position += refpos
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]
366                                         if varslice == nil {
367                                                 varslice = make([]hgvs.Variant, len(cgs)*2)
368                                                 variantAt[v.Position] = varslice
369                                         }
370                                         varslice[cgidx*2+phase] = v
371                                 }
372                         }
373                 }
374                 refpos += len(reftile.Sequence) - taglen
375
376                 // Flush entries from variantAt that are behind
377                 // refpos. Flush all entries if this is the last
378                 // reftile of the path/chromosome.
379                 var flushpos []int
380                 lastrefstep := refstep == len(reftiles)-1
381                 for pos := range variantAt {
382                         if lastrefstep || pos <= refpos {
383                                 flushpos = append(flushpos, pos)
384                         }
385                 }
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
393                                 }
394                         }
395                         cmd.outputFormat.Print(outw, seqname, varslice)
396                 }
397                 if bedw != nil && len(reftile.Sequence) > 0 {
398                         tilestart := refpos - len(reftile.Sequence) + taglen
399                         tileend := refpos
400                         if !lastrefstep {
401                                 tileend += taglen
402                         }
403                         thickstart := tilestart + taglen
404                         if refstep == 0 {
405                                 thickstart = 0
406                         }
407                         thickend := refpos
408
409                         // coverage score, 0 to 1000
410                         score := 1000
411                         if len(cgs) > 0 {
412                                 score = 1000 * tagcoverage / len(cgs) / 2
413                         }
414
415                         fmt.Fprintf(bedw, "%s %d %d %d %d . %d %d\n",
416                                 seqname, tilestart, tileend,
417                                 libref.Tag,
418                                 score,
419                                 thickstart, thickend)
420                 }
421         }
422 }
423
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 == "" {
428                         continue
429                 }
430                 alts := refs[v.Ref]
431                 if alts == nil {
432                         alts = map[string]int{}
433                         refs[v.Ref] = alts
434                 }
435                 alts[v.New] = 0
436         }
437         for ref, alts := range refs {
438                 var altslice []string
439                 for alt := range alts {
440                         altslice = append(altslice, alt)
441                 }
442                 sort.Strings(altslice)
443                 for i, a := range altslice {
444                         alts[a] = i + 1
445                 }
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]
450                         if v1.Ref != ref {
451                                 a1 = 0
452                         }
453                         if v2.Ref != ref {
454                                 a2 = 0
455                         }
456                         fmt.Fprintf(out, "\t%d/%d", a1, a2)
457                 }
458                 out.Write([]byte{'\n'})
459         }
460 }
461
462 func printHGVS(out io.Writer, seqname string, varslice []hgvs.Variant) {
463         for i := 0; i < len(varslice)/2; i++ {
464                 if i > 0 {
465                         out.Write([]byte{'\t'})
466                 }
467                 var1, var2 := varslice[i*2], varslice[i*2+1]
468                 if var1 == var2 {
469                         if var1.Ref == var1.New {
470                                 out.Write([]byte{'.'})
471                         } else {
472                                 fmt.Fprintf(out, "%s:g.%s", seqname, var1.String())
473                         }
474                 } else {
475                         fmt.Fprintf(out, "%s:g.[%s];[%s]", seqname, var1.String(), var2.String())
476                 }
477         }
478         out.Write([]byte{'\n'})
479 }