19566: Merge branch 'main'
[lightning.git] / export.go
1 // Copyright (C) The Lightning Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package lightning
6
7 import (
8         "bufio"
9         "bytes"
10         "context"
11         "errors"
12         "flag"
13         "fmt"
14         "io"
15         "net/http"
16         _ "net/http/pprof"
17         "os"
18         "path/filepath"
19         "runtime"
20         "sort"
21         "strconv"
22         "strings"
23         "sync"
24         "time"
25
26         "git.arvados.org/arvados.git/sdk/go/arvados"
27         "github.com/arvados/lightning/hgvs"
28         "github.com/klauspost/pgzip"
29         "github.com/kshedden/gonpy"
30         "github.com/sirupsen/logrus"
31         log "github.com/sirupsen/logrus"
32 )
33
34 type tvVariant struct {
35         hgvs.Variant
36         librefs map[tileLibRef]bool
37 }
38
39 type outputFormat interface {
40         Filename() string
41         PadLeft() bool
42         Head(out io.Writer, cgs []CompactGenome, cases []bool, p float64) error
43         Print(out io.Writer, seqname string, varslice []tvVariant) error
44         Finish(outdir string, out io.Writer, seqname string) error
45         MaxGoroutines() int
46 }
47
48 var outputFormats = map[string]func() outputFormat{
49         "hgvs-numpy": func() outputFormat {
50                 return &formatHGVSNumpy{alleles: map[string][][]int8{}}
51         },
52         "hgvs-onehot": func() outputFormat { return formatHGVSOneHot{} },
53         "hgvs":        func() outputFormat { return formatHGVS{} },
54         "pvcf":        func() outputFormat { return formatPVCF{} },
55         "vcf":         func() outputFormat { return formatVCF{} },
56 }
57
58 type exporter struct {
59         outputFormat   outputFormat
60         outputPerChrom bool
61         compress       bool
62         maxTileSize    int
63         filter         filter
64         maxPValue      float64
65         cases          []bool
66 }
67
68 func (cmd *exporter) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
69         var err error
70         defer func() {
71                 if err != nil {
72                         fmt.Fprintf(stderr, "%s\n", err)
73                 }
74         }()
75         flags := flag.NewFlagSet("", flag.ContinueOnError)
76         flags.SetOutput(stderr)
77         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
78         pprofdir := flags.String("pprof-dir", "", "write Go profile data to `directory` periodically")
79         runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
80         projectUUID := flags.String("project", "", "project `UUID` for output data")
81         priority := flags.Int("priority", 500, "container request priority")
82         refname := flags.String("ref", "", "reference genome `name`")
83         inputDir := flags.String("input-dir", ".", "input `directory`")
84         cases := flags.String("cases", "", "file indicating which genomes are positive cases (for computing p-values)")
85         flags.Float64Var(&cmd.maxPValue, "p-value", 1, "do chi square test and omit columns with p-value above this threshold")
86         outputDir := flags.String("output-dir", ".", "output `directory`")
87         outputFormatStr := flags.String("output-format", "hgvs", "output `format`: hgvs, pvcf, or vcf")
88         outputBed := flags.String("output-bed", "", "also output bed `file`")
89         flags.BoolVar(&cmd.outputPerChrom, "output-per-chromosome", true, "output one file per chromosome")
90         flags.BoolVar(&cmd.compress, "z", false, "write gzip-compressed output files")
91         labelsFilename := flags.String("output-labels", "", "also output genome labels csv `file`")
92         flags.IntVar(&cmd.maxTileSize, "max-tile-size", 50000, "don't try to make annotations for tiles bigger than given `size`")
93         cmd.filter.Flags(flags)
94         err = flags.Parse(args)
95         if err == flag.ErrHelp {
96                 err = nil
97                 return 0
98         } else if err != nil {
99                 return 2
100         } else if flags.NArg() > 0 {
101                 err = fmt.Errorf("errant command line arguments after parsed flags: %v", flags.Args())
102                 return 2
103         }
104
105         if f, ok := outputFormats[*outputFormatStr]; !ok {
106                 err = fmt.Errorf("invalid output format %q", *outputFormatStr)
107                 return 2
108         } else {
109                 cmd.outputFormat = f()
110         }
111
112         if *pprof != "" {
113                 go func() {
114                         log.Println(http.ListenAndServe(*pprof, nil))
115                 }()
116         }
117         if *pprofdir != "" {
118                 go writeProfilesPeriodically(*pprofdir)
119         }
120
121         if !*runlocal {
122                 if *outputDir != "." {
123                         err = errors.New("cannot specify output directory in container mode: not implemented")
124                         return 1
125                 }
126                 runner := arvadosContainerRunner{
127                         Name:        "lightning export",
128                         Client:      arvados.NewClientFromEnv(),
129                         ProjectUUID: *projectUUID,
130                         RAM:         750000000000,
131                         VCPUs:       96,
132                         Priority:    *priority,
133                         APIAccess:   true,
134                 }
135                 err = runner.TranslatePaths(inputDir, cases)
136                 if err != nil {
137                         return 1
138                 }
139                 if *outputBed != "" {
140                         if strings.Contains(*outputBed, "/") {
141                                 err = fmt.Errorf("cannot use -output-bed filename %q containing '/' char", *outputBed)
142                                 return 1
143                         }
144                         *outputBed = "/mnt/output/" + *outputBed
145                 }
146                 runner.Args = []string{"export", "-local=true",
147                         "-pprof", ":6000",
148                         "-pprof-dir", "/mnt/output",
149                         "-ref", *refname,
150                         "-cases", *cases,
151                         "-p-value", fmt.Sprintf("%f", cmd.maxPValue),
152                         "-output-format", *outputFormatStr,
153                         "-output-bed", *outputBed,
154                         "-output-labels", "/mnt/output/labels.csv",
155                         "-output-per-chromosome=" + fmt.Sprintf("%v", cmd.outputPerChrom),
156                         "-max-tile-size", fmt.Sprintf("%d", cmd.maxTileSize),
157                         "-input-dir", *inputDir,
158                         "-output-dir", "/mnt/output",
159                         "-z=" + fmt.Sprintf("%v", cmd.compress),
160                 }
161                 runner.Args = append(runner.Args, cmd.filter.Args()...)
162                 var output string
163                 output, err = runner.Run()
164                 if err != nil {
165                         return 1
166                 }
167                 fmt.Fprintln(stdout, output)
168                 return 0
169         }
170
171         var cgs []CompactGenome
172         tilelib := &tileLibrary{
173                 retainNoCalls:       true,
174                 retainTileSequences: true,
175                 compactGenomes:      map[string][]tileVariantID{},
176         }
177         err = tilelib.LoadDir(context.Background(), *inputDir)
178         if err != nil {
179                 return 1
180         }
181
182         refseq, ok := tilelib.refseqs[*refname]
183         if !ok {
184                 err = fmt.Errorf("reference name %q not found in input; have %v", *refname, func() (names []string) {
185                         for name := range tilelib.refseqs {
186                                 names = append(names, name)
187                         }
188                         return
189                 }())
190                 return 1
191         }
192
193         log.Infof("filtering: %+v", cmd.filter)
194         cmd.filter.Apply(tilelib)
195
196         names := cgnames(tilelib)
197         for _, name := range names {
198                 cgs = append(cgs, CompactGenome{Name: name, Variants: tilelib.compactGenomes[name]})
199         }
200         if *labelsFilename != "" {
201                 log.Infof("writing labels to %s", *labelsFilename)
202                 var f *os.File
203                 f, err = os.OpenFile(*labelsFilename, os.O_CREATE|os.O_WRONLY, 0777)
204                 if err != nil {
205                         return 1
206                 }
207                 defer f.Close()
208                 for i, name := range names {
209                         _, err = fmt.Fprintf(f, "%d,%q,%q\n", i, trimFilenameForLabel(name), cmd.outputFormat.Filename())
210                         if err != nil {
211                                 err = fmt.Errorf("write %s: %w", *labelsFilename, err)
212                                 return 1
213                         }
214                 }
215                 err = f.Close()
216                 if err != nil {
217                         err = fmt.Errorf("close %s: %w", *labelsFilename, err)
218                         return 1
219                 }
220         }
221
222         cmd.cases = make([]bool, len(names))
223         if *cases != "" {
224                 log.Infof("reading cases file: %s", *cases)
225                 var f io.ReadCloser
226                 f, err = open(*cases)
227                 if err != nil {
228                         return 1
229                 }
230                 defer f.Close()
231                 var buf []byte
232                 buf, err = io.ReadAll(f)
233                 if err != nil {
234                         return 1
235                 }
236                 for _, pattern := range bytes.Split(buf, []byte("\n")) {
237                         if len(pattern) == 0 {
238                                 continue
239                         }
240                         pattern := string(pattern)
241                         idx := -1
242                         for i, name := range names {
243                                 if !strings.Contains(name, pattern) {
244                                         continue
245                                 } else if idx >= 0 {
246                                         err = fmt.Errorf("pattern %q in cases file matches multiple genome IDs: %q, %q", pattern, names[idx], name)
247                                         return 1
248                                 } else {
249                                         idx = i
250                                 }
251                         }
252                         if idx < 0 {
253                                 log.Warnf("pattern %q in cases file does not match any genome IDs", pattern)
254                                 continue
255                         }
256                         cmd.cases[idx] = true
257                 }
258         }
259
260         var bedout io.Writer
261         var bedfile *os.File
262         var bedbufw *bufio.Writer
263         if *outputBed != "" {
264                 bedfile, err = os.OpenFile(*outputBed, os.O_CREATE|os.O_WRONLY, 0666)
265                 if err != nil {
266                         return 1
267                 }
268                 defer bedfile.Close()
269                 bedbufw = bufio.NewWriterSize(bedfile, 16*1024*1024)
270                 bedout = bedbufw
271         }
272
273         err = cmd.export(*outputDir, bedout, tilelib, refseq, cgs)
274         if err != nil {
275                 return 1
276         }
277         if bedout != nil {
278                 err = bedbufw.Flush()
279                 if err != nil {
280                         return 1
281                 }
282                 err = bedfile.Close()
283                 if err != nil {
284                         return 1
285                 }
286         }
287         return 0
288 }
289
290 func (cmd *exporter) export(outdir string, bedout io.Writer, tilelib *tileLibrary, refseq map[string][]tileLibRef, cgs []CompactGenome) error {
291         var seqnames []string
292         var missing []tileLibRef
293         for seqname, librefs := range refseq {
294                 seqnames = append(seqnames, seqname)
295                 for _, libref := range librefs {
296                         if libref.Variant != 0 && tilelib.TileVariantSequence(libref) == nil {
297                                 missing = append(missing, libref)
298                         }
299                 }
300         }
301         sort.Strings(seqnames)
302
303         if len(missing) > 0 {
304                 if limit := 100; len(missing) > limit {
305                         log.Warnf("first %d missing tiles: %v", limit, missing[:limit])
306                 } else {
307                         log.Warnf("missing tiles: %v", missing)
308                 }
309                 return fmt.Errorf("%d needed tiles are missing from library", len(missing))
310         }
311
312         outw := make([]io.WriteCloser, len(seqnames))
313         bedw := make([]io.WriteCloser, len(seqnames))
314
315         var merges sync.WaitGroup
316         merge := func(dst io.Writer, src []io.WriteCloser, label string) {
317                 var mtx sync.Mutex
318                 for i, seqname := range seqnames {
319                         pr, pw := io.Pipe()
320                         src[i] = pw
321                         merges.Add(1)
322                         seqname := seqname
323                         go func() {
324                                 defer merges.Done()
325                                 log.Infof("writing %s %s", seqname, label)
326                                 scanner := bufio.NewScanner(pr)
327                                 for scanner.Scan() {
328                                         mtx.Lock()
329                                         dst.Write(scanner.Bytes())
330                                         dst.Write([]byte{'\n'})
331                                         mtx.Unlock()
332                                 }
333                                 log.Infof("writing %s %s done", seqname, label)
334                         }()
335                 }
336         }
337         if cmd.outputPerChrom {
338                 for i, seqname := range seqnames {
339                         fnm := filepath.Join(outdir, strings.Replace(cmd.outputFormat.Filename(), ".", "."+seqname+".", 1))
340                         if cmd.compress {
341                                 fnm += ".gz"
342                         }
343                         f, err := os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
344                         if err != nil {
345                                 return err
346                         }
347                         defer f.Close()
348                         log.Infof("writing %q", f.Name())
349                         outw[i] = f
350                         if cmd.compress {
351                                 z := pgzip.NewWriter(f)
352                                 defer z.Close()
353                                 outw[i] = z
354                         }
355                         err = cmd.outputFormat.Head(outw[i], cgs, cmd.cases, cmd.maxPValue)
356                         if err != nil {
357                                 return err
358                         }
359                 }
360         } else {
361                 fnm := filepath.Join(outdir, cmd.outputFormat.Filename())
362                 if cmd.compress {
363                         fnm += ".gz"
364                 }
365                 f, err := os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
366                 if err != nil {
367                         return err
368                 }
369                 defer f.Close()
370                 log.Infof("writing %q", fnm)
371                 var out io.Writer = f
372                 if cmd.compress {
373                         z := pgzip.NewWriter(out)
374                         defer z.Close()
375                         out = z
376                 }
377                 cmd.outputFormat.Head(out, cgs, cmd.cases, cmd.maxPValue)
378                 merge(out, outw, "output")
379         }
380         if bedout != nil {
381                 merge(bedout, bedw, "bed")
382         }
383
384         throttle := throttle{Max: runtime.NumCPU()}
385         if max := cmd.outputFormat.MaxGoroutines(); max > 0 {
386                 throttle.Max = max
387         }
388         log.Infof("assembling %d sequences in %d goroutines", len(seqnames), throttle.Max)
389         for seqidx, seqname := range seqnames {
390                 seqidx, seqname := seqidx, seqname
391                 outw := outw[seqidx]
392                 bedw := bedw[seqidx]
393                 throttle.Acquire()
394                 go func() {
395                         defer throttle.Release()
396                         if bedw != nil {
397                                 defer bedw.Close()
398                         }
399                         outwb := bufio.NewWriterSize(outw, 8*1024*1024)
400                         eachVariant(bedw, tilelib.taglib.keylen, seqname, refseq[seqname], tilelib, cgs, cmd.outputFormat.PadLeft(), cmd.maxTileSize, func(varslice []tvVariant) {
401                                 err := cmd.outputFormat.Print(outwb, seqname, varslice)
402                                 throttle.Report(err)
403                         })
404                         err := cmd.outputFormat.Finish(outdir, outwb, seqname)
405                         throttle.Report(err)
406                         err = outwb.Flush()
407                         throttle.Report(err)
408                         err = outw.Close()
409                         throttle.Report(err)
410                 }()
411         }
412
413         merges.Wait()
414         throttle.Wait()
415         return throttle.Err()
416 }
417
418 // Align genome tiles to reference tiles, call callback func on each
419 // variant, and (if bedw is not nil) write tile coverage to bedw.
420 func eachVariant(bedw io.Writer, taglen int, seqname string, reftiles []tileLibRef, tilelib *tileLibrary, cgs []CompactGenome, padLeft bool, maxTileSize int, callback func(varslice []tvVariant)) {
421         t0 := time.Now()
422         progressbar := time.NewTicker(time.Minute)
423         defer progressbar.Stop()
424         var outmtx sync.Mutex
425         defer outmtx.Lock()
426         refpos := 0
427         variantAt := map[int][]tvVariant{} // variantAt[chromOffset][genomeIndex*2+phase]
428         for refstep, libref := range reftiles {
429                 select {
430                 case <-progressbar.C:
431                         var eta interface{}
432                         if refstep > 0 {
433                                 fin := t0.Add(time.Duration(float64(time.Now().Sub(t0)) * float64(len(reftiles)) / float64(refstep)))
434                                 eta = fmt.Sprintf("%v (%v)", fin.Format(time.RFC3339), fin.Sub(time.Now()))
435                         } else {
436                                 eta = "N/A"
437                         }
438                         log.Printf("exportSeq: %s: refstep %d of %d, %.0f/s, ETA %v", seqname, refstep, len(reftiles), float64(refstep)/time.Now().Sub(t0).Seconds(), eta)
439                 default:
440                 }
441                 diffs := map[tileLibRef][]hgvs.Variant{}
442                 refseq := tilelib.TileVariantSequence(libref)
443                 tagcoverage := 0 // number of times the start tag was found in genomes -- max is len(cgs)*2
444                 for cgidx, cg := range cgs {
445                         for phase := 0; phase < 2; phase++ {
446                                 var variant tileVariantID
447                                 if i := int(libref.Tag)*2 + phase; len(cg.Variants) > i {
448                                         variant = cg.Variants[i]
449                                 }
450                                 if variant > 0 {
451                                         tagcoverage++
452                                 }
453                                 if variant == libref.Variant || variant == 0 {
454                                         continue
455                                 }
456                                 glibref := tileLibRef{Tag: libref.Tag, Variant: variant}
457                                 vars, ok := diffs[glibref]
458                                 if !ok {
459                                         genomeseq := tilelib.TileVariantSequence(glibref)
460                                         if len(genomeseq) == 0 {
461                                                 // Hash is known but sequence
462                                                 // is not, e.g., retainNoCalls
463                                                 // was false during import
464                                                 continue
465                                         }
466                                         if len(genomeseq) > maxTileSize {
467                                                 continue
468                                         }
469                                         refSequence := refseq
470                                         // If needed, extend the
471                                         // reference sequence up to
472                                         // the tag at the end of the
473                                         // genomeseq sequence.
474                                         refstepend := refstep + 1
475                                         for refstepend < len(reftiles) && len(refSequence) >= taglen && !bytes.EqualFold(refSequence[len(refSequence)-taglen:], genomeseq[len(genomeseq)-taglen:]) && len(refSequence) <= maxTileSize {
476                                                 if &refSequence[0] == &refseq[0] {
477                                                         refSequence = append([]byte(nil), refSequence...)
478                                                 }
479                                                 refSequence = append(refSequence, tilelib.TileVariantSequence(reftiles[refstepend])...)
480                                                 refstepend++
481                                         }
482                                         // (TODO: handle no-calls)
483                                         if len(refSequence) <= maxTileSize {
484                                                 refstr := strings.ToUpper(string(refSequence))
485                                                 genomestr := strings.ToUpper(string(genomeseq))
486                                                 vars, _ = hgvs.Diff(refstr, genomestr, time.Second)
487                                         }
488                                         diffs[glibref] = vars
489                                 }
490                                 for _, v := range vars {
491                                         if padLeft {
492                                                 v = v.PadLeft()
493                                         }
494                                         v.Position += refpos
495                                         varslice := variantAt[v.Position]
496                                         if varslice == nil {
497                                                 varslice = make([]tvVariant, len(cgs)*2)
498                                                 variantAt[v.Position] = varslice
499                                         }
500                                         varslice[cgidx*2+phase].Variant = v
501                                         if varslice[cgidx*2+phase].librefs == nil {
502                                                 varslice[cgidx*2+phase].librefs = map[tileLibRef]bool{glibref: true}
503                                         } else {
504                                                 varslice[cgidx*2+phase].librefs[glibref] = true
505                                         }
506                                 }
507                         }
508                 }
509                 refpos += len(refseq) - taglen
510
511                 // Flush entries from variantAt that are behind
512                 // refpos. Flush all entries if this is the last
513                 // reftile of the path/chromosome.
514                 flushpos := make([]int, 0, len(variantAt))
515                 lastrefstep := refstep == len(reftiles)-1
516                 for pos := range variantAt {
517                         if lastrefstep || pos <= refpos {
518                                 flushpos = append(flushpos, pos)
519                         }
520                 }
521                 sort.Slice(flushpos, func(i, j int) bool { return flushpos[i] < flushpos[j] })
522                 flushvariants := make([][]tvVariant, len(flushpos))
523                 for i, pos := range flushpos {
524                         varslice := variantAt[pos]
525                         delete(variantAt, pos)
526                         // Check for uninitialized (zero-value)
527                         // elements in varslice
528                         for i := range varslice {
529                                 if varslice[i].Position != 0 {
530                                         // Not a zero-value element
531                                         continue
532                                 }
533                                 // Set the position so
534                                 // varslice[*].Position are all equal
535                                 varslice[i].Position = pos
536                                 // This could be either =ref or a
537                                 // missing/low-quality tile. Figure
538                                 // out which.
539                                 vidx := int(libref.Tag)*2 + i%2
540                                 if vidx >= len(cgs[i/2].Variants) {
541                                         // Missing tile.
542                                         varslice[i].New = "-"
543                                         continue
544                                 }
545                                 v := cgs[i/2].Variants[vidx]
546                                 if v < 1 || len(tilelib.TileVariantSequence(tileLibRef{Tag: libref.Tag, Variant: v})) == 0 {
547                                         // Missing/low-quality tile.
548                                         varslice[i].New = "-" // fasta "gap of indeterminate length"
549                                 }
550                         }
551                         flushvariants[i] = varslice
552                 }
553                 outmtx.Lock()
554                 go func() {
555                         defer outmtx.Unlock()
556                         for _, varslice := range flushvariants {
557                                 callback(varslice)
558                         }
559                 }()
560                 if bedw != nil && len(refseq) > 0 {
561                         tilestart := refpos - len(refseq) + taglen
562                         tileend := refpos
563                         if !lastrefstep {
564                                 tileend += taglen
565                         }
566                         thickstart := tilestart + taglen
567                         if refstep == 0 {
568                                 thickstart = 0
569                         }
570                         thickend := refpos
571
572                         // coverage score, 0 to 1000
573                         score := 1000
574                         if len(cgs) > 0 {
575                                 score = 1000 * tagcoverage / len(cgs) / 2
576                         }
577
578                         fmt.Fprintf(bedw, "%s %d %d %d %d . %d %d\n",
579                                 seqname, tilestart, tileend,
580                                 libref.Tag,
581                                 score,
582                                 thickstart, thickend)
583                 }
584         }
585 }
586
587 func bucketVarsliceByRef(varslice []tvVariant) map[string]map[string]int {
588         byref := map[string]map[string]int{}
589         for _, v := range varslice {
590                 if v.Ref == "" && v.New == "" {
591                         // =ref
592                         continue
593                 }
594                 if v.New == "-" {
595                         // no-call
596                         continue
597                 }
598                 alts := byref[v.Ref]
599                 if alts == nil {
600                         alts = map[string]int{}
601                         byref[v.Ref] = alts
602                 }
603                 alts[v.New]++
604         }
605         return byref
606 }
607
608 type formatVCF struct{}
609
610 func (formatVCF) MaxGoroutines() int                     { return 0 }
611 func (formatVCF) Filename() string                       { return "out.vcf" }
612 func (formatVCF) PadLeft() bool                          { return true }
613 func (formatVCF) Finish(string, io.Writer, string) error { return nil }
614 func (formatVCF) Head(out io.Writer, cgs []CompactGenome, cases []bool, p float64) error {
615         _, err := fmt.Fprint(out, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n")
616         return err
617 }
618 func (formatVCF) Print(out io.Writer, seqname string, varslice []tvVariant) error {
619         for ref, alts := range bucketVarsliceByRef(varslice) {
620                 altslice := make([]string, 0, len(alts))
621                 for alt := range alts {
622                         altslice = append(altslice, alt)
623                 }
624                 sort.Strings(altslice)
625
626                 info := "AC="
627                 for i, a := range altslice {
628                         if i > 0 {
629                                 info += ","
630                         }
631                         info += strconv.Itoa(alts[a])
632                 }
633                 _, err := fmt.Fprintf(out, "%s\t%d\t.\t%s\t%s\t.\t.\t%s\n", seqname, varslice[0].Position, ref, strings.Join(altslice, ","), info)
634                 if err != nil {
635                         return err
636                 }
637         }
638         return nil
639 }
640
641 type formatPVCF struct{}
642
643 func (formatPVCF) MaxGoroutines() int                     { return 0 }
644 func (formatPVCF) Filename() string                       { return "out.vcf" }
645 func (formatPVCF) PadLeft() bool                          { return true }
646 func (formatPVCF) Finish(string, io.Writer, string) error { return nil }
647 func (formatPVCF) Head(out io.Writer, cgs []CompactGenome, cases []bool, p float64) error {
648         fmt.Fprintln(out, `##FORMAT=<ID=GT,Number=1,Type=String,Description="Genotype">`)
649         fmt.Fprintf(out, "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT")
650         for _, cg := range cgs {
651                 fmt.Fprintf(out, "\t%s", cg.Name)
652         }
653         _, err := fmt.Fprintf(out, "\n")
654         return err
655 }
656
657 func (formatPVCF) Print(out io.Writer, seqname string, varslice []tvVariant) error {
658         for ref, alts := range bucketVarsliceByRef(varslice) {
659                 altslice := make([]string, 0, len(alts))
660                 for alt := range alts {
661                         altslice = append(altslice, alt)
662                 }
663                 sort.Strings(altslice)
664                 for i, a := range altslice {
665                         alts[a] = i + 1
666                 }
667                 _, err := fmt.Fprintf(out, "%s\t%d\t.\t%s\t%s\t.\t.\t.\tGT", seqname, varslice[0].Position, ref, strings.Join(altslice, ","))
668                 if err != nil {
669                         return err
670                 }
671                 for i := 0; i < len(varslice); i += 2 {
672                         v1, v2 := varslice[i], varslice[i+1]
673                         a1, a2 := alts[v1.New], alts[v2.New]
674                         if v1.Ref != ref {
675                                 // variant on allele 0 belongs on a
676                                 // different output line -- same
677                                 // chr,pos but different "ref" length
678                                 a1 = 0
679                         }
680                         if v2.Ref != ref {
681                                 a2 = 0
682                         }
683                         _, err := fmt.Fprintf(out, "\t%d/%d", a1, a2)
684                         if err != nil {
685                                 return err
686                         }
687                 }
688                 _, err = out.Write([]byte{'\n'})
689                 if err != nil {
690                         return err
691                 }
692         }
693         return nil
694 }
695
696 type formatHGVS struct{}
697
698 func (formatHGVS) MaxGoroutines() int                                                     { return 0 }
699 func (formatHGVS) Filename() string                                                       { return "out.tsv" }
700 func (formatHGVS) PadLeft() bool                                                          { return false }
701 func (formatHGVS) Head(out io.Writer, cgs []CompactGenome, cases []bool, p float64) error { return nil }
702 func (formatHGVS) Finish(string, io.Writer, string) error                                 { return nil }
703 func (formatHGVS) Print(out io.Writer, seqname string, varslice []tvVariant) error {
704         for i := 0; i < len(varslice)/2; i++ {
705                 if i > 0 {
706                         out.Write([]byte{'\t'})
707                 }
708                 var1, var2 := varslice[i*2], varslice[i*2+1]
709                 if var1.New == "-" || var2.New == "-" {
710                         _, err := out.Write([]byte{'N'})
711                         if err != nil {
712                                 return err
713                         }
714                         continue
715                 }
716                 if var1.Variant == var2.Variant {
717                         if var1.Ref == var1.New {
718                                 _, err := out.Write([]byte{'.'})
719                                 if err != nil {
720                                         return err
721                                 }
722                         } else {
723                                 _, err := fmt.Fprintf(out, "%s:g.%s", seqname, var1.String())
724                                 if err != nil {
725                                         return err
726                                 }
727                         }
728                 } else {
729                         _, err := fmt.Fprintf(out, "%s:g.[%s];[%s]", seqname, var1.String(), var2.String())
730                         if err != nil {
731                                 return err
732                         }
733                 }
734         }
735         _, err := out.Write([]byte{'\n'})
736         return err
737 }
738
739 type formatHGVSOneHot struct{}
740
741 func (formatHGVSOneHot) MaxGoroutines() int { return 0 }
742 func (formatHGVSOneHot) Filename() string   { return "out.tsv" }
743 func (formatHGVSOneHot) PadLeft() bool      { return false }
744 func (formatHGVSOneHot) Head(out io.Writer, cgs []CompactGenome, cases []bool, p float64) error {
745         return nil
746 }
747 func (formatHGVSOneHot) Finish(string, io.Writer, string) error { return nil }
748 func (formatHGVSOneHot) Print(out io.Writer, seqname string, varslice []tvVariant) error {
749         vars := map[hgvs.Variant]bool{}
750         for _, v := range varslice {
751                 if v.Ref != v.New {
752                         vars[v.Variant] = true
753                 }
754         }
755
756         // sort variants to ensure output is deterministic
757         sorted := make([]hgvs.Variant, 0, len(vars))
758         for v := range vars {
759                 sorted = append(sorted, v)
760         }
761         sort.Slice(sorted, func(a, b int) bool { return hgvs.Less(sorted[a], sorted[b]) })
762
763         for _, v := range sorted {
764                 if v.New == "-" {
765                         continue
766                 }
767                 fmt.Fprintf(out, "%s.%s", seqname, v.String())
768                 for i := 0; i < len(varslice); i += 2 {
769                         if varslice[i].Variant == v || varslice[i+1].Variant == v {
770                                 out.Write([]byte("\t1"))
771                         } else {
772                                 out.Write([]byte("\t0"))
773                         }
774                 }
775                 _, err := out.Write([]byte{'\n'})
776                 if err != nil {
777                         return err
778                 }
779         }
780         return nil
781 }
782
783 type formatHGVSNumpy struct {
784         sync.Mutex
785         writelock sync.Mutex
786         alleles   map[string][][]int8 // alleles[seqname][variantidx][genomeidx*2+phase]
787         cases     []bool
788         maxPValue float64
789 }
790
791 func (*formatHGVSNumpy) MaxGoroutines() int { return 4 }
792 func (*formatHGVSNumpy) Filename() string   { return "annotations.csv" }
793 func (*formatHGVSNumpy) PadLeft() bool      { return false }
794 func (f *formatHGVSNumpy) Head(out io.Writer, cgs []CompactGenome, cases []bool, p float64) error {
795         f.cases = cases
796         f.maxPValue = p
797         return nil
798 }
799 func (f *formatHGVSNumpy) Print(outw io.Writer, seqname string, varslice []tvVariant) error {
800         // sort variants to ensure output is deterministic
801         sorted := make([]hgvs.Variant, 0, len(varslice))
802         for _, v := range varslice {
803                 sorted = append(sorted, v.Variant)
804         }
805         sort.Slice(sorted, func(a, b int) bool { return hgvs.Less(sorted[a], sorted[b]) })
806
807         f.Lock()
808         seqalleles := f.alleles[seqname]
809         f.Unlock()
810
811         chi2x := make([]bool, 0, len(varslice))
812         chi2y := make([]bool, 0, len(varslice))
813
814         // append a row to seqalleles for each unique non-ref variant
815         // in varslice.
816         var previous hgvs.Variant
817         for _, v := range sorted {
818                 if previous == v || v.Ref == v.New || v.New == "-" {
819                         continue
820                 }
821                 previous = v
822                 chi2x, chi2y := chi2x, chi2y
823                 newrow := make([]int8, len(varslice))
824                 for i, allele := range varslice {
825                         if allele.Variant == v {
826                                 newrow[i] = 1
827                                 chi2x = append(chi2x, true)
828                                 chi2y = append(chi2y, f.cases[i/2])
829                         } else if allele.Variant.New == "-" {
830                                 newrow[i] = -1
831                         } else {
832                                 chi2x = append(chi2x, false)
833                                 chi2y = append(chi2y, f.cases[i/2])
834                         }
835                 }
836                 if f.maxPValue < 1 && pvalue(chi2x, chi2y) > f.maxPValue {
837                         continue
838                 }
839                 seqalleles = append(seqalleles, newrow)
840                 _, err := fmt.Fprintf(outw, "%d,%q\n", len(seqalleles)-1, seqname+"."+v.String())
841                 if err != nil {
842                         return err
843                 }
844         }
845
846         f.Lock()
847         f.alleles[seqname] = seqalleles
848         f.Unlock()
849         return nil
850 }
851 func (f *formatHGVSNumpy) Finish(outdir string, _ io.Writer, seqname string) error {
852         // Write seqname's data to a .npy matrix with one row per
853         // genome and 2 columns per variant.
854         f.Lock()
855         seqalleles := f.alleles[seqname]
856         delete(f.alleles, seqname)
857         f.Unlock()
858         if len(seqalleles) == 0 {
859                 return nil
860         }
861         out := make([]int8, len(seqalleles)*len(seqalleles[0]))
862         rows := len(seqalleles[0]) / 2
863         cols := len(seqalleles) * 2
864         // copy seqalleles[varidx][genome*2+phase] to
865         // out[genome*nvars*2 + varidx*2 + phase]
866         for varidx, alleles := range seqalleles {
867                 for g := 0; g < len(alleles)/2; g++ {
868                         aa, ab := alleles[g*2], alleles[g*2+1]
869                         if aa < 0 || ab < 0 {
870                                 // no-call
871                                 out[g*cols+varidx*2] = -1
872                                 out[g*cols+varidx*2+1] = -1
873                         } else if aa > 0 && ab > 0 {
874                                 // hom
875                                 out[g*cols+varidx*2] = 1
876                         } else if aa > 0 || ab > 0 {
877                                 // het
878                                 out[g*cols+varidx*2+1] = 1
879                         }
880                 }
881         }
882         outf, err := os.OpenFile(outdir+"/matrix."+seqname+".npy", os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0777)
883         if err != nil {
884                 return err
885         }
886         defer outf.Close()
887         bufw := bufio.NewWriter(outf)
888         npw, err := gonpy.NewWriter(nopCloser{bufw})
889         if err != nil {
890                 return err
891         }
892         log.WithFields(logrus.Fields{
893                 "seqname": seqname,
894                 "rows":    rows,
895                 "cols":    cols,
896         }).Info("writing numpy")
897         npw.Shape = []int{rows, cols}
898         f.writelock.Lock() // serialize because WriteInt8 uses lots of memory
899         npw.WriteInt8(out)
900         f.writelock.Unlock()
901         err = bufw.Flush()
902         if err != nil {
903                 return err
904         }
905         err = outf.Close()
906         if err != nil {
907                 return err
908         }
909         return nil
910 }