19524: Fix colormap.
[lightning.git] / exportnumpy.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         "io/ioutil"
16         "net/http"
17         _ "net/http/pprof"
18         "os"
19         "sort"
20         "strconv"
21         "strings"
22         "sync"
23         "sync/atomic"
24
25         "git.arvados.org/arvados.git/sdk/go/arvados"
26         "github.com/arvados/lightning/hgvs"
27         "github.com/kshedden/gonpy"
28         "github.com/sirupsen/logrus"
29         log "github.com/sirupsen/logrus"
30 )
31
32 type exportNumpy struct {
33         filter filter
34 }
35
36 func (cmd *exportNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
37         var err error
38         defer func() {
39                 if err != nil {
40                         fmt.Fprintf(stderr, "%s\n", err)
41                 }
42         }()
43         flags := flag.NewFlagSet("", flag.ContinueOnError)
44         flags.SetOutput(stderr)
45         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
46         runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
47         projectUUID := flags.String("project", "", "project `UUID` for output data")
48         priority := flags.Int("priority", 500, "container request priority")
49         inputDir := flags.String("input-dir", "./in", "input `directory`")
50         outputDir := flags.String("output-dir", "./out", "output `directory`")
51         annotationsFilename := flags.String("output-annotations", "", "output `file` for tile variant annotations csv")
52         librefsFilename := flags.String("output-onehot2tilevar", "", "when using -one-hot, create csv `file` mapping column# to tag# and variant#")
53         labelsFilename := flags.String("output-labels", "", "output `file` for genome labels csv")
54         regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
55         expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
56         onehot := flags.Bool("one-hot", false, "recode tile variants as one-hot")
57         chunks := flags.Int("chunks", 1, "split output into `N` numpy files")
58         cmd.filter.Flags(flags)
59         err = flags.Parse(args)
60         if err == flag.ErrHelp {
61                 err = nil
62                 return 0
63         } else if err != nil {
64                 return 2
65         }
66
67         if *pprof != "" {
68                 go func() {
69                         log.Println(http.ListenAndServe(*pprof, nil))
70                 }()
71         }
72
73         if !*runlocal {
74                 runner := arvadosContainerRunner{
75                         Name:        "lightning export-numpy",
76                         Client:      arvados.NewClientFromEnv(),
77                         ProjectUUID: *projectUUID,
78                         RAM:         500000000000,
79                         VCPUs:       96,
80                         Priority:    *priority,
81                         KeepCache:   1,
82                         APIAccess:   true,
83                 }
84                 err = runner.TranslatePaths(inputDir, regionsFilename)
85                 if err != nil {
86                         return 1
87                 }
88                 runner.Args = []string{"export-numpy", "-local=true",
89                         "-pprof", ":6060",
90                         fmt.Sprintf("-one-hot=%v", *onehot),
91                         "-input-dir", *inputDir,
92                         "-output-dir", "/mnt/output",
93                         "-output-annotations", "/mnt/output/annotations.csv",
94                         "-output-onehot2tilevar", "/mnt/output/onehot2tilevar.csv",
95                         "-output-labels", "/mnt/output/labels.csv",
96                         "-regions", *regionsFilename,
97                         "-expand-regions", fmt.Sprintf("%d", *expandRegions),
98                         "-chunks", fmt.Sprintf("%d", *chunks),
99                 }
100                 runner.Args = append(runner.Args, cmd.filter.Args()...)
101                 var output string
102                 output, err = runner.Run()
103                 if err != nil {
104                         return 1
105                 }
106                 fmt.Fprintln(stdout, output+"/matrix.npy")
107                 return 0
108         }
109
110         tilelib := &tileLibrary{
111                 retainNoCalls:       true,
112                 retainTileSequences: true,
113                 compactGenomes:      map[string][]tileVariantID{},
114         }
115         err = tilelib.LoadDir(context.Background(), *inputDir)
116         if err != nil {
117                 return 1
118         }
119
120         log.Info("filtering")
121         cmd.filter.Apply(tilelib)
122         log.Info("tidying")
123         tilelib.Tidy()
124
125         log.Info("building lowqual map")
126         lowqual := lowqual(tilelib)
127         names := cgnames(tilelib)
128
129         if *labelsFilename != "" {
130                 log.Infof("writing labels to %s", *labelsFilename)
131                 var f *os.File
132                 f, err = os.OpenFile(*labelsFilename, os.O_CREATE|os.O_WRONLY, 0777)
133                 if err != nil {
134                         return 1
135                 }
136                 defer f.Close()
137                 outBasename := "matrix.npy"
138                 for i, name := range names {
139                         _, err = fmt.Fprintf(f, "%d,%q,%q\n", i, trimFilenameForLabel(name), outBasename)
140                         if err != nil {
141                                 err = fmt.Errorf("write %s: %w", *labelsFilename, err)
142                                 return 1
143                         }
144                 }
145                 err = f.Close()
146                 if err != nil {
147                         err = fmt.Errorf("close %s: %w", *labelsFilename, err)
148                         return 1
149                 }
150         }
151
152         log.Info("determining which tiles intersect given regions")
153         dropTiles, err := chooseTiles(tilelib, *regionsFilename, *expandRegions)
154         if err != nil {
155                 return 1
156         }
157
158         annotation2tvs := map[string]map[hgvs.Variant][]tileLibRef{}
159         if *annotationsFilename != "" {
160                 log.Info("writing annotations")
161                 var annow io.WriteCloser
162                 annow, err = os.OpenFile(*annotationsFilename, os.O_CREATE|os.O_WRONLY, 0666)
163                 if err != nil {
164                         return 1
165                 }
166                 defer annow.Close()
167                 var mtx sync.Mutex
168                 err = (&annotatecmd{
169                         maxTileSize: 5000,
170                         dropTiles:   dropTiles,
171                         reportAnnotation: func(tag tagID, _ int, variant tileVariantID, refname string, seqname string, pdi hgvs.Variant) {
172                                 mtx.Lock()
173                                 defer mtx.Unlock()
174                                 if annotation2tvs[seqname] == nil {
175                                         annotation2tvs[seqname] = map[hgvs.Variant][]tileLibRef{}
176                                 }
177                                 annotation2tvs[seqname][pdi] = append(annotation2tvs[seqname][pdi], tileLibRef{Tag: tag, Variant: variant})
178                         },
179                 }).exportTileDiffs(annow, tilelib)
180                 if err != nil {
181                         return 1
182                 }
183                 err = annow.Close()
184                 if err != nil {
185                         return 1
186                 }
187         }
188
189         var lastErr atomic.Value
190         var wg sync.WaitGroup
191         for seqname, pdivars := range annotation2tvs {
192                 seqname, pdivars := seqname, pdivars
193                 wg.Add(1)
194                 go func() {
195                         defer wg.Done()
196                         log.Infof("choosing hgvs columns for seq %s", seqname)
197                         var pdis []hgvs.Variant
198                         for pdi, librefs := range pdivars {
199                                 // Include this HGVS column if it was
200                                 // seen in a variant of any
201                                 // non-dropped tile.
202                                 for _, libref := range librefs {
203                                         if int(libref.Tag) >= len(dropTiles) || !dropTiles[libref.Tag] {
204                                                 pdis = append(pdis, pdi)
205                                                 break
206                                         }
207                                 }
208                         }
209                         sort.Slice(pdis, func(i, j int) bool {
210                                 if cmp := pdis[i].Position - pdis[j].Position; cmp != 0 {
211                                         return cmp < 0
212                                 } else if pdis[i].Ref != pdis[j].Ref {
213                                         return pdis[i].Ref < pdis[j].Ref
214                                 } else {
215                                         return pdis[i].New < pdis[j].New
216                                 }
217                         })
218                         log.Infof("writing column labels for seq %s", seqname)
219                         var buf bytes.Buffer
220                         for _, pdi := range pdis {
221                                 fmt.Fprintf(&buf, "%s:g.%s\n", seqname, pdi.String())
222                         }
223                         err := ioutil.WriteFile(*outputDir+"/"+seqname+".columns.csv", buf.Bytes(), 0777)
224                         if err != nil {
225                                 lastErr.Store(err)
226                                 return
227                         }
228
229                         log.Infof("building hgvs matrix for seq %s", seqname)
230                         data := make([]int8, len(names)*len(pdis)*2)
231                         for row, name := range names {
232                                 cg := tilelib.compactGenomes[name]
233                                 rowstart := row * len(pdis) * 2
234                                 for col, pdi := range pdis {
235                                         for _, libref := range pdivars[pdi] {
236                                                 if len(cg) <= int(libref.Tag)*2+1 {
237                                                         continue
238                                                 }
239                                                 for phase := 0; phase < 2; phase++ {
240                                                         if cg[int(libref.Tag)*2+phase] == libref.Variant {
241                                                                 data[rowstart+col*2+phase] = 1
242                                                         }
243                                                 }
244                                         }
245                                 }
246                         }
247                         log.Infof("writing hgvs numpy for seq %s", seqname)
248                         f, err := os.OpenFile(*outputDir+"/"+seqname+".npy", os.O_CREATE|os.O_WRONLY, 0777)
249                         if err != nil {
250                                 lastErr.Store(err)
251                                 return
252                         }
253                         defer f.Close()
254                         // gonpy closes our writer and ignores errors. Give it a nopCloser so we can close f properly.
255                         npw, err := gonpy.NewWriter(nopCloser{f})
256                         if err != nil {
257                                 lastErr.Store(err)
258                                 return
259                         }
260                         npw.Shape = []int{len(names), len(pdis) * 2}
261                         err = npw.WriteInt8(data)
262                         if err != nil {
263                                 lastErr.Store(err)
264                                 return
265                         }
266                         err = f.Close()
267                         if err != nil {
268                                 lastErr.Store(err)
269                                 return
270                         }
271                 }()
272         }
273         wg.Wait()
274         if e, ok := lastErr.Load().(error); ok {
275                 err = e
276                 return 1
277         }
278
279         chunksize := (len(tilelib.variant) + *chunks - 1) / *chunks
280         for chunk := 0; chunk < *chunks; chunk++ {
281                 log.Infof("preparing chunk %d of %d", chunk+1, *chunks)
282                 tagstart := chunk * chunksize
283                 tagend := tagstart + chunksize
284                 if tagend > len(tilelib.variant) {
285                         tagend = len(tilelib.variant)
286                 }
287                 out, rows, cols := cgs2array(tilelib, names, lowqual, dropTiles, tagstart, tagend)
288
289                 var npw *gonpy.NpyWriter
290                 var output io.WriteCloser
291                 fnm := *outputDir + "/matrix.npy"
292                 if *chunks > 1 {
293                         fnm = fmt.Sprintf("%s/matrix.%d.npy", *outputDir, chunk)
294                 }
295                 output, err = os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY, 0777)
296                 if err != nil {
297                         return 1
298                 }
299                 defer output.Close()
300                 bufw := bufio.NewWriter(output)
301                 npw, err = gonpy.NewWriter(nopCloser{bufw})
302                 if err != nil {
303                         return 1
304                 }
305                 if *onehot {
306                         log.Info("recoding to onehot")
307                         recoded, librefs, recodedcols := recodeOnehot(out, cols)
308                         out, cols = recoded, recodedcols
309                         if *librefsFilename != "" {
310                                 log.Infof("writing onehot column mapping")
311                                 err = cmd.writeLibRefs(*librefsFilename, tilelib, librefs)
312                                 if err != nil {
313                                         return 1
314                                 }
315                         }
316                 }
317                 log.WithFields(logrus.Fields{
318                         "filename": fnm,
319                         "rows":     rows,
320                         "cols":     cols,
321                 }).Info("writing numpy")
322                 npw.Shape = []int{rows, cols}
323                 npw.WriteInt16(out)
324                 err = bufw.Flush()
325                 if err != nil {
326                         return 1
327                 }
328                 err = output.Close()
329                 if err != nil {
330                         return 1
331                 }
332         }
333         return 0
334 }
335
336 func (*exportNumpy) writeLibRefs(fnm string, tilelib *tileLibrary, librefs []tileLibRef) error {
337         f, err := os.OpenFile(fnm, os.O_CREATE|os.O_WRONLY, 0666)
338         if err != nil {
339                 return err
340         }
341         defer f.Close()
342         for i, libref := range librefs {
343                 _, err = fmt.Fprintf(f, "%d,%d,%d\n", i, libref.Tag, libref.Variant)
344                 if err != nil {
345                         return err
346                 }
347         }
348         return f.Close()
349 }
350
351 func cgnames(tilelib *tileLibrary) (cgnames []string) {
352         for name := range tilelib.compactGenomes {
353                 cgnames = append(cgnames, name)
354         }
355         sort.Slice(cgnames, func(i, j int) bool {
356                 return trimFilenameForLabel(cgnames[i]) < trimFilenameForLabel(cgnames[j])
357         })
358         return
359 }
360
361 func lowqual(tilelib *tileLibrary) (lowqual []map[tileVariantID]bool) {
362         lowqual = make([]map[tileVariantID]bool, len(tilelib.variant))
363         for tag, variants := range tilelib.variant {
364                 lq := lowqual[tag]
365                 for varidx, hash := range variants {
366                         if len(tilelib.hashSequence(hash)) == 0 {
367                                 if lq == nil {
368                                         lq = map[tileVariantID]bool{}
369                                         lowqual[tag] = lq
370                                 }
371                                 lq[tileVariantID(varidx+1)] = true
372                         }
373                 }
374         }
375         return
376 }
377
378 func cgs2array(tilelib *tileLibrary, names []string, lowqual []map[tileVariantID]bool, dropTiles []bool, tagstart, tagend int) (data []int16, rows, cols int) {
379         rows = len(tilelib.compactGenomes)
380         for tag := tagstart; tag < tagend; tag++ {
381                 if len(dropTiles) <= tag || !dropTiles[tag] {
382                         cols += 2
383                 }
384         }
385         data = make([]int16, rows*cols)
386         for row, name := range names {
387                 cg := tilelib.compactGenomes[name]
388                 outidx := 0
389                 for tag := tagstart; tag < tagend && tag*2+1 < len(cg); tag++ {
390                         if len(dropTiles) > tag && dropTiles[tag] {
391                                 continue
392                         }
393                         for phase := 0; phase < 2; phase++ {
394                                 v := cg[tag*2+phase]
395                                 if v > 0 && lowqual[tag][v] {
396                                         data[row*cols+outidx] = -1
397                                 } else {
398                                         data[row*cols+outidx] = int16(v)
399                                 }
400                                 outidx++
401                         }
402                 }
403         }
404         return
405 }
406
407 func makeMask(regionsFilename string, expandRegions int) (*mask, error) {
408         log.Printf("makeMask: reading %s", regionsFilename)
409         rfile, err := zopen(regionsFilename)
410         if err != nil {
411                 return nil, err
412         }
413         defer rfile.Close()
414         regions, err := io.ReadAll(rfile)
415         if err != nil {
416                 return nil, err
417         }
418
419         log.Print("makeMask: building mask")
420         var mask mask
421         for _, line := range bytes.Split(regions, []byte{'\n'}) {
422                 if bytes.HasPrefix(line, []byte{'#'}) {
423                         continue
424                 }
425                 fields := bytes.Split(line, []byte{'\t'})
426                 if len(fields) < 3 {
427                         continue
428                 }
429                 refseqname := string(fields[0])
430                 if strings.HasPrefix(refseqname, "chr") {
431                         refseqname = refseqname[3:]
432                 }
433                 start, err1 := strconv.Atoi(string(fields[1]))
434                 end, err2 := strconv.Atoi(string(fields[2]))
435                 if err1 == nil && err2 == nil {
436                         // BED
437                 } else {
438                         start, err1 = strconv.Atoi(string(fields[3]))
439                         end, err2 = strconv.Atoi(string(fields[4]))
440                         if err1 == nil && err2 == nil {
441                                 // GFF/GTF
442                                 end++
443                         } else {
444                                 return nil, fmt.Errorf("cannot parse input line as BED or GFF/GTF: %q", line)
445                         }
446                 }
447                 mask.Add(refseqname, start-expandRegions, end+expandRegions)
448         }
449         log.Print("makeMask: mask.Freeze")
450         mask.Freeze()
451         return &mask, nil
452 }
453
454 func chooseTiles(tilelib *tileLibrary, regionsFilename string, expandRegions int) (drop []bool, err error) {
455         if regionsFilename == "" {
456                 return
457         }
458         mask, err := makeMask(regionsFilename, expandRegions)
459         if err != nil {
460                 return
461         }
462
463         tagset := tilelib.taglib.Tags()
464         if len(tagset) == 0 {
465                 err = errors.New("cannot choose tiles by region in a library without tags")
466                 return
467         }
468         taglen := len(tagset[0])
469
470         log.Print("chooseTiles: check ref tiles")
471         // Find position+size of each reference tile, and if it
472         // intersects any of the desired regions, set drop[tag]=false.
473         //
474         // (Note it doesn't quite work to do the more obvious thing --
475         // start with drop=false and change to true when ref tiles
476         // intersect target regions -- because that would give us
477         // drop=false for tiles that don't appear at all in the
478         // reference.)
479         //
480         // TODO: (optionally?) don't drop tags for which some tile
481         // variants are spanning tiles, i.e., where the reference tile
482         // does not intersect the desired regions, but a spanning tile
483         // from a genome does.
484         drop = make([]bool, len(tilelib.variant))
485         for i := range drop {
486                 drop[i] = true
487         }
488         for refname, refseqs := range tilelib.refseqs {
489                 for refseqname, reftiles := range refseqs {
490                         if strings.HasPrefix(refseqname, "chr") {
491                                 refseqname = refseqname[3:]
492                         }
493                         tileend := 0
494                         for _, libref := range reftiles {
495                                 if libref.Variant < 1 {
496                                         err = fmt.Errorf("reference %q seq %q uses variant zero at tag %d", refname, refseqname, libref.Tag)
497                                         return
498                                 }
499                                 seq := tilelib.TileVariantSequence(libref)
500                                 if len(seq) < taglen {
501                                         err = fmt.Errorf("reference %q seq %q uses tile %d variant %d with sequence len %d < taglen %d", refname, refseqname, libref.Tag, libref.Variant, len(seq), taglen)
502                                         return
503                                 }
504                                 tilestart := tileend
505                                 tileend = tilestart + len(seq) - taglen
506                                 if mask.Check(refseqname, tilestart, tileend) {
507                                         drop[libref.Tag] = false
508                                 }
509                         }
510                 }
511         }
512
513         log.Print("chooseTiles: done")
514         return
515 }
516
517 func recodeOnehot(in []int16, incols int) (out []int16, librefs []tileLibRef, outcols int) {
518         rows := len(in) / incols
519         maxvalue := make([]int16, incols)
520         for row := 0; row < rows; row++ {
521                 for col := 0; col < incols; col++ {
522                         if v := in[row*incols+col]; maxvalue[col] < v {
523                                 maxvalue[col] = v
524                         }
525                 }
526         }
527         outcol := make([]int, incols)
528         dropped := 0
529         for incol, maxv := range maxvalue {
530                 outcol[incol] = outcols
531                 if maxv == 0 {
532                         dropped++
533                 }
534                 for v := 1; v <= int(maxv); v++ {
535                         librefs = append(librefs, tileLibRef{Tag: tagID(incol), Variant: tileVariantID(v)})
536                         outcols++
537                 }
538         }
539         log.Printf("recodeOnehot: dropped %d input cols with zero maxvalue", dropped)
540
541         out = make([]int16, rows*outcols)
542         for inidx, row := 0, 0; row < rows; row++ {
543                 outrow := out[row*outcols:]
544                 for col := 0; col < incols; col++ {
545                         if v := in[inidx]; v > 0 {
546                                 outrow[outcol[col]+int(v)-1] = 1
547                         }
548                         inidx++
549                 }
550         }
551         return
552 }
553
554 type nopCloser struct {
555         io.Writer
556 }
557
558 func (nopCloser) Close() error { return nil }
559
560 func trimFilenameForLabel(s string) string {
561         if i := strings.LastIndex(s, "/"); i >= 0 {
562                 s = s[i+1:]
563         }
564         s = strings.TrimSuffix(s, ".gz")
565         s = strings.TrimSuffix(s, ".fa")
566         s = strings.TrimSuffix(s, ".fasta")
567         s = strings.TrimSuffix(s, ".1")
568         s = strings.TrimSuffix(s, ".2")
569         s = strings.TrimSuffix(s, ".gz")
570         s = strings.TrimSuffix(s, ".vcf")
571         return s
572 }