c48a5d54a9ce508d7137f24a078168363a2e40dc
[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         "net/http"
14         _ "net/http/pprof"
15         "os"
16         "runtime"
17         "sort"
18         "strings"
19         "sync/atomic"
20
21         "git.arvados.org/arvados.git/sdk/go/arvados"
22         "github.com/arvados/lightning/hgvs"
23         "github.com/kshedden/gonpy"
24         "github.com/sirupsen/logrus"
25         log "github.com/sirupsen/logrus"
26         "golang.org/x/crypto/blake2b"
27 )
28
29 type sliceNumpy struct {
30         filter  filter
31         threads int
32 }
33
34 func (cmd *sliceNumpy) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
35         var err error
36         defer func() {
37                 if err != nil {
38                         fmt.Fprintf(stderr, "%s\n", err)
39                 }
40         }()
41         flags := flag.NewFlagSet("", flag.ContinueOnError)
42         flags.SetOutput(stderr)
43         pprof := flags.String("pprof", "", "serve Go profile data at http://`[addr]:port`")
44         runlocal := flags.Bool("local", false, "run on local host (default: run in an arvados container)")
45         projectUUID := flags.String("project", "", "project `UUID` for output data")
46         priority := flags.Int("priority", 500, "container request priority")
47         inputDir := flags.String("input-dir", "./in", "input `directory`")
48         outputDir := flags.String("output-dir", "./out", "output `directory`")
49         ref := flags.String("ref", "", "reference name (if blank, choose last one that appears in input)")
50         regionsFilename := flags.String("regions", "", "only output columns/annotations that intersect regions in specified bed `file`")
51         expandRegions := flags.Int("expand-regions", 0, "expand specified regions by `N` base pairs on each side`")
52         flags.IntVar(&cmd.threads, "threads", 16, "number of memory-hungry assembly threads")
53         cmd.filter.Flags(flags)
54         err = flags.Parse(args)
55         if err == flag.ErrHelp {
56                 err = nil
57                 return 0
58         } else if err != nil {
59                 return 2
60         }
61
62         if *pprof != "" {
63                 go func() {
64                         log.Println(http.ListenAndServe(*pprof, nil))
65                 }()
66         }
67
68         if !*runlocal {
69                 runner := arvadosContainerRunner{
70                         Name:        "lightning slice-numpy",
71                         Client:      arvados.NewClientFromEnv(),
72                         ProjectUUID: *projectUUID,
73                         RAM:         240000000000,
74                         VCPUs:       64,
75                         Priority:    *priority,
76                         KeepCache:   2,
77                         APIAccess:   true,
78                 }
79                 err = runner.TranslatePaths(inputDir, regionsFilename)
80                 if err != nil {
81                         return 1
82                 }
83                 runner.Args = []string{"slice-numpy", "-local=true",
84                         "-pprof", ":6060",
85                         "-input-dir", *inputDir,
86                         "-output-dir", "/mnt/output",
87                         "-threads", fmt.Sprintf("%d", cmd.threads),
88                         "-regions", *regionsFilename,
89                         "-expand-regions", fmt.Sprintf("%d", *expandRegions),
90                 }
91                 runner.Args = append(runner.Args, cmd.filter.Args()...)
92                 var output string
93                 output, err = runner.Run()
94                 if err != nil {
95                         return 1
96                 }
97                 fmt.Fprintln(stdout, output)
98                 return 0
99         }
100
101         infiles, err := allGobFiles(*inputDir)
102         if err != nil {
103                 return 1
104         }
105         if len(infiles) == 0 {
106                 err = fmt.Errorf("no input files found in %s", *inputDir)
107                 return 1
108         }
109         sort.Strings(infiles)
110
111         var cgnames []string
112         var refseq map[string][]tileLibRef
113         var reftiledata = make(map[tileLibRef][]byte, 11000000)
114         in0, err := open(infiles[0])
115         if err != nil {
116                 return 1
117         }
118
119         taglen := -1
120         DecodeLibrary(in0, strings.HasSuffix(infiles[0], ".gz"), func(ent *LibraryEntry) error {
121                 if len(ent.TagSet) > 0 {
122                         taglen = len(ent.TagSet[0])
123                 }
124                 for _, cseq := range ent.CompactSequences {
125                         if cseq.Name == *ref || *ref == "" {
126                                 refseq = cseq.TileSequences
127                         }
128                 }
129                 for _, cg := range ent.CompactGenomes {
130                         cgnames = append(cgnames, cg.Name)
131                 }
132                 for _, tv := range ent.TileVariants {
133                         if tv.Ref {
134                                 reftiledata[tileLibRef{tv.Tag, tv.Variant}] = tv.Sequence
135                         }
136                 }
137                 return nil
138         })
139         if err != nil {
140                 return 1
141         }
142         in0.Close()
143         if refseq == nil {
144                 err = fmt.Errorf("%s: reference sequence not found", infiles[0])
145                 return 1
146         }
147         if taglen < 0 {
148                 err = fmt.Errorf("tagset not found")
149                 return 1
150         }
151         sort.Strings(cgnames)
152
153         {
154                 labelsFilename := *outputDir + "/labels.csv"
155                 log.Infof("writing labels to %s", labelsFilename)
156                 var f *os.File
157                 f, err = os.Create(labelsFilename)
158                 if err != nil {
159                         return 1
160                 }
161                 defer f.Close()
162                 for i, name := range cgnames {
163                         _, err = fmt.Fprintf(f, "%d,%q\n", i, trimFilenameForLabel(name))
164                         if err != nil {
165                                 err = fmt.Errorf("write %s: %w", labelsFilename, err)
166                                 return 1
167                         }
168                 }
169                 err = f.Close()
170                 if err != nil {
171                         err = fmt.Errorf("close %s: %w", labelsFilename, err)
172                         return 1
173                 }
174         }
175
176         log.Info("indexing reference tiles")
177         type reftileinfo struct {
178                 variant  tileVariantID
179                 seqname  string // chr1
180                 pos      int    // distance from start of chr1 to start of tile
181                 tiledata []byte // acgtggcaa...
182         }
183         reftile := map[tagID]*reftileinfo{}
184         for seqname, cseq := range refseq {
185                 for _, libref := range cseq {
186                         reftile[libref.Tag] = &reftileinfo{
187                                 seqname:  seqname,
188                                 variant:  libref.Variant,
189                                 tiledata: reftiledata[libref],
190                         }
191                 }
192         }
193
194         throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
195         log.Info("reconstructing reference sequences")
196         for seqname, cseq := range refseq {
197                 seqname, cseq := seqname, cseq
198                 throttleCPU.Go(func() error {
199                         defer log.Printf("... %s done", seqname)
200                         pos := 0
201                         for _, libref := range cseq {
202                                 rt := reftile[libref.Tag]
203                                 rt.pos = pos
204                                 if len(rt.tiledata) == 0 {
205                                         return fmt.Errorf("missing tiledata for tag %d variant %d in %s in ref", libref.Tag, libref.Variant, seqname)
206                                 }
207                                 pos += len(rt.tiledata) - taglen
208                         }
209                         return nil
210                 })
211         }
212         throttleCPU.Wait()
213
214         log.Info("TODO: determining which tiles intersect given regions")
215
216         throttleMem := throttle{Max: cmd.threads} // TODO: estimate using mem and data size
217         throttleNumpyMem := throttle{Max: cmd.threads/2 + 1}
218         log.Info("generating annotations and numpy matrix for each slice")
219         var done int64
220         for infileIdx, infile := range infiles {
221                 infileIdx, infile := infileIdx, infile
222                 throttleMem.Go(func() error {
223                         seq := make(map[tagID][]TileVariant, 50000)
224                         cgs := make(map[string]CompactGenome, len(cgnames))
225                         f, err := open(infile)
226                         if err != nil {
227                                 return err
228                         }
229                         defer f.Close()
230                         log.Infof("%04d: reading %s", infileIdx, infile)
231                         err = DecodeLibrary(f, strings.HasSuffix(infile, ".gz"), func(ent *LibraryEntry) error {
232                                 for _, tv := range ent.TileVariants {
233                                         if tv.Ref {
234                                                 continue
235                                         }
236                                         variants := seq[tv.Tag]
237                                         if len(variants) == 0 {
238                                                 variants = make([]TileVariant, 100)
239                                         }
240                                         for len(variants) <= int(tv.Variant) {
241                                                 variants = append(variants, TileVariant{})
242                                         }
243                                         variants[int(tv.Variant)] = tv
244                                         seq[tv.Tag] = variants
245                                 }
246                                 for _, cg := range ent.CompactGenomes {
247                                         cgs[cg.Name] = cg
248                                 }
249                                 return nil
250                         })
251                         if err != nil {
252                                 return err
253                         }
254                         tagstart := cgs[cgnames[0]].StartTag
255                         tagend := cgs[cgnames[0]].EndTag
256
257                         // TODO: filters
258
259                         log.Infof("%04d: renumber/dedup variants for tags %d-%d", infileIdx, tagstart, tagend)
260                         variantRemap := make([][]tileVariantID, tagend-tagstart)
261                         throttleCPU := throttle{Max: runtime.GOMAXPROCS(0)}
262                         for tag, variants := range seq {
263                                 tag, variants := tag, variants
264                                 throttleCPU.Acquire()
265                                 go func() {
266                                         defer throttleCPU.Release()
267                                         count := make(map[[blake2b.Size256]byte]int, len(variants))
268                                         for _, cg := range cgs {
269                                                 idx := (tag - tagstart) * 2
270                                                 if int(idx) < len(cg.Variants) {
271                                                         count[variants[cg.Variants[idx]].Blake2b]++
272                                                         count[variants[cg.Variants[idx+1]].Blake2b]++
273                                                 }
274                                         }
275                                         // hash[i] will be the hash of
276                                         // the variant(s) that should
277                                         // be at rank i (0-based).
278                                         hash := make([][blake2b.Size256]byte, 0, len(count))
279                                         for b := range count {
280                                                 hash = append(hash, b)
281                                         }
282                                         sort.Slice(hash, func(i, j int) bool {
283                                                 bi, bj := &hash[i], &hash[j]
284                                                 if ci, cj := count[*bi], count[*bj]; ci != cj {
285                                                         return ci > cj
286                                                 } else {
287                                                         return bytes.Compare((*bi)[:], (*bj)[:]) < 0
288                                                 }
289                                         })
290                                         // rank[b] will be the 1-based
291                                         // new variant number for
292                                         // variants whose hash is b.
293                                         rank := make(map[[blake2b.Size256]byte]tileVariantID, len(hash))
294                                         for i, h := range hash {
295                                                 rank[h] = tileVariantID(i + 1)
296                                         }
297                                         // remap[v] will be the new
298                                         // variant number for original
299                                         // variant number v.
300                                         remap := make([]tileVariantID, len(variants))
301                                         for i, tv := range variants {
302                                                 remap[i] = rank[tv.Blake2b]
303                                         }
304                                         variantRemap[tag-tagstart] = remap
305                                 }()
306                         }
307                         throttleCPU.Wait()
308
309                         annotationsFilename := fmt.Sprintf("%s/matrix.%04d.annotations.csv", *outputDir, infileIdx)
310                         log.Infof("%04d: writing %s", infileIdx, annotationsFilename)
311                         annof, err := os.Create(annotationsFilename)
312                         if err != nil {
313                                 return err
314                         }
315                         annow := bufio.NewWriterSize(annof, 1<<20)
316                         for tag, variants := range seq {
317                                 rt, ok := reftile[tag]
318                                 if !ok {
319                                         // Reference does not use any
320                                         // variant of this tile.
321                                         // TODO: log this? mention it
322                                         // in annotations?
323                                         continue
324                                 }
325                                 outcol := tag - tagID(tagstart)
326                                 reftilestr := strings.ToUpper(string(rt.tiledata))
327                                 remap := variantRemap[tag-tagstart]
328                                 for v, tv := range variants {
329                                         if len(tv.Sequence) < taglen || !bytes.HasSuffix(rt.tiledata, tv.Sequence[len(tv.Sequence)-taglen:]) {
330                                                 continue
331                                         }
332                                         if lendiff := len(rt.tiledata) - len(tv.Sequence); lendiff < -1000 || lendiff > 1000 {
333                                                 continue
334                                         }
335                                         diffs, _ := hgvs.Diff(reftilestr, strings.ToUpper(string(tv.Sequence)), 0)
336                                         for _, diff := range diffs {
337                                                 diff.Position += rt.pos
338                                                 fmt.Fprintf(annow, "%d,%d,%d,%s:g.%s\n", tag, outcol, remap[v], rt.seqname, diff.String())
339                                         }
340                                 }
341                         }
342                         err = annow.Flush()
343                         if err != nil {
344                                 return err
345                         }
346                         err = annof.Close()
347                         if err != nil {
348                                 return err
349                         }
350
351                         throttleNumpyMem.Acquire()
352                         log.Infof("%04d: preparing numpy", infileIdx)
353                         rows := len(cgnames)
354                         cols := 2 * int(tagend-tagstart)
355                         out := make([]int16, rows*cols)
356                         for row, name := range cgnames {
357                                 out := out[row*cols:]
358                                 for col, v := range cgs[name].Variants {
359                                         if variants, ok := seq[tagstart+tagID(col/2)]; ok && len(variants) > int(v) && len(variants[v].Sequence) > 0 {
360                                                 out[col] = int16(variantRemap[col/2][v])
361                                         } else {
362                                                 out[col] = -1
363                                         }
364                                 }
365                         }
366                         seq = nil
367                         throttleNumpyMem.Release()
368
369                         fnm := fmt.Sprintf("%s/matrix.%04d.npy", *outputDir, infileIdx)
370                         output, err := os.Create(fnm)
371                         if err != nil {
372                                 return err
373                         }
374                         defer output.Close()
375                         bufw := bufio.NewWriterSize(output, 1<<26)
376                         npw, err := gonpy.NewWriter(nopCloser{bufw})
377                         if err != nil {
378                                 return err
379                         }
380                         log.WithFields(logrus.Fields{
381                                 "filename": fnm,
382                                 "rows":     rows,
383                                 "cols":     cols,
384                         }).Infof("%04d: writing numpy", infileIdx)
385                         npw.Shape = []int{rows, cols}
386                         npw.WriteInt16(out)
387                         err = bufw.Flush()
388                         if err != nil {
389                                 return err
390                         }
391                         err = output.Close()
392                         if err != nil {
393                                 return err
394                         }
395                         log.Infof("%s: done (%d/%d)", infile, int(atomic.AddInt64(&done, 1)), len(infiles))
396                         return nil
397                 })
398         }
399         if err = throttleMem.Wait(); err != nil {
400                 return 1
401         }
402         return 0
403 }