Mention undiffable variants in annotations, write -2 in hgvs matrix.
[lightning.git] / slicenumpy.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         "flag"
11         "fmt"
12         "io"
13         "io/ioutil"
14         "net/http"
15         _ "net/http/pprof"
16         "os"
17         "regexp"
18         "runtime"
19         "sort"
20         "strconv"
21         "strings"
22         "sync/atomic"
23
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25         "github.com/arvados/lightning/hgvs"
26         "github.com/kshedden/gonpy"
27         log "github.com/sirupsen/logrus"
28         "golang.org/x/crypto/blake2b"
29 )
30
31 type sliceNumpy struct {
32         filter  filter
33         threads int
34 }
35
36 func (cmd *sliceNumpy) 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         ref := flags.String("ref", "", "reference name (if blank, choose last one that appears in input)")
52         regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
53         expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
54         mergeOutput := flags.Bool("merge-output", false, "merge output into one matrix.npy and one matrix.annotations.csv")
55         flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads")
56         cmd.filter.Flags(flags)
57         err = flags.Parse(args)
58         if err == flag.ErrHelp {
59                 err = nil
60                 return 0
61         } else if err != nil {
62                 return 2
63         }
64
65         if *pprof != "" {
66                 go func() {
67                         log.Println(http.ListenAndServe(*pprof, nil))
68                 }()
69         }
70
71         if !*runlocal {
72                 runner := arvadosContainerRunner{
73                         Name:        "lightning slice-numpy",
74                         Client:      arvados.NewClientFromEnv(),
75                         ProjectUUID: *projectUUID,
76                         RAM:         650000000000,
77                         VCPUs:       96,
78                         Priority:    *priority,
79                         KeepCache:   2,
80                         APIAccess:   true,
81                 }
82                 err = runner.TranslatePaths(inputDir, regionsFilename)
83                 if err != nil {
84                         return 1
85                 }
86                 runner.Args = []string{"slice-numpy", "-local=true",
87                         "-pprof=:6060",
88                         "-input-dir=" + *inputDir,
89                         "-output-dir=/mnt/output",
90                         "-threads=" + fmt.Sprintf("%d", cmd.threads),
91                         "-regions=" + *regionsFilename,
92                         "-expand-regions=" + fmt.Sprintf("%d", *expandRegions),
93                         "-merge-output=" + fmt.Sprintf("%v", *mergeOutput),
94                 }
95                 runner.Args = append(runner.Args, cmd.filter.Args()...)
96                 var output string
97                 output, err = runner.Run()
98                 if err != nil {
99                         return 1
100                 }
101                 fmt.Fprintln(stdout, output)
102                 return 0
103         }
104
105         infiles, err := allGobFiles(*inputDir)
106         if err != nil {
107                 return 1
108         }
109         if len(infiles) == 0 {
110                 err = fmt.Errorf("no input files found in %s", *inputDir)
111                 return 1
112         }
113         sort.Strings(infiles)
114
115         var cgnames []string
116         var refseq map[string][]tileLibRef
117         var reftiledata = make(map[tileLibRef][]byte, 11000000)
118         in0, err := open(infiles[0])
119         if err != nil {
120                 return 1
121         }
122
123         matchGenome, err := regexp.Compile(cmd.filter.MatchGenome)
124         if err != nil {
125                 err = fmt.Errorf("-match-genome: invalid regexp: %q", cmd.filter.MatchGenome)
126                 return 1
127         }
128
129         taglen := -1
130         DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
131                 if len(ent.TagSet) > 0 {
132                         taglen = len(ent.TagSet[0])
133                 }
134                 for _, cseq := range ent.CompactSequences {
135                         if cseq.Name == *ref || *ref == "" {
136                                 refseq = cseq.TileSequences
137                         }
138                 }
139                 for _, cg := range ent.CompactGenomes {
140                         if matchGenome.MatchString(cg.Name) {
141                                 cgnames = append(cgnames, cg.Name)
142                         }
143                 }
144                 for _, tv := range ent.TileVariants {
145                         if tv.Ref {
146                                 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
147                         }
148                 }
149                 return nil
150         })
151         if err != nil {
152                 return 1
153         }
154         in0.Close()
155         if refseq == nil {
156                 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
157                 return 1
158         }
159         if taglen < 0 {
160                 err = fmt.Errorf("tagset not found")
161                 return 1
162         }
163         if len(cgnames) == 0 {
164                 err = fmt.Errorf("no genomes found matching regexp %q", cmd.filter.MatchGenome)
165                 return 1
166         }
167         sort.Strings(cgnames)
168
169         {
170                 labelsFilename := *outputDir + "/labels.csv"
171                 log.Infof("writing labels to %s", labelsFilename)
172                 var f *os.File
173                 f, err = os.Create(labelsFilename)
174                 if err != nil {
175                         return 1
176                 }
177                 defer f.Close()
178                 for i, name := range cgnames {
179                         _, err = fmt.Fprintf(f, "%d,%q\n", i, trimFilenameForLabel(name))
180                         if err != nil {
181                                 err = fmt.Errorf("write %s: %w", labelsFilename, err)
182                                 return 1
183                         }
184                 }
185                 err = f.Close()
186                 if err != nil {
187                         err = fmt.Errorf("close %s: %w", labelsFilename, err)
188                         return 1
189                 }
190         }
191
192         log.Info("indexing reference tiles")
193         type reftileinfo struct {
194                 variant  tileVariantID
195                 seqname  string // chr1
196                 pos      int    // distance from start of chromosome to starttag
197                 tiledata []byte // acgtggcaa...
198         }
199         isdup := map[tagID]bool{}
200         reftile := map[tagID]*reftileinfo{}
201         for seqname, cseq := range refseq {
202                 pos := 0
203                 for _, libref := range cseq {
204                         tiledata := reftiledata[libref]
205                         if len(tiledata) == 0 {
206                                 err = fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
207                                 return 1
208                         }
209                         if isdup[libref.Tag] {
210                                 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
211                         } else if reftile[libref.Tag] != nil {
212                                 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", tileLibRef{Tag: libref.Tag, Variant: reftile[libref.Tag].variant}, reftile[libref.Tag].seqname, reftile[libref.Tag].pos)
213                                 delete(reftile, libref.Tag)
214                                 log.Printf("dropping reference tile %+v from %s @ %d, tag not unique", libref, seqname, pos)
215                                 isdup[libref.Tag] = true
216                         } else {
217                                 reftile[libref.Tag] = &reftileinfo{
218                                         seqname:  seqname,
219                                         variant:  libref.Variant,
220                                         tiledata: tiledata,
221                                         pos:      pos,
222                                 }
223                         }
224                         pos += len(tiledata) - taglen
225                 }
226                 log.Printf("... %s done, len %d", seqname, pos+taglen)
227         }
228
229         var mask *mask
230         if *regionsFilename != "" {
231                 log.Printf("loading regions from %s", *regionsFilename)
232                 mask, err = makeMask(*regionsFilename, *expandRegions)
233                 if err != nil {
234                         return 1
235                 }
236                 log.Printf("before applying mask, len(reftile) == %d", len(reftile))
237                 log.Printf("deleting reftile entries for regions outside %d intervals", mask.Len())
238                 for tag, rt := range reftile {
239                         if !mask.Check(strings.TrimPrefix(rt.seqname, "chr"), rt.pos, rt.pos+len(rt.tiledata)) {
240                                 delete(reftile, tag)
241                         }
242                 }
243                 log.Printf("after applying mask, len(reftile) == %d", len(reftile))
244         }
245
246         var toMerge [][]int16
247         if *mergeOutput {
248                 toMerge = make([][]int16, len(infiles))
249         }
250
251         throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
252         throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
253         log.Info("generating annotations and numpy matrix for each slice")
254         var done int64
255         for infileIdx, infile := range infiles {
256                 infileIdx, infile := infileIdx, infile
257                 throttleMem.Go(func() error {
258                         seq := make(map[tagID][]TileVariant, 50000)
259                         cgs := make(map[string]CompactGenome, len(cgnames))
260                         f, err := open(infile)
261                         if err != nil {
262                                 return err
263                         }
264                         defer f.Close()
265                         log.Infof("%04d: reading %s", infileIdx, infile)
266                         err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
267                                 for _, tv := range ent.TileVariants {
268                                         if tv.Ref {
269                                                 continue
270                                         }
271                                         if mask != nil && reftile[tv.Tag] == nil {
272                                                 // Don't waste
273                                                 // time/memory on
274                                                 // masked-out tiles.
275                                                 continue
276                                         }
277                                         variants := seq[tv.Tag]
278                                         if len(variants) == 0 {
279                                                 variants = make([]TileVariant, 100)
280                                         }
281                                         for len(variants) <= int(tv.Variant) {
282                                                 variants = append(variants, TileVariant{})
283                                         }
284                                         variants[int(tv.Variant)] = tv
285                                         seq[tv.Tag] = variants
286                                 }
287                                 for _, cg := range ent.CompactGenomes {
288                                         if matchGenome.MatchString(cg.Name) {
289                                                 cgs[cg.Name] = cg
290                                         }
291                                 }
292                                 return nil
293                         })
294                         if err != nil {
295                                 return err
296                         }
297                         tagstart := cgs[cgnames[0]].StartTag
298                         tagend := cgs[cgnames[0]].EndTag
299
300                         // TODO: filters
301
302                         log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
303                         variantRemap := make([][]tileVariantID, tagend-tagstart)
304                         throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
305                         for tag, variants := range seq {
306                                 tag, variants := tag, variants
307                                 throttleCPU.Acquire()
308                                 go func() {
309                                         defer throttleCPU.Release()
310                                         count := make(map[[blake2b.Size256]byte]int, len(variants))
311                                         for _, cg := range cgs {
312                                                 idx := int(tag-tagstart) * 2
313                                                 if idx < len(cg.Variants) {
314                                                         for allele := 0; allele < 2; allele++ {
315                                                                 v := cg.Variants[idx+allele]
316                                                                 if v > 0 && len(variants[v].Sequence) > 0 {
317                                                                         count[variants[v].Blake2b]++
318                                                                 }
319                                                         }
320                                                 }
321                                         }
322                                         // hash[i] will be the hash of
323                                         // the variant(s) that should
324                                         // be at rank i (0-based).
325                                         hash := make([][blake2b.Size256]byte, 0, len(count))
326                                         for b := range count {
327                                                 hash = append(hash, b)
328                                         }
329                                         sort.Slice(hash, func(i, j int) bool {
330                                                 bi, bj := &hash[i], &hash[j]
331                                                 if ci, cj := count[*bi], count[*bj]; ci != cj {
332                                                         return ci > cj
333                                                 } else {
334                                                         return bytes.Compare((*bi)[:], (*bj)[:]) < 0
335                                                 }
336                                         })
337                                         // rank[b] will be the 1-based
338                                         // new variant number for
339                                         // variants whose hash is b.
340                                         rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
341                                         for i, h := range hash {
342                                                 rank[h] = tileVariantID(i + 1)
343                                         }
344                                         // remap[v] will be the new
345                                         // variant number for original
346                                         // variant number v.
347                                         remap := make([]tileVariantID, len(variants))
348                                         for i, tv := range variants {
349                                                 remap[i] = rank[tv.Blake2b]
350                                         }
351                                         variantRemap[tag-tagstart] = remap
352                                 }()
353                         }
354                         throttleCPU.Wait()
355
356                         annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
357                         log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
358                         annof, err := os.Create(annotationsFilename)
359                         if err != nil {
360                                 return err
361                         }
362                         annow := bufio.NewWriterSize(annof, 1<<20)
363                         outcol := 0
364                         for tag := tagstart; tag < tagend; tag++ {
365                                 rt, ok := reftile[tag]
366                                 if !ok {
367                                         if mask == nil {
368                                                 outcol++
369                                         }
370                                         // Excluded by specified
371                                         // regions, or reference does
372                                         // not use any variant of this
373                                         // tile. (TODO: log this?
374                                         // mention it in annotations?)
375                                         continue
376                                 }
377                                 variants, ok := seq[tag]
378                                 if !ok {
379                                         // how could we even have a reftile if there is no sequence data??
380                                         return fmt.Errorf("bug: have no variants for tag %d but reftile is %+v", tag, rt)
381                                 }
382                                 reftilestr := strings.ToUpper(string(rt.tiledata))
383                                 remap := variantRemap[tag-tagstart]
384                                 done := make([]bool, len(variants))
385                                 for v, tv := range variants {
386                                         v := remap[v]
387                                         if done[v] {
388                                                 continue
389                                         } else {
390                                                 done[v] = true
391                                         }
392                                         if len(tv.Sequence) < taglen || !bytes.HasSuffix(rt.tiledata, tv.Sequence[len(tv.Sequence)-taglen:]) {
393                                                 fmt.Fprintf(annow, "%d,%d,%d,.,%s,%d,.,,\n", tag, outcol, v, rt.seqname, rt.pos)
394                                                 continue
395                                         }
396                                         if lendiff := len(rt.tiledata) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
397                                                 fmt.Fprintf(annow, "%d,%d,%d,,%s,%d,,,\n", tag, outcol, v, rt.seqname, rt.pos)
398                                                 continue
399                                         }
400                                         diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
401                                         for _, diff := range diffs {
402                                                 diff.Position += rt.pos
403                                                 fmt.Fprintf(annow, "%d,%d,%d,%s:g.%s,%s,%d,%s,%s,%s\n", tag, outcol, v, rt.seqname, diff.String(), rt.seqname, diff.Position, diff.Ref, diff.New, diff.Left)
404                                         }
405                                 }
406                                 outcol++
407                         }
408                         err = annow.Flush()
409                         if err != nil {
410                                 return err
411                         }
412                         err = annof.Close()
413                         if err != nil {
414                                 return err
415                         }
416
417                         log.Infof("%04d: preparing numpy", infileIdx)
418                         throttleNumpyMem.Acquire()
419                         rows := len(cgnames)
420                         cols := 2 * outcol
421                         out := make([]int16, rows*cols)
422                         for row, name := range cgnames {
423                                 out := out[row*cols:]
424                                 outcol := 0
425                                 for col, v := range cgs[name].Variants {
426                                         tag := tagstart + tagID(col/2)
427                                         if mask != nil && reftile[tag] == nil {
428                                                 continue
429                                         }
430                                         if variants, ok := seq[tag]; ok && len(variants) > int(v) && len(variants[v].Sequence) > 0 {
431                                                 out[outcol] = int16(variantRemap[tag-tagstart][v])
432                                         } else {
433                                                 out[outcol] = -1
434                                         }
435                                         outcol++
436                                 }
437                         }
438                         seq = nil
439                         throttleNumpyMem.Release()
440
441                         if *mergeOutput {
442                                 log.Infof("%04d: matrix fragment %d rows x %d cols", infileIdx, rows, cols)
443                                 toMerge[infileIdx] = out
444                         } else {
445                                 fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
446                                 err = writeNumpyInt16(fnm, out, rows, cols)
447                                 if err != nil {
448                                         return err
449                                 }
450                         }
451                         log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
452                         return nil
453                 })
454         }
455         if err = throttleMem.Wait(); err != nil {
456                 return 1
457         }
458         if *mergeOutput {
459                 log.Info("merging output matrix and annotations")
460
461                 annoFilename := fmt.Sprintf("%s/matrix.annotations.csv", *outputDir)
462                 annof, err := os.Create(annoFilename)
463                 if err != nil {
464                         return 1
465                 }
466                 annow := bufio.NewWriterSize(annof, 1<<20)
467
468                 rows := len(cgnames)
469                 cols := 0
470                 for _, chunk := range toMerge {
471                         cols += len(chunk) / rows
472                 }
473                 out := make([]int16, rows*cols)
474                 hgvs := map[string][2][]int16{} // hgvs -> [[g0,g1,g2,...], [g0,g1,g2,...]] (slice of genomes for each phase)
475                 startcol := 0
476                 for outIdx, chunk := range toMerge {
477                         chunkcols := len(chunk) / rows
478                         for row := 0; row < rows; row++ {
479                                 copy(out[row*cols+startcol:], chunk[row*chunkcols:(row+1)*chunkcols])
480                         }
481                         toMerge[outIdx] = nil
482
483                         annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, outIdx)
484                         log.Infof("reading %s", annotationsFilename)
485                         buf, err := os.ReadFile(annotationsFilename)
486                         if err != nil {
487                                 return 1
488                         }
489                         err = os.Remove(annotationsFilename)
490                         if err != nil {
491                                 return 1
492                         }
493                         for _, line := range bytes.Split(buf, []byte{'\n'}) {
494                                 if len(line) == 0 {
495                                         continue
496                                 }
497                                 fields := bytes.SplitN(line, []byte{','}, 8)
498                                 incol, _ := strconv.Atoi(string(fields[1]))
499                                 tileVariant, _ := strconv.Atoi(string(fields[2]))
500                                 hgvsID := string(fields[3])
501                                 seqname := string(fields[4])
502                                 pos, _ := strconv.Atoi(string(fields[5]))
503                                 refseq := fields[6]
504                                 if mask != nil && !mask.Check(strings.TrimPrefix(seqname, "chr"), pos, pos+len(refseq)) {
505                                         // The tile intersects one of
506                                         // the selected regions, but
507                                         // this particular HGVS
508                                         // variant does not.
509                                         continue
510                                 }
511                                 fmt.Fprintf(annow, "%s,%d,%d,%s,%s,%d,%s,%s\n", fields[0], incol+startcol/2, tileVariant, hgvsID, seqname, pos, refseq, fields[7])
512                                 hgvscols := hgvs[hgvsID]
513                                 if hgvscols[0] == nil {
514                                         hgvscols = [2][]int16{make([]int16, len(cgnames)), make([]int16, len(cgnames))}
515                                         hgvs[hgvsID] = hgvscols
516                                 }
517                                 for ph := 0; ph < 2; ph++ {
518                                         for row := 0; row < rows; row++ {
519                                                 v := chunk[row*chunkcols+incol*2+ph]
520                                                 if int(v) == tileVariant {
521                                                         if len(hgvsID) == 0 {
522                                                                 // we have the tile variant sequence, but the diff against ref didn't work out (see lendiff above)
523                                                                 hgvscols[ph][row] = -2
524                                                         } else {
525                                                                 hgvscols[ph][row] = 1
526                                                         }
527                                                 } else if v < 0 {
528                                                         hgvscols[ph][row] = -1
529                                                 }
530                                         }
531                                 }
532                         }
533
534                         startcol += chunkcols
535                 }
536                 err = annow.Flush()
537                 if err != nil {
538                         return 1
539                 }
540                 err = annof.Close()
541                 if err != nil {
542                         return 1
543                 }
544                 err = writeNumpyInt16(fmt.Sprintf("%s/matrix.npy", *outputDir), out, rows, cols)
545                 if err != nil {
546                         return 1
547                 }
548                 out = nil
549
550                 cols = len(hgvs) * 2
551                 log.Printf("building hgvs-based matrix: %d rows x %d cols", rows, cols)
552                 out = make([]int16, rows*cols)
553                 hgvsIDs := make([]string, 0, len(hgvs))
554                 for hgvsID := range hgvs {
555                         hgvsIDs = append(hgvsIDs, hgvsID)
556                 }
557                 sort.Strings(hgvsIDs)
558                 var hgvsLabels bytes.Buffer
559                 for idx, hgvsID := range hgvsIDs {
560                         fmt.Fprintf(&hgvsLabels, "%d,%s\n", idx, hgvsID)
561                         for ph := 0; ph < 2; ph++ {
562                                 hgvscol := hgvs[hgvsID][ph]
563                                 for row, val := range hgvscol {
564                                         out[row*cols+idx*2+ph] = val
565                                 }
566                         }
567                 }
568                 err = writeNumpyInt16(fmt.Sprintf("%s/hgvs.npy", *outputDir), out, rows, cols)
569                 if err != nil {
570                         return 1
571                 }
572
573                 fnm := fmt.Sprintf("%s/hgvs.annotations.csv", *outputDir)
574                 log.Printf("writing hgvs labels: %s", fnm)
575                 err = ioutil.WriteFile(fnm, hgvsLabels.Bytes(), 0777)
576                 if err != nil {
577                         return 1
578                 }
579         }
580         return 0
581 }
582
583 func writeNumpyInt16(fnm string, out []int16, rows, cols int) error {
584         output, err := os.Create(fnm)
585         if err != nil {
586                 return err
587         }
588         defer output.Close()
589         bufw := bufio.NewWriterSize(output, 1<<26)
590         npw, err := gonpy.NewWriter(nopCloser{bufw})
591         if err != nil {
592                 return err
593         }
594         log.WithFields(log.Fields{
595                 "filename": fnm,
596                 "rows":     rows,
597                 "cols":     cols,
598         }).Infof("writing numpy: %s", fnm)
599         npw.Shape = []int{rows, cols}
600         npw.WriteInt16(out)
601         err = bufw.Flush()
602         if err != nil {
603                 return err
604         }
605         return output.Close()
606 }